repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java
|
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java
|
ClustersInner.beginStop
|
public void beginStop(String resourceGroupName, String clusterName) {
"""
Stops a Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
beginStopWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body();
}
|
java
|
public void beginStop(String resourceGroupName, String clusterName) {
beginStopWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body();
}
|
[
"public",
"void",
"beginStop",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"beginStopWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Stops a Kusto cluster.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
|
[
"Stops",
"a",
"Kusto",
"cluster",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L796-L798
|
looly/hutool
|
hutool-http/src/main/java/cn/hutool/http/HttpUtil.java
|
HttpUtil.download
|
public static long download(String url, OutputStream out, boolean isCloseOut) {
"""
下载远程文件
@param url 请求的url
@param out 将下载内容写到输出流中 {@link OutputStream}
@param isCloseOut 是否关闭输出流
@return 文件大小
"""
return download(url, out, isCloseOut, null);
}
|
java
|
public static long download(String url, OutputStream out, boolean isCloseOut) {
return download(url, out, isCloseOut, null);
}
|
[
"public",
"static",
"long",
"download",
"(",
"String",
"url",
",",
"OutputStream",
"out",
",",
"boolean",
"isCloseOut",
")",
"{",
"return",
"download",
"(",
"url",
",",
"out",
",",
"isCloseOut",
",",
"null",
")",
";",
"}"
] |
下载远程文件
@param url 请求的url
@param out 将下载内容写到输出流中 {@link OutputStream}
@param isCloseOut 是否关闭输出流
@return 文件大小
|
[
"下载远程文件"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L326-L328
|
cdk/cdk
|
display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/BasicAtomGenerator.java
|
BasicAtomGenerator.canDraw
|
protected boolean canDraw(IAtom atom, IAtomContainer container, RendererModel model) {
"""
Checks an atom to see if it should be drawn. There are three reasons
not to draw an atom - a) no coordinates, b) an invisible hydrogen or
c) an invisible carbon.
@param atom the atom to check
@param container the atom container the atom is part of
@param model the renderer model
@return true if the atom should be drawn
"""
// don't draw atoms without coordinates
if (!hasCoordinates(atom)) {
return false;
}
// don't draw invisible hydrogens
if (invisibleHydrogen(atom, model)) {
return false;
}
// don't draw invisible carbons
if (invisibleCarbon(atom, container, model)) {
return false;
}
return true;
}
|
java
|
protected boolean canDraw(IAtom atom, IAtomContainer container, RendererModel model) {
// don't draw atoms without coordinates
if (!hasCoordinates(atom)) {
return false;
}
// don't draw invisible hydrogens
if (invisibleHydrogen(atom, model)) {
return false;
}
// don't draw invisible carbons
if (invisibleCarbon(atom, container, model)) {
return false;
}
return true;
}
|
[
"protected",
"boolean",
"canDraw",
"(",
"IAtom",
"atom",
",",
"IAtomContainer",
"container",
",",
"RendererModel",
"model",
")",
"{",
"// don't draw atoms without coordinates",
"if",
"(",
"!",
"hasCoordinates",
"(",
"atom",
")",
")",
"{",
"return",
"false",
";",
"}",
"// don't draw invisible hydrogens",
"if",
"(",
"invisibleHydrogen",
"(",
"atom",
",",
"model",
")",
")",
"{",
"return",
"false",
";",
"}",
"// don't draw invisible carbons",
"if",
"(",
"invisibleCarbon",
"(",
"atom",
",",
"container",
",",
"model",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Checks an atom to see if it should be drawn. There are three reasons
not to draw an atom - a) no coordinates, b) an invisible hydrogen or
c) an invisible carbon.
@param atom the atom to check
@param container the atom container the atom is part of
@param model the renderer model
@return true if the atom should be drawn
|
[
"Checks",
"an",
"atom",
"to",
"see",
"if",
"it",
"should",
"be",
"drawn",
".",
"There",
"are",
"three",
"reasons",
"not",
"to",
"draw",
"an",
"atom",
"-",
"a",
")",
"no",
"coordinates",
"b",
")",
"an",
"invisible",
"hydrogen",
"or",
"c",
")",
"an",
"invisible",
"carbon",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/BasicAtomGenerator.java#L289-L306
|
linkedin/PalDB
|
paldb/src/main/java/com/linkedin/paldb/api/PalDB.java
|
PalDB.createWriter
|
public static StoreWriter createWriter(OutputStream stream, Configuration config) {
"""
Creates a store writer with the specified <code>stream</code> as destination.
<p>
The writer will only write bytes to the stream when {@link StoreWriter#close() }
is called.
@param stream output stream
@param config configuration
@return a store writer
"""
return StoreImpl.createWriter(stream, config);
}
|
java
|
public static StoreWriter createWriter(OutputStream stream, Configuration config) {
return StoreImpl.createWriter(stream, config);
}
|
[
"public",
"static",
"StoreWriter",
"createWriter",
"(",
"OutputStream",
"stream",
",",
"Configuration",
"config",
")",
"{",
"return",
"StoreImpl",
".",
"createWriter",
"(",
"stream",
",",
"config",
")",
";",
"}"
] |
Creates a store writer with the specified <code>stream</code> as destination.
<p>
The writer will only write bytes to the stream when {@link StoreWriter#close() }
is called.
@param stream output stream
@param config configuration
@return a store writer
|
[
"Creates",
"a",
"store",
"writer",
"with",
"the",
"specified",
"<code",
">",
"stream<",
"/",
"code",
">",
"as",
"destination",
".",
"<p",
">",
"The",
"writer",
"will",
"only",
"write",
"bytes",
"to",
"the",
"stream",
"when",
"{",
"@link",
"StoreWriter#close",
"()",
"}",
"is",
"called",
"."
] |
train
|
https://github.com/linkedin/PalDB/blob/d05ccdd3f67855eb2675dbd82599f19aa7a9f650/paldb/src/main/java/com/linkedin/paldb/api/PalDB.java#L111-L113
|
google/closure-compiler
|
src/com/google/javascript/jscomp/TypeValidator.java
|
TypeValidator.expectStringOrSymbol
|
void expectStringOrSymbol(Node n, JSType type, String msg) {
"""
Expect the type to be a string or symbol, or a type convertible to a string. If the expectation
is not met, issue a warning at the provided node's source code position.
"""
if (!type.matchesStringContext() && !type.matchesSymbolContext()) {
mismatch(n, msg, type, STRING_SYMBOL);
}
}
|
java
|
void expectStringOrSymbol(Node n, JSType type, String msg) {
if (!type.matchesStringContext() && !type.matchesSymbolContext()) {
mismatch(n, msg, type, STRING_SYMBOL);
}
}
|
[
"void",
"expectStringOrSymbol",
"(",
"Node",
"n",
",",
"JSType",
"type",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"!",
"type",
".",
"matchesStringContext",
"(",
")",
"&&",
"!",
"type",
".",
"matchesSymbolContext",
"(",
")",
")",
"{",
"mismatch",
"(",
"n",
",",
"msg",
",",
"type",
",",
"STRING_SYMBOL",
")",
";",
"}",
"}"
] |
Expect the type to be a string or symbol, or a type convertible to a string. If the expectation
is not met, issue a warning at the provided node's source code position.
|
[
"Expect",
"the",
"type",
"to",
"be",
"a",
"string",
"or",
"symbol",
"or",
"a",
"type",
"convertible",
"to",
"a",
"string",
".",
"If",
"the",
"expectation",
"is",
"not",
"met",
"issue",
"a",
"warning",
"at",
"the",
"provided",
"node",
"s",
"source",
"code",
"position",
"."
] |
train
|
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeValidator.java#L423-L427
|
mangstadt/biweekly
|
src/main/java/biweekly/io/ParseContext.java
|
ParseContext.addDate
|
public void addDate(ICalDate icalDate, ICalProperty property, ICalParameters parameters) {
"""
Adds a parsed date to this parse context so its timezone can be applied
to it after the iCalendar object has been parsed (if it has one).
@param icalDate the parsed date
@param property the property that the date value belongs to
@param parameters the property's parameters
"""
if (!icalDate.hasTime()) {
//dates don't have timezones
return;
}
if (icalDate.getRawComponents().isUtc()) {
//it's a UTC date, so it was already parsed under the correct timezone
return;
}
//TODO handle UTC offsets within the date strings (not part of iCal standard)
String tzid = parameters.getTimezoneId();
if (tzid == null) {
addFloatingDate(property, icalDate);
} else {
addTimezonedDate(tzid, property, icalDate);
}
}
|
java
|
public void addDate(ICalDate icalDate, ICalProperty property, ICalParameters parameters) {
if (!icalDate.hasTime()) {
//dates don't have timezones
return;
}
if (icalDate.getRawComponents().isUtc()) {
//it's a UTC date, so it was already parsed under the correct timezone
return;
}
//TODO handle UTC offsets within the date strings (not part of iCal standard)
String tzid = parameters.getTimezoneId();
if (tzid == null) {
addFloatingDate(property, icalDate);
} else {
addTimezonedDate(tzid, property, icalDate);
}
}
|
[
"public",
"void",
"addDate",
"(",
"ICalDate",
"icalDate",
",",
"ICalProperty",
"property",
",",
"ICalParameters",
"parameters",
")",
"{",
"if",
"(",
"!",
"icalDate",
".",
"hasTime",
"(",
")",
")",
"{",
"//dates don't have timezones",
"return",
";",
"}",
"if",
"(",
"icalDate",
".",
"getRawComponents",
"(",
")",
".",
"isUtc",
"(",
")",
")",
"{",
"//it's a UTC date, so it was already parsed under the correct timezone",
"return",
";",
"}",
"//TODO handle UTC offsets within the date strings (not part of iCal standard)",
"String",
"tzid",
"=",
"parameters",
".",
"getTimezoneId",
"(",
")",
";",
"if",
"(",
"tzid",
"==",
"null",
")",
"{",
"addFloatingDate",
"(",
"property",
",",
"icalDate",
")",
";",
"}",
"else",
"{",
"addTimezonedDate",
"(",
"tzid",
",",
"property",
",",
"icalDate",
")",
";",
"}",
"}"
] |
Adds a parsed date to this parse context so its timezone can be applied
to it after the iCalendar object has been parsed (if it has one).
@param icalDate the parsed date
@param property the property that the date value belongs to
@param parameters the property's parameters
|
[
"Adds",
"a",
"parsed",
"date",
"to",
"this",
"parse",
"context",
"so",
"its",
"timezone",
"can",
"be",
"applied",
"to",
"it",
"after",
"the",
"iCalendar",
"object",
"has",
"been",
"parsed",
"(",
"if",
"it",
"has",
"one",
")",
"."
] |
train
|
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/io/ParseContext.java#L105-L123
|
apache/incubator-gobblin
|
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/workunit/packer/KafkaWorkUnitPacker.java
|
KafkaWorkUnitPacker.populateMultiPartitionWorkUnit
|
private static void populateMultiPartitionWorkUnit(List<KafkaPartition> partitions, WorkUnit workUnit) {
"""
Add a list of partitions of the same topic to a {@link WorkUnit}.
"""
Preconditions.checkArgument(!partitions.isEmpty(), "There should be at least one partition");
GobblinMetrics.addCustomTagToState(workUnit, new Tag<>("kafkaTopic", partitions.get(0).getTopicName()));
for (int i = 0; i < partitions.size(); i++) {
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.PARTITION_ID, i), partitions.get(i).getId());
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_ID, i),
partitions.get(i).getLeader().getId());
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_HOSTANDPORT, i),
partitions.get(i).getLeader().getHostAndPort());
}
}
|
java
|
private static void populateMultiPartitionWorkUnit(List<KafkaPartition> partitions, WorkUnit workUnit) {
Preconditions.checkArgument(!partitions.isEmpty(), "There should be at least one partition");
GobblinMetrics.addCustomTagToState(workUnit, new Tag<>("kafkaTopic", partitions.get(0).getTopicName()));
for (int i = 0; i < partitions.size(); i++) {
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.PARTITION_ID, i), partitions.get(i).getId());
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_ID, i),
partitions.get(i).getLeader().getId());
workUnit.setProp(KafkaUtils.getPartitionPropName(KafkaSource.LEADER_HOSTANDPORT, i),
partitions.get(i).getLeader().getHostAndPort());
}
}
|
[
"private",
"static",
"void",
"populateMultiPartitionWorkUnit",
"(",
"List",
"<",
"KafkaPartition",
">",
"partitions",
",",
"WorkUnit",
"workUnit",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"!",
"partitions",
".",
"isEmpty",
"(",
")",
",",
"\"There should be at least one partition\"",
")",
";",
"GobblinMetrics",
".",
"addCustomTagToState",
"(",
"workUnit",
",",
"new",
"Tag",
"<>",
"(",
"\"kafkaTopic\"",
",",
"partitions",
".",
"get",
"(",
"0",
")",
".",
"getTopicName",
"(",
")",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"partitions",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"workUnit",
".",
"setProp",
"(",
"KafkaUtils",
".",
"getPartitionPropName",
"(",
"KafkaSource",
".",
"PARTITION_ID",
",",
"i",
")",
",",
"partitions",
".",
"get",
"(",
"i",
")",
".",
"getId",
"(",
")",
")",
";",
"workUnit",
".",
"setProp",
"(",
"KafkaUtils",
".",
"getPartitionPropName",
"(",
"KafkaSource",
".",
"LEADER_ID",
",",
"i",
")",
",",
"partitions",
".",
"get",
"(",
"i",
")",
".",
"getLeader",
"(",
")",
".",
"getId",
"(",
")",
")",
";",
"workUnit",
".",
"setProp",
"(",
"KafkaUtils",
".",
"getPartitionPropName",
"(",
"KafkaSource",
".",
"LEADER_HOSTANDPORT",
",",
"i",
")",
",",
"partitions",
".",
"get",
"(",
"i",
")",
".",
"getLeader",
"(",
")",
".",
"getHostAndPort",
"(",
")",
")",
";",
"}",
"}"
] |
Add a list of partitions of the same topic to a {@link WorkUnit}.
|
[
"Add",
"a",
"list",
"of",
"partitions",
"of",
"the",
"same",
"topic",
"to",
"a",
"{"
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/workunit/packer/KafkaWorkUnitPacker.java#L256-L266
|
Azure/azure-sdk-for-java
|
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
|
KeyVaultClientBaseImpl.updateStorageAccountAsync
|
public Observable<StorageBundle> updateStorageAccountAsync(String vaultBaseUrl, String storageAccountName, String activeKeyName, Boolean autoRegenerateKey, String regenerationPeriod, StorageAccountAttributes storageAccountAttributes, Map<String, String> tags) {
"""
Updates the specified attributes associated with the given storage account. This operation requires the storage/set/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@param activeKeyName The current active storage account key name.
@param autoRegenerateKey whether keyvault should manage the storage account for the user.
@param regenerationPeriod The key regeneration time duration specified in ISO-8601 format.
@param storageAccountAttributes The attributes of the storage account.
@param tags Application specific metadata in the form of key-value pairs.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageBundle object
"""
return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, activeKeyName, autoRegenerateKey, regenerationPeriod, storageAccountAttributes, tags).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
}
|
java
|
public Observable<StorageBundle> updateStorageAccountAsync(String vaultBaseUrl, String storageAccountName, String activeKeyName, Boolean autoRegenerateKey, String regenerationPeriod, StorageAccountAttributes storageAccountAttributes, Map<String, String> tags) {
return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, activeKeyName, autoRegenerateKey, regenerationPeriod, storageAccountAttributes, tags).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"StorageBundle",
">",
"updateStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"storageAccountName",
",",
"String",
"activeKeyName",
",",
"Boolean",
"autoRegenerateKey",
",",
"String",
"regenerationPeriod",
",",
"StorageAccountAttributes",
"storageAccountAttributes",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"updateStorageAccountWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName",
",",
"activeKeyName",
",",
"autoRegenerateKey",
",",
"regenerationPeriod",
",",
"storageAccountAttributes",
",",
"tags",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"StorageBundle",
">",
",",
"StorageBundle",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"StorageBundle",
"call",
"(",
"ServiceResponse",
"<",
"StorageBundle",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates the specified attributes associated with the given storage account. This operation requires the storage/set/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@param activeKeyName The current active storage account key name.
@param autoRegenerateKey whether keyvault should manage the storage account for the user.
@param regenerationPeriod The key regeneration time duration specified in ISO-8601 format.
@param storageAccountAttributes The attributes of the storage account.
@param tags Application specific metadata in the form of key-value pairs.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageBundle object
|
[
"Updates",
"the",
"specified",
"attributes",
"associated",
"with",
"the",
"given",
"storage",
"account",
".",
"This",
"operation",
"requires",
"the",
"storage",
"/",
"set",
"/",
"update",
"permission",
"."
] |
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#L10221-L10228
|
netty/netty
|
example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java
|
HttpStaticFileServerHandler.sendAndCleanupConnection
|
private void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response) {
"""
If Keep-Alive is disabled, attaches "Connection: close" header to the response
and closes the connection after the response being sent.
"""
final FullHttpRequest request = this.request;
final boolean keepAlive = HttpUtil.isKeepAlive(request);
HttpUtil.setContentLength(response, response.content().readableBytes());
if (!keepAlive) {
// We're going to close the connection as soon as the response is sent,
// so we should also make it clear for the client.
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
} else if (request.protocolVersion().equals(HTTP_1_0)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ChannelFuture flushPromise = ctx.writeAndFlush(response);
if (!keepAlive) {
// Close the connection as soon as the response is sent.
flushPromise.addListener(ChannelFutureListener.CLOSE);
}
}
|
java
|
private void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response) {
final FullHttpRequest request = this.request;
final boolean keepAlive = HttpUtil.isKeepAlive(request);
HttpUtil.setContentLength(response, response.content().readableBytes());
if (!keepAlive) {
// We're going to close the connection as soon as the response is sent,
// so we should also make it clear for the client.
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
} else if (request.protocolVersion().equals(HTTP_1_0)) {
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
}
ChannelFuture flushPromise = ctx.writeAndFlush(response);
if (!keepAlive) {
// Close the connection as soon as the response is sent.
flushPromise.addListener(ChannelFutureListener.CLOSE);
}
}
|
[
"private",
"void",
"sendAndCleanupConnection",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullHttpResponse",
"response",
")",
"{",
"final",
"FullHttpRequest",
"request",
"=",
"this",
".",
"request",
";",
"final",
"boolean",
"keepAlive",
"=",
"HttpUtil",
".",
"isKeepAlive",
"(",
"request",
")",
";",
"HttpUtil",
".",
"setContentLength",
"(",
"response",
",",
"response",
".",
"content",
"(",
")",
".",
"readableBytes",
"(",
")",
")",
";",
"if",
"(",
"!",
"keepAlive",
")",
"{",
"// We're going to close the connection as soon as the response is sent,",
"// so we should also make it clear for the client.",
"response",
".",
"headers",
"(",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"CONNECTION",
",",
"HttpHeaderValues",
".",
"CLOSE",
")",
";",
"}",
"else",
"if",
"(",
"request",
".",
"protocolVersion",
"(",
")",
".",
"equals",
"(",
"HTTP_1_0",
")",
")",
"{",
"response",
".",
"headers",
"(",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"CONNECTION",
",",
"HttpHeaderValues",
".",
"KEEP_ALIVE",
")",
";",
"}",
"ChannelFuture",
"flushPromise",
"=",
"ctx",
".",
"writeAndFlush",
"(",
"response",
")",
";",
"if",
"(",
"!",
"keepAlive",
")",
"{",
"// Close the connection as soon as the response is sent.",
"flushPromise",
".",
"addListener",
"(",
"ChannelFutureListener",
".",
"CLOSE",
")",
";",
"}",
"}"
] |
If Keep-Alive is disabled, attaches "Connection: close" header to the response
and closes the connection after the response being sent.
|
[
"If",
"Keep",
"-",
"Alive",
"is",
"disabled",
"attaches",
"Connection",
":",
"close",
"header",
"to",
"the",
"response",
"and",
"closes",
"the",
"connection",
"after",
"the",
"response",
"being",
"sent",
"."
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java#L349-L367
|
JodaOrg/joda-time
|
src/main/java/org/joda/time/DateTimeUtils.java
|
DateTimeUtils.getIntervalChronology
|
public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) {
"""
Gets the chronology from the specified instant based interval handling null.
<p>
The chronology is obtained from the start if that is not null, or from the
end if the start is null. The result is additionally checked, and if still
null then {@link ISOChronology#getInstance()} will be returned.
@param start the instant to examine and use as the primary source of the chronology
@param end the instant to examine and use as the secondary source of the chronology
@return the chronology, never null
"""
Chronology chrono = null;
if (start != null) {
chrono = start.getChronology();
} else if (end != null) {
chrono = end.getChronology();
}
if (chrono == null) {
chrono = ISOChronology.getInstance();
}
return chrono;
}
|
java
|
public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) {
Chronology chrono = null;
if (start != null) {
chrono = start.getChronology();
} else if (end != null) {
chrono = end.getChronology();
}
if (chrono == null) {
chrono = ISOChronology.getInstance();
}
return chrono;
}
|
[
"public",
"static",
"final",
"Chronology",
"getIntervalChronology",
"(",
"ReadableInstant",
"start",
",",
"ReadableInstant",
"end",
")",
"{",
"Chronology",
"chrono",
"=",
"null",
";",
"if",
"(",
"start",
"!=",
"null",
")",
"{",
"chrono",
"=",
"start",
".",
"getChronology",
"(",
")",
";",
"}",
"else",
"if",
"(",
"end",
"!=",
"null",
")",
"{",
"chrono",
"=",
"end",
".",
"getChronology",
"(",
")",
";",
"}",
"if",
"(",
"chrono",
"==",
"null",
")",
"{",
"chrono",
"=",
"ISOChronology",
".",
"getInstance",
"(",
")",
";",
"}",
"return",
"chrono",
";",
"}"
] |
Gets the chronology from the specified instant based interval handling null.
<p>
The chronology is obtained from the start if that is not null, or from the
end if the start is null. The result is additionally checked, and if still
null then {@link ISOChronology#getInstance()} will be returned.
@param start the instant to examine and use as the primary source of the chronology
@param end the instant to examine and use as the secondary source of the chronology
@return the chronology, never null
|
[
"Gets",
"the",
"chronology",
"from",
"the",
"specified",
"instant",
"based",
"interval",
"handling",
"null",
".",
"<p",
">",
"The",
"chronology",
"is",
"obtained",
"from",
"the",
"start",
"if",
"that",
"is",
"not",
"null",
"or",
"from",
"the",
"end",
"if",
"the",
"start",
"is",
"null",
".",
"The",
"result",
"is",
"additionally",
"checked",
"and",
"if",
"still",
"null",
"then",
"{",
"@link",
"ISOChronology#getInstance",
"()",
"}",
"will",
"be",
"returned",
"."
] |
train
|
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/DateTimeUtils.java#L202-L213
|
facebookarchive/hadoop-20
|
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
|
FSNamesystem.countNodes
|
private NumberReplicas countNodes(Block b,
Iterator<DatanodeDescriptor> nodeIter) {
"""
Counts the number of nodes in the given list into active and
decommissioned counters.
"""
int count = 0;
int live = 0;
int corrupt = 0;
int excess = 0;
Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(b);
while (nodeIter.hasNext()) {
DatanodeDescriptor node = nodeIter.next();
if ((nodesCorrupt != null) && (nodesCorrupt.contains(node))) {
corrupt++;
} else if (node.isDecommissionInProgress() || node.isDecommissioned()) {
count++;
} else {
Collection<Block> blocksExcess = initializedReplQueues ?
excessReplicateMap.get(node.getStorageID()) : null;
if (blocksExcess != null && blocksExcess.contains(b)) {
excess++;
} else {
live++;
}
}
}
return new NumberReplicas(live, count, corrupt, excess);
}
|
java
|
private NumberReplicas countNodes(Block b,
Iterator<DatanodeDescriptor> nodeIter) {
int count = 0;
int live = 0;
int corrupt = 0;
int excess = 0;
Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(b);
while (nodeIter.hasNext()) {
DatanodeDescriptor node = nodeIter.next();
if ((nodesCorrupt != null) && (nodesCorrupt.contains(node))) {
corrupt++;
} else if (node.isDecommissionInProgress() || node.isDecommissioned()) {
count++;
} else {
Collection<Block> blocksExcess = initializedReplQueues ?
excessReplicateMap.get(node.getStorageID()) : null;
if (blocksExcess != null && blocksExcess.contains(b)) {
excess++;
} else {
live++;
}
}
}
return new NumberReplicas(live, count, corrupt, excess);
}
|
[
"private",
"NumberReplicas",
"countNodes",
"(",
"Block",
"b",
",",
"Iterator",
"<",
"DatanodeDescriptor",
">",
"nodeIter",
")",
"{",
"int",
"count",
"=",
"0",
";",
"int",
"live",
"=",
"0",
";",
"int",
"corrupt",
"=",
"0",
";",
"int",
"excess",
"=",
"0",
";",
"Collection",
"<",
"DatanodeDescriptor",
">",
"nodesCorrupt",
"=",
"corruptReplicas",
".",
"getNodes",
"(",
"b",
")",
";",
"while",
"(",
"nodeIter",
".",
"hasNext",
"(",
")",
")",
"{",
"DatanodeDescriptor",
"node",
"=",
"nodeIter",
".",
"next",
"(",
")",
";",
"if",
"(",
"(",
"nodesCorrupt",
"!=",
"null",
")",
"&&",
"(",
"nodesCorrupt",
".",
"contains",
"(",
"node",
")",
")",
")",
"{",
"corrupt",
"++",
";",
"}",
"else",
"if",
"(",
"node",
".",
"isDecommissionInProgress",
"(",
")",
"||",
"node",
".",
"isDecommissioned",
"(",
")",
")",
"{",
"count",
"++",
";",
"}",
"else",
"{",
"Collection",
"<",
"Block",
">",
"blocksExcess",
"=",
"initializedReplQueues",
"?",
"excessReplicateMap",
".",
"get",
"(",
"node",
".",
"getStorageID",
"(",
")",
")",
":",
"null",
";",
"if",
"(",
"blocksExcess",
"!=",
"null",
"&&",
"blocksExcess",
".",
"contains",
"(",
"b",
")",
")",
"{",
"excess",
"++",
";",
"}",
"else",
"{",
"live",
"++",
";",
"}",
"}",
"}",
"return",
"new",
"NumberReplicas",
"(",
"live",
",",
"count",
",",
"corrupt",
",",
"excess",
")",
";",
"}"
] |
Counts the number of nodes in the given list into active and
decommissioned counters.
|
[
"Counts",
"the",
"number",
"of",
"nodes",
"in",
"the",
"given",
"list",
"into",
"active",
"and",
"decommissioned",
"counters",
"."
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java#L8076-L8100
|
lessthanoptimal/BoofCV
|
main/boofcv-ip/src/main/java/boofcv/alg/denoise/wavelet/DenoiseVisuShrink_F32.java
|
DenoiseVisuShrink_F32.denoise
|
@Override
public void denoise(GrayF32 transform , int numLevels ) {
"""
Applies VisuShrink denoising to the provided multilevel wavelet transform using
the provided threshold.
@param transform Mult-level wavelet transform. Modified.
@param numLevels Number of levels in the transform.
"""
int scale = UtilWavelet.computeScale(numLevels);
final int h = transform.height;
final int w = transform.width;
// width and height of scaling image
final int innerWidth = w/scale;
final int innerHeight = h/scale;
GrayF32 subbandHH = transform.subimage(w/2,h/2,w,h, null);
float sigma = UtilDenoiseWavelet.estimateNoiseStdDev(subbandHH,null);
float threshold = (float) UtilDenoiseWavelet.universalThreshold(subbandHH,sigma);
// apply same threshold to all wavelet coefficients
rule.process(transform.subimage(innerWidth,0,w,h, null),threshold);
rule.process(transform.subimage(0,innerHeight,innerWidth,h, null),threshold);
}
|
java
|
@Override
public void denoise(GrayF32 transform , int numLevels ) {
int scale = UtilWavelet.computeScale(numLevels);
final int h = transform.height;
final int w = transform.width;
// width and height of scaling image
final int innerWidth = w/scale;
final int innerHeight = h/scale;
GrayF32 subbandHH = transform.subimage(w/2,h/2,w,h, null);
float sigma = UtilDenoiseWavelet.estimateNoiseStdDev(subbandHH,null);
float threshold = (float) UtilDenoiseWavelet.universalThreshold(subbandHH,sigma);
// apply same threshold to all wavelet coefficients
rule.process(transform.subimage(innerWidth,0,w,h, null),threshold);
rule.process(transform.subimage(0,innerHeight,innerWidth,h, null),threshold);
}
|
[
"@",
"Override",
"public",
"void",
"denoise",
"(",
"GrayF32",
"transform",
",",
"int",
"numLevels",
")",
"{",
"int",
"scale",
"=",
"UtilWavelet",
".",
"computeScale",
"(",
"numLevels",
")",
";",
"final",
"int",
"h",
"=",
"transform",
".",
"height",
";",
"final",
"int",
"w",
"=",
"transform",
".",
"width",
";",
"// width and height of scaling image",
"final",
"int",
"innerWidth",
"=",
"w",
"/",
"scale",
";",
"final",
"int",
"innerHeight",
"=",
"h",
"/",
"scale",
";",
"GrayF32",
"subbandHH",
"=",
"transform",
".",
"subimage",
"(",
"w",
"/",
"2",
",",
"h",
"/",
"2",
",",
"w",
",",
"h",
",",
"null",
")",
";",
"float",
"sigma",
"=",
"UtilDenoiseWavelet",
".",
"estimateNoiseStdDev",
"(",
"subbandHH",
",",
"null",
")",
";",
"float",
"threshold",
"=",
"(",
"float",
")",
"UtilDenoiseWavelet",
".",
"universalThreshold",
"(",
"subbandHH",
",",
"sigma",
")",
";",
"// apply same threshold to all wavelet coefficients",
"rule",
".",
"process",
"(",
"transform",
".",
"subimage",
"(",
"innerWidth",
",",
"0",
",",
"w",
",",
"h",
",",
"null",
")",
",",
"threshold",
")",
";",
"rule",
".",
"process",
"(",
"transform",
".",
"subimage",
"(",
"0",
",",
"innerHeight",
",",
"innerWidth",
",",
"h",
",",
"null",
")",
",",
"threshold",
")",
";",
"}"
] |
Applies VisuShrink denoising to the provided multilevel wavelet transform using
the provided threshold.
@param transform Mult-level wavelet transform. Modified.
@param numLevels Number of levels in the transform.
|
[
"Applies",
"VisuShrink",
"denoising",
"to",
"the",
"provided",
"multilevel",
"wavelet",
"transform",
"using",
"the",
"provided",
"threshold",
"."
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/denoise/wavelet/DenoiseVisuShrink_F32.java#L51-L69
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
|
ModelsImpl.getCompositeEntityAsync
|
public Observable<CompositeEntityExtractor> getCompositeEntityAsync(UUID appId, String versionId, UUID cEntityId) {
"""
Gets information about the composite entity model.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CompositeEntityExtractor object
"""
return getCompositeEntityWithServiceResponseAsync(appId, versionId, cEntityId).map(new Func1<ServiceResponse<CompositeEntityExtractor>, CompositeEntityExtractor>() {
@Override
public CompositeEntityExtractor call(ServiceResponse<CompositeEntityExtractor> response) {
return response.body();
}
});
}
|
java
|
public Observable<CompositeEntityExtractor> getCompositeEntityAsync(UUID appId, String versionId, UUID cEntityId) {
return getCompositeEntityWithServiceResponseAsync(appId, versionId, cEntityId).map(new Func1<ServiceResponse<CompositeEntityExtractor>, CompositeEntityExtractor>() {
@Override
public CompositeEntityExtractor call(ServiceResponse<CompositeEntityExtractor> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"CompositeEntityExtractor",
">",
"getCompositeEntityAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"cEntityId",
")",
"{",
"return",
"getCompositeEntityWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"cEntityId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"CompositeEntityExtractor",
">",
",",
"CompositeEntityExtractor",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"CompositeEntityExtractor",
"call",
"(",
"ServiceResponse",
"<",
"CompositeEntityExtractor",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Gets information about the composite entity model.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CompositeEntityExtractor object
|
[
"Gets",
"information",
"about",
"the",
"composite",
"entity",
"model",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3964-L3971
|
box/box-java-sdk
|
src/main/java/com/box/sdk/MetadataTemplate.java
|
MetadataTemplate.updateMetadataTemplate
|
public static MetadataTemplate updateMetadataTemplate(BoxAPIConnection api, String scope, String template,
List<FieldOperation> fieldOperations) {
"""
Updates the schema of an existing metadata template.
@param api the API connection to be used
@param scope the scope of the object
@param template Unique identifier of the template
@param fieldOperations the fields that needs to be updated / added in the template
@return the updated metadata template
"""
JsonArray array = new JsonArray();
for (FieldOperation fieldOperation : fieldOperations) {
JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation);
array.add(jsonObject);
}
QueryStringBuilder builder = new QueryStringBuilder();
URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);
BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT");
request.setBody(array.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJson = JsonObject.readFrom(response.getJSON());
return new MetadataTemplate(responseJson);
}
|
java
|
public static MetadataTemplate updateMetadataTemplate(BoxAPIConnection api, String scope, String template,
List<FieldOperation> fieldOperations) {
JsonArray array = new JsonArray();
for (FieldOperation fieldOperation : fieldOperations) {
JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation);
array.add(jsonObject);
}
QueryStringBuilder builder = new QueryStringBuilder();
URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);
BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT");
request.setBody(array.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJson = JsonObject.readFrom(response.getJSON());
return new MetadataTemplate(responseJson);
}
|
[
"public",
"static",
"MetadataTemplate",
"updateMetadataTemplate",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"scope",
",",
"String",
"template",
",",
"List",
"<",
"FieldOperation",
">",
"fieldOperations",
")",
"{",
"JsonArray",
"array",
"=",
"new",
"JsonArray",
"(",
")",
";",
"for",
"(",
"FieldOperation",
"fieldOperation",
":",
"fieldOperations",
")",
"{",
"JsonObject",
"jsonObject",
"=",
"getFieldOperationJsonObject",
"(",
"fieldOperation",
")",
";",
"array",
".",
"add",
"(",
"jsonObject",
")",
";",
"}",
"QueryStringBuilder",
"builder",
"=",
"new",
"QueryStringBuilder",
"(",
")",
";",
"URL",
"url",
"=",
"METADATA_TEMPLATE_URL_TEMPLATE",
".",
"build",
"(",
"api",
".",
"getBaseURL",
"(",
")",
",",
"scope",
",",
"template",
")",
";",
"BoxJSONRequest",
"request",
"=",
"new",
"BoxJSONRequest",
"(",
"api",
",",
"url",
",",
"\"PUT\"",
")",
";",
"request",
".",
"setBody",
"(",
"array",
".",
"toString",
"(",
")",
")",
";",
"BoxJSONResponse",
"response",
"=",
"(",
"BoxJSONResponse",
")",
"request",
".",
"send",
"(",
")",
";",
"JsonObject",
"responseJson",
"=",
"JsonObject",
".",
"readFrom",
"(",
"response",
".",
"getJSON",
"(",
")",
")",
";",
"return",
"new",
"MetadataTemplate",
"(",
"responseJson",
")",
";",
"}"
] |
Updates the schema of an existing metadata template.
@param api the API connection to be used
@param scope the scope of the object
@param template Unique identifier of the template
@param fieldOperations the fields that needs to be updated / added in the template
@return the updated metadata template
|
[
"Updates",
"the",
"schema",
"of",
"an",
"existing",
"metadata",
"template",
"."
] |
train
|
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/MetadataTemplate.java#L276-L295
|
google/closure-compiler
|
src/com/google/javascript/jscomp/AstFactory.java
|
AstFactory.createYield
|
Node createYield(JSType jsType, Node value) {
"""
Returns a new {@code yield} expression.
@param jsType Type we expect to get back after the yield
@param value value to yield
"""
Node result = IR.yield(value);
if (isAddingTypes()) {
result.setJSType(checkNotNull(jsType));
}
return result;
}
|
java
|
Node createYield(JSType jsType, Node value) {
Node result = IR.yield(value);
if (isAddingTypes()) {
result.setJSType(checkNotNull(jsType));
}
return result;
}
|
[
"Node",
"createYield",
"(",
"JSType",
"jsType",
",",
"Node",
"value",
")",
"{",
"Node",
"result",
"=",
"IR",
".",
"yield",
"(",
"value",
")",
";",
"if",
"(",
"isAddingTypes",
"(",
")",
")",
"{",
"result",
".",
"setJSType",
"(",
"checkNotNull",
"(",
"jsType",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Returns a new {@code yield} expression.
@param jsType Type we expect to get back after the yield
@param value value to yield
|
[
"Returns",
"a",
"new",
"{",
"@code",
"yield",
"}",
"expression",
"."
] |
train
|
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L186-L192
|
Carbonado/Carbonado
|
src/main/java/com/amazon/carbonado/repo/jdbc/SQLStatement.java
|
SQLStatement.buildStatement
|
public String buildStatement(int initialCapacity, FilterValues<S> filterValues) {
"""
Builds a statement string from the given values.
@param initialCapacity expected size of finished string
length. Should be value returned from maxLength.
@param filterValues values may be needed to build complete statement
"""
StringBuilder b = new StringBuilder(initialCapacity);
this.appendTo(b, filterValues);
return b.toString();
}
|
java
|
public String buildStatement(int initialCapacity, FilterValues<S> filterValues) {
StringBuilder b = new StringBuilder(initialCapacity);
this.appendTo(b, filterValues);
return b.toString();
}
|
[
"public",
"String",
"buildStatement",
"(",
"int",
"initialCapacity",
",",
"FilterValues",
"<",
"S",
">",
"filterValues",
")",
"{",
"StringBuilder",
"b",
"=",
"new",
"StringBuilder",
"(",
"initialCapacity",
")",
";",
"this",
".",
"appendTo",
"(",
"b",
",",
"filterValues",
")",
";",
"return",
"b",
".",
"toString",
"(",
")",
";",
"}"
] |
Builds a statement string from the given values.
@param initialCapacity expected size of finished string
length. Should be value returned from maxLength.
@param filterValues values may be needed to build complete statement
|
[
"Builds",
"a",
"statement",
"string",
"from",
"the",
"given",
"values",
"."
] |
train
|
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/SQLStatement.java#L41-L45
|
fcrepo3/fcrepo
|
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java
|
JournalCreator.setDatastreamState
|
public Date setDatastreamState(Context context,
String pid,
String dsID,
String dsState,
String logMessage) throws ServerException {
"""
Create a journal entry, add the arguments, and invoke the method.
"""
try {
CreatorJournalEntry cje =
new CreatorJournalEntry(METHOD_SET_DATASTREAM_STATE,
context);
cje.addArgument(ARGUMENT_NAME_PID, pid);
cje.addArgument(ARGUMENT_NAME_DS_ID, dsID);
cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState);
cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage);
return (Date) cje.invokeAndClose(delegate, writer);
} catch (JournalException e) {
throw new GeneralException("Problem creating the Journal", e);
}
}
|
java
|
public Date setDatastreamState(Context context,
String pid,
String dsID,
String dsState,
String logMessage) throws ServerException {
try {
CreatorJournalEntry cje =
new CreatorJournalEntry(METHOD_SET_DATASTREAM_STATE,
context);
cje.addArgument(ARGUMENT_NAME_PID, pid);
cje.addArgument(ARGUMENT_NAME_DS_ID, dsID);
cje.addArgument(ARGUMENT_NAME_DS_STATE, dsState);
cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage);
return (Date) cje.invokeAndClose(delegate, writer);
} catch (JournalException e) {
throw new GeneralException("Problem creating the Journal", e);
}
}
|
[
"public",
"Date",
"setDatastreamState",
"(",
"Context",
"context",
",",
"String",
"pid",
",",
"String",
"dsID",
",",
"String",
"dsState",
",",
"String",
"logMessage",
")",
"throws",
"ServerException",
"{",
"try",
"{",
"CreatorJournalEntry",
"cje",
"=",
"new",
"CreatorJournalEntry",
"(",
"METHOD_SET_DATASTREAM_STATE",
",",
"context",
")",
";",
"cje",
".",
"addArgument",
"(",
"ARGUMENT_NAME_PID",
",",
"pid",
")",
";",
"cje",
".",
"addArgument",
"(",
"ARGUMENT_NAME_DS_ID",
",",
"dsID",
")",
";",
"cje",
".",
"addArgument",
"(",
"ARGUMENT_NAME_DS_STATE",
",",
"dsState",
")",
";",
"cje",
".",
"addArgument",
"(",
"ARGUMENT_NAME_LOG_MESSAGE",
",",
"logMessage",
")",
";",
"return",
"(",
"Date",
")",
"cje",
".",
"invokeAndClose",
"(",
"delegate",
",",
"writer",
")",
";",
"}",
"catch",
"(",
"JournalException",
"e",
")",
"{",
"throw",
"new",
"GeneralException",
"(",
"\"Problem creating the Journal\"",
",",
"e",
")",
";",
"}",
"}"
] |
Create a journal entry, add the arguments, and invoke the method.
|
[
"Create",
"a",
"journal",
"entry",
"add",
"the",
"arguments",
"and",
"invoke",
"the",
"method",
"."
] |
train
|
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java#L277-L294
|
xiancloud/xian
|
xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/RetryLoop.java
|
RetryLoop.callWithRetry
|
public static<T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception {
"""
Convenience utility: creates a retry loop calling the given proc and retrying if needed
@param client Zookeeper
@param proc procedure to call with retry
@param <T> return type
@return procedure result
@throws Exception any non-retriable errors
"""
T result = null;
RetryLoop retryLoop = client.newRetryLoop();
while ( retryLoop.shouldContinue() )
{
try
{
client.internalBlockUntilConnectedOrTimedOut();
result = proc.call();
retryLoop.markComplete();
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
return result;
}
|
java
|
public static<T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception
{
T result = null;
RetryLoop retryLoop = client.newRetryLoop();
while ( retryLoop.shouldContinue() )
{
try
{
client.internalBlockUntilConnectedOrTimedOut();
result = proc.call();
retryLoop.markComplete();
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
return result;
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"callWithRetry",
"(",
"CuratorZookeeperClient",
"client",
",",
"Callable",
"<",
"T",
">",
"proc",
")",
"throws",
"Exception",
"{",
"T",
"result",
"=",
"null",
";",
"RetryLoop",
"retryLoop",
"=",
"client",
".",
"newRetryLoop",
"(",
")",
";",
"while",
"(",
"retryLoop",
".",
"shouldContinue",
"(",
")",
")",
"{",
"try",
"{",
"client",
".",
"internalBlockUntilConnectedOrTimedOut",
"(",
")",
";",
"result",
"=",
"proc",
".",
"call",
"(",
")",
";",
"retryLoop",
".",
"markComplete",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"ThreadUtils",
".",
"checkInterrupted",
"(",
"e",
")",
";",
"retryLoop",
".",
"takeException",
"(",
"e",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Convenience utility: creates a retry loop calling the given proc and retrying if needed
@param client Zookeeper
@param proc procedure to call with retry
@param <T> return type
@return procedure result
@throws Exception any non-retriable errors
|
[
"Convenience",
"utility",
":",
"creates",
"a",
"retry",
"loop",
"calling",
"the",
"given",
"proc",
"and",
"retrying",
"if",
"needed"
] |
train
|
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/RetryLoop.java#L99-L119
|
bushidowallet/bushido-java-service
|
bushido-service-lib/src/main/java/com/bccapi/bitlib/util/HexUtils.java
|
HexUtils.toHex
|
public static String toHex(byte[] bytes, int offset, int length) {
"""
Encodes an array of bytes as hex symbols.
@param bytes
the array of bytes to encode
@param offset
the start offset in the array of bytes
@param length
the number of bytes to encode
@return the resulting hex string
"""
return toHex(bytes, offset, length, null);
}
|
java
|
public static String toHex(byte[] bytes, int offset, int length) {
return toHex(bytes, offset, length, null);
}
|
[
"public",
"static",
"String",
"toHex",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"return",
"toHex",
"(",
"bytes",
",",
"offset",
",",
"length",
",",
"null",
")",
";",
"}"
] |
Encodes an array of bytes as hex symbols.
@param bytes
the array of bytes to encode
@param offset
the start offset in the array of bytes
@param length
the number of bytes to encode
@return the resulting hex string
|
[
"Encodes",
"an",
"array",
"of",
"bytes",
"as",
"hex",
"symbols",
"."
] |
train
|
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-service-lib/src/main/java/com/bccapi/bitlib/util/HexUtils.java#L59-L61
|
BlueBrain/bluima
|
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/sentdetect/SentenceDetectorME.java
|
SentenceDetectorME.sentPosDetect
|
public int[] sentPosDetect(String s) {
"""
Detect the position of the first words of sentences in a String.
@param s The string to be processed.
@return A integer array containing the positions of the end index of
every sentence
"""
double sentProb = 1;
sentProbs.clear();
StringBuffer sb = new StringBuffer(s);
List enders = scanner.getPositions(s);
List positions = new ArrayList(enders.size());
for (int i = 0, end = enders.size(), index = 0; i < end; i++) {
Integer candidate = (Integer) enders.get(i);
int cint = candidate.intValue();
// skip over the leading parts of non-token final delimiters
int fws = getFirstWS(s,cint + 1);
if (((i + 1) < end) && (((Integer) enders.get(i + 1)).intValue() < fws)) {
continue;
}
Pair pair = new Pair(sb, candidate);
double[] probs = model.eval(cgen.getContext(pair));
String bestOutcome = model.getBestOutcome(probs);
sentProb *= probs[model.getIndex(bestOutcome)];
if (bestOutcome.equals("T") && isAcceptableBreak(s, index, cint)) {
if (index != cint) {
positions.add(INT_POOL.get(getFirstNonWS(s, getFirstWS(s,cint + 1))));
sentProbs.add(new Double(probs[model.getIndex(bestOutcome)]));
}
index = cint + 1;
}
}
int[] sentPositions = new int[positions.size()];
for (int i = 0; i < sentPositions.length; i++) {
sentPositions[i] = ((Integer) positions.get(i)).intValue();
}
return sentPositions;
}
|
java
|
public int[] sentPosDetect(String s) {
double sentProb = 1;
sentProbs.clear();
StringBuffer sb = new StringBuffer(s);
List enders = scanner.getPositions(s);
List positions = new ArrayList(enders.size());
for (int i = 0, end = enders.size(), index = 0; i < end; i++) {
Integer candidate = (Integer) enders.get(i);
int cint = candidate.intValue();
// skip over the leading parts of non-token final delimiters
int fws = getFirstWS(s,cint + 1);
if (((i + 1) < end) && (((Integer) enders.get(i + 1)).intValue() < fws)) {
continue;
}
Pair pair = new Pair(sb, candidate);
double[] probs = model.eval(cgen.getContext(pair));
String bestOutcome = model.getBestOutcome(probs);
sentProb *= probs[model.getIndex(bestOutcome)];
if (bestOutcome.equals("T") && isAcceptableBreak(s, index, cint)) {
if (index != cint) {
positions.add(INT_POOL.get(getFirstNonWS(s, getFirstWS(s,cint + 1))));
sentProbs.add(new Double(probs[model.getIndex(bestOutcome)]));
}
index = cint + 1;
}
}
int[] sentPositions = new int[positions.size()];
for (int i = 0; i < sentPositions.length; i++) {
sentPositions[i] = ((Integer) positions.get(i)).intValue();
}
return sentPositions;
}
|
[
"public",
"int",
"[",
"]",
"sentPosDetect",
"(",
"String",
"s",
")",
"{",
"double",
"sentProb",
"=",
"1",
";",
"sentProbs",
".",
"clear",
"(",
")",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"s",
")",
";",
"List",
"enders",
"=",
"scanner",
".",
"getPositions",
"(",
"s",
")",
";",
"List",
"positions",
"=",
"new",
"ArrayList",
"(",
"enders",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"end",
"=",
"enders",
".",
"size",
"(",
")",
",",
"index",
"=",
"0",
";",
"i",
"<",
"end",
";",
"i",
"++",
")",
"{",
"Integer",
"candidate",
"=",
"(",
"Integer",
")",
"enders",
".",
"get",
"(",
"i",
")",
";",
"int",
"cint",
"=",
"candidate",
".",
"intValue",
"(",
")",
";",
"// skip over the leading parts of non-token final delimiters",
"int",
"fws",
"=",
"getFirstWS",
"(",
"s",
",",
"cint",
"+",
"1",
")",
";",
"if",
"(",
"(",
"(",
"i",
"+",
"1",
")",
"<",
"end",
")",
"&&",
"(",
"(",
"(",
"Integer",
")",
"enders",
".",
"get",
"(",
"i",
"+",
"1",
")",
")",
".",
"intValue",
"(",
")",
"<",
"fws",
")",
")",
"{",
"continue",
";",
"}",
"Pair",
"pair",
"=",
"new",
"Pair",
"(",
"sb",
",",
"candidate",
")",
";",
"double",
"[",
"]",
"probs",
"=",
"model",
".",
"eval",
"(",
"cgen",
".",
"getContext",
"(",
"pair",
")",
")",
";",
"String",
"bestOutcome",
"=",
"model",
".",
"getBestOutcome",
"(",
"probs",
")",
";",
"sentProb",
"*=",
"probs",
"[",
"model",
".",
"getIndex",
"(",
"bestOutcome",
")",
"]",
";",
"if",
"(",
"bestOutcome",
".",
"equals",
"(",
"\"T\"",
")",
"&&",
"isAcceptableBreak",
"(",
"s",
",",
"index",
",",
"cint",
")",
")",
"{",
"if",
"(",
"index",
"!=",
"cint",
")",
"{",
"positions",
".",
"add",
"(",
"INT_POOL",
".",
"get",
"(",
"getFirstNonWS",
"(",
"s",
",",
"getFirstWS",
"(",
"s",
",",
"cint",
"+",
"1",
")",
")",
")",
")",
";",
"sentProbs",
".",
"add",
"(",
"new",
"Double",
"(",
"probs",
"[",
"model",
".",
"getIndex",
"(",
"bestOutcome",
")",
"]",
")",
")",
";",
"}",
"index",
"=",
"cint",
"+",
"1",
";",
"}",
"}",
"int",
"[",
"]",
"sentPositions",
"=",
"new",
"int",
"[",
"positions",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"sentPositions",
".",
"length",
";",
"i",
"++",
")",
"{",
"sentPositions",
"[",
"i",
"]",
"=",
"(",
"(",
"Integer",
")",
"positions",
".",
"get",
"(",
"i",
")",
")",
".",
"intValue",
"(",
")",
";",
"}",
"return",
"sentPositions",
";",
"}"
] |
Detect the position of the first words of sentences in a String.
@param s The string to be processed.
@return A integer array containing the positions of the end index of
every sentence
|
[
"Detect",
"the",
"position",
"of",
"the",
"first",
"words",
"of",
"sentences",
"in",
"a",
"String",
"."
] |
train
|
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/sentdetect/SentenceDetectorME.java#L160-L194
|
augustd/burp-suite-utils
|
src/main/java/com/codemagi/burp/Utils.java
|
Utils.getSelection
|
public static String getSelection(byte[] message, int[] offsets) {
"""
Returns the user-selected text in the passed array.
@param message The array of bytes to get the selection from
@param offsets The offsets within the array that indicate the start and end points of the selection
@return A String representing the selected bytes. If offsets is null or if both values are the same, "" is returned.
"""
if (offsets == null || message == null) return "";
if (offsets.length < 2 || offsets[0] == offsets[1]) return "";
byte[] selection = Arrays.copyOfRange(message, offsets[0], offsets[1]);
return new String(selection);
}
|
java
|
public static String getSelection(byte[] message, int[] offsets) {
if (offsets == null || message == null) return "";
if (offsets.length < 2 || offsets[0] == offsets[1]) return "";
byte[] selection = Arrays.copyOfRange(message, offsets[0], offsets[1]);
return new String(selection);
}
|
[
"public",
"static",
"String",
"getSelection",
"(",
"byte",
"[",
"]",
"message",
",",
"int",
"[",
"]",
"offsets",
")",
"{",
"if",
"(",
"offsets",
"==",
"null",
"||",
"message",
"==",
"null",
")",
"return",
"\"\"",
";",
"if",
"(",
"offsets",
".",
"length",
"<",
"2",
"||",
"offsets",
"[",
"0",
"]",
"==",
"offsets",
"[",
"1",
"]",
")",
"return",
"\"\"",
";",
"byte",
"[",
"]",
"selection",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"message",
",",
"offsets",
"[",
"0",
"]",
",",
"offsets",
"[",
"1",
"]",
")",
";",
"return",
"new",
"String",
"(",
"selection",
")",
";",
"}"
] |
Returns the user-selected text in the passed array.
@param message The array of bytes to get the selection from
@param offsets The offsets within the array that indicate the start and end points of the selection
@return A String representing the selected bytes. If offsets is null or if both values are the same, "" is returned.
|
[
"Returns",
"the",
"user",
"-",
"selected",
"text",
"in",
"the",
"passed",
"array",
"."
] |
train
|
https://github.com/augustd/burp-suite-utils/blob/5e34a6b9147f5705382f98049dd9e4f387b78629/src/main/java/com/codemagi/burp/Utils.java#L71-L79
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/sorting/SortUtils.java
|
SortUtils.getChain
|
public static IntComparatorChain getChain(Table table, Sort key) {
"""
Returns a comparator chain for sorting according to the given key
"""
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
Column<?> column = table.column(sort.getKey());
IntComparator comparator = rowComparator(column, sort.getValue());
IntComparatorChain chain = new IntComparatorChain(comparator);
while (entries.hasNext()) {
sort = entries.next();
chain.addComparator(rowComparator(table.column(sort.getKey()), sort.getValue()));
}
return chain;
}
|
java
|
public static IntComparatorChain getChain(Table table, Sort key) {
Iterator<Map.Entry<String, Sort.Order>> entries = key.iterator();
Map.Entry<String, Sort.Order> sort = entries.next();
Column<?> column = table.column(sort.getKey());
IntComparator comparator = rowComparator(column, sort.getValue());
IntComparatorChain chain = new IntComparatorChain(comparator);
while (entries.hasNext()) {
sort = entries.next();
chain.addComparator(rowComparator(table.column(sort.getKey()), sort.getValue()));
}
return chain;
}
|
[
"public",
"static",
"IntComparatorChain",
"getChain",
"(",
"Table",
"table",
",",
"Sort",
"key",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"Sort",
".",
"Order",
">",
">",
"entries",
"=",
"key",
".",
"iterator",
"(",
")",
";",
"Map",
".",
"Entry",
"<",
"String",
",",
"Sort",
".",
"Order",
">",
"sort",
"=",
"entries",
".",
"next",
"(",
")",
";",
"Column",
"<",
"?",
">",
"column",
"=",
"table",
".",
"column",
"(",
"sort",
".",
"getKey",
"(",
")",
")",
";",
"IntComparator",
"comparator",
"=",
"rowComparator",
"(",
"column",
",",
"sort",
".",
"getValue",
"(",
")",
")",
";",
"IntComparatorChain",
"chain",
"=",
"new",
"IntComparatorChain",
"(",
"comparator",
")",
";",
"while",
"(",
"entries",
".",
"hasNext",
"(",
")",
")",
"{",
"sort",
"=",
"entries",
".",
"next",
"(",
")",
";",
"chain",
".",
"addComparator",
"(",
"rowComparator",
"(",
"table",
".",
"column",
"(",
"sort",
".",
"getKey",
"(",
")",
")",
",",
"sort",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
"return",
"chain",
";",
"}"
] |
Returns a comparator chain for sorting according to the given key
|
[
"Returns",
"a",
"comparator",
"chain",
"for",
"sorting",
"according",
"to",
"the",
"given",
"key"
] |
train
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/sorting/SortUtils.java#L17-L29
|
junit-team/junit4
|
src/main/java/org/junit/runners/ParentRunner.java
|
ParentRunner.withBeforeClasses
|
protected Statement withBeforeClasses(Statement statement) {
"""
Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class
and superclasses before executing {@code statement}; if any throws an
Exception, stop execution and pass the exception on.
"""
List<FrameworkMethod> befores = testClass
.getAnnotatedMethods(BeforeClass.class);
return befores.isEmpty() ? statement :
new RunBefores(statement, befores, null);
}
|
java
|
protected Statement withBeforeClasses(Statement statement) {
List<FrameworkMethod> befores = testClass
.getAnnotatedMethods(BeforeClass.class);
return befores.isEmpty() ? statement :
new RunBefores(statement, befores, null);
}
|
[
"protected",
"Statement",
"withBeforeClasses",
"(",
"Statement",
"statement",
")",
"{",
"List",
"<",
"FrameworkMethod",
">",
"befores",
"=",
"testClass",
".",
"getAnnotatedMethods",
"(",
"BeforeClass",
".",
"class",
")",
";",
"return",
"befores",
".",
"isEmpty",
"(",
")",
"?",
"statement",
":",
"new",
"RunBefores",
"(",
"statement",
",",
"befores",
",",
"null",
")",
";",
"}"
] |
Returns a {@link Statement}: run all non-overridden {@code @BeforeClass} methods on this class
and superclasses before executing {@code statement}; if any throws an
Exception, stop execution and pass the exception on.
|
[
"Returns",
"a",
"{"
] |
train
|
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/ParentRunner.java#L236-L241
|
skyscreamer/JSONassert
|
src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
|
JSONAssert.assertNotEquals
|
public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
"""
Asserts that the json string provided does not match the expected string. If it is it throws an
{@link AssertionError}.
@param message Error message to be displayed in case of assertion failure
@param expectedStr Expected JSON string
@param actualStr String to compare
@param comparator Comparator
@throws JSONException JSON parsing error
"""
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
|
java
|
public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
|
[
"public",
"static",
"void",
"assertNotEquals",
"(",
"String",
"message",
",",
"String",
"expectedStr",
",",
"String",
"actualStr",
",",
"JSONComparator",
"comparator",
")",
"throws",
"JSONException",
"{",
"JSONCompareResult",
"result",
"=",
"JSONCompare",
".",
"compareJSON",
"(",
"expectedStr",
",",
"actualStr",
",",
"comparator",
")",
";",
"if",
"(",
"result",
".",
"passed",
"(",
")",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"getCombinedMessage",
"(",
"message",
",",
"result",
".",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"}"
] |
Asserts that the json string provided does not match the expected string. If it is it throws an
{@link AssertionError}.
@param message Error message to be displayed in case of assertion failure
@param expectedStr Expected JSON string
@param actualStr String to compare
@param comparator Comparator
@throws JSONException JSON parsing error
|
[
"Asserts",
"that",
"the",
"json",
"string",
"provided",
"does",
"not",
"match",
"the",
"expected",
"string",
".",
"If",
"it",
"is",
"it",
"throws",
"an",
"{",
"@link",
"AssertionError",
"}",
"."
] |
train
|
https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L510-L516
|
jamesagnew/hapi-fhir
|
hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java
|
IniFile.getDoubleProperty
|
public Double getDoubleProperty(String pstrSection, String pstrProp) {
"""
Returns the specified double property from the specified section.
@param pstrSection the INI section name.
@param pstrProp the property to be retrieved.
@return the double property value.
"""
Double dblRet = null;
String strVal = null;
INIProperty objProp = null;
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objProp = objSec.getProperty(pstrProp);
try
{
if (objProp != null)
{
strVal = objProp.getPropValue();
if (strVal != null) dblRet = new Double(strVal);
}
}
catch (NumberFormatException NFExIgnore)
{
}
finally
{
if (objProp != null) objProp = null;
}
objSec = null;
}
return dblRet;
}
|
java
|
public Double getDoubleProperty(String pstrSection, String pstrProp)
{
Double dblRet = null;
String strVal = null;
INIProperty objProp = null;
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec != null)
{
objProp = objSec.getProperty(pstrProp);
try
{
if (objProp != null)
{
strVal = objProp.getPropValue();
if (strVal != null) dblRet = new Double(strVal);
}
}
catch (NumberFormatException NFExIgnore)
{
}
finally
{
if (objProp != null) objProp = null;
}
objSec = null;
}
return dblRet;
}
|
[
"public",
"Double",
"getDoubleProperty",
"(",
"String",
"pstrSection",
",",
"String",
"pstrProp",
")",
"{",
"Double",
"dblRet",
"=",
"null",
";",
"String",
"strVal",
"=",
"null",
";",
"INIProperty",
"objProp",
"=",
"null",
";",
"INISection",
"objSec",
"=",
"null",
";",
"objSec",
"=",
"(",
"INISection",
")",
"this",
".",
"mhmapSections",
".",
"get",
"(",
"pstrSection",
")",
";",
"if",
"(",
"objSec",
"!=",
"null",
")",
"{",
"objProp",
"=",
"objSec",
".",
"getProperty",
"(",
"pstrProp",
")",
";",
"try",
"{",
"if",
"(",
"objProp",
"!=",
"null",
")",
"{",
"strVal",
"=",
"objProp",
".",
"getPropValue",
"(",
")",
";",
"if",
"(",
"strVal",
"!=",
"null",
")",
"dblRet",
"=",
"new",
"Double",
"(",
"strVal",
")",
";",
"}",
"}",
"catch",
"(",
"NumberFormatException",
"NFExIgnore",
")",
"{",
"}",
"finally",
"{",
"if",
"(",
"objProp",
"!=",
"null",
")",
"objProp",
"=",
"null",
";",
"}",
"objSec",
"=",
"null",
";",
"}",
"return",
"dblRet",
";",
"}"
] |
Returns the specified double property from the specified section.
@param pstrSection the INI section name.
@param pstrProp the property to be retrieved.
@return the double property value.
|
[
"Returns",
"the",
"specified",
"double",
"property",
"from",
"the",
"specified",
"section",
"."
] |
train
|
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/IniFile.java#L254-L283
|
dmerkushov/log-helper
|
src/main/java/ru/dmerkushov/loghelper/LoggerWrapper.java
|
LoggerWrapper.logDomNodeList
|
public void logDomNodeList (String msg, NodeList nodeList) {
"""
Log a DOM node list at the FINER level
@param msg The message to show with the list, or null if no message
needed
@param nodeList
@see NodeList
"""
StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement ();
String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n");
for (int i = 0; i < nodeList.getLength (); i++) {
toLog += domNodeDescription (nodeList.item (i), 0) + "\n";
}
if (caller != null) {
logger.logp (Level.FINER, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog);
} else {
logger.logp (Level.FINER, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog);
}
}
|
java
|
public void logDomNodeList (String msg, NodeList nodeList) {
StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement ();
String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n");
for (int i = 0; i < nodeList.getLength (); i++) {
toLog += domNodeDescription (nodeList.item (i), 0) + "\n";
}
if (caller != null) {
logger.logp (Level.FINER, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog);
} else {
logger.logp (Level.FINER, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog);
}
}
|
[
"public",
"void",
"logDomNodeList",
"(",
"String",
"msg",
",",
"NodeList",
"nodeList",
")",
"{",
"StackTraceElement",
"caller",
"=",
"StackTraceUtils",
".",
"getCallerStackTraceElement",
"(",
")",
";",
"String",
"toLog",
"=",
"(",
"msg",
"!=",
"null",
"?",
"msg",
"+",
"\"\\n\"",
":",
"\"DOM nodelist:\\n\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nodeList",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"toLog",
"+=",
"domNodeDescription",
"(",
"nodeList",
".",
"item",
"(",
"i",
")",
",",
"0",
")",
"+",
"\"\\n\"",
";",
"}",
"if",
"(",
"caller",
"!=",
"null",
")",
"{",
"logger",
".",
"logp",
"(",
"Level",
".",
"FINER",
",",
"caller",
".",
"getClassName",
"(",
")",
",",
"caller",
".",
"getMethodName",
"(",
")",
"+",
"\"():\"",
"+",
"caller",
".",
"getLineNumber",
"(",
")",
",",
"toLog",
")",
";",
"}",
"else",
"{",
"logger",
".",
"logp",
"(",
"Level",
".",
"FINER",
",",
"\"(UnknownSourceClass)\"",
",",
"\"(unknownSourceMethod)\"",
",",
"toLog",
")",
";",
"}",
"}"
] |
Log a DOM node list at the FINER level
@param msg The message to show with the list, or null if no message
needed
@param nodeList
@see NodeList
|
[
"Log",
"a",
"DOM",
"node",
"list",
"at",
"the",
"FINER",
"level"
] |
train
|
https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/LoggerWrapper.java#L418-L431
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
|
ApiOvhHostingweb.serviceName_statistics_GET
|
public ArrayList<OvhChartSerie<OvhChartTimestampValue>> serviceName_statistics_GET(String serviceName, OvhStatisticsPeriodEnum period, OvhStatisticsTypeEnum type) throws IOException {
"""
Get statistics about this web hosting
REST: GET /hosting/web/{serviceName}/statistics
@param period [required]
@param type [required]
@param serviceName [required] The internal name of your hosting
"""
String qPath = "/hosting/web/{serviceName}/statistics";
StringBuilder sb = path(qPath, serviceName);
query(sb, "period", period);
query(sb, "type", type);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t6);
}
|
java
|
public ArrayList<OvhChartSerie<OvhChartTimestampValue>> serviceName_statistics_GET(String serviceName, OvhStatisticsPeriodEnum period, OvhStatisticsTypeEnum type) throws IOException {
String qPath = "/hosting/web/{serviceName}/statistics";
StringBuilder sb = path(qPath, serviceName);
query(sb, "period", period);
query(sb, "type", type);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t6);
}
|
[
"public",
"ArrayList",
"<",
"OvhChartSerie",
"<",
"OvhChartTimestampValue",
">",
">",
"serviceName_statistics_GET",
"(",
"String",
"serviceName",
",",
"OvhStatisticsPeriodEnum",
"period",
",",
"OvhStatisticsTypeEnum",
"type",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/hosting/web/{serviceName}/statistics\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"query",
"(",
"sb",
",",
"\"period\"",
",",
"period",
")",
";",
"query",
"(",
"sb",
",",
"\"type\"",
",",
"type",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t6",
")",
";",
"}"
] |
Get statistics about this web hosting
REST: GET /hosting/web/{serviceName}/statistics
@param period [required]
@param type [required]
@param serviceName [required] The internal name of your hosting
|
[
"Get",
"statistics",
"about",
"this",
"web",
"hosting"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L531-L538
|
albfernandez/itext2
|
src/main/java/com/lowagie/text/pdf/CFFFontSubset.java
|
CFFFontSubset.ReconstructPrivateSubrs
|
void ReconstructPrivateSubrs(int Font,IndexBaseItem[] fdPrivateBase,
OffsetItem[] fdSubrs) {
"""
Function Adds the new LSubrs dicts (only for the FDs used) to the list
@param Font The index of the font
@param fdPrivateBase The IndexBaseItem array for the linked list
@param fdSubrs OffsetItem array for the linked list
"""
// For each private dict
for (int i=0;i<fonts[Font].fdprivateLengths.length;i++)
{
// If that private dict's Subrs are used insert the new LSubrs
// computed earlier
if (fdSubrs[i]!= null && fonts[Font].PrivateSubrsOffset[i] >= 0)
{
OutputList.addLast(new SubrMarkerItem(fdSubrs[i],fdPrivateBase[i]));
OutputList.addLast(new RangeItem(new RandomAccessFileOrArray(NewLSubrsIndex[i]),0,NewLSubrsIndex[i].length));
}
}
}
|
java
|
void ReconstructPrivateSubrs(int Font,IndexBaseItem[] fdPrivateBase,
OffsetItem[] fdSubrs)
{
// For each private dict
for (int i=0;i<fonts[Font].fdprivateLengths.length;i++)
{
// If that private dict's Subrs are used insert the new LSubrs
// computed earlier
if (fdSubrs[i]!= null && fonts[Font].PrivateSubrsOffset[i] >= 0)
{
OutputList.addLast(new SubrMarkerItem(fdSubrs[i],fdPrivateBase[i]));
OutputList.addLast(new RangeItem(new RandomAccessFileOrArray(NewLSubrsIndex[i]),0,NewLSubrsIndex[i].length));
}
}
}
|
[
"void",
"ReconstructPrivateSubrs",
"(",
"int",
"Font",
",",
"IndexBaseItem",
"[",
"]",
"fdPrivateBase",
",",
"OffsetItem",
"[",
"]",
"fdSubrs",
")",
"{",
"// For each private dict",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fonts",
"[",
"Font",
"]",
".",
"fdprivateLengths",
".",
"length",
";",
"i",
"++",
")",
"{",
"// If that private dict's Subrs are used insert the new LSubrs",
"// computed earlier",
"if",
"(",
"fdSubrs",
"[",
"i",
"]",
"!=",
"null",
"&&",
"fonts",
"[",
"Font",
"]",
".",
"PrivateSubrsOffset",
"[",
"i",
"]",
">=",
"0",
")",
"{",
"OutputList",
".",
"addLast",
"(",
"new",
"SubrMarkerItem",
"(",
"fdSubrs",
"[",
"i",
"]",
",",
"fdPrivateBase",
"[",
"i",
"]",
")",
")",
";",
"OutputList",
".",
"addLast",
"(",
"new",
"RangeItem",
"(",
"new",
"RandomAccessFileOrArray",
"(",
"NewLSubrsIndex",
"[",
"i",
"]",
")",
",",
"0",
",",
"NewLSubrsIndex",
"[",
"i",
"]",
".",
"length",
")",
")",
";",
"}",
"}",
"}"
] |
Function Adds the new LSubrs dicts (only for the FDs used) to the list
@param Font The index of the font
@param fdPrivateBase The IndexBaseItem array for the linked list
@param fdSubrs OffsetItem array for the linked list
|
[
"Function",
"Adds",
"the",
"new",
"LSubrs",
"dicts",
"(",
"only",
"for",
"the",
"FDs",
"used",
")",
"to",
"the",
"list"
] |
train
|
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/CFFFontSubset.java#L1532-L1546
|
HiddenStage/divide
|
Shared/src/main/java/io/divide/shared/transitory/TransientObject.java
|
TransientObject.get
|
public <O> O get(Class<O> clazz, String key, boolean deserialize) {
"""
Retrieve a specific element from this object.
@param clazz type of object to be retrieved. If type given does not match a classcast exception will be thrown.
@param key key of object to be retrieved.
@param deserialize specify of whether or not this object needs to be manually deserialized(stored as a json string).
@return element of type specified corrosponding to the given key.
"""
if(deserialize)
return gson.fromJson(get(String.class,key),clazz);
else
return get(clazz,key);
}
|
java
|
public <O> O get(Class<O> clazz, String key, boolean deserialize){
if(deserialize)
return gson.fromJson(get(String.class,key),clazz);
else
return get(clazz,key);
}
|
[
"public",
"<",
"O",
">",
"O",
"get",
"(",
"Class",
"<",
"O",
">",
"clazz",
",",
"String",
"key",
",",
"boolean",
"deserialize",
")",
"{",
"if",
"(",
"deserialize",
")",
"return",
"gson",
".",
"fromJson",
"(",
"get",
"(",
"String",
".",
"class",
",",
"key",
")",
",",
"clazz",
")",
";",
"else",
"return",
"get",
"(",
"clazz",
",",
"key",
")",
";",
"}"
] |
Retrieve a specific element from this object.
@param clazz type of object to be retrieved. If type given does not match a classcast exception will be thrown.
@param key key of object to be retrieved.
@param deserialize specify of whether or not this object needs to be manually deserialized(stored as a json string).
@return element of type specified corrosponding to the given key.
|
[
"Retrieve",
"a",
"specific",
"element",
"from",
"this",
"object",
"."
] |
train
|
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/shared/transitory/TransientObject.java#L215-L220
|
OpenNTF/JavascriptAggregator
|
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java
|
DepTreeNode.createOrGet
|
public DepTreeNode createOrGet(String path, URI uri) {
"""
Returns the node at the specified path location within the tree, or
creates it if it is not already in the tree. Will create any required
parent nodes.
@param path
The path name, relative to this node, of the node to return.
@param uri
the source URI
@return The node at the specified path.
"""
if (path.startsWith("/")) { //$NON-NLS-1$
throw new IllegalArgumentException(path);
}
if (path.length() == 0)
return this;
String[] pathComps = path.split("/"); //$NON-NLS-1$
DepTreeNode node = this;
int i = 0;
for (String comp : pathComps) {
DepTreeNode childNode = node.getChild(comp);
if (childNode == null) {
childNode = new DepTreeNode(comp, i == pathComps.length-1 ? uri : null);
node.add(childNode);
}
node = childNode;
i++;
}
return node;
}
|
java
|
public DepTreeNode createOrGet(String path, URI uri) {
if (path.startsWith("/")) { //$NON-NLS-1$
throw new IllegalArgumentException(path);
}
if (path.length() == 0)
return this;
String[] pathComps = path.split("/"); //$NON-NLS-1$
DepTreeNode node = this;
int i = 0;
for (String comp : pathComps) {
DepTreeNode childNode = node.getChild(comp);
if (childNode == null) {
childNode = new DepTreeNode(comp, i == pathComps.length-1 ? uri : null);
node.add(childNode);
}
node = childNode;
i++;
}
return node;
}
|
[
"public",
"DepTreeNode",
"createOrGet",
"(",
"String",
"path",
",",
"URI",
"uri",
")",
"{",
"if",
"(",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"//$NON-NLS-1$\r",
"throw",
"new",
"IllegalArgumentException",
"(",
"path",
")",
";",
"}",
"if",
"(",
"path",
".",
"length",
"(",
")",
"==",
"0",
")",
"return",
"this",
";",
"String",
"[",
"]",
"pathComps",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
";",
"//$NON-NLS-1$\r",
"DepTreeNode",
"node",
"=",
"this",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"String",
"comp",
":",
"pathComps",
")",
"{",
"DepTreeNode",
"childNode",
"=",
"node",
".",
"getChild",
"(",
"comp",
")",
";",
"if",
"(",
"childNode",
"==",
"null",
")",
"{",
"childNode",
"=",
"new",
"DepTreeNode",
"(",
"comp",
",",
"i",
"==",
"pathComps",
".",
"length",
"-",
"1",
"?",
"uri",
":",
"null",
")",
";",
"node",
".",
"add",
"(",
"childNode",
")",
";",
"}",
"node",
"=",
"childNode",
";",
"i",
"++",
";",
"}",
"return",
"node",
";",
"}"
] |
Returns the node at the specified path location within the tree, or
creates it if it is not already in the tree. Will create any required
parent nodes.
@param path
The path name, relative to this node, of the node to return.
@param uri
the source URI
@return The node at the specified path.
|
[
"Returns",
"the",
"node",
"at",
"the",
"specified",
"path",
"location",
"within",
"the",
"tree",
"or",
"creates",
"it",
"if",
"it",
"is",
"not",
"already",
"in",
"the",
"tree",
".",
"Will",
"create",
"any",
"required",
"parent",
"nodes",
"."
] |
train
|
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/deps/DepTreeNode.java#L306-L326
|
windup/windup
|
utils/src/main/java/org/jboss/windup/util/ServiceLogger.java
|
ServiceLogger.logLoadedServices
|
public static void logLoadedServices(Logger log, Class<?> type, List<?> services) {
"""
Log the list of service implementations to the given {@link Logger}.
"""
log.info("Loaded [" + services.size() + "] " + type.getName() + " [" + NEWLINE
+ joinTypeNames(new ArrayList<>(services)) + "]");
}
|
java
|
public static void logLoadedServices(Logger log, Class<?> type, List<?> services)
{
log.info("Loaded [" + services.size() + "] " + type.getName() + " [" + NEWLINE
+ joinTypeNames(new ArrayList<>(services)) + "]");
}
|
[
"public",
"static",
"void",
"logLoadedServices",
"(",
"Logger",
"log",
",",
"Class",
"<",
"?",
">",
"type",
",",
"List",
"<",
"?",
">",
"services",
")",
"{",
"log",
".",
"info",
"(",
"\"Loaded [\"",
"+",
"services",
".",
"size",
"(",
")",
"+",
"\"] \"",
"+",
"type",
".",
"getName",
"(",
")",
"+",
"\" [\"",
"+",
"NEWLINE",
"+",
"joinTypeNames",
"(",
"new",
"ArrayList",
"<>",
"(",
"services",
")",
")",
"+",
"\"]\"",
")",
";",
"}"
] |
Log the list of service implementations to the given {@link Logger}.
|
[
"Log",
"the",
"list",
"of",
"service",
"implementations",
"to",
"the",
"given",
"{"
] |
train
|
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ServiceLogger.java#L21-L25
|
astrapi69/jaulp-wicket
|
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java
|
ComponentFactory.newPasswordTextField
|
public static PasswordTextField newPasswordTextField(final String id,
final IModel<String> model) {
"""
Factory method for create a new {@link PasswordTextField}.
@param id
the id
@param model
the model
@return the new {@link PasswordTextField}
"""
final PasswordTextField passwordTextField = new PasswordTextField(id, model);
passwordTextField.setOutputMarkupId(true);
return passwordTextField;
}
|
java
|
public static PasswordTextField newPasswordTextField(final String id,
final IModel<String> model)
{
final PasswordTextField passwordTextField = new PasswordTextField(id, model);
passwordTextField.setOutputMarkupId(true);
return passwordTextField;
}
|
[
"public",
"static",
"PasswordTextField",
"newPasswordTextField",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"String",
">",
"model",
")",
"{",
"final",
"PasswordTextField",
"passwordTextField",
"=",
"new",
"PasswordTextField",
"(",
"id",
",",
"model",
")",
";",
"passwordTextField",
".",
"setOutputMarkupId",
"(",
"true",
")",
";",
"return",
"passwordTextField",
";",
"}"
] |
Factory method for create a new {@link PasswordTextField}.
@param id
the id
@param model
the model
@return the new {@link PasswordTextField}
|
[
"Factory",
"method",
"for",
"create",
"a",
"new",
"{",
"@link",
"PasswordTextField",
"}",
"."
] |
train
|
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java#L536-L542
|
moleculer-java/moleculer-java
|
src/main/java/services/moleculer/cacher/DistributedCacher.java
|
DistributedCacher.getCacheKey
|
@Override
public String getCacheKey(String name, Tree params, String... keys) {
"""
Creates a cacher-specific key by name and params. Concatenates the name
and params.
@param name
action name
@param params
input (JSON) structure
@param keys
keys in the "params" structure (optional)
@return generated cache key String
"""
if (params == null) {
return name;
}
StringBuilder buffer = new StringBuilder(128);
serializeKey(buffer, params, keys);
String serializedParams = buffer.toString();
int paramsLength = serializedParams.length();
if (maxParamsLength < 44 || paramsLength <= maxParamsLength) {
// Key = action name : serialized key
return name + ':' + serializedParams;
}
// Length of unhashed part (begining of the serialized params)
int prefixLength = maxParamsLength - 44;
// Create SHA-256 hash from the entire key
byte[] bytes = serializedParams.getBytes(StandardCharsets.UTF_8);
MessageDigest hasher = hashers.poll();
if (hasher == null) {
try {
hasher = MessageDigest.getInstance("SHA-256");
} catch (Exception cause) {
logger.warn("Unable to get SHA-256 hasher!", cause);
return name + ':' + serializedParams;
}
}
bytes = hasher.digest(bytes);
hashers.add(hasher);
// Concatenate key and the 44 character long hash
String base64 = BASE64.encode(bytes);
if (prefixLength < 1) {
// Fully hashed key = action name : hash code
return name + ':' + base64;
}
// Partly hashed key = action name : beginig of the prefix + hash code
return name + ':' + serializedParams.substring(0, prefixLength) + base64;
}
|
java
|
@Override
public String getCacheKey(String name, Tree params, String... keys) {
if (params == null) {
return name;
}
StringBuilder buffer = new StringBuilder(128);
serializeKey(buffer, params, keys);
String serializedParams = buffer.toString();
int paramsLength = serializedParams.length();
if (maxParamsLength < 44 || paramsLength <= maxParamsLength) {
// Key = action name : serialized key
return name + ':' + serializedParams;
}
// Length of unhashed part (begining of the serialized params)
int prefixLength = maxParamsLength - 44;
// Create SHA-256 hash from the entire key
byte[] bytes = serializedParams.getBytes(StandardCharsets.UTF_8);
MessageDigest hasher = hashers.poll();
if (hasher == null) {
try {
hasher = MessageDigest.getInstance("SHA-256");
} catch (Exception cause) {
logger.warn("Unable to get SHA-256 hasher!", cause);
return name + ':' + serializedParams;
}
}
bytes = hasher.digest(bytes);
hashers.add(hasher);
// Concatenate key and the 44 character long hash
String base64 = BASE64.encode(bytes);
if (prefixLength < 1) {
// Fully hashed key = action name : hash code
return name + ':' + base64;
}
// Partly hashed key = action name : beginig of the prefix + hash code
return name + ':' + serializedParams.substring(0, prefixLength) + base64;
}
|
[
"@",
"Override",
"public",
"String",
"getCacheKey",
"(",
"String",
"name",
",",
"Tree",
"params",
",",
"String",
"...",
"keys",
")",
"{",
"if",
"(",
"params",
"==",
"null",
")",
"{",
"return",
"name",
";",
"}",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
"128",
")",
";",
"serializeKey",
"(",
"buffer",
",",
"params",
",",
"keys",
")",
";",
"String",
"serializedParams",
"=",
"buffer",
".",
"toString",
"(",
")",
";",
"int",
"paramsLength",
"=",
"serializedParams",
".",
"length",
"(",
")",
";",
"if",
"(",
"maxParamsLength",
"<",
"44",
"||",
"paramsLength",
"<=",
"maxParamsLength",
")",
"{",
"// Key = action name : serialized key\r",
"return",
"name",
"+",
"'",
"'",
"+",
"serializedParams",
";",
"}",
"// Length of unhashed part (begining of the serialized params)\r",
"int",
"prefixLength",
"=",
"maxParamsLength",
"-",
"44",
";",
"// Create SHA-256 hash from the entire key\r",
"byte",
"[",
"]",
"bytes",
"=",
"serializedParams",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"MessageDigest",
"hasher",
"=",
"hashers",
".",
"poll",
"(",
")",
";",
"if",
"(",
"hasher",
"==",
"null",
")",
"{",
"try",
"{",
"hasher",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"SHA-256\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"cause",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Unable to get SHA-256 hasher!\"",
",",
"cause",
")",
";",
"return",
"name",
"+",
"'",
"'",
"+",
"serializedParams",
";",
"}",
"}",
"bytes",
"=",
"hasher",
".",
"digest",
"(",
"bytes",
")",
";",
"hashers",
".",
"add",
"(",
"hasher",
")",
";",
"// Concatenate key and the 44 character long hash\r",
"String",
"base64",
"=",
"BASE64",
".",
"encode",
"(",
"bytes",
")",
";",
"if",
"(",
"prefixLength",
"<",
"1",
")",
"{",
"// Fully hashed key = action name : hash code\r",
"return",
"name",
"+",
"'",
"'",
"+",
"base64",
";",
"}",
"// Partly hashed key = action name : beginig of the prefix + hash code\r",
"return",
"name",
"+",
"'",
"'",
"+",
"serializedParams",
".",
"substring",
"(",
"0",
",",
"prefixLength",
")",
"+",
"base64",
";",
"}"
] |
Creates a cacher-specific key by name and params. Concatenates the name
and params.
@param name
action name
@param params
input (JSON) structure
@param keys
keys in the "params" structure (optional)
@return generated cache key String
|
[
"Creates",
"a",
"cacher",
"-",
"specific",
"key",
"by",
"name",
"and",
"params",
".",
"Concatenates",
"the",
"name",
"and",
"params",
"."
] |
train
|
https://github.com/moleculer-java/moleculer-java/blob/27575c44b9ecacc17c4456ceacf5d1851abf1cc4/src/main/java/services/moleculer/cacher/DistributedCacher.java#L82-L124
|
facebookarchive/hadoop-20
|
src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/NamespaceNotifierClient.java
|
NamespaceNotifierClient.haveWatch
|
public boolean haveWatch(String path, EventType watchType) {
"""
Tests if a watch is placed at the given path and of the given type.
@param path the path where we should test if a watch is placed. For the
FILE_ADDED event type, this represents the path of the directory
under which the file will be created.
@param watchType the type of the event for which we test if a watch is
present.
@return <code>true</code> if a watch is placed, <code>false</code>
otherwise.
"""
return watchedEvents.containsKey(new NamespaceEventKey(path, watchType));
}
|
java
|
public boolean haveWatch(String path, EventType watchType) {
return watchedEvents.containsKey(new NamespaceEventKey(path, watchType));
}
|
[
"public",
"boolean",
"haveWatch",
"(",
"String",
"path",
",",
"EventType",
"watchType",
")",
"{",
"return",
"watchedEvents",
".",
"containsKey",
"(",
"new",
"NamespaceEventKey",
"(",
"path",
",",
"watchType",
")",
")",
";",
"}"
] |
Tests if a watch is placed at the given path and of the given type.
@param path the path where we should test if a watch is placed. For the
FILE_ADDED event type, this represents the path of the directory
under which the file will be created.
@param watchType the type of the event for which we test if a watch is
present.
@return <code>true</code> if a watch is placed, <code>false</code>
otherwise.
|
[
"Tests",
"if",
"a",
"watch",
"is",
"placed",
"at",
"the",
"given",
"path",
"and",
"of",
"the",
"given",
"type",
"."
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/NamespaceNotifierClient.java#L410-L412
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java
|
MCMPHandler.processCommand
|
void processCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException {
"""
Process a mod_cluster mgmt command.
@param exchange the http server exchange
@param requestData the request data
@param action the mgmt action
@throws IOException
"""
if (exchange.getRequestPath().equals("*") || exchange.getRequestPath().endsWith("/*")) {
processNodeCommand(exchange, requestData, action);
} else {
processAppCommand(exchange, requestData, action);
}
}
|
java
|
void processCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException {
if (exchange.getRequestPath().equals("*") || exchange.getRequestPath().endsWith("/*")) {
processNodeCommand(exchange, requestData, action);
} else {
processAppCommand(exchange, requestData, action);
}
}
|
[
"void",
"processCommand",
"(",
"final",
"HttpServerExchange",
"exchange",
",",
"final",
"RequestData",
"requestData",
",",
"final",
"MCMPAction",
"action",
")",
"throws",
"IOException",
"{",
"if",
"(",
"exchange",
".",
"getRequestPath",
"(",
")",
".",
"equals",
"(",
"\"*\"",
")",
"||",
"exchange",
".",
"getRequestPath",
"(",
")",
".",
"endsWith",
"(",
"\"/*\"",
")",
")",
"{",
"processNodeCommand",
"(",
"exchange",
",",
"requestData",
",",
"action",
")",
";",
"}",
"else",
"{",
"processAppCommand",
"(",
"exchange",
",",
"requestData",
",",
"action",
")",
";",
"}",
"}"
] |
Process a mod_cluster mgmt command.
@param exchange the http server exchange
@param requestData the request data
@param action the mgmt action
@throws IOException
|
[
"Process",
"a",
"mod_cluster",
"mgmt",
"command",
"."
] |
train
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/handlers/proxy/mod_cluster/MCMPHandler.java#L325-L331
|
stagemonitor/stagemonitor
|
stagemonitor-core/src/main/java/org/stagemonitor/core/metrics/metrics2/MetricName.java
|
MetricName.withTag
|
public MetricName withTag(String key, String value) {
"""
Returns a copy of this name and appends a single tag
<p>
Note that this method does not override existing tags
@param key the key of the tag
@param value the value of the tag
@return a copy of this name including the provided tag
"""
return name(name).tags(tags).tag(key, value).build();
}
|
java
|
public MetricName withTag(String key, String value) {
return name(name).tags(tags).tag(key, value).build();
}
|
[
"public",
"MetricName",
"withTag",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"return",
"name",
"(",
"name",
")",
".",
"tags",
"(",
"tags",
")",
".",
"tag",
"(",
"key",
",",
"value",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Returns a copy of this name and appends a single tag
<p>
Note that this method does not override existing tags
@param key the key of the tag
@param value the value of the tag
@return a copy of this name including the provided tag
|
[
"Returns",
"a",
"copy",
"of",
"this",
"name",
"and",
"appends",
"a",
"single",
"tag",
"<p",
">",
"Note",
"that",
"this",
"method",
"does",
"not",
"override",
"existing",
"tags"
] |
train
|
https://github.com/stagemonitor/stagemonitor/blob/7a1bf6848906f816aa465983f602ea1f1e8f2b7b/stagemonitor-core/src/main/java/org/stagemonitor/core/metrics/metrics2/MetricName.java#L63-L65
|
baidubce/bce-sdk-java
|
src/main/java/com/baidubce/services/lss/LssClient.java
|
LssClient.getPreset
|
public GetPresetResponse getPreset(GetPresetRequest request) {
"""
Get your live preset by live preset name.
@param request The request object containing all parameters for getting live preset.
@return Your live preset
"""
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_PRESET,
request.getName());
return invokeHttpClient(internalRequest, GetPresetResponse.class);
}
|
java
|
public GetPresetResponse getPreset(GetPresetRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_PRESET,
request.getName());
return invokeHttpClient(internalRequest, GetPresetResponse.class);
}
|
[
"public",
"GetPresetResponse",
"getPreset",
"(",
"GetPresetRequest",
"request",
")",
"{",
"checkNotNull",
"(",
"request",
",",
"\"The parameter request should NOT be null.\"",
")",
";",
"checkStringNotEmpty",
"(",
"request",
".",
"getName",
"(",
")",
",",
"\"The parameter name should NOT be null or empty string.\"",
")",
";",
"InternalRequest",
"internalRequest",
"=",
"createRequest",
"(",
"HttpMethodName",
".",
"GET",
",",
"request",
",",
"LIVE_PRESET",
",",
"request",
".",
"getName",
"(",
")",
")",
";",
"return",
"invokeHttpClient",
"(",
"internalRequest",
",",
"GetPresetResponse",
".",
"class",
")",
";",
"}"
] |
Get your live preset by live preset name.
@param request The request object containing all parameters for getting live preset.
@return Your live preset
|
[
"Get",
"your",
"live",
"preset",
"by",
"live",
"preset",
"name",
"."
] |
train
|
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L417-L423
|
Microsoft/malmo
|
Minecraft/src/main/java/com/microsoft/Malmo/Server/ServerStateMachine.java
|
ServerStateMachine.getStateEpisodeForState
|
@Override
protected StateEpisode getStateEpisodeForState(IState state) {
"""
Create the episode object for the requested state.
@param state the state the mod is entering
@return a MissionStateEpisode that localises all the logic required to run this state
"""
if (!(state instanceof ServerState))
return null;
ServerState sstate = (ServerState)state;
switch (sstate)
{
case WAITING_FOR_MOD_READY:
return new InitialiseServerModEpisode(this);
case DORMANT:
return new DormantEpisode(this);
case BUILDING_WORLD:
return new BuildingWorldEpisode(this);
case WAITING_FOR_AGENTS_TO_ASSEMBLE:
return new WaitingForAgentsEpisode(this);
case RUNNING:
return new RunningEpisode(this);
case WAITING_FOR_AGENTS_TO_QUIT:
return new WaitingForAgentsToQuitEpisode(this);
case ERROR:
return new ErrorEpisode(this);
case CLEAN_UP:
return new CleanUpEpisode(this);
case MISSION_ENDED:
return null;//new MissionEndedEpisode(this, MissionResult.ENDED);
case MISSION_ABORTED:
return null;//new MissionEndedEpisode(this, MissionResult.AGENT_QUIT);
default:
break;
}
return null;
}
|
java
|
@Override
protected StateEpisode getStateEpisodeForState(IState state)
{
if (!(state instanceof ServerState))
return null;
ServerState sstate = (ServerState)state;
switch (sstate)
{
case WAITING_FOR_MOD_READY:
return new InitialiseServerModEpisode(this);
case DORMANT:
return new DormantEpisode(this);
case BUILDING_WORLD:
return new BuildingWorldEpisode(this);
case WAITING_FOR_AGENTS_TO_ASSEMBLE:
return new WaitingForAgentsEpisode(this);
case RUNNING:
return new RunningEpisode(this);
case WAITING_FOR_AGENTS_TO_QUIT:
return new WaitingForAgentsToQuitEpisode(this);
case ERROR:
return new ErrorEpisode(this);
case CLEAN_UP:
return new CleanUpEpisode(this);
case MISSION_ENDED:
return null;//new MissionEndedEpisode(this, MissionResult.ENDED);
case MISSION_ABORTED:
return null;//new MissionEndedEpisode(this, MissionResult.AGENT_QUIT);
default:
break;
}
return null;
}
|
[
"@",
"Override",
"protected",
"StateEpisode",
"getStateEpisodeForState",
"(",
"IState",
"state",
")",
"{",
"if",
"(",
"!",
"(",
"state",
"instanceof",
"ServerState",
")",
")",
"return",
"null",
";",
"ServerState",
"sstate",
"=",
"(",
"ServerState",
")",
"state",
";",
"switch",
"(",
"sstate",
")",
"{",
"case",
"WAITING_FOR_MOD_READY",
":",
"return",
"new",
"InitialiseServerModEpisode",
"(",
"this",
")",
";",
"case",
"DORMANT",
":",
"return",
"new",
"DormantEpisode",
"(",
"this",
")",
";",
"case",
"BUILDING_WORLD",
":",
"return",
"new",
"BuildingWorldEpisode",
"(",
"this",
")",
";",
"case",
"WAITING_FOR_AGENTS_TO_ASSEMBLE",
":",
"return",
"new",
"WaitingForAgentsEpisode",
"(",
"this",
")",
";",
"case",
"RUNNING",
":",
"return",
"new",
"RunningEpisode",
"(",
"this",
")",
";",
"case",
"WAITING_FOR_AGENTS_TO_QUIT",
":",
"return",
"new",
"WaitingForAgentsToQuitEpisode",
"(",
"this",
")",
";",
"case",
"ERROR",
":",
"return",
"new",
"ErrorEpisode",
"(",
"this",
")",
";",
"case",
"CLEAN_UP",
":",
"return",
"new",
"CleanUpEpisode",
"(",
"this",
")",
";",
"case",
"MISSION_ENDED",
":",
"return",
"null",
";",
"//new MissionEndedEpisode(this, MissionResult.ENDED);",
"case",
"MISSION_ABORTED",
":",
"return",
"null",
";",
"//new MissionEndedEpisode(this, MissionResult.AGENT_QUIT);",
"default",
":",
"break",
";",
"}",
"return",
"null",
";",
"}"
] |
Create the episode object for the requested state.
@param state the state the mod is entering
@return a MissionStateEpisode that localises all the logic required to run this state
|
[
"Create",
"the",
"episode",
"object",
"for",
"the",
"requested",
"state",
"."
] |
train
|
https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Minecraft/src/main/java/com/microsoft/Malmo/Server/ServerStateMachine.java#L297-L330
|
google/j2objc
|
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X500Name.java
|
X500Name.asX500Name
|
public static X500Name asX500Name(X500Principal p) {
"""
Get the X500Name contained in the given X500Principal.
Note that the X500Name is retrieved using reflection.
"""
try {
X500Name name = (X500Name)principalField.get(p);
name.x500Principal = p;
return name;
} catch (Exception e) {
throw new RuntimeException("Unexpected exception", e);
}
}
|
java
|
public static X500Name asX500Name(X500Principal p) {
try {
X500Name name = (X500Name)principalField.get(p);
name.x500Principal = p;
return name;
} catch (Exception e) {
throw new RuntimeException("Unexpected exception", e);
}
}
|
[
"public",
"static",
"X500Name",
"asX500Name",
"(",
"X500Principal",
"p",
")",
"{",
"try",
"{",
"X500Name",
"name",
"=",
"(",
"X500Name",
")",
"principalField",
".",
"get",
"(",
"p",
")",
";",
"name",
".",
"x500Principal",
"=",
"p",
";",
"return",
"name",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unexpected exception\"",
",",
"e",
")",
";",
"}",
"}"
] |
Get the X500Name contained in the given X500Principal.
Note that the X500Name is retrieved using reflection.
|
[
"Get",
"the",
"X500Name",
"contained",
"in",
"the",
"given",
"X500Principal",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X500Name.java#L1455-L1463
|
apache/incubator-atlas
|
webapp/src/main/java/org/apache/atlas/web/service/ActiveInstanceState.java
|
ActiveInstanceState.getActiveServerAddress
|
public String getActiveServerAddress() {
"""
Retrieve state of the active server instance.
This method reads the active server location from the shared node in Zookeeper.
@return the active server's address and port of form http://host-or-ip:port
"""
CuratorFramework client = curatorFactory.clientInstance();
String serverAddress = null;
try {
HAConfiguration.ZookeeperProperties zookeeperProperties =
HAConfiguration.getZookeeperProperties(configuration);
byte[] bytes = client.getData().forPath(getZnodePath(zookeeperProperties));
serverAddress = new String(bytes, Charset.forName("UTF-8"));
} catch (Exception e) {
LOG.error("Error getting active server address", e);
}
return serverAddress;
}
|
java
|
public String getActiveServerAddress() {
CuratorFramework client = curatorFactory.clientInstance();
String serverAddress = null;
try {
HAConfiguration.ZookeeperProperties zookeeperProperties =
HAConfiguration.getZookeeperProperties(configuration);
byte[] bytes = client.getData().forPath(getZnodePath(zookeeperProperties));
serverAddress = new String(bytes, Charset.forName("UTF-8"));
} catch (Exception e) {
LOG.error("Error getting active server address", e);
}
return serverAddress;
}
|
[
"public",
"String",
"getActiveServerAddress",
"(",
")",
"{",
"CuratorFramework",
"client",
"=",
"curatorFactory",
".",
"clientInstance",
"(",
")",
";",
"String",
"serverAddress",
"=",
"null",
";",
"try",
"{",
"HAConfiguration",
".",
"ZookeeperProperties",
"zookeeperProperties",
"=",
"HAConfiguration",
".",
"getZookeeperProperties",
"(",
"configuration",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"client",
".",
"getData",
"(",
")",
".",
"forPath",
"(",
"getZnodePath",
"(",
"zookeeperProperties",
")",
")",
";",
"serverAddress",
"=",
"new",
"String",
"(",
"bytes",
",",
"Charset",
".",
"forName",
"(",
"\"UTF-8\"",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Error getting active server address\"",
",",
"e",
")",
";",
"}",
"return",
"serverAddress",
";",
"}"
] |
Retrieve state of the active server instance.
This method reads the active server location from the shared node in Zookeeper.
@return the active server's address and port of form http://host-or-ip:port
|
[
"Retrieve",
"state",
"of",
"the",
"active",
"server",
"instance",
"."
] |
train
|
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/service/ActiveInstanceState.java#L121-L133
|
youngmonkeys/ezyfox-sfs2x
|
src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/UserZoneEventHandler.java
|
UserZoneEventHandler.notifyHandler
|
private void notifyHandler(ZoneHandlerClass handler, ApiZone apiZone, Object userAgent) {
"""
Propagate event to handler
@param handler
structure of handler class
@param apiZone
api zone reference
@param userAgent
user agent reference
"""
Object instance = handler.newInstance();
callHandleMethod(handler.getHandleMethod(), instance, apiZone, userAgent);
}
|
java
|
private void notifyHandler(ZoneHandlerClass handler, ApiZone apiZone, Object userAgent) {
Object instance = handler.newInstance();
callHandleMethod(handler.getHandleMethod(), instance, apiZone, userAgent);
}
|
[
"private",
"void",
"notifyHandler",
"(",
"ZoneHandlerClass",
"handler",
",",
"ApiZone",
"apiZone",
",",
"Object",
"userAgent",
")",
"{",
"Object",
"instance",
"=",
"handler",
".",
"newInstance",
"(",
")",
";",
"callHandleMethod",
"(",
"handler",
".",
"getHandleMethod",
"(",
")",
",",
"instance",
",",
"apiZone",
",",
"userAgent",
")",
";",
"}"
] |
Propagate event to handler
@param handler
structure of handler class
@param apiZone
api zone reference
@param userAgent
user agent reference
|
[
"Propagate",
"event",
"to",
"handler"
] |
train
|
https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/serverhandler/UserZoneEventHandler.java#L106-L109
|
GenesysPureEngage/workspace-client-java
|
src/main/java/com/genesys/workspace/VoiceApi.java
|
VoiceApi.initiateConference
|
public void initiateConference(
String connId,
String destination,
String location,
String outboundCallerId,
KeyValueCollection userData,
KeyValueCollection reasons,
KeyValueCollection extensions
) throws WorkspaceApiException {
"""
Initiate a two-step conference to the specified destination. This places the existing call on
hold and creates a new call in the dialing state. After initiating the conference you can use
completeConference to complete the conference and bring all parties into the same call.
@param connId The connection ID of the call to start the conference from. This call will be placed on hold.
@param destination The number to be dialed.
@param location Name of the remote location in the form of <SwitchName> or <T-ServerApplicationName>@<SwitchName>. This value is used by Workspace to set the location attribute for the corresponding T-Server requests. (optional)
@param outboundCallerId The caller ID information to display on the destination party's phone. The value should be set as CPNDigits. For more information about caller ID, see the SIP Server Deployment Guide. (optional)
@param userData Key/value data to include with the call. (optional)
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons). (optional)
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional)
"""
try {
VoicecallsidinitiateconferenceData initData = new VoicecallsidinitiateconferenceData();
initData.setDestination(destination);
initData.setLocation(location);
initData.setOutboundCallerId(outboundCallerId);
initData.setUserData(Util.toKVList(userData));
initData.setReasons(Util.toKVList(reasons));
initData.setExtensions(Util.toKVList(extensions));
InitiateConferenceData data = new InitiateConferenceData();
data.data(initData);
ApiSuccessResponse response = this.voiceApi.initiateConference(connId, data);
throwIfNotOk("initiateConference", response);
} catch (ApiException e) {
throw new WorkspaceApiException("initiateConference failed.", e);
}
}
|
java
|
public void initiateConference(
String connId,
String destination,
String location,
String outboundCallerId,
KeyValueCollection userData,
KeyValueCollection reasons,
KeyValueCollection extensions
) throws WorkspaceApiException {
try {
VoicecallsidinitiateconferenceData initData = new VoicecallsidinitiateconferenceData();
initData.setDestination(destination);
initData.setLocation(location);
initData.setOutboundCallerId(outboundCallerId);
initData.setUserData(Util.toKVList(userData));
initData.setReasons(Util.toKVList(reasons));
initData.setExtensions(Util.toKVList(extensions));
InitiateConferenceData data = new InitiateConferenceData();
data.data(initData);
ApiSuccessResponse response = this.voiceApi.initiateConference(connId, data);
throwIfNotOk("initiateConference", response);
} catch (ApiException e) {
throw new WorkspaceApiException("initiateConference failed.", e);
}
}
|
[
"public",
"void",
"initiateConference",
"(",
"String",
"connId",
",",
"String",
"destination",
",",
"String",
"location",
",",
"String",
"outboundCallerId",
",",
"KeyValueCollection",
"userData",
",",
"KeyValueCollection",
"reasons",
",",
"KeyValueCollection",
"extensions",
")",
"throws",
"WorkspaceApiException",
"{",
"try",
"{",
"VoicecallsidinitiateconferenceData",
"initData",
"=",
"new",
"VoicecallsidinitiateconferenceData",
"(",
")",
";",
"initData",
".",
"setDestination",
"(",
"destination",
")",
";",
"initData",
".",
"setLocation",
"(",
"location",
")",
";",
"initData",
".",
"setOutboundCallerId",
"(",
"outboundCallerId",
")",
";",
"initData",
".",
"setUserData",
"(",
"Util",
".",
"toKVList",
"(",
"userData",
")",
")",
";",
"initData",
".",
"setReasons",
"(",
"Util",
".",
"toKVList",
"(",
"reasons",
")",
")",
";",
"initData",
".",
"setExtensions",
"(",
"Util",
".",
"toKVList",
"(",
"extensions",
")",
")",
";",
"InitiateConferenceData",
"data",
"=",
"new",
"InitiateConferenceData",
"(",
")",
";",
"data",
".",
"data",
"(",
"initData",
")",
";",
"ApiSuccessResponse",
"response",
"=",
"this",
".",
"voiceApi",
".",
"initiateConference",
"(",
"connId",
",",
"data",
")",
";",
"throwIfNotOk",
"(",
"\"initiateConference\"",
",",
"response",
")",
";",
"}",
"catch",
"(",
"ApiException",
"e",
")",
"{",
"throw",
"new",
"WorkspaceApiException",
"(",
"\"initiateConference failed.\"",
",",
"e",
")",
";",
"}",
"}"
] |
Initiate a two-step conference to the specified destination. This places the existing call on
hold and creates a new call in the dialing state. After initiating the conference you can use
completeConference to complete the conference and bring all parties into the same call.
@param connId The connection ID of the call to start the conference from. This call will be placed on hold.
@param destination The number to be dialed.
@param location Name of the remote location in the form of <SwitchName> or <T-ServerApplicationName>@<SwitchName>. This value is used by Workspace to set the location attribute for the corresponding T-Server requests. (optional)
@param outboundCallerId The caller ID information to display on the destination party's phone. The value should be set as CPNDigits. For more information about caller ID, see the SIP Server Deployment Guide. (optional)
@param userData Key/value data to include with the call. (optional)
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons). (optional)
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional)
|
[
"Initiate",
"a",
"two",
"-",
"step",
"conference",
"to",
"the",
"specified",
"destination",
".",
"This",
"places",
"the",
"existing",
"call",
"on",
"hold",
"and",
"creates",
"a",
"new",
"call",
"in",
"the",
"dialing",
"state",
".",
"After",
"initiating",
"the",
"conference",
"you",
"can",
"use",
"completeConference",
"to",
"complete",
"the",
"conference",
"and",
"bring",
"all",
"parties",
"into",
"the",
"same",
"call",
"."
] |
train
|
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/workspace/VoiceApi.java#L695-L721
|
Waikato/moa
|
moa/src/main/java/moa/classifiers/oneclass/NearestNeighbourDescription.java
|
NearestNeighbourDescription.getNearestNeighbour
|
private Instance getNearestNeighbour(Instance inst, List<Instance> neighbourhood2, boolean inNbhd) {
"""
Searches the neighbourhood in order to find the argument instance's nearest neighbour.
@param inst the instance whose nearest neighbour is sought
@param neighbourhood2 the neighbourhood to search for the nearest neighbour
@param inNbhd if inst is in neighbourhood2: <b>true</b>, else: <b>false</b>
@return the instance that is inst's nearest neighbour in neighbourhood2
"""
double dist = Double.MAX_VALUE;
Instance nearestNeighbour = null;
for(Instance candidateNN : neighbourhood2)
{
// If inst is in neighbourhood2 and an identical instance is found, then it is no longer required to
// look for inst and the inNbhd flag can be set to FALSE.
if(inNbhd && (distance(inst, candidateNN) == 0))
{
inNbhd = false;
}
else
{
if(distance(inst, candidateNN) < dist)
{
nearestNeighbour = candidateNN.copy();
dist = distance(inst, candidateNN);
}
}
}
return nearestNeighbour;
}
|
java
|
private Instance getNearestNeighbour(Instance inst, List<Instance> neighbourhood2, boolean inNbhd)
{
double dist = Double.MAX_VALUE;
Instance nearestNeighbour = null;
for(Instance candidateNN : neighbourhood2)
{
// If inst is in neighbourhood2 and an identical instance is found, then it is no longer required to
// look for inst and the inNbhd flag can be set to FALSE.
if(inNbhd && (distance(inst, candidateNN) == 0))
{
inNbhd = false;
}
else
{
if(distance(inst, candidateNN) < dist)
{
nearestNeighbour = candidateNN.copy();
dist = distance(inst, candidateNN);
}
}
}
return nearestNeighbour;
}
|
[
"private",
"Instance",
"getNearestNeighbour",
"(",
"Instance",
"inst",
",",
"List",
"<",
"Instance",
">",
"neighbourhood2",
",",
"boolean",
"inNbhd",
")",
"{",
"double",
"dist",
"=",
"Double",
".",
"MAX_VALUE",
";",
"Instance",
"nearestNeighbour",
"=",
"null",
";",
"for",
"(",
"Instance",
"candidateNN",
":",
"neighbourhood2",
")",
"{",
"// If inst is in neighbourhood2 and an identical instance is found, then it is no longer required to",
"// look for inst and the inNbhd flag can be set to FALSE.",
"if",
"(",
"inNbhd",
"&&",
"(",
"distance",
"(",
"inst",
",",
"candidateNN",
")",
"==",
"0",
")",
")",
"{",
"inNbhd",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"distance",
"(",
"inst",
",",
"candidateNN",
")",
"<",
"dist",
")",
"{",
"nearestNeighbour",
"=",
"candidateNN",
".",
"copy",
"(",
")",
";",
"dist",
"=",
"distance",
"(",
"inst",
",",
"candidateNN",
")",
";",
"}",
"}",
"}",
"return",
"nearestNeighbour",
";",
"}"
] |
Searches the neighbourhood in order to find the argument instance's nearest neighbour.
@param inst the instance whose nearest neighbour is sought
@param neighbourhood2 the neighbourhood to search for the nearest neighbour
@param inNbhd if inst is in neighbourhood2: <b>true</b>, else: <b>false</b>
@return the instance that is inst's nearest neighbour in neighbourhood2
|
[
"Searches",
"the",
"neighbourhood",
"in",
"order",
"to",
"find",
"the",
"argument",
"instance",
"s",
"nearest",
"neighbour",
"."
] |
train
|
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/NearestNeighbourDescription.java#L170-L194
|
haraldk/TwelveMonkeys
|
imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java
|
PICTUtil.readDimension
|
public static Dimension readDimension(final DataInput pStream) throws IOException {
"""
Reads a dimension from the given stream.
@param pStream the input stream
@return the dimension read
@throws java.io.IOException if an I/O error occurs during read
"""
int h = pStream.readShort();
int v = pStream.readShort();
return new Dimension(h, v);
}
|
java
|
public static Dimension readDimension(final DataInput pStream) throws IOException {
int h = pStream.readShort();
int v = pStream.readShort();
return new Dimension(h, v);
}
|
[
"public",
"static",
"Dimension",
"readDimension",
"(",
"final",
"DataInput",
"pStream",
")",
"throws",
"IOException",
"{",
"int",
"h",
"=",
"pStream",
".",
"readShort",
"(",
")",
";",
"int",
"v",
"=",
"pStream",
".",
"readShort",
"(",
")",
";",
"return",
"new",
"Dimension",
"(",
"h",
",",
"v",
")",
";",
"}"
] |
Reads a dimension from the given stream.
@param pStream the input stream
@return the dimension read
@throws java.io.IOException if an I/O error occurs during read
|
[
"Reads",
"a",
"dimension",
"from",
"the",
"given",
"stream",
"."
] |
train
|
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L90-L94
|
Mozu/mozu-java
|
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/ExtendedPropertyUrl.java
|
ExtendedPropertyUrl.addExtendedPropertiesUrl
|
public static MozuUrl addExtendedPropertiesUrl(String orderId, String updateMode, String version) {
"""
Get Resource Url for AddExtendedProperties
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/extendedproperties?updatemode={updateMode}&version={version}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
|
java
|
public static MozuUrl addExtendedPropertiesUrl(String orderId, String updateMode, String version)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/extendedproperties?updatemode={updateMode}&version={version}");
formatter.formatUrl("orderId", orderId);
formatter.formatUrl("updateMode", updateMode);
formatter.formatUrl("version", version);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
|
[
"public",
"static",
"MozuUrl",
"addExtendedPropertiesUrl",
"(",
"String",
"orderId",
",",
"String",
"updateMode",
",",
"String",
"version",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/orders/{orderId}/extendedproperties?updatemode={updateMode}&version={version}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"orderId\"",
",",
"orderId",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"updateMode\"",
",",
"updateMode",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"version\"",
",",
"version",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
] |
Get Resource Url for AddExtendedProperties
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version Determines whether or not to check versioning of items for concurrency purposes.
@return String Resource Url
|
[
"Get",
"Resource",
"Url",
"for",
"AddExtendedProperties"
] |
train
|
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/ExtendedPropertyUrl.java#L37-L44
|
jcuda/jcusparse
|
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
|
JCusparse.cusparseXcsrsv2_zeroPivot
|
public static int cusparseXcsrsv2_zeroPivot(
cusparseHandle handle,
csrsv2Info info,
Pointer position) {
"""
<pre>
Description: Solution of triangular linear system op(A) * x = alpha * f,
where A is a sparse matrix in CSR storage format, rhs f and solution y
are dense vectors. This routine implements algorithm 1 for this problem.
Also, it provides a utility function to query size of buffer used.
</pre>
"""
return checkResult(cusparseXcsrsv2_zeroPivotNative(handle, info, position));
}
|
java
|
public static int cusparseXcsrsv2_zeroPivot(
cusparseHandle handle,
csrsv2Info info,
Pointer position)
{
return checkResult(cusparseXcsrsv2_zeroPivotNative(handle, info, position));
}
|
[
"public",
"static",
"int",
"cusparseXcsrsv2_zeroPivot",
"(",
"cusparseHandle",
"handle",
",",
"csrsv2Info",
"info",
",",
"Pointer",
"position",
")",
"{",
"return",
"checkResult",
"(",
"cusparseXcsrsv2_zeroPivotNative",
"(",
"handle",
",",
"info",
",",
"position",
")",
")",
";",
"}"
] |
<pre>
Description: Solution of triangular linear system op(A) * x = alpha * f,
where A is a sparse matrix in CSR storage format, rhs f and solution y
are dense vectors. This routine implements algorithm 1 for this problem.
Also, it provides a utility function to query size of buffer used.
</pre>
|
[
"<pre",
">",
"Description",
":",
"Solution",
"of",
"triangular",
"linear",
"system",
"op",
"(",
"A",
")",
"*",
"x",
"=",
"alpha",
"*",
"f",
"where",
"A",
"is",
"a",
"sparse",
"matrix",
"in",
"CSR",
"storage",
"format",
"rhs",
"f",
"and",
"solution",
"y",
"are",
"dense",
"vectors",
".",
"This",
"routine",
"implements",
"algorithm",
"1",
"for",
"this",
"problem",
".",
"Also",
"it",
"provides",
"a",
"utility",
"function",
"to",
"query",
"size",
"of",
"buffer",
"used",
".",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L2435-L2441
|
Omertron/api-thetvdb
|
src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java
|
TvdbParser.getUpdates
|
public static TVDBUpdates getUpdates(String urlString, int seriesId) throws TvDbException {
"""
Get a list of updates from the URL
@param urlString
@param seriesId
@return
@throws com.omertron.thetvdbapi.TvDbException
"""
TVDBUpdates updates = new TVDBUpdates();
Document doc = DOMHelper.getEventDocFromUrl(urlString);
if (doc != null) {
Node root = doc.getChildNodes().item(0);
List<SeriesUpdate> seriesUpdates = new ArrayList<>();
List<EpisodeUpdate> episodeUpdates = new ArrayList<>();
List<BannerUpdate> bannerUpdates = new ArrayList<>();
NodeList updateNodes = root.getChildNodes();
Node updateNode;
for (int i = 0; i < updateNodes.getLength(); i++) {
updateNode = updateNodes.item(i);
switch (updateNode.getNodeName()) {
case SERIES:
SeriesUpdate su = parseNextSeriesUpdate((Element) updateNode);
if (isValidUpdate(seriesId, su)) {
seriesUpdates.add(su);
}
break;
case EPISODE:
EpisodeUpdate eu = parseNextEpisodeUpdate((Element) updateNode);
if (isValidUpdate(seriesId, eu)) {
episodeUpdates.add(eu);
}
break;
case BANNER:
BannerUpdate bu = parseNextBannerUpdate((Element) updateNode);
if (isValidUpdate(seriesId, bu)) {
bannerUpdates.add(bu);
}
break;
default:
LOG.warn("Unknown update type '{}'", updateNode.getNodeName());
}
}
updates.setTime(DOMHelper.getValueFromElement((Element) root, TIME));
updates.setSeriesUpdates(seriesUpdates);
updates.setEpisodeUpdates(episodeUpdates);
updates.setBannerUpdates(bannerUpdates);
}
return updates;
}
|
java
|
public static TVDBUpdates getUpdates(String urlString, int seriesId) throws TvDbException {
TVDBUpdates updates = new TVDBUpdates();
Document doc = DOMHelper.getEventDocFromUrl(urlString);
if (doc != null) {
Node root = doc.getChildNodes().item(0);
List<SeriesUpdate> seriesUpdates = new ArrayList<>();
List<EpisodeUpdate> episodeUpdates = new ArrayList<>();
List<BannerUpdate> bannerUpdates = new ArrayList<>();
NodeList updateNodes = root.getChildNodes();
Node updateNode;
for (int i = 0; i < updateNodes.getLength(); i++) {
updateNode = updateNodes.item(i);
switch (updateNode.getNodeName()) {
case SERIES:
SeriesUpdate su = parseNextSeriesUpdate((Element) updateNode);
if (isValidUpdate(seriesId, su)) {
seriesUpdates.add(su);
}
break;
case EPISODE:
EpisodeUpdate eu = parseNextEpisodeUpdate((Element) updateNode);
if (isValidUpdate(seriesId, eu)) {
episodeUpdates.add(eu);
}
break;
case BANNER:
BannerUpdate bu = parseNextBannerUpdate((Element) updateNode);
if (isValidUpdate(seriesId, bu)) {
bannerUpdates.add(bu);
}
break;
default:
LOG.warn("Unknown update type '{}'", updateNode.getNodeName());
}
}
updates.setTime(DOMHelper.getValueFromElement((Element) root, TIME));
updates.setSeriesUpdates(seriesUpdates);
updates.setEpisodeUpdates(episodeUpdates);
updates.setBannerUpdates(bannerUpdates);
}
return updates;
}
|
[
"public",
"static",
"TVDBUpdates",
"getUpdates",
"(",
"String",
"urlString",
",",
"int",
"seriesId",
")",
"throws",
"TvDbException",
"{",
"TVDBUpdates",
"updates",
"=",
"new",
"TVDBUpdates",
"(",
")",
";",
"Document",
"doc",
"=",
"DOMHelper",
".",
"getEventDocFromUrl",
"(",
"urlString",
")",
";",
"if",
"(",
"doc",
"!=",
"null",
")",
"{",
"Node",
"root",
"=",
"doc",
".",
"getChildNodes",
"(",
")",
".",
"item",
"(",
"0",
")",
";",
"List",
"<",
"SeriesUpdate",
">",
"seriesUpdates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"EpisodeUpdate",
">",
"episodeUpdates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"BannerUpdate",
">",
"bannerUpdates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"NodeList",
"updateNodes",
"=",
"root",
".",
"getChildNodes",
"(",
")",
";",
"Node",
"updateNode",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"updateNodes",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"updateNode",
"=",
"updateNodes",
".",
"item",
"(",
"i",
")",
";",
"switch",
"(",
"updateNode",
".",
"getNodeName",
"(",
")",
")",
"{",
"case",
"SERIES",
":",
"SeriesUpdate",
"su",
"=",
"parseNextSeriesUpdate",
"(",
"(",
"Element",
")",
"updateNode",
")",
";",
"if",
"(",
"isValidUpdate",
"(",
"seriesId",
",",
"su",
")",
")",
"{",
"seriesUpdates",
".",
"add",
"(",
"su",
")",
";",
"}",
"break",
";",
"case",
"EPISODE",
":",
"EpisodeUpdate",
"eu",
"=",
"parseNextEpisodeUpdate",
"(",
"(",
"Element",
")",
"updateNode",
")",
";",
"if",
"(",
"isValidUpdate",
"(",
"seriesId",
",",
"eu",
")",
")",
"{",
"episodeUpdates",
".",
"add",
"(",
"eu",
")",
";",
"}",
"break",
";",
"case",
"BANNER",
":",
"BannerUpdate",
"bu",
"=",
"parseNextBannerUpdate",
"(",
"(",
"Element",
")",
"updateNode",
")",
";",
"if",
"(",
"isValidUpdate",
"(",
"seriesId",
",",
"bu",
")",
")",
"{",
"bannerUpdates",
".",
"add",
"(",
"bu",
")",
";",
"}",
"break",
";",
"default",
":",
"LOG",
".",
"warn",
"(",
"\"Unknown update type '{}'\"",
",",
"updateNode",
".",
"getNodeName",
"(",
")",
")",
";",
"}",
"}",
"updates",
".",
"setTime",
"(",
"DOMHelper",
".",
"getValueFromElement",
"(",
"(",
"Element",
")",
"root",
",",
"TIME",
")",
")",
";",
"updates",
".",
"setSeriesUpdates",
"(",
"seriesUpdates",
")",
";",
"updates",
".",
"setEpisodeUpdates",
"(",
"episodeUpdates",
")",
";",
"updates",
".",
"setBannerUpdates",
"(",
"bannerUpdates",
")",
";",
"}",
"return",
"updates",
";",
"}"
] |
Get a list of updates from the URL
@param urlString
@param seriesId
@return
@throws com.omertron.thetvdbapi.TvDbException
|
[
"Get",
"a",
"list",
"of",
"updates",
"from",
"the",
"URL"
] |
train
|
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/TvdbParser.java#L284-L330
|
moparisthebest/beehive
|
beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventRef.java
|
EventRef.computeEventDescriptor
|
private String computeEventDescriptor(Method method) {
"""
Helper method that computes the event descriptor sting for a method
"""
StringBuilder sb = new StringBuilder();
// Add event class and method name
sb.append(method.getDeclaringClass().getName());
sb.append(".");
sb.append(method.getName());
// Add event arguments
Class [] parms = method.getParameterTypes();
sb.append("(");
for (int i = 0; i < parms.length; i++)
appendTypeDescriptor(sb, parms[i]);
sb.append(")");
// Add event return type
appendTypeDescriptor(sb, method.getReturnType());
return sb.toString();
}
|
java
|
private String computeEventDescriptor(Method method)
{
StringBuilder sb = new StringBuilder();
// Add event class and method name
sb.append(method.getDeclaringClass().getName());
sb.append(".");
sb.append(method.getName());
// Add event arguments
Class [] parms = method.getParameterTypes();
sb.append("(");
for (int i = 0; i < parms.length; i++)
appendTypeDescriptor(sb, parms[i]);
sb.append(")");
// Add event return type
appendTypeDescriptor(sb, method.getReturnType());
return sb.toString();
}
|
[
"private",
"String",
"computeEventDescriptor",
"(",
"Method",
"method",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"// Add event class and method name",
"sb",
".",
"append",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\".\"",
")",
";",
"sb",
".",
"append",
"(",
"method",
".",
"getName",
"(",
")",
")",
";",
"// Add event arguments",
"Class",
"[",
"]",
"parms",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"(\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"parms",
".",
"length",
";",
"i",
"++",
")",
"appendTypeDescriptor",
"(",
"sb",
",",
"parms",
"[",
"i",
"]",
")",
";",
"sb",
".",
"append",
"(",
"\")\"",
")",
";",
"// Add event return type",
"appendTypeDescriptor",
"(",
"sb",
",",
"method",
".",
"getReturnType",
"(",
")",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Helper method that computes the event descriptor sting for a method
|
[
"Helper",
"method",
"that",
"computes",
"the",
"event",
"descriptor",
"sting",
"for",
"a",
"method"
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/api/events/EventRef.java#L127-L147
|
boncey/Flickr4Java
|
src/main/java/com/flickr4java/flickr/groups/discuss/GroupDiscussInterface.java
|
GroupDiscussInterface.getReplyInfo
|
public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {
"""
Get info for a given topic reply
@param topicId
Unique identifier of a topic for a given group {@link Topic}.
@param replyId
Unique identifier of a reply for a given topic {@link Reply}.
@return A group topic
@throws FlickrException
@see <a href="http://www.flickr.com/services/api/flickr.groups.discuss.replies.getInfo.html">API Documentation</a>
"""
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_REPLIES_GET_INFO);
parameters.put("topic_id", topicId);
parameters.put("reply_id", replyId);
Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element replyElement = response.getPayload();
return parseReply(replyElement);
}
|
java
|
public Reply getReplyInfo(String topicId, String replyId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_REPLIES_GET_INFO);
parameters.put("topic_id", topicId);
parameters.put("reply_id", replyId);
Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element replyElement = response.getPayload();
return parseReply(replyElement);
}
|
[
"public",
"Reply",
"getReplyInfo",
"(",
"String",
"topicId",
",",
"String",
"replyId",
")",
"throws",
"FlickrException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"parameters",
".",
"put",
"(",
"\"method\"",
",",
"METHOD_REPLIES_GET_INFO",
")",
";",
"parameters",
".",
"put",
"(",
"\"topic_id\"",
",",
"topicId",
")",
";",
"parameters",
".",
"put",
"(",
"\"reply_id\"",
",",
"replyId",
")",
";",
"Response",
"response",
"=",
"transportAPI",
".",
"get",
"(",
"transportAPI",
".",
"getPath",
"(",
")",
",",
"parameters",
",",
"apiKey",
",",
"sharedSecret",
")",
";",
"if",
"(",
"response",
".",
"isError",
"(",
")",
")",
"{",
"throw",
"new",
"FlickrException",
"(",
"response",
".",
"getErrorCode",
"(",
")",
",",
"response",
".",
"getErrorMessage",
"(",
")",
")",
";",
"}",
"Element",
"replyElement",
"=",
"response",
".",
"getPayload",
"(",
")",
";",
"return",
"parseReply",
"(",
"replyElement",
")",
";",
"}"
] |
Get info for a given topic reply
@param topicId
Unique identifier of a topic for a given group {@link Topic}.
@param replyId
Unique identifier of a reply for a given topic {@link Reply}.
@return A group topic
@throws FlickrException
@see <a href="http://www.flickr.com/services/api/flickr.groups.discuss.replies.getInfo.html">API Documentation</a>
|
[
"Get",
"info",
"for",
"a",
"given",
"topic",
"reply"
] |
train
|
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/groups/discuss/GroupDiscussInterface.java#L180-L194
|
sebastiangraf/jSCSI
|
bundles/initiator/src/main/java/org/jscsi/initiator/Initiator.java
|
Initiator.createSession
|
public final void createSession (final InetSocketAddress targetAddress, final String targetName) {
"""
Creates a new session to a target with the given Internet address and port. The target has the name
<code>targetName</code>.
@param targetAddress The Internet address and Port of the target.
@param targetName Name of the target, to which a connection should be created.
@throws Exception if any error occurs.
"""
final Session session = factory.getSession(configuration, targetName, targetAddress);
sessions.put(session.getTargetName(), session);
LOGGER.info("Created the session with iSCSI Target '" + targetName + "' at " + targetAddress.getHostName() + " on port " + targetAddress.getPort() + ".");
}
|
java
|
public final void createSession (final InetSocketAddress targetAddress, final String targetName) {
final Session session = factory.getSession(configuration, targetName, targetAddress);
sessions.put(session.getTargetName(), session);
LOGGER.info("Created the session with iSCSI Target '" + targetName + "' at " + targetAddress.getHostName() + " on port " + targetAddress.getPort() + ".");
}
|
[
"public",
"final",
"void",
"createSession",
"(",
"final",
"InetSocketAddress",
"targetAddress",
",",
"final",
"String",
"targetName",
")",
"{",
"final",
"Session",
"session",
"=",
"factory",
".",
"getSession",
"(",
"configuration",
",",
"targetName",
",",
"targetAddress",
")",
";",
"sessions",
".",
"put",
"(",
"session",
".",
"getTargetName",
"(",
")",
",",
"session",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Created the session with iSCSI Target '\"",
"+",
"targetName",
"+",
"\"' at \"",
"+",
"targetAddress",
".",
"getHostName",
"(",
")",
"+",
"\" on port \"",
"+",
"targetAddress",
".",
"getPort",
"(",
")",
"+",
"\".\"",
")",
";",
"}"
] |
Creates a new session to a target with the given Internet address and port. The target has the name
<code>targetName</code>.
@param targetAddress The Internet address and Port of the target.
@param targetName Name of the target, to which a connection should be created.
@throws Exception if any error occurs.
|
[
"Creates",
"a",
"new",
"session",
"to",
"a",
"target",
"with",
"the",
"given",
"Internet",
"address",
"and",
"port",
".",
"The",
"target",
"has",
"the",
"name",
"<code",
">",
"targetName<",
"/",
"code",
">",
"."
] |
train
|
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/initiator/src/main/java/org/jscsi/initiator/Initiator.java#L99-L104
|
leancloud/java-sdk-all
|
android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/hwid/SignInApi.java
|
SignInApi.onConnect
|
@Override
public void onConnect(int rst, HuaweiApiClient client) {
"""
HuaweiApiClient 连接结果回调
@param rst 结果码
@param client HuaweiApiClient 实例
"""
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
onSignInResult(rst, null);
return;
}
Activity curActivity = ActivityMgr.INST.getLastActivity();
if (curActivity == null) {
HMSAgentLog.e("activity is null");
onSignInResult(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE, null);
return;
}
PendingResult<SignInResult> signInResult = HuaweiId.HuaweiIdApi.signIn(curActivity, client);
signInResult.setResultCallback(new ResultCallback<SignInResult>() {
@Override
public void onResult(SignInResult result) {
disposeSignInResult(result);
}
});
}
|
java
|
@Override
public void onConnect(int rst, HuaweiApiClient client) {
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
onSignInResult(rst, null);
return;
}
Activity curActivity = ActivityMgr.INST.getLastActivity();
if (curActivity == null) {
HMSAgentLog.e("activity is null");
onSignInResult(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE, null);
return;
}
PendingResult<SignInResult> signInResult = HuaweiId.HuaweiIdApi.signIn(curActivity, client);
signInResult.setResultCallback(new ResultCallback<SignInResult>() {
@Override
public void onResult(SignInResult result) {
disposeSignInResult(result);
}
});
}
|
[
"@",
"Override",
"public",
"void",
"onConnect",
"(",
"int",
"rst",
",",
"HuaweiApiClient",
"client",
")",
"{",
"if",
"(",
"client",
"==",
"null",
"||",
"!",
"ApiClientMgr",
".",
"INST",
".",
"isConnect",
"(",
"client",
")",
")",
"{",
"HMSAgentLog",
".",
"e",
"(",
"\"client not connted\"",
")",
";",
"onSignInResult",
"(",
"rst",
",",
"null",
")",
";",
"return",
";",
"}",
"Activity",
"curActivity",
"=",
"ActivityMgr",
".",
"INST",
".",
"getLastActivity",
"(",
")",
";",
"if",
"(",
"curActivity",
"==",
"null",
")",
"{",
"HMSAgentLog",
".",
"e",
"(",
"\"activity is null\"",
")",
";",
"onSignInResult",
"(",
"HMSAgent",
".",
"AgentResultCode",
".",
"NO_ACTIVITY_FOR_USE",
",",
"null",
")",
";",
"return",
";",
"}",
"PendingResult",
"<",
"SignInResult",
">",
"signInResult",
"=",
"HuaweiId",
".",
"HuaweiIdApi",
".",
"signIn",
"(",
"curActivity",
",",
"client",
")",
";",
"signInResult",
".",
"setResultCallback",
"(",
"new",
"ResultCallback",
"<",
"SignInResult",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onResult",
"(",
"SignInResult",
"result",
")",
"{",
"disposeSignInResult",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"}"
] |
HuaweiApiClient 连接结果回调
@param rst 结果码
@param client HuaweiApiClient 实例
|
[
"HuaweiApiClient",
"连接结果回调"
] |
train
|
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/hwid/SignInApi.java#L64-L86
|
alkacon/opencms-core
|
src/org/opencms/ade/containerpage/CmsDetailOnlyContainerUtil.java
|
CmsDetailOnlyContainerUtil.isDetailContainersPage
|
public static boolean isDetailContainersPage(CmsObject cms, String detailContainersPage) {
"""
Checks whether the given resource path is of a detail containers page.<p>
@param cms the cms context
@param detailContainersPage the resource site path
@return <code>true</code> if the given resource path is of a detail containers page
"""
boolean result = false;
try {
String detailName = CmsResource.getName(detailContainersPage);
String parentFolder = CmsResource.getParentFolder(detailContainersPage);
if (!parentFolder.endsWith("/" + DETAIL_CONTAINERS_FOLDER_NAME + "/")) {
// this will be the case for locale dependent detail only pages, move one level up
parentFolder = CmsResource.getParentFolder(parentFolder);
}
detailName = CmsStringUtil.joinPaths(CmsResource.getParentFolder(parentFolder), detailName);
result = parentFolder.endsWith("/" + DETAIL_CONTAINERS_FOLDER_NAME + "/")
&& cms.existsResource(detailName, CmsResourceFilter.IGNORE_EXPIRATION);
} catch (Throwable t) {
// may happen in case string operations fail
LOG.debug(t.getLocalizedMessage(), t);
}
return result;
}
|
java
|
public static boolean isDetailContainersPage(CmsObject cms, String detailContainersPage) {
boolean result = false;
try {
String detailName = CmsResource.getName(detailContainersPage);
String parentFolder = CmsResource.getParentFolder(detailContainersPage);
if (!parentFolder.endsWith("/" + DETAIL_CONTAINERS_FOLDER_NAME + "/")) {
// this will be the case for locale dependent detail only pages, move one level up
parentFolder = CmsResource.getParentFolder(parentFolder);
}
detailName = CmsStringUtil.joinPaths(CmsResource.getParentFolder(parentFolder), detailName);
result = parentFolder.endsWith("/" + DETAIL_CONTAINERS_FOLDER_NAME + "/")
&& cms.existsResource(detailName, CmsResourceFilter.IGNORE_EXPIRATION);
} catch (Throwable t) {
// may happen in case string operations fail
LOG.debug(t.getLocalizedMessage(), t);
}
return result;
}
|
[
"public",
"static",
"boolean",
"isDetailContainersPage",
"(",
"CmsObject",
"cms",
",",
"String",
"detailContainersPage",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"try",
"{",
"String",
"detailName",
"=",
"CmsResource",
".",
"getName",
"(",
"detailContainersPage",
")",
";",
"String",
"parentFolder",
"=",
"CmsResource",
".",
"getParentFolder",
"(",
"detailContainersPage",
")",
";",
"if",
"(",
"!",
"parentFolder",
".",
"endsWith",
"(",
"\"/\"",
"+",
"DETAIL_CONTAINERS_FOLDER_NAME",
"+",
"\"/\"",
")",
")",
"{",
"// this will be the case for locale dependent detail only pages, move one level up",
"parentFolder",
"=",
"CmsResource",
".",
"getParentFolder",
"(",
"parentFolder",
")",
";",
"}",
"detailName",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"CmsResource",
".",
"getParentFolder",
"(",
"parentFolder",
")",
",",
"detailName",
")",
";",
"result",
"=",
"parentFolder",
".",
"endsWith",
"(",
"\"/\"",
"+",
"DETAIL_CONTAINERS_FOLDER_NAME",
"+",
"\"/\"",
")",
"&&",
"cms",
".",
"existsResource",
"(",
"detailName",
",",
"CmsResourceFilter",
".",
"IGNORE_EXPIRATION",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"// may happen in case string operations fail",
"LOG",
".",
"debug",
"(",
"t",
".",
"getLocalizedMessage",
"(",
")",
",",
"t",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Checks whether the given resource path is of a detail containers page.<p>
@param cms the cms context
@param detailContainersPage the resource site path
@return <code>true</code> if the given resource path is of a detail containers page
|
[
"Checks",
"whether",
"the",
"given",
"resource",
"path",
"is",
"of",
"a",
"detail",
"containers",
"page",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsDetailOnlyContainerUtil.java#L305-L323
|
ulisesbocchio/spring-boot-security-saml
|
spring-boot-security-saml/src/main/java/com/github/ulisesbocchio/spring/boot/security/saml/resource/KeystoreFactory.java
|
KeystoreFactory.loadKeystore
|
@SneakyThrows
public KeyStore loadKeystore(String certResourceLocation, String privateKeyResourceLocation, String alias, String keyPassword) {
"""
Based on a public certificate, private key, alias and password, this method will load the certificate and
private key as an entry into a newly created keystore, and it will set the provided alias and password to the
keystore entry.
@param certResourceLocation
@param privateKeyResourceLocation
@param alias
@param keyPassword
@return
"""
KeyStore keystore = createEmptyKeystore();
X509Certificate cert = loadCert(certResourceLocation);
RSAPrivateKey privateKey = loadPrivateKey(privateKeyResourceLocation);
addKeyToKeystore(keystore, cert, privateKey, alias, keyPassword);
return keystore;
}
|
java
|
@SneakyThrows
public KeyStore loadKeystore(String certResourceLocation, String privateKeyResourceLocation, String alias, String keyPassword) {
KeyStore keystore = createEmptyKeystore();
X509Certificate cert = loadCert(certResourceLocation);
RSAPrivateKey privateKey = loadPrivateKey(privateKeyResourceLocation);
addKeyToKeystore(keystore, cert, privateKey, alias, keyPassword);
return keystore;
}
|
[
"@",
"SneakyThrows",
"public",
"KeyStore",
"loadKeystore",
"(",
"String",
"certResourceLocation",
",",
"String",
"privateKeyResourceLocation",
",",
"String",
"alias",
",",
"String",
"keyPassword",
")",
"{",
"KeyStore",
"keystore",
"=",
"createEmptyKeystore",
"(",
")",
";",
"X509Certificate",
"cert",
"=",
"loadCert",
"(",
"certResourceLocation",
")",
";",
"RSAPrivateKey",
"privateKey",
"=",
"loadPrivateKey",
"(",
"privateKeyResourceLocation",
")",
";",
"addKeyToKeystore",
"(",
"keystore",
",",
"cert",
",",
"privateKey",
",",
"alias",
",",
"keyPassword",
")",
";",
"return",
"keystore",
";",
"}"
] |
Based on a public certificate, private key, alias and password, this method will load the certificate and
private key as an entry into a newly created keystore, and it will set the provided alias and password to the
keystore entry.
@param certResourceLocation
@param privateKeyResourceLocation
@param alias
@param keyPassword
@return
|
[
"Based",
"on",
"a",
"public",
"certificate",
"private",
"key",
"alias",
"and",
"password",
"this",
"method",
"will",
"load",
"the",
"certificate",
"and",
"private",
"key",
"as",
"an",
"entry",
"into",
"a",
"newly",
"created",
"keystore",
"and",
"it",
"will",
"set",
"the",
"provided",
"alias",
"and",
"password",
"to",
"the",
"keystore",
"entry",
"."
] |
train
|
https://github.com/ulisesbocchio/spring-boot-security-saml/blob/63596fe9b4b5504053392b9ee9a925b9a77644d4/spring-boot-security-saml/src/main/java/com/github/ulisesbocchio/spring/boot/security/saml/resource/KeystoreFactory.java#L46-L53
|
jMetal/jMetal
|
jmetal-core/src/main/java/org/uma/jmetal/util/pseudorandom/impl/ExtendedPseudoRandomGenerator.java
|
ExtendedPseudoRandomGenerator.randNormal
|
public double randNormal(double mean, double standardDeviation) {
"""
Use the polar form of the Box-Muller transformation to obtain
a pseudo random number from a Gaussian distribution
Code taken from Maurice Clerc's implementation
@param mean
@param standardDeviation
@return A pseudo random number
"""
double x1, x2, w, y1;
do {
x1 = 2.0 * randomGenerator.nextDouble() - 1.0;
x2 = 2.0 * randomGenerator.nextDouble() - 1.0;
w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w)) / w);
y1 = x1 * w;
y1 = y1 * standardDeviation + mean;
return y1;
}
|
java
|
public double randNormal(double mean, double standardDeviation) {
double x1, x2, w, y1;
do {
x1 = 2.0 * randomGenerator.nextDouble() - 1.0;
x2 = 2.0 * randomGenerator.nextDouble() - 1.0;
w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w)) / w);
y1 = x1 * w;
y1 = y1 * standardDeviation + mean;
return y1;
}
|
[
"public",
"double",
"randNormal",
"(",
"double",
"mean",
",",
"double",
"standardDeviation",
")",
"{",
"double",
"x1",
",",
"x2",
",",
"w",
",",
"y1",
";",
"do",
"{",
"x1",
"=",
"2.0",
"*",
"randomGenerator",
".",
"nextDouble",
"(",
")",
"-",
"1.0",
";",
"x2",
"=",
"2.0",
"*",
"randomGenerator",
".",
"nextDouble",
"(",
")",
"-",
"1.0",
";",
"w",
"=",
"x1",
"*",
"x1",
"+",
"x2",
"*",
"x2",
";",
"}",
"while",
"(",
"w",
">=",
"1.0",
")",
";",
"w",
"=",
"Math",
".",
"sqrt",
"(",
"(",
"-",
"2.0",
"*",
"Math",
".",
"log",
"(",
"w",
")",
")",
"/",
"w",
")",
";",
"y1",
"=",
"x1",
"*",
"w",
";",
"y1",
"=",
"y1",
"*",
"standardDeviation",
"+",
"mean",
";",
"return",
"y1",
";",
"}"
] |
Use the polar form of the Box-Muller transformation to obtain
a pseudo random number from a Gaussian distribution
Code taken from Maurice Clerc's implementation
@param mean
@param standardDeviation
@return A pseudo random number
|
[
"Use",
"the",
"polar",
"form",
"of",
"the",
"Box",
"-",
"Muller",
"transformation",
"to",
"obtain",
"a",
"pseudo",
"random",
"number",
"from",
"a",
"Gaussian",
"distribution",
"Code",
"taken",
"from",
"Maurice",
"Clerc",
"s",
"implementation"
] |
train
|
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/util/pseudorandom/impl/ExtendedPseudoRandomGenerator.java#L58-L71
|
JOML-CI/JOML
|
src/org/joml/Matrix4f.java
|
Matrix4f.rotateAroundLocal
|
public Matrix4f rotateAroundLocal(Quaternionfc quat, float ox, float oy, float oz) {
"""
Pre-multiply the rotation transformation of the given {@link Quaternionfc} to this matrix while using <code>(ox, oy, oz)</code>
as the rotation origin.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion,
then the new matrix will be <code>Q * M</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>Q * M * v</code>,
the quaternion rotation will be applied last!
<p>
This method is equivalent to calling: <code>translateLocal(-ox, -oy, -oz).rotateLocal(quat).translateLocal(ox, oy, oz)</code>
<p>
Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a>
@param quat
the {@link Quaternionfc}
@param ox
the x coordinate of the rotation origin
@param oy
the y coordinate of the rotation origin
@param oz
the z coordinate of the rotation origin
@return a matrix holding the result
"""
return rotateAroundLocal(quat, ox, oy, oz, thisOrNew());
}
|
java
|
public Matrix4f rotateAroundLocal(Quaternionfc quat, float ox, float oy, float oz) {
return rotateAroundLocal(quat, ox, oy, oz, thisOrNew());
}
|
[
"public",
"Matrix4f",
"rotateAroundLocal",
"(",
"Quaternionfc",
"quat",
",",
"float",
"ox",
",",
"float",
"oy",
",",
"float",
"oz",
")",
"{",
"return",
"rotateAroundLocal",
"(",
"quat",
",",
"ox",
",",
"oy",
",",
"oz",
",",
"thisOrNew",
"(",
")",
")",
";",
"}"
] |
Pre-multiply the rotation transformation of the given {@link Quaternionfc} to this matrix while using <code>(ox, oy, oz)</code>
as the rotation origin.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion,
then the new matrix will be <code>Q * M</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>Q * M * v</code>,
the quaternion rotation will be applied last!
<p>
This method is equivalent to calling: <code>translateLocal(-ox, -oy, -oz).rotateLocal(quat).translateLocal(ox, oy, oz)</code>
<p>
Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a>
@param quat
the {@link Quaternionfc}
@param ox
the x coordinate of the rotation origin
@param oy
the y coordinate of the rotation origin
@param oz
the z coordinate of the rotation origin
@return a matrix holding the result
|
[
"Pre",
"-",
"multiply",
"the",
"rotation",
"transformation",
"of",
"the",
"given",
"{",
"@link",
"Quaternionfc",
"}",
"to",
"this",
"matrix",
"while",
"using",
"<code",
">",
"(",
"ox",
"oy",
"oz",
")",
"<",
"/",
"code",
">",
"as",
"the",
"rotation",
"origin",
".",
"<p",
">",
"When",
"used",
"with",
"a",
"right",
"-",
"handed",
"coordinate",
"system",
"the",
"produced",
"rotation",
"will",
"rotate",
"a",
"vector",
"counter",
"-",
"clockwise",
"around",
"the",
"rotation",
"axis",
"when",
"viewing",
"along",
"the",
"negative",
"axis",
"direction",
"towards",
"the",
"origin",
".",
"When",
"used",
"with",
"a",
"left",
"-",
"handed",
"coordinate",
"system",
"the",
"rotation",
"is",
"clockwise",
".",
"<p",
">",
"If",
"<code",
">",
"M<",
"/",
"code",
">",
"is",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"and",
"<code",
">",
"Q<",
"/",
"code",
">",
"the",
"rotation",
"matrix",
"obtained",
"from",
"the",
"given",
"quaternion",
"then",
"the",
"new",
"matrix",
"will",
"be",
"<code",
">",
"Q",
"*",
"M<",
"/",
"code",
">",
".",
"So",
"when",
"transforming",
"a",
"vector",
"<code",
">",
"v<",
"/",
"code",
">",
"with",
"the",
"new",
"matrix",
"by",
"using",
"<code",
">",
"Q",
"*",
"M",
"*",
"v<",
"/",
"code",
">",
"the",
"quaternion",
"rotation",
"will",
"be",
"applied",
"last!",
"<p",
">",
"This",
"method",
"is",
"equivalent",
"to",
"calling",
":",
"<code",
">",
"translateLocal",
"(",
"-",
"ox",
"-",
"oy",
"-",
"oz",
")",
".",
"rotateLocal",
"(",
"quat",
")",
".",
"translateLocal",
"(",
"ox",
"oy",
"oz",
")",
"<",
"/",
"code",
">",
"<p",
">",
"Reference",
":",
"<a",
"href",
"=",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Rotation_matrix#Quaternion",
">",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org<",
"/",
"a",
">"
] |
train
|
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L11563-L11565
|
rundeck/rundeck
|
core/src/main/java/com/dtolabs/rundeck/core/plugins/ScriptDataContextUtil.java
|
ScriptDataContextUtil.createScriptDataContext
|
public static DataContext createScriptDataContext(final Framework framework) {
"""
@return a data context for executing a script plugin or provider, which contains two datasets:
plugin: {vardir: [dir], tmpdir: [dir]}
and
rundeck: {base: [basedir]}
@param framework framework
"""
BaseDataContext data = new BaseDataContext();
final File vardir = new File(Constants.getBaseVar(framework.getBaseDir().getAbsolutePath()));
final File tmpdir = new File(vardir, "tmp");
data.group("plugin").put("vardir", vardir.getAbsolutePath());
data.group("plugin").put("tmpdir", tmpdir.getAbsolutePath());
data.put("rundeck", "base", framework.getBaseDir().getAbsolutePath());
return data;
}
|
java
|
public static DataContext createScriptDataContext(final Framework framework) {
BaseDataContext data = new BaseDataContext();
final File vardir = new File(Constants.getBaseVar(framework.getBaseDir().getAbsolutePath()));
final File tmpdir = new File(vardir, "tmp");
data.group("plugin").put("vardir", vardir.getAbsolutePath());
data.group("plugin").put("tmpdir", tmpdir.getAbsolutePath());
data.put("rundeck", "base", framework.getBaseDir().getAbsolutePath());
return data;
}
|
[
"public",
"static",
"DataContext",
"createScriptDataContext",
"(",
"final",
"Framework",
"framework",
")",
"{",
"BaseDataContext",
"data",
"=",
"new",
"BaseDataContext",
"(",
")",
";",
"final",
"File",
"vardir",
"=",
"new",
"File",
"(",
"Constants",
".",
"getBaseVar",
"(",
"framework",
".",
"getBaseDir",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
")",
";",
"final",
"File",
"tmpdir",
"=",
"new",
"File",
"(",
"vardir",
",",
"\"tmp\"",
")",
";",
"data",
".",
"group",
"(",
"\"plugin\"",
")",
".",
"put",
"(",
"\"vardir\"",
",",
"vardir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"data",
".",
"group",
"(",
"\"plugin\"",
")",
".",
"put",
"(",
"\"tmpdir\"",
",",
"tmpdir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"data",
".",
"put",
"(",
"\"rundeck\"",
",",
"\"base\"",
",",
"framework",
".",
"getBaseDir",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"return",
"data",
";",
"}"
] |
@return a data context for executing a script plugin or provider, which contains two datasets:
plugin: {vardir: [dir], tmpdir: [dir]}
and
rundeck: {base: [basedir]}
@param framework framework
|
[
"@return",
"a",
"data",
"context",
"for",
"executing",
"a",
"script",
"plugin",
"or",
"provider",
"which",
"contains",
"two",
"datasets",
":",
"plugin",
":",
"{",
"vardir",
":",
"[",
"dir",
"]",
"tmpdir",
":",
"[",
"dir",
"]",
"}",
"and",
"rundeck",
":",
"{",
"base",
":",
"[",
"basedir",
"]",
"}",
"@param",
"framework",
"framework"
] |
train
|
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/ScriptDataContextUtil.java#L60-L70
|
fabric8io/fabric8-forge
|
fabric8-forge-rest-client/src/main/java/io/fabric8/forge/rest/client/TailResults.java
|
TailResults.isNewLine
|
public boolean isNewLine(String line, int index) {
"""
Returns true if this line index is newer than the last results
or the last line has changed (e.g. if output was appended to the last line)
"""
return index > lastIndex || (index == lastIndex && !Objects.equals(line, lastLine));
}
|
java
|
public boolean isNewLine(String line, int index) {
return index > lastIndex || (index == lastIndex && !Objects.equals(line, lastLine));
}
|
[
"public",
"boolean",
"isNewLine",
"(",
"String",
"line",
",",
"int",
"index",
")",
"{",
"return",
"index",
">",
"lastIndex",
"||",
"(",
"index",
"==",
"lastIndex",
"&&",
"!",
"Objects",
".",
"equals",
"(",
"line",
",",
"lastLine",
")",
")",
";",
"}"
] |
Returns true if this line index is newer than the last results
or the last line has changed (e.g. if output was appended to the last line)
|
[
"Returns",
"true",
"if",
"this",
"line",
"index",
"is",
"newer",
"than",
"the",
"last",
"results",
"or",
"the",
"last",
"line",
"has",
"changed",
"(",
"e",
".",
"g",
".",
"if",
"output",
"was",
"appended",
"to",
"the",
"last",
"line",
")"
] |
train
|
https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/fabric8-forge-rest-client/src/main/java/io/fabric8/forge/rest/client/TailResults.java#L54-L56
|
msteiger/jxmapviewer2
|
jxmapviewer2/src/main/java/org/jxmapviewer/input/MapClickListener.java
|
MapClickListener.mouseClicked
|
@Override
public void mouseClicked(MouseEvent evt) {
"""
Gets called on mouseClicked events, calculates the GeoPosition and fires
the mapClicked method that the extending class needs to implement.
@param evt the mouse event
"""
final boolean left = SwingUtilities.isLeftMouseButton(evt);
final boolean singleClick = (evt.getClickCount() == 1);
if ((left && singleClick)) {
Rectangle bounds = viewer.getViewportBounds();
int x = bounds.x + evt.getX();
int y = bounds.y + evt.getY();
Point pixelCoordinates = new Point(x, y);
mapClicked(viewer.getTileFactory().pixelToGeo(pixelCoordinates, viewer.getZoom()));
}
}
|
java
|
@Override
public void mouseClicked(MouseEvent evt) {
final boolean left = SwingUtilities.isLeftMouseButton(evt);
final boolean singleClick = (evt.getClickCount() == 1);
if ((left && singleClick)) {
Rectangle bounds = viewer.getViewportBounds();
int x = bounds.x + evt.getX();
int y = bounds.y + evt.getY();
Point pixelCoordinates = new Point(x, y);
mapClicked(viewer.getTileFactory().pixelToGeo(pixelCoordinates, viewer.getZoom()));
}
}
|
[
"@",
"Override",
"public",
"void",
"mouseClicked",
"(",
"MouseEvent",
"evt",
")",
"{",
"final",
"boolean",
"left",
"=",
"SwingUtilities",
".",
"isLeftMouseButton",
"(",
"evt",
")",
";",
"final",
"boolean",
"singleClick",
"=",
"(",
"evt",
".",
"getClickCount",
"(",
")",
"==",
"1",
")",
";",
"if",
"(",
"(",
"left",
"&&",
"singleClick",
")",
")",
"{",
"Rectangle",
"bounds",
"=",
"viewer",
".",
"getViewportBounds",
"(",
")",
";",
"int",
"x",
"=",
"bounds",
".",
"x",
"+",
"evt",
".",
"getX",
"(",
")",
";",
"int",
"y",
"=",
"bounds",
".",
"y",
"+",
"evt",
".",
"getY",
"(",
")",
";",
"Point",
"pixelCoordinates",
"=",
"new",
"Point",
"(",
"x",
",",
"y",
")",
";",
"mapClicked",
"(",
"viewer",
".",
"getTileFactory",
"(",
")",
".",
"pixelToGeo",
"(",
"pixelCoordinates",
",",
"viewer",
".",
"getZoom",
"(",
")",
")",
")",
";",
"}",
"}"
] |
Gets called on mouseClicked events, calculates the GeoPosition and fires
the mapClicked method that the extending class needs to implement.
@param evt the mouse event
|
[
"Gets",
"called",
"on",
"mouseClicked",
"events",
"calculates",
"the",
"GeoPosition",
"and",
"fires",
"the",
"mapClicked",
"method",
"that",
"the",
"extending",
"class",
"needs",
"to",
"implement",
"."
] |
train
|
https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/input/MapClickListener.java#L39-L51
|
apache/incubator-gobblin
|
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java
|
GobblinClusterManager.initializeAppLauncherAndServices
|
private void initializeAppLauncherAndServices() throws Exception {
"""
Create the service based application launcher and other associated services
@throws Exception
"""
// Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes
Properties properties = ConfigUtils.configToProperties(this.config);
if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) {
properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300));
}
this.applicationLauncher = new ServiceBasedAppLauncher(properties, this.clusterName);
// create a job catalog for keeping track of received jobs if a job config path is specified
if (this.config.hasPath(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX
+ ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) {
String jobCatalogClassName = ConfigUtils.getString(config, GobblinClusterConfigurationKeys.JOB_CATALOG_KEY,
GobblinClusterConfigurationKeys.DEFAULT_JOB_CATALOG);
this.jobCatalog =
(MutableJobCatalog) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(jobCatalogClassName),
ImmutableList.of(config
.getConfig(StringUtils.removeEnd(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX, "."))
.withFallback(this.config)));
} else {
this.jobCatalog = null;
}
SchedulerService schedulerService = new SchedulerService(properties);
this.applicationLauncher.addService(schedulerService);
this.jobScheduler = buildGobblinHelixJobScheduler(config, this.appWorkDir, getMetadataTags(clusterName, applicationId),
schedulerService);
this.applicationLauncher.addService(this.jobScheduler);
this.jobConfigurationManager = buildJobConfigurationManager(config);
this.applicationLauncher.addService(this.jobConfigurationManager);
}
|
java
|
private void initializeAppLauncherAndServices() throws Exception {
// Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes
Properties properties = ConfigUtils.configToProperties(this.config);
if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) {
properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300));
}
this.applicationLauncher = new ServiceBasedAppLauncher(properties, this.clusterName);
// create a job catalog for keeping track of received jobs if a job config path is specified
if (this.config.hasPath(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX
+ ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) {
String jobCatalogClassName = ConfigUtils.getString(config, GobblinClusterConfigurationKeys.JOB_CATALOG_KEY,
GobblinClusterConfigurationKeys.DEFAULT_JOB_CATALOG);
this.jobCatalog =
(MutableJobCatalog) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(jobCatalogClassName),
ImmutableList.of(config
.getConfig(StringUtils.removeEnd(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX, "."))
.withFallback(this.config)));
} else {
this.jobCatalog = null;
}
SchedulerService schedulerService = new SchedulerService(properties);
this.applicationLauncher.addService(schedulerService);
this.jobScheduler = buildGobblinHelixJobScheduler(config, this.appWorkDir, getMetadataTags(clusterName, applicationId),
schedulerService);
this.applicationLauncher.addService(this.jobScheduler);
this.jobConfigurationManager = buildJobConfigurationManager(config);
this.applicationLauncher.addService(this.jobConfigurationManager);
}
|
[
"private",
"void",
"initializeAppLauncherAndServices",
"(",
")",
"throws",
"Exception",
"{",
"// Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes",
"Properties",
"properties",
"=",
"ConfigUtils",
".",
"configToProperties",
"(",
"this",
".",
"config",
")",
";",
"if",
"(",
"!",
"properties",
".",
"contains",
"(",
"ServiceBasedAppLauncher",
".",
"APP_STOP_TIME_SECONDS",
")",
")",
"{",
"properties",
".",
"setProperty",
"(",
"ServiceBasedAppLauncher",
".",
"APP_STOP_TIME_SECONDS",
",",
"Long",
".",
"toString",
"(",
"300",
")",
")",
";",
"}",
"this",
".",
"applicationLauncher",
"=",
"new",
"ServiceBasedAppLauncher",
"(",
"properties",
",",
"this",
".",
"clusterName",
")",
";",
"// create a job catalog for keeping track of received jobs if a job config path is specified",
"if",
"(",
"this",
".",
"config",
".",
"hasPath",
"(",
"GobblinClusterConfigurationKeys",
".",
"GOBBLIN_CLUSTER_PREFIX",
"+",
"ConfigurationKeys",
".",
"JOB_CONFIG_FILE_GENERAL_PATH_KEY",
")",
")",
"{",
"String",
"jobCatalogClassName",
"=",
"ConfigUtils",
".",
"getString",
"(",
"config",
",",
"GobblinClusterConfigurationKeys",
".",
"JOB_CATALOG_KEY",
",",
"GobblinClusterConfigurationKeys",
".",
"DEFAULT_JOB_CATALOG",
")",
";",
"this",
".",
"jobCatalog",
"=",
"(",
"MutableJobCatalog",
")",
"GobblinConstructorUtils",
".",
"invokeFirstConstructor",
"(",
"Class",
".",
"forName",
"(",
"jobCatalogClassName",
")",
",",
"ImmutableList",
".",
"of",
"(",
"config",
".",
"getConfig",
"(",
"StringUtils",
".",
"removeEnd",
"(",
"GobblinClusterConfigurationKeys",
".",
"GOBBLIN_CLUSTER_PREFIX",
",",
"\".\"",
")",
")",
".",
"withFallback",
"(",
"this",
".",
"config",
")",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"jobCatalog",
"=",
"null",
";",
"}",
"SchedulerService",
"schedulerService",
"=",
"new",
"SchedulerService",
"(",
"properties",
")",
";",
"this",
".",
"applicationLauncher",
".",
"addService",
"(",
"schedulerService",
")",
";",
"this",
".",
"jobScheduler",
"=",
"buildGobblinHelixJobScheduler",
"(",
"config",
",",
"this",
".",
"appWorkDir",
",",
"getMetadataTags",
"(",
"clusterName",
",",
"applicationId",
")",
",",
"schedulerService",
")",
";",
"this",
".",
"applicationLauncher",
".",
"addService",
"(",
"this",
".",
"jobScheduler",
")",
";",
"this",
".",
"jobConfigurationManager",
"=",
"buildJobConfigurationManager",
"(",
"config",
")",
";",
"this",
".",
"applicationLauncher",
".",
"addService",
"(",
"this",
".",
"jobConfigurationManager",
")",
";",
"}"
] |
Create the service based application launcher and other associated services
@throws Exception
|
[
"Create",
"the",
"service",
"based",
"application",
"launcher",
"and",
"other",
"associated",
"services"
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java#L163-L193
|
cdk/cdk
|
base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/CompatibilityMatrix.java
|
CompatibilityMatrix.markRow
|
void markRow(int i, int marking) {
"""
Mark all values in row i allowing it to be reset later.
@param i row index
@param marking the marking to store (should be negative)
"""
for (int j = (i * mCols), end = j + mCols; j < end; j++)
if (data[j] > 0) data[j] = marking;
}
|
java
|
void markRow(int i, int marking) {
for (int j = (i * mCols), end = j + mCols; j < end; j++)
if (data[j] > 0) data[j] = marking;
}
|
[
"void",
"markRow",
"(",
"int",
"i",
",",
"int",
"marking",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"(",
"i",
"*",
"mCols",
")",
",",
"end",
"=",
"j",
"+",
"mCols",
";",
"j",
"<",
"end",
";",
"j",
"++",
")",
"if",
"(",
"data",
"[",
"j",
"]",
">",
"0",
")",
"data",
"[",
"j",
"]",
"=",
"marking",
";",
"}"
] |
Mark all values in row i allowing it to be reset later.
@param i row index
@param marking the marking to store (should be negative)
|
[
"Mark",
"all",
"values",
"in",
"row",
"i",
"allowing",
"it",
"to",
"be",
"reset",
"later",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/CompatibilityMatrix.java#L108-L111
|
Azure/azure-sdk-for-java
|
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
|
AccountsInner.deleteStorageAccountAsync
|
public Observable<Void> deleteStorageAccountAsync(String resourceGroupName, String accountName, String storageAccountName) {
"""
Updates the specified Data Lake Analytics account to remove an Azure Storage account.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account from which to remove the Azure Storage account.
@param storageAccountName The name of the Azure Storage account to remove
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return deleteStorageAccountWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
|
java
|
public Observable<Void> deleteStorageAccountAsync(String resourceGroupName, String accountName, String storageAccountName) {
return deleteStorageAccountWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Void",
">",
"deleteStorageAccountAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"storageAccountName",
")",
"{",
"return",
"deleteStorageAccountWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"storageAccountName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Void",
">",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"call",
"(",
"ServiceResponse",
"<",
"Void",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates the specified Data Lake Analytics account to remove an Azure Storage account.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account from which to remove the Azure Storage account.
@param storageAccountName The name of the Azure Storage account to remove
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
|
[
"Updates",
"the",
"specified",
"Data",
"Lake",
"Analytics",
"account",
"to",
"remove",
"an",
"Azure",
"Storage",
"account",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L311-L318
|
ribot/easy-adapter
|
library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java
|
FieldAnnotationParser.setViewFields
|
public static void setViewFields(final Object object, final View view) {
"""
Parse {@link ViewId} annotation and try to assign the view with that id to the annotated field.
It will throw a {@link ClassCastException} if the field and the view with the given ID have different types.
@param object object where the annotation is.
@param view parent view that contains a view with the viewId given in the annotation.
"""
setViewFields(object, new ViewFinder() {
@Override
public View findViewById(int viewId) {
return view.findViewById(viewId);
}
});
}
|
java
|
public static void setViewFields(final Object object, final View view) {
setViewFields(object, new ViewFinder() {
@Override
public View findViewById(int viewId) {
return view.findViewById(viewId);
}
});
}
|
[
"public",
"static",
"void",
"setViewFields",
"(",
"final",
"Object",
"object",
",",
"final",
"View",
"view",
")",
"{",
"setViewFields",
"(",
"object",
",",
"new",
"ViewFinder",
"(",
")",
"{",
"@",
"Override",
"public",
"View",
"findViewById",
"(",
"int",
"viewId",
")",
"{",
"return",
"view",
".",
"findViewById",
"(",
"viewId",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Parse {@link ViewId} annotation and try to assign the view with that id to the annotated field.
It will throw a {@link ClassCastException} if the field and the view with the given ID have different types.
@param object object where the annotation is.
@param view parent view that contains a view with the viewId given in the annotation.
|
[
"Parse",
"{",
"@link",
"ViewId",
"}",
"annotation",
"and",
"try",
"to",
"assign",
"the",
"view",
"with",
"that",
"id",
"to",
"the",
"annotated",
"field",
".",
"It",
"will",
"throw",
"a",
"{",
"@link",
"ClassCastException",
"}",
"if",
"the",
"field",
"and",
"the",
"view",
"with",
"the",
"given",
"ID",
"have",
"different",
"types",
"."
] |
train
|
https://github.com/ribot/easy-adapter/blob/8cf85023a79c781aa2013e9dc39fd66734fb2019/library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java#L33-L40
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java
|
HttpChannelConfig.parseThrowIOEForInboundConnections
|
private void parseThrowIOEForInboundConnections(Map<?, ?> props) {
"""
Check the configuration map for if we should swallow inbound connections IOEs
@ param props
"""
//PI57542
Object value = props.get(HttpConfigConstants.PROPNAME_THROW_IOE_FOR_INBOUND_CONNECTIONS);
if (null != value) {
this.throwIOEForInboundConnections = convertBoolean(value);
if ((TraceComponent.isAnyTracingEnabled()) && (tc.isEventEnabled())) {
Tr.event(tc, "Config: ThrowIOEForInboundConnections is " + throwIOEForInboundConnections());
}
}
}
|
java
|
private void parseThrowIOEForInboundConnections(Map<?, ?> props) {
//PI57542
Object value = props.get(HttpConfigConstants.PROPNAME_THROW_IOE_FOR_INBOUND_CONNECTIONS);
if (null != value) {
this.throwIOEForInboundConnections = convertBoolean(value);
if ((TraceComponent.isAnyTracingEnabled()) && (tc.isEventEnabled())) {
Tr.event(tc, "Config: ThrowIOEForInboundConnections is " + throwIOEForInboundConnections());
}
}
}
|
[
"private",
"void",
"parseThrowIOEForInboundConnections",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"props",
")",
"{",
"//PI57542",
"Object",
"value",
"=",
"props",
".",
"get",
"(",
"HttpConfigConstants",
".",
"PROPNAME_THROW_IOE_FOR_INBOUND_CONNECTIONS",
")",
";",
"if",
"(",
"null",
"!=",
"value",
")",
"{",
"this",
".",
"throwIOEForInboundConnections",
"=",
"convertBoolean",
"(",
"value",
")",
";",
"if",
"(",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
")",
"&&",
"(",
"tc",
".",
"isEventEnabled",
"(",
")",
")",
")",
"{",
"Tr",
".",
"event",
"(",
"tc",
",",
"\"Config: ThrowIOEForInboundConnections is \"",
"+",
"throwIOEForInboundConnections",
"(",
")",
")",
";",
"}",
"}",
"}"
] |
Check the configuration map for if we should swallow inbound connections IOEs
@ param props
|
[
"Check",
"the",
"configuration",
"map",
"for",
"if",
"we",
"should",
"swallow",
"inbound",
"connections",
"IOEs"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L1326-L1335
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/impl/PatternWrapper.java
|
PatternWrapper.matchMidClauses
|
public boolean matchMidClauses(char[] chars, int start, int length) {
"""
Test whether the underlying pattern's mid clauses match a set of characters.
@param chars
@param start
@param length
@return
"""
return pattern.matchMiddle(chars, start, start+length);
}
|
java
|
public boolean matchMidClauses(char[] chars, int start, int length)
{
return pattern.matchMiddle(chars, start, start+length);
}
|
[
"public",
"boolean",
"matchMidClauses",
"(",
"char",
"[",
"]",
"chars",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"return",
"pattern",
".",
"matchMiddle",
"(",
"chars",
",",
"start",
",",
"start",
"+",
"length",
")",
";",
"}"
] |
Test whether the underlying pattern's mid clauses match a set of characters.
@param chars
@param start
@param length
@return
|
[
"Test",
"whether",
"the",
"underlying",
"pattern",
"s",
"mid",
"clauses",
"match",
"a",
"set",
"of",
"characters",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/matchspace/impl/PatternWrapper.java#L162-L166
|
jmapper-framework/jmapper-core
|
JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java
|
Error.mapping
|
public static void mapping(String mappedFieldName, String mappedClassName, String targetFieldName, String targetClassName) {
"""
Thrown when the target field doesn't exist.
@param mappedFieldName name of the mapped field
@param mappedClassName name of the mapped field's class
@param targetFieldName name of the target field
@param targetClassName name of the target field's class
"""
throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorException4,mappedFieldName,mappedClassName, targetFieldName,targetClassName));
}
|
java
|
public static void mapping(String mappedFieldName, String mappedClassName, String targetFieldName, String targetClassName){
throw new MappingErrorException(MSG.INSTANCE.message(mappingErrorException4,mappedFieldName,mappedClassName, targetFieldName,targetClassName));
}
|
[
"public",
"static",
"void",
"mapping",
"(",
"String",
"mappedFieldName",
",",
"String",
"mappedClassName",
",",
"String",
"targetFieldName",
",",
"String",
"targetClassName",
")",
"{",
"throw",
"new",
"MappingErrorException",
"(",
"MSG",
".",
"INSTANCE",
".",
"message",
"(",
"mappingErrorException4",
",",
"mappedFieldName",
",",
"mappedClassName",
",",
"targetFieldName",
",",
"targetClassName",
")",
")",
";",
"}"
] |
Thrown when the target field doesn't exist.
@param mappedFieldName name of the mapped field
@param mappedClassName name of the mapped field's class
@param targetFieldName name of the target field
@param targetClassName name of the target field's class
|
[
"Thrown",
"when",
"the",
"target",
"field",
"doesn",
"t",
"exist",
"."
] |
train
|
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L482-L484
|
EdwardRaff/JSAT
|
JSAT/src/jsat/distributions/kernels/RBFKernel.java
|
RBFKernel.sigmaToGamma
|
public static double sigmaToGamma(double sigma) {
"""
Another common (equivalent) form of the RBF kernel is k(x, y) =
exp(-γ||x-y||<sup>2</sup>). This method converts the σ value
used by this class to the equivalent γ value.
@param sigma the value of σ
@return the equivalent γ value.
"""
if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma))
throw new IllegalArgumentException("sigma must be positive, not " + sigma);
return 1/(2*sigma*sigma);
}
|
java
|
public static double sigmaToGamma(double sigma)
{
if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma))
throw new IllegalArgumentException("sigma must be positive, not " + sigma);
return 1/(2*sigma*sigma);
}
|
[
"public",
"static",
"double",
"sigmaToGamma",
"(",
"double",
"sigma",
")",
"{",
"if",
"(",
"sigma",
"<=",
"0",
"||",
"Double",
".",
"isNaN",
"(",
"sigma",
")",
"||",
"Double",
".",
"isInfinite",
"(",
"sigma",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"sigma must be positive, not \"",
"+",
"sigma",
")",
";",
"return",
"1",
"/",
"(",
"2",
"*",
"sigma",
"*",
"sigma",
")",
";",
"}"
] |
Another common (equivalent) form of the RBF kernel is k(x, y) =
exp(-γ||x-y||<sup>2</sup>). This method converts the σ value
used by this class to the equivalent γ value.
@param sigma the value of σ
@return the equivalent γ value.
|
[
"Another",
"common",
"(",
"equivalent",
")",
"form",
"of",
"the",
"RBF",
"kernel",
"is",
"k",
"(",
"x",
"y",
")",
"=",
"exp",
"(",
"-",
"&gamma",
";",
"||x",
"-",
"y||<sup",
">",
"2<",
"/",
"sup",
">",
")",
".",
"This",
"method",
"converts",
"the",
"&sigma",
";",
"value",
"used",
"by",
"this",
"class",
"to",
"the",
"equivalent",
"&gamma",
";",
"value",
"."
] |
train
|
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/RBFKernel.java#L111-L116
|
b3log/latke
|
latke-core/src/main/java/org/json/JSONArray.java
|
JSONArray.optBigDecimal
|
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
"""
Get the optional BigDecimal value associated with an index. The
defaultValue is returned if there is no value for the index, or if the
value is not a number and cannot be converted to a number. If the value
is float or double, the the {@link BigDecimal#BigDecimal(double)}
constructor will be used. See notes on the constructor for conversion
issues that may arise.
@param index
The index must be between 0 and length() - 1.
@param defaultValue
The default value.
@return The value.
"""
Object val = this.opt(index);
return JSONObject.objectToBigDecimal(val, defaultValue);
}
|
java
|
public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
Object val = this.opt(index);
return JSONObject.objectToBigDecimal(val, defaultValue);
}
|
[
"public",
"BigDecimal",
"optBigDecimal",
"(",
"int",
"index",
",",
"BigDecimal",
"defaultValue",
")",
"{",
"Object",
"val",
"=",
"this",
".",
"opt",
"(",
"index",
")",
";",
"return",
"JSONObject",
".",
"objectToBigDecimal",
"(",
"val",
",",
"defaultValue",
")",
";",
"}"
] |
Get the optional BigDecimal value associated with an index. The
defaultValue is returned if there is no value for the index, or if the
value is not a number and cannot be converted to a number. If the value
is float or double, the the {@link BigDecimal#BigDecimal(double)}
constructor will be used. See notes on the constructor for conversion
issues that may arise.
@param index
The index must be between 0 and length() - 1.
@param defaultValue
The default value.
@return The value.
|
[
"Get",
"the",
"optional",
"BigDecimal",
"value",
"associated",
"with",
"an",
"index",
".",
"The",
"defaultValue",
"is",
"returned",
"if",
"there",
"is",
"no",
"value",
"for",
"the",
"index",
"or",
"if",
"the",
"value",
"is",
"not",
"a",
"number",
"and",
"cannot",
"be",
"converted",
"to",
"a",
"number",
".",
"If",
"the",
"value",
"is",
"float",
"or",
"double",
"the",
"the",
"{",
"@link",
"BigDecimal#BigDecimal",
"(",
"double",
")",
"}",
"constructor",
"will",
"be",
"used",
".",
"See",
"notes",
"on",
"the",
"constructor",
"for",
"conversion",
"issues",
"that",
"may",
"arise",
"."
] |
train
|
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L728-L731
|
omadahealth/CircularBarPager
|
library/src/main/java/com/github/omadahealth/circularbarpager/library/CircularBarPager.java
|
CircularBarPager.onMeasure
|
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
"""
Apply a {@link android.support.v4.view.ViewPager#setPadding(int, int, int, int)} and
{@link android.support.v4.view.ViewPager#setPageMargin(int)} in order to get a nicer animation
on the {@link android.support.v4.view.ViewPager} inside the {@link CircularBar}
"""
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!isPaddingSet && mViewPager != null) {
int paddingForViewPager = this.getMeasuredWidth() / mPaddingRatio;
mViewPager.setPadding(paddingForViewPager, mViewPager.getPaddingTop(), paddingForViewPager, mViewPager.getPaddingBottom());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mViewPager.setPageMargin(-(int) (((float) mViewPager.getPaddingLeft() + (float) mViewPager.getPaddingRight()) * 2.0f));
}
isPaddingSet = true;
}
}
|
java
|
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!isPaddingSet && mViewPager != null) {
int paddingForViewPager = this.getMeasuredWidth() / mPaddingRatio;
mViewPager.setPadding(paddingForViewPager, mViewPager.getPaddingTop(), paddingForViewPager, mViewPager.getPaddingBottom());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mViewPager.setPageMargin(-(int) (((float) mViewPager.getPaddingLeft() + (float) mViewPager.getPaddingRight()) * 2.0f));
}
isPaddingSet = true;
}
}
|
[
"@",
"Override",
"protected",
"void",
"onMeasure",
"(",
"int",
"widthMeasureSpec",
",",
"int",
"heightMeasureSpec",
")",
"{",
"super",
".",
"onMeasure",
"(",
"widthMeasureSpec",
",",
"heightMeasureSpec",
")",
";",
"if",
"(",
"!",
"isPaddingSet",
"&&",
"mViewPager",
"!=",
"null",
")",
"{",
"int",
"paddingForViewPager",
"=",
"this",
".",
"getMeasuredWidth",
"(",
")",
"/",
"mPaddingRatio",
";",
"mViewPager",
".",
"setPadding",
"(",
"paddingForViewPager",
",",
"mViewPager",
".",
"getPaddingTop",
"(",
")",
",",
"paddingForViewPager",
",",
"mViewPager",
".",
"getPaddingBottom",
"(",
")",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"HONEYCOMB",
")",
"{",
"mViewPager",
".",
"setPageMargin",
"(",
"-",
"(",
"int",
")",
"(",
"(",
"(",
"float",
")",
"mViewPager",
".",
"getPaddingLeft",
"(",
")",
"+",
"(",
"float",
")",
"mViewPager",
".",
"getPaddingRight",
"(",
")",
")",
"*",
"2.0f",
")",
")",
";",
"}",
"isPaddingSet",
"=",
"true",
";",
"}",
"}"
] |
Apply a {@link android.support.v4.view.ViewPager#setPadding(int, int, int, int)} and
{@link android.support.v4.view.ViewPager#setPageMargin(int)} in order to get a nicer animation
on the {@link android.support.v4.view.ViewPager} inside the {@link CircularBar}
|
[
"Apply",
"a",
"{"
] |
train
|
https://github.com/omadahealth/CircularBarPager/blob/3a43e8828849da727fd13345e83b8432f7271155/library/src/main/java/com/github/omadahealth/circularbarpager/library/CircularBarPager.java#L155-L169
|
logic-ng/LogicNG
|
src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java
|
MiniSatStyleSolver.addClause
|
public boolean addClause(int lit, final Proposition proposition) {
"""
Adds a unit clause to the solver.
@param lit the unit clause's literal
@param proposition a proposition (if required for proof tracing)
@return {@code true} if the clause was added successfully, {@code false} otherwise
"""
final LNGIntVector unit = new LNGIntVector(1);
unit.push(lit);
return this.addClause(unit, proposition);
}
|
java
|
public boolean addClause(int lit, final Proposition proposition) {
final LNGIntVector unit = new LNGIntVector(1);
unit.push(lit);
return this.addClause(unit, proposition);
}
|
[
"public",
"boolean",
"addClause",
"(",
"int",
"lit",
",",
"final",
"Proposition",
"proposition",
")",
"{",
"final",
"LNGIntVector",
"unit",
"=",
"new",
"LNGIntVector",
"(",
"1",
")",
";",
"unit",
".",
"push",
"(",
"lit",
")",
";",
"return",
"this",
".",
"addClause",
"(",
"unit",
",",
"proposition",
")",
";",
"}"
] |
Adds a unit clause to the solver.
@param lit the unit clause's literal
@param proposition a proposition (if required for proof tracing)
@return {@code true} if the clause was added successfully, {@code false} otherwise
|
[
"Adds",
"a",
"unit",
"clause",
"to",
"the",
"solver",
"."
] |
train
|
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java#L314-L318
|
erlang/otp
|
lib/jinterface/java_src/com/ericsson/otp/erlang/OtpInputStream.java
|
OtpInputStream.read_compressed
|
public OtpErlangObject read_compressed() throws OtpErlangDecodeException {
"""
Read a compressed term from the stream
@return the resulting uncompressed term.
@exception OtpErlangDecodeException
if the next term in the stream is not a compressed term.
"""
final int tag = read1skip_version();
if (tag != OtpExternal.compressedTag) {
throw new OtpErlangDecodeException(
"Wrong tag encountered, expected "
+ OtpExternal.compressedTag + ", got " + tag);
}
final int size = read4BE();
final byte[] abuf = new byte[size];
final java.util.zip.InflaterInputStream is = new java.util.zip.InflaterInputStream(
this, new java.util.zip.Inflater(), size);
int curPos = 0;
try {
int curRead;
while (curPos < size
&& (curRead = is.read(abuf, curPos, size - curPos)) != -1) {
curPos += curRead;
}
if (curPos != size) {
throw new OtpErlangDecodeException("Decompression gave "
+ curPos + " bytes, not " + size);
}
} catch (final IOException e) {
throw new OtpErlangDecodeException("Cannot read from input stream");
}
@SuppressWarnings("resource")
final OtpInputStream ois = new OtpInputStream(abuf, flags);
return ois.read_any();
}
|
java
|
public OtpErlangObject read_compressed() throws OtpErlangDecodeException {
final int tag = read1skip_version();
if (tag != OtpExternal.compressedTag) {
throw new OtpErlangDecodeException(
"Wrong tag encountered, expected "
+ OtpExternal.compressedTag + ", got " + tag);
}
final int size = read4BE();
final byte[] abuf = new byte[size];
final java.util.zip.InflaterInputStream is = new java.util.zip.InflaterInputStream(
this, new java.util.zip.Inflater(), size);
int curPos = 0;
try {
int curRead;
while (curPos < size
&& (curRead = is.read(abuf, curPos, size - curPos)) != -1) {
curPos += curRead;
}
if (curPos != size) {
throw new OtpErlangDecodeException("Decompression gave "
+ curPos + " bytes, not " + size);
}
} catch (final IOException e) {
throw new OtpErlangDecodeException("Cannot read from input stream");
}
@SuppressWarnings("resource")
final OtpInputStream ois = new OtpInputStream(abuf, flags);
return ois.read_any();
}
|
[
"public",
"OtpErlangObject",
"read_compressed",
"(",
")",
"throws",
"OtpErlangDecodeException",
"{",
"final",
"int",
"tag",
"=",
"read1skip_version",
"(",
")",
";",
"if",
"(",
"tag",
"!=",
"OtpExternal",
".",
"compressedTag",
")",
"{",
"throw",
"new",
"OtpErlangDecodeException",
"(",
"\"Wrong tag encountered, expected \"",
"+",
"OtpExternal",
".",
"compressedTag",
"+",
"\", got \"",
"+",
"tag",
")",
";",
"}",
"final",
"int",
"size",
"=",
"read4BE",
"(",
")",
";",
"final",
"byte",
"[",
"]",
"abuf",
"=",
"new",
"byte",
"[",
"size",
"]",
";",
"final",
"java",
".",
"util",
".",
"zip",
".",
"InflaterInputStream",
"is",
"=",
"new",
"java",
".",
"util",
".",
"zip",
".",
"InflaterInputStream",
"(",
"this",
",",
"new",
"java",
".",
"util",
".",
"zip",
".",
"Inflater",
"(",
")",
",",
"size",
")",
";",
"int",
"curPos",
"=",
"0",
";",
"try",
"{",
"int",
"curRead",
";",
"while",
"(",
"curPos",
"<",
"size",
"&&",
"(",
"curRead",
"=",
"is",
".",
"read",
"(",
"abuf",
",",
"curPos",
",",
"size",
"-",
"curPos",
")",
")",
"!=",
"-",
"1",
")",
"{",
"curPos",
"+=",
"curRead",
";",
"}",
"if",
"(",
"curPos",
"!=",
"size",
")",
"{",
"throw",
"new",
"OtpErlangDecodeException",
"(",
"\"Decompression gave \"",
"+",
"curPos",
"+",
"\" bytes, not \"",
"+",
"size",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"IOException",
"e",
")",
"{",
"throw",
"new",
"OtpErlangDecodeException",
"(",
"\"Cannot read from input stream\"",
")",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"resource\"",
")",
"final",
"OtpInputStream",
"ois",
"=",
"new",
"OtpInputStream",
"(",
"abuf",
",",
"flags",
")",
";",
"return",
"ois",
".",
"read_any",
"(",
")",
";",
"}"
] |
Read a compressed term from the stream
@return the resulting uncompressed term.
@exception OtpErlangDecodeException
if the next term in the stream is not a compressed term.
|
[
"Read",
"a",
"compressed",
"term",
"from",
"the",
"stream"
] |
train
|
https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpInputStream.java#L1156-L1187
|
hazelcast/hazelcast
|
hazelcast/src/main/java/com/hazelcast/config/matcher/LegacyMatchingPointConfigPatternMatcher.java
|
LegacyMatchingPointConfigPatternMatcher.getMatchingPoint
|
private int getMatchingPoint(String pattern, String itemName) {
"""
This method returns higher values the better the matching is.
@param pattern configuration pattern to match with
@param itemName item name to match
@return -1 if name does not match at all, zero or positive otherwise
"""
int index = pattern.indexOf('*');
if (index == -1) {
return -1;
}
String firstPart = pattern.substring(0, index);
int indexFirstPart = itemName.indexOf(firstPart, 0);
if (indexFirstPart == -1) {
return -1;
}
String secondPart = pattern.substring(index + 1);
int indexSecondPart = itemName.indexOf(secondPart, index + 1);
if (indexSecondPart == -1) {
return -1;
}
return firstPart.length() + secondPart.length();
}
|
java
|
private int getMatchingPoint(String pattern, String itemName) {
int index = pattern.indexOf('*');
if (index == -1) {
return -1;
}
String firstPart = pattern.substring(0, index);
int indexFirstPart = itemName.indexOf(firstPart, 0);
if (indexFirstPart == -1) {
return -1;
}
String secondPart = pattern.substring(index + 1);
int indexSecondPart = itemName.indexOf(secondPart, index + 1);
if (indexSecondPart == -1) {
return -1;
}
return firstPart.length() + secondPart.length();
}
|
[
"private",
"int",
"getMatchingPoint",
"(",
"String",
"pattern",
",",
"String",
"itemName",
")",
"{",
"int",
"index",
"=",
"pattern",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"index",
"==",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"String",
"firstPart",
"=",
"pattern",
".",
"substring",
"(",
"0",
",",
"index",
")",
";",
"int",
"indexFirstPart",
"=",
"itemName",
".",
"indexOf",
"(",
"firstPart",
",",
"0",
")",
";",
"if",
"(",
"indexFirstPart",
"==",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"String",
"secondPart",
"=",
"pattern",
".",
"substring",
"(",
"index",
"+",
"1",
")",
";",
"int",
"indexSecondPart",
"=",
"itemName",
".",
"indexOf",
"(",
"secondPart",
",",
"index",
"+",
"1",
")",
";",
"if",
"(",
"indexSecondPart",
"==",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"firstPart",
".",
"length",
"(",
")",
"+",
"secondPart",
".",
"length",
"(",
")",
";",
"}"
] |
This method returns higher values the better the matching is.
@param pattern configuration pattern to match with
@param itemName item name to match
@return -1 if name does not match at all, zero or positive otherwise
|
[
"This",
"method",
"returns",
"higher",
"values",
"the",
"better",
"the",
"matching",
"is",
"."
] |
train
|
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/matcher/LegacyMatchingPointConfigPatternMatcher.java#L58-L77
|
ehcache/ehcache3
|
impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java
|
CacheEventListenerConfigurationBuilder.constructedWith
|
public CacheEventListenerConfigurationBuilder constructedWith(Object... arguments) {
"""
Adds arguments that will be passed to the constructor of the {@link CacheEventListener} subclass configured
previously.
@param arguments the constructor arguments
@return a new builder with the added constructor arguments
@throws IllegalArgumentException if this builder is instance based
"""
if (this.listenerClass == null) {
throw new IllegalArgumentException("Arguments only are meaningful with class-based builder, this one seems to be an instance-based one");
}
CacheEventListenerConfigurationBuilder otherBuilder = new CacheEventListenerConfigurationBuilder(this);
otherBuilder.listenerArguments = arguments;
return otherBuilder;
}
|
java
|
public CacheEventListenerConfigurationBuilder constructedWith(Object... arguments) {
if (this.listenerClass == null) {
throw new IllegalArgumentException("Arguments only are meaningful with class-based builder, this one seems to be an instance-based one");
}
CacheEventListenerConfigurationBuilder otherBuilder = new CacheEventListenerConfigurationBuilder(this);
otherBuilder.listenerArguments = arguments;
return otherBuilder;
}
|
[
"public",
"CacheEventListenerConfigurationBuilder",
"constructedWith",
"(",
"Object",
"...",
"arguments",
")",
"{",
"if",
"(",
"this",
".",
"listenerClass",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Arguments only are meaningful with class-based builder, this one seems to be an instance-based one\"",
")",
";",
"}",
"CacheEventListenerConfigurationBuilder",
"otherBuilder",
"=",
"new",
"CacheEventListenerConfigurationBuilder",
"(",
"this",
")",
";",
"otherBuilder",
".",
"listenerArguments",
"=",
"arguments",
";",
"return",
"otherBuilder",
";",
"}"
] |
Adds arguments that will be passed to the constructor of the {@link CacheEventListener} subclass configured
previously.
@param arguments the constructor arguments
@return a new builder with the added constructor arguments
@throws IllegalArgumentException if this builder is instance based
|
[
"Adds",
"arguments",
"that",
"will",
"be",
"passed",
"to",
"the",
"constructor",
"of",
"the",
"{",
"@link",
"CacheEventListener",
"}",
"subclass",
"configured",
"previously",
"."
] |
train
|
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheEventListenerConfigurationBuilder.java#L159-L166
|
aspectran/aspectran
|
core/src/main/java/com/aspectran/core/util/ExceptionUtils.java
|
ExceptionUtils.throwAsIAE
|
public static void throwAsIAE(Throwable t, String msg) {
"""
Method that will wrap 't' as an {@link IllegalArgumentException} (and with
specified message) if it is a checked exception; otherwise (runtime exception or error)
throw as is.
@param t the Throwable to possibly propagate
@param msg the detail message
"""
throwIfRTE(t);
throwIfError(t);
throw new IllegalArgumentException(msg, t);
}
|
java
|
public static void throwAsIAE(Throwable t, String msg) {
throwIfRTE(t);
throwIfError(t);
throw new IllegalArgumentException(msg, t);
}
|
[
"public",
"static",
"void",
"throwAsIAE",
"(",
"Throwable",
"t",
",",
"String",
"msg",
")",
"{",
"throwIfRTE",
"(",
"t",
")",
";",
"throwIfError",
"(",
"t",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"msg",
",",
"t",
")",
";",
"}"
] |
Method that will wrap 't' as an {@link IllegalArgumentException} (and with
specified message) if it is a checked exception; otherwise (runtime exception or error)
throw as is.
@param t the Throwable to possibly propagate
@param msg the detail message
|
[
"Method",
"that",
"will",
"wrap",
"t",
"as",
"an",
"{",
"@link",
"IllegalArgumentException",
"}",
"(",
"and",
"with",
"specified",
"message",
")",
"if",
"it",
"is",
"a",
"checked",
"exception",
";",
"otherwise",
"(",
"runtime",
"exception",
"or",
"error",
")",
"throw",
"as",
"is",
"."
] |
train
|
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ExceptionUtils.java#L146-L150
|
googleapis/google-cloud-java
|
google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/GrafeasV1Beta1Client.java
|
GrafeasV1Beta1Client.listNotes
|
public final ListNotesPagedResponse listNotes(String parent, String filter) {
"""
Lists notes for the specified project.
<p>Sample code:
<pre><code>
try (GrafeasV1Beta1Client grafeasV1Beta1Client = GrafeasV1Beta1Client.create()) {
ProjectName parent = ProjectName.of("[PROJECT]");
String filter = "";
for (Note element : grafeasV1Beta1Client.listNotes(parent.toString(), filter).iterateAll()) {
// doThingsWith(element);
}
}
</code></pre>
@param parent The name of the project to list notes for in the form of `projects/[PROJECT_ID]`.
@param filter The filter expression.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
ListNotesRequest request =
ListNotesRequest.newBuilder().setParent(parent).setFilter(filter).build();
return listNotes(request);
}
|
java
|
public final ListNotesPagedResponse listNotes(String parent, String filter) {
ListNotesRequest request =
ListNotesRequest.newBuilder().setParent(parent).setFilter(filter).build();
return listNotes(request);
}
|
[
"public",
"final",
"ListNotesPagedResponse",
"listNotes",
"(",
"String",
"parent",
",",
"String",
"filter",
")",
"{",
"ListNotesRequest",
"request",
"=",
"ListNotesRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
")",
".",
"setFilter",
"(",
"filter",
")",
".",
"build",
"(",
")",
";",
"return",
"listNotes",
"(",
"request",
")",
";",
"}"
] |
Lists notes for the specified project.
<p>Sample code:
<pre><code>
try (GrafeasV1Beta1Client grafeasV1Beta1Client = GrafeasV1Beta1Client.create()) {
ProjectName parent = ProjectName.of("[PROJECT]");
String filter = "";
for (Note element : grafeasV1Beta1Client.listNotes(parent.toString(), filter).iterateAll()) {
// doThingsWith(element);
}
}
</code></pre>
@param parent The name of the project to list notes for in the form of `projects/[PROJECT_ID]`.
@param filter The filter expression.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
|
[
"Lists",
"notes",
"for",
"the",
"specified",
"project",
"."
] |
train
|
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/GrafeasV1Beta1Client.java#L1090-L1094
|
podio/podio-java
|
src/main/java/com/podio/tag/TagAPI.java
|
TagAPI.getTagsOnOrg
|
public List<TagCount> getTagsOnOrg(int orgId, int limit, String text) {
"""
Returns the tags on the given org. This includes both items and statuses on
all spaces in the organization that the user is part of. The tags are first
limited ordered by their frequency of use, and then returned sorted
alphabetically.
@param orgId
The id of the org to return tags from
@param limit
limit on number of tags returned (max 250)
@param text
text of tag to search for
@return The list of tags with their count
"""
MultivaluedMap<String, String> params=new MultivaluedMapImpl();
params.add("limit", new Integer(limit).toString());
if ((text != null) && (!text.isEmpty())) {
params.add("text", text);
}
return getTagsOnOrg(orgId, params);
}
|
java
|
public List<TagCount> getTagsOnOrg(int orgId, int limit, String text) {
MultivaluedMap<String, String> params=new MultivaluedMapImpl();
params.add("limit", new Integer(limit).toString());
if ((text != null) && (!text.isEmpty())) {
params.add("text", text);
}
return getTagsOnOrg(orgId, params);
}
|
[
"public",
"List",
"<",
"TagCount",
">",
"getTagsOnOrg",
"(",
"int",
"orgId",
",",
"int",
"limit",
",",
"String",
"text",
")",
"{",
"MultivaluedMap",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"MultivaluedMapImpl",
"(",
")",
";",
"params",
".",
"add",
"(",
"\"limit\"",
",",
"new",
"Integer",
"(",
"limit",
")",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"(",
"text",
"!=",
"null",
")",
"&&",
"(",
"!",
"text",
".",
"isEmpty",
"(",
")",
")",
")",
"{",
"params",
".",
"add",
"(",
"\"text\"",
",",
"text",
")",
";",
"}",
"return",
"getTagsOnOrg",
"(",
"orgId",
",",
"params",
")",
";",
"}"
] |
Returns the tags on the given org. This includes both items and statuses on
all spaces in the organization that the user is part of. The tags are first
limited ordered by their frequency of use, and then returned sorted
alphabetically.
@param orgId
The id of the org to return tags from
@param limit
limit on number of tags returned (max 250)
@param text
text of tag to search for
@return The list of tags with their count
|
[
"Returns",
"the",
"tags",
"on",
"the",
"given",
"org",
".",
"This",
"includes",
"both",
"items",
"and",
"statuses",
"on",
"all",
"spaces",
"in",
"the",
"organization",
"that",
"the",
"user",
"is",
"part",
"of",
".",
"The",
"tags",
"are",
"first",
"limited",
"ordered",
"by",
"their",
"frequency",
"of",
"use",
"and",
"then",
"returned",
"sorted",
"alphabetically",
"."
] |
train
|
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/tag/TagAPI.java#L199-L206
|
Azure/azure-sdk-for-java
|
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
|
AccountsInner.listSasTokensWithServiceResponseAsync
|
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> listSasTokensWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final String containerName) {
"""
Gets the SAS token associated with the specified Data Lake Analytics and Azure Storage account and container combination.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account from which an Azure Storage account's SAS token is being requested.
@param storageAccountName The name of the Azure storage account for which the SAS token is being requested.
@param containerName The name of the Azure storage container for which the SAS token is being requested.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SasTokenInfoInner> object
"""
return listSasTokensSinglePageAsync(resourceGroupName, accountName, storageAccountName, containerName)
.concatMap(new Func1<ServiceResponse<Page<SasTokenInfoInner>>, Observable<ServiceResponse<Page<SasTokenInfoInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> call(ServiceResponse<Page<SasTokenInfoInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
java
|
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> listSasTokensWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final String containerName) {
return listSasTokensSinglePageAsync(resourceGroupName, accountName, storageAccountName, containerName)
.concatMap(new Func1<ServiceResponse<Page<SasTokenInfoInner>>, Observable<ServiceResponse<Page<SasTokenInfoInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> call(ServiceResponse<Page<SasTokenInfoInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink));
}
});
}
|
[
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SasTokenInfoInner",
">",
">",
">",
"listSasTokensWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
",",
"final",
"String",
"storageAccountName",
",",
"final",
"String",
"containerName",
")",
"{",
"return",
"listSasTokensSinglePageAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"storageAccountName",
",",
"containerName",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SasTokenInfoInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SasTokenInfoInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SasTokenInfoInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"SasTokenInfoInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listSasTokensNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Gets the SAS token associated with the specified Data Lake Analytics and Azure Storage account and container combination.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account from which an Azure Storage account's SAS token is being requested.
@param storageAccountName The name of the Azure storage account for which the SAS token is being requested.
@param containerName The name of the Azure storage container for which the SAS token is being requested.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SasTokenInfoInner> object
|
[
"Gets",
"the",
"SAS",
"token",
"associated",
"with",
"the",
"specified",
"Data",
"Lake",
"Analytics",
"and",
"Azure",
"Storage",
"account",
"and",
"container",
"combination",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L872-L884
|
Sonoport/freesound-java
|
src/main/java/com/sonoport/freesound/FreesoundClient.java
|
FreesoundClient.executeQuery
|
@SuppressWarnings("unchecked")
public <S extends Object, R extends Object> Response<R> executeQuery(final Query<S, R> query)
throws FreesoundClientException {
"""
Execute a given query (synchronously) against the freesound API.
@param <S> The expected response type from the query
@param <R> The response type to return
@param query The query to execute
@return The result of the query
@throws FreesoundClientException Any errors encountered when performing API call
"""
final HttpRequest request = buildHTTPRequest(query);
final String credential = buildAuthorisationCredential(query);
if (credential != null) {
request.header("Authorization", credential);
}
try {
if (query instanceof JSONResponseQuery) {
final HttpResponse<JsonNode> httpResponse = request.asJson();
final S responseBody = (S) httpResponse.getBody().getObject();
return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody);
} else if (query instanceof BinaryResponseQuery) {
final HttpResponse<InputStream> httpResponse = request.asBinary();
final S responseBody = (S) httpResponse.getBody();
return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody);
} else {
throw new FreesoundClientException(String.format("Unknown request type: %s", query.getClass()));
}
} catch (final ClassCastException | UnirestException e) {
throw new FreesoundClientException("Error when attempting to make API call", e);
}
}
|
java
|
@SuppressWarnings("unchecked")
public <S extends Object, R extends Object> Response<R> executeQuery(final Query<S, R> query)
throws FreesoundClientException {
final HttpRequest request = buildHTTPRequest(query);
final String credential = buildAuthorisationCredential(query);
if (credential != null) {
request.header("Authorization", credential);
}
try {
if (query instanceof JSONResponseQuery) {
final HttpResponse<JsonNode> httpResponse = request.asJson();
final S responseBody = (S) httpResponse.getBody().getObject();
return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody);
} else if (query instanceof BinaryResponseQuery) {
final HttpResponse<InputStream> httpResponse = request.asBinary();
final S responseBody = (S) httpResponse.getBody();
return query.processResponse(httpResponse.getStatus(), httpResponse.getStatusText(), responseBody);
} else {
throw new FreesoundClientException(String.format("Unknown request type: %s", query.getClass()));
}
} catch (final ClassCastException | UnirestException e) {
throw new FreesoundClientException("Error when attempting to make API call", e);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"S",
"extends",
"Object",
",",
"R",
"extends",
"Object",
">",
"Response",
"<",
"R",
">",
"executeQuery",
"(",
"final",
"Query",
"<",
"S",
",",
"R",
">",
"query",
")",
"throws",
"FreesoundClientException",
"{",
"final",
"HttpRequest",
"request",
"=",
"buildHTTPRequest",
"(",
"query",
")",
";",
"final",
"String",
"credential",
"=",
"buildAuthorisationCredential",
"(",
"query",
")",
";",
"if",
"(",
"credential",
"!=",
"null",
")",
"{",
"request",
".",
"header",
"(",
"\"Authorization\"",
",",
"credential",
")",
";",
"}",
"try",
"{",
"if",
"(",
"query",
"instanceof",
"JSONResponseQuery",
")",
"{",
"final",
"HttpResponse",
"<",
"JsonNode",
">",
"httpResponse",
"=",
"request",
".",
"asJson",
"(",
")",
";",
"final",
"S",
"responseBody",
"=",
"(",
"S",
")",
"httpResponse",
".",
"getBody",
"(",
")",
".",
"getObject",
"(",
")",
";",
"return",
"query",
".",
"processResponse",
"(",
"httpResponse",
".",
"getStatus",
"(",
")",
",",
"httpResponse",
".",
"getStatusText",
"(",
")",
",",
"responseBody",
")",
";",
"}",
"else",
"if",
"(",
"query",
"instanceof",
"BinaryResponseQuery",
")",
"{",
"final",
"HttpResponse",
"<",
"InputStream",
">",
"httpResponse",
"=",
"request",
".",
"asBinary",
"(",
")",
";",
"final",
"S",
"responseBody",
"=",
"(",
"S",
")",
"httpResponse",
".",
"getBody",
"(",
")",
";",
"return",
"query",
".",
"processResponse",
"(",
"httpResponse",
".",
"getStatus",
"(",
")",
",",
"httpResponse",
".",
"getStatusText",
"(",
")",
",",
"responseBody",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"FreesoundClientException",
"(",
"String",
".",
"format",
"(",
"\"Unknown request type: %s\"",
",",
"query",
".",
"getClass",
"(",
")",
")",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"ClassCastException",
"|",
"UnirestException",
"e",
")",
"{",
"throw",
"new",
"FreesoundClientException",
"(",
"\"Error when attempting to make API call\"",
",",
"e",
")",
";",
"}",
"}"
] |
Execute a given query (synchronously) against the freesound API.
@param <S> The expected response type from the query
@param <R> The response type to return
@param query The query to execute
@return The result of the query
@throws FreesoundClientException Any errors encountered when performing API call
|
[
"Execute",
"a",
"given",
"query",
"(",
"synchronously",
")",
"against",
"the",
"freesound",
"API",
"."
] |
train
|
https://github.com/Sonoport/freesound-java/blob/ab029e25de068c6f8cc028bc7f916938fd97c036/src/main/java/com/sonoport/freesound/FreesoundClient.java#L107-L134
|
google/j2objc
|
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UTF16.java
|
UTF16.setCharAt
|
public static void setCharAt(StringBuffer target, int offset16, int char32) {
"""
Set a code point into a UTF16 position. Adjusts target according if we are replacing a
non-supplementary codepoint with a supplementary and vice versa.
@param target Stringbuffer
@param offset16 UTF16 position to insert into
@param char32 Code point
"""
int count = 1;
char single = target.charAt(offset16);
if (isSurrogate(single)) {
// pairs of the surrogate with offset16 at the lead char found
if (isLeadSurrogate(single) && (target.length() > offset16 + 1)
&& isTrailSurrogate(target.charAt(offset16 + 1))) {
count++;
} else {
// pairs of the surrogate with offset16 at the trail char
// found
if (isTrailSurrogate(single) && (offset16 > 0)
&& isLeadSurrogate(target.charAt(offset16 - 1))) {
offset16--;
count++;
}
}
}
target.replace(offset16, offset16 + count, valueOf(char32));
}
|
java
|
public static void setCharAt(StringBuffer target, int offset16, int char32) {
int count = 1;
char single = target.charAt(offset16);
if (isSurrogate(single)) {
// pairs of the surrogate with offset16 at the lead char found
if (isLeadSurrogate(single) && (target.length() > offset16 + 1)
&& isTrailSurrogate(target.charAt(offset16 + 1))) {
count++;
} else {
// pairs of the surrogate with offset16 at the trail char
// found
if (isTrailSurrogate(single) && (offset16 > 0)
&& isLeadSurrogate(target.charAt(offset16 - 1))) {
offset16--;
count++;
}
}
}
target.replace(offset16, offset16 + count, valueOf(char32));
}
|
[
"public",
"static",
"void",
"setCharAt",
"(",
"StringBuffer",
"target",
",",
"int",
"offset16",
",",
"int",
"char32",
")",
"{",
"int",
"count",
"=",
"1",
";",
"char",
"single",
"=",
"target",
".",
"charAt",
"(",
"offset16",
")",
";",
"if",
"(",
"isSurrogate",
"(",
"single",
")",
")",
"{",
"// pairs of the surrogate with offset16 at the lead char found",
"if",
"(",
"isLeadSurrogate",
"(",
"single",
")",
"&&",
"(",
"target",
".",
"length",
"(",
")",
">",
"offset16",
"+",
"1",
")",
"&&",
"isTrailSurrogate",
"(",
"target",
".",
"charAt",
"(",
"offset16",
"+",
"1",
")",
")",
")",
"{",
"count",
"++",
";",
"}",
"else",
"{",
"// pairs of the surrogate with offset16 at the trail char",
"// found",
"if",
"(",
"isTrailSurrogate",
"(",
"single",
")",
"&&",
"(",
"offset16",
">",
"0",
")",
"&&",
"isLeadSurrogate",
"(",
"target",
".",
"charAt",
"(",
"offset16",
"-",
"1",
")",
")",
")",
"{",
"offset16",
"--",
";",
"count",
"++",
";",
"}",
"}",
"}",
"target",
".",
"replace",
"(",
"offset16",
",",
"offset16",
"+",
"count",
",",
"valueOf",
"(",
"char32",
")",
")",
";",
"}"
] |
Set a code point into a UTF16 position. Adjusts target according if we are replacing a
non-supplementary codepoint with a supplementary and vice versa.
@param target Stringbuffer
@param offset16 UTF16 position to insert into
@param char32 Code point
|
[
"Set",
"a",
"code",
"point",
"into",
"a",
"UTF16",
"position",
".",
"Adjusts",
"target",
"according",
"if",
"we",
"are",
"replacing",
"a",
"non",
"-",
"supplementary",
"codepoint",
"with",
"a",
"supplementary",
"and",
"vice",
"versa",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UTF16.java#L1082-L1102
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/runtime/impl/RemoteConsumerTransmit.java
|
RemoteConsumerTransmit.getCurrentMaxIndoubtMessages
|
public int getCurrentMaxIndoubtMessages(int priority, int COS) {
"""
The anycast protocol contains no indoubt messages
@see com.ibm.ws.sib.processor.runtime.SIMPDeliveryStreamSetTransmitControllable#getCurrentMaxIndoubtMessages(int, int)
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getCurrentMaxIndoubtMessages", new Object[]{new Integer(priority), new Integer(COS)});
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getCurrentMaxIndoubtMessages");
return 0;
}
|
java
|
public int getCurrentMaxIndoubtMessages(int priority, int COS)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getCurrentMaxIndoubtMessages", new Object[]{new Integer(priority), new Integer(COS)});
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getCurrentMaxIndoubtMessages");
return 0;
}
|
[
"public",
"int",
"getCurrentMaxIndoubtMessages",
"(",
"int",
"priority",
",",
"int",
"COS",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"tc",
",",
"\"getCurrentMaxIndoubtMessages\"",
",",
"new",
"Object",
"[",
"]",
"{",
"new",
"Integer",
"(",
"priority",
")",
",",
"new",
"Integer",
"(",
"COS",
")",
"}",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"tc",
",",
"\"getCurrentMaxIndoubtMessages\"",
")",
";",
"return",
"0",
";",
"}"
] |
The anycast protocol contains no indoubt messages
@see com.ibm.ws.sib.processor.runtime.SIMPDeliveryStreamSetTransmitControllable#getCurrentMaxIndoubtMessages(int, int)
|
[
"The",
"anycast",
"protocol",
"contains",
"no",
"indoubt",
"messages"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/runtime/impl/RemoteConsumerTransmit.java#L124-L131
|
cdk/cdk
|
app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java
|
DepictionGenerator.withSize
|
public DepictionGenerator withSize(double w, double h) {
"""
Specify a desired size of depiction. The units depend on the output format with
raster images using pixels and vector graphics using millimeters. By default depictions
are only ever made smaller if you would also like to make depictions fill all available
space use the {@link #withFillToFit()} option.
Currently the size must either both be precisely specified (e.g. 256x256) or
automatic (e.g. {@link #AUTOMATIC}x{@link #AUTOMATIC}) you cannot for example
specify a fixed height and automatic width.
@param w max width
@param h max height
@return new generator for method chaining
@see #withFillToFit()
"""
if (w < 0 && h >= 0 || h < 0 && w >= 0)
throw new IllegalArgumentException("Width and height must either both be automatic or both specified");
DepictionGenerator copy = new DepictionGenerator(this);
copy.dimensions = w == AUTOMATIC ? Dimensions.AUTOMATIC : new Dimensions(w, h);
return copy;
}
|
java
|
public DepictionGenerator withSize(double w, double h) {
if (w < 0 && h >= 0 || h < 0 && w >= 0)
throw new IllegalArgumentException("Width and height must either both be automatic or both specified");
DepictionGenerator copy = new DepictionGenerator(this);
copy.dimensions = w == AUTOMATIC ? Dimensions.AUTOMATIC : new Dimensions(w, h);
return copy;
}
|
[
"public",
"DepictionGenerator",
"withSize",
"(",
"double",
"w",
",",
"double",
"h",
")",
"{",
"if",
"(",
"w",
"<",
"0",
"&&",
"h",
">=",
"0",
"||",
"h",
"<",
"0",
"&&",
"w",
">=",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Width and height must either both be automatic or both specified\"",
")",
";",
"DepictionGenerator",
"copy",
"=",
"new",
"DepictionGenerator",
"(",
"this",
")",
";",
"copy",
".",
"dimensions",
"=",
"w",
"==",
"AUTOMATIC",
"?",
"Dimensions",
".",
"AUTOMATIC",
":",
"new",
"Dimensions",
"(",
"w",
",",
"h",
")",
";",
"return",
"copy",
";",
"}"
] |
Specify a desired size of depiction. The units depend on the output format with
raster images using pixels and vector graphics using millimeters. By default depictions
are only ever made smaller if you would also like to make depictions fill all available
space use the {@link #withFillToFit()} option.
Currently the size must either both be precisely specified (e.g. 256x256) or
automatic (e.g. {@link #AUTOMATIC}x{@link #AUTOMATIC}) you cannot for example
specify a fixed height and automatic width.
@param w max width
@param h max height
@return new generator for method chaining
@see #withFillToFit()
|
[
"Specify",
"a",
"desired",
"size",
"of",
"depiction",
".",
"The",
"units",
"depend",
"on",
"the",
"output",
"format",
"with",
"raster",
"images",
"using",
"pixels",
"and",
"vector",
"graphics",
"using",
"millimeters",
".",
"By",
"default",
"depictions",
"are",
"only",
"ever",
"made",
"smaller",
"if",
"you",
"would",
"also",
"like",
"to",
"make",
"depictions",
"fill",
"all",
"available",
"space",
"use",
"the",
"{",
"@link",
"#withFillToFit",
"()",
"}",
"option",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java#L1000-L1006
|
52inc/android-52Kit
|
library-winds/src/main/java/com/ftinc/kit/winds/Winds.java
|
Winds.openChangelogDialog
|
public static void openChangelogDialog(Activity ctx, @XmlRes int configId) {
"""
Open the changelog dialog
@param ctx the activity to launch the dialog fragment with
@param configId the changelog configuration resource id
"""
ChangeLogDialog dialog = ChangeLogDialog.createInstance(configId);
dialog.show(ctx.getFragmentManager(), null);
}
|
java
|
public static void openChangelogDialog(Activity ctx, @XmlRes int configId){
ChangeLogDialog dialog = ChangeLogDialog.createInstance(configId);
dialog.show(ctx.getFragmentManager(), null);
}
|
[
"public",
"static",
"void",
"openChangelogDialog",
"(",
"Activity",
"ctx",
",",
"@",
"XmlRes",
"int",
"configId",
")",
"{",
"ChangeLogDialog",
"dialog",
"=",
"ChangeLogDialog",
".",
"createInstance",
"(",
"configId",
")",
";",
"dialog",
".",
"show",
"(",
"ctx",
".",
"getFragmentManager",
"(",
")",
",",
"null",
")",
";",
"}"
] |
Open the changelog dialog
@param ctx the activity to launch the dialog fragment with
@param configId the changelog configuration resource id
|
[
"Open",
"the",
"changelog",
"dialog"
] |
train
|
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library-winds/src/main/java/com/ftinc/kit/winds/Winds.java#L101-L104
|
orbisgis/h2gis
|
h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/SunCalc.java
|
SunCalc.getPosition
|
public static Coordinate getPosition(Date date, double lat,
double lng) {
"""
Returns the sun position as a coordinate with the following properties
x: sun azimuth in radians (direction along the horizon, measured from south to
west), e.g. 0 is south and Math.PI * 3/4 is northwest.
y: sun altitude above the horizon in radians, e.g. 0 at the
horizon and PI/2 at the zenith (straight over your head).
@param date
@param lat
@param lng
@return
"""
if (isGeographic(lat, lng)) {
double lw = rad * -lng;
double phi = rad * lat;
double J = dateToJulianDate(date);
double M = getSolarMeanAnomaly(J);
double C = getEquationOfCenter(M);
double Ls = getEclipticLongitude(M, C);
double d = getSunDeclination(Ls);
double a = getRightAscension(Ls);
double th = getSiderealTime(J, lw);
double H = th - a;
return new Coordinate(getAzimuth(H, phi, d),getAltitude(H, phi, d));
} else {
throw new IllegalArgumentException("The coordinate of the point must in latitude and longitude.");
}
}
|
java
|
public static Coordinate getPosition(Date date, double lat,
double lng) {
if (isGeographic(lat, lng)) {
double lw = rad * -lng;
double phi = rad * lat;
double J = dateToJulianDate(date);
double M = getSolarMeanAnomaly(J);
double C = getEquationOfCenter(M);
double Ls = getEclipticLongitude(M, C);
double d = getSunDeclination(Ls);
double a = getRightAscension(Ls);
double th = getSiderealTime(J, lw);
double H = th - a;
return new Coordinate(getAzimuth(H, phi, d),getAltitude(H, phi, d));
} else {
throw new IllegalArgumentException("The coordinate of the point must in latitude and longitude.");
}
}
|
[
"public",
"static",
"Coordinate",
"getPosition",
"(",
"Date",
"date",
",",
"double",
"lat",
",",
"double",
"lng",
")",
"{",
"if",
"(",
"isGeographic",
"(",
"lat",
",",
"lng",
")",
")",
"{",
"double",
"lw",
"=",
"rad",
"*",
"-",
"lng",
";",
"double",
"phi",
"=",
"rad",
"*",
"lat",
";",
"double",
"J",
"=",
"dateToJulianDate",
"(",
"date",
")",
";",
"double",
"M",
"=",
"getSolarMeanAnomaly",
"(",
"J",
")",
";",
"double",
"C",
"=",
"getEquationOfCenter",
"(",
"M",
")",
";",
"double",
"Ls",
"=",
"getEclipticLongitude",
"(",
"M",
",",
"C",
")",
";",
"double",
"d",
"=",
"getSunDeclination",
"(",
"Ls",
")",
";",
"double",
"a",
"=",
"getRightAscension",
"(",
"Ls",
")",
";",
"double",
"th",
"=",
"getSiderealTime",
"(",
"J",
",",
"lw",
")",
";",
"double",
"H",
"=",
"th",
"-",
"a",
";",
"return",
"new",
"Coordinate",
"(",
"getAzimuth",
"(",
"H",
",",
"phi",
",",
"d",
")",
",",
"getAltitude",
"(",
"H",
",",
"phi",
",",
"d",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The coordinate of the point must in latitude and longitude.\"",
")",
";",
"}",
"}"
] |
Returns the sun position as a coordinate with the following properties
x: sun azimuth in radians (direction along the horizon, measured from south to
west), e.g. 0 is south and Math.PI * 3/4 is northwest.
y: sun altitude above the horizon in radians, e.g. 0 at the
horizon and PI/2 at the zenith (straight over your head).
@param date
@param lat
@param lng
@return
|
[
"Returns",
"the",
"sun",
"position",
"as",
"a",
"coordinate",
"with",
"the",
"following",
"properties"
] |
train
|
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/SunCalc.java#L155-L172
|
jferard/fastods
|
fastods/src/main/java/com/github/jferard/fastods/ParagraphBuilder.java
|
ParagraphBuilder.styledSpan
|
public ParagraphBuilder styledSpan(final String text, final TextStyle ts) {
"""
Create a styled span with a text content
@param text the text
@param ts the style
@return this for fluent style
"""
final ParagraphElement paragraphElement = new Span(text, ts);
this.paragraphElements.add(paragraphElement);
return this;
}
|
java
|
public ParagraphBuilder styledSpan(final String text, final TextStyle ts) {
final ParagraphElement paragraphElement = new Span(text, ts);
this.paragraphElements.add(paragraphElement);
return this;
}
|
[
"public",
"ParagraphBuilder",
"styledSpan",
"(",
"final",
"String",
"text",
",",
"final",
"TextStyle",
"ts",
")",
"{",
"final",
"ParagraphElement",
"paragraphElement",
"=",
"new",
"Span",
"(",
"text",
",",
"ts",
")",
";",
"this",
".",
"paragraphElements",
".",
"add",
"(",
"paragraphElement",
")",
";",
"return",
"this",
";",
"}"
] |
Create a styled span with a text content
@param text the text
@param ts the style
@return this for fluent style
|
[
"Create",
"a",
"styled",
"span",
"with",
"a",
"text",
"content"
] |
train
|
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/ParagraphBuilder.java#L183-L187
|
r0adkll/PostOffice
|
library/src/main/java/com/r0adkll/postoffice/PostOffice.java
|
PostOffice.newAlertMail
|
public static Delivery newAlertMail(@NotNull Context ctx, @NotNull CharSequence title, @NotNull CharSequence message) {
"""
Create a new AlertDialog 'Mail' delivery to display
@param ctx the application context
@param title the dialog title
@param message the dialog message
@return the delivery
"""
// Create the delivery builder
Delivery.Builder builder = newMail(ctx)
.setTitle(title)
.setMessage(message);
// Return the delivery
return builder.build();
}
|
java
|
public static Delivery newAlertMail(@NotNull Context ctx, @NotNull CharSequence title, @NotNull CharSequence message){
// Create the delivery builder
Delivery.Builder builder = newMail(ctx)
.setTitle(title)
.setMessage(message);
// Return the delivery
return builder.build();
}
|
[
"public",
"static",
"Delivery",
"newAlertMail",
"(",
"@",
"NotNull",
"Context",
"ctx",
",",
"@",
"NotNull",
"CharSequence",
"title",
",",
"@",
"NotNull",
"CharSequence",
"message",
")",
"{",
"// Create the delivery builder",
"Delivery",
".",
"Builder",
"builder",
"=",
"newMail",
"(",
"ctx",
")",
".",
"setTitle",
"(",
"title",
")",
".",
"setMessage",
"(",
"message",
")",
";",
"// Return the delivery",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] |
Create a new AlertDialog 'Mail' delivery to display
@param ctx the application context
@param title the dialog title
@param message the dialog message
@return the delivery
|
[
"Create",
"a",
"new",
"AlertDialog",
"Mail",
"delivery",
"to",
"display"
] |
train
|
https://github.com/r0adkll/PostOffice/blob/f98e365fd66c004ccce64ee87d9f471b97e4e3c2/library/src/main/java/com/r0adkll/postoffice/PostOffice.java#L100-L108
|
orbisgis/h2gis
|
h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java
|
GeometryCoordinateDimension.convert
|
public static MultiPolygon convert(MultiPolygon multiPolygon,int dimension) {
"""
Force the dimension of the MultiPolygon and update correctly the coordinate
dimension
@param multiPolygon
@param dimension
@return
"""
int nb = multiPolygon.getNumGeometries();
final Polygon[] pl = new Polygon[nb];
for (int i = 0; i < nb; i++) {
pl[i] = GeometryCoordinateDimension.convert((Polygon) multiPolygon.getGeometryN(i),dimension);
}
return gf.createMultiPolygon(pl);
}
|
java
|
public static MultiPolygon convert(MultiPolygon multiPolygon,int dimension) {
int nb = multiPolygon.getNumGeometries();
final Polygon[] pl = new Polygon[nb];
for (int i = 0; i < nb; i++) {
pl[i] = GeometryCoordinateDimension.convert((Polygon) multiPolygon.getGeometryN(i),dimension);
}
return gf.createMultiPolygon(pl);
}
|
[
"public",
"static",
"MultiPolygon",
"convert",
"(",
"MultiPolygon",
"multiPolygon",
",",
"int",
"dimension",
")",
"{",
"int",
"nb",
"=",
"multiPolygon",
".",
"getNumGeometries",
"(",
")",
";",
"final",
"Polygon",
"[",
"]",
"pl",
"=",
"new",
"Polygon",
"[",
"nb",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nb",
";",
"i",
"++",
")",
"{",
"pl",
"[",
"i",
"]",
"=",
"GeometryCoordinateDimension",
".",
"convert",
"(",
"(",
"Polygon",
")",
"multiPolygon",
".",
"getGeometryN",
"(",
"i",
")",
",",
"dimension",
")",
";",
"}",
"return",
"gf",
".",
"createMultiPolygon",
"(",
"pl",
")",
";",
"}"
] |
Force the dimension of the MultiPolygon and update correctly the coordinate
dimension
@param multiPolygon
@param dimension
@return
|
[
"Force",
"the",
"dimension",
"of",
"the",
"MultiPolygon",
"and",
"update",
"correctly",
"the",
"coordinate",
"dimension"
] |
train
|
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/GeometryCoordinateDimension.java#L94-L101
|
elki-project/elki
|
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java
|
DiSH.weightedDistance
|
protected static double weightedDistance(NumberVector v1, NumberVector v2, long[] weightVector) {
"""
Computes the weighted distance between the two specified vectors according
to the given preference vector.
@param v1 the first vector
@param v2 the second vector
@param weightVector the preference vector
@return the weighted distance between the two specified vectors according
to the given preference vector
"""
double sqrDist = 0;
for(int i = BitsUtil.nextSetBit(weightVector, 0); i >= 0; i = BitsUtil.nextSetBit(weightVector, i + 1)) {
double manhattanI = v1.doubleValue(i) - v2.doubleValue(i);
sqrDist += manhattanI * manhattanI;
}
return FastMath.sqrt(sqrDist);
}
|
java
|
protected static double weightedDistance(NumberVector v1, NumberVector v2, long[] weightVector) {
double sqrDist = 0;
for(int i = BitsUtil.nextSetBit(weightVector, 0); i >= 0; i = BitsUtil.nextSetBit(weightVector, i + 1)) {
double manhattanI = v1.doubleValue(i) - v2.doubleValue(i);
sqrDist += manhattanI * manhattanI;
}
return FastMath.sqrt(sqrDist);
}
|
[
"protected",
"static",
"double",
"weightedDistance",
"(",
"NumberVector",
"v1",
",",
"NumberVector",
"v2",
",",
"long",
"[",
"]",
"weightVector",
")",
"{",
"double",
"sqrDist",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"BitsUtil",
".",
"nextSetBit",
"(",
"weightVector",
",",
"0",
")",
";",
"i",
">=",
"0",
";",
"i",
"=",
"BitsUtil",
".",
"nextSetBit",
"(",
"weightVector",
",",
"i",
"+",
"1",
")",
")",
"{",
"double",
"manhattanI",
"=",
"v1",
".",
"doubleValue",
"(",
"i",
")",
"-",
"v2",
".",
"doubleValue",
"(",
"i",
")",
";",
"sqrDist",
"+=",
"manhattanI",
"*",
"manhattanI",
";",
"}",
"return",
"FastMath",
".",
"sqrt",
"(",
"sqrDist",
")",
";",
"}"
] |
Computes the weighted distance between the two specified vectors according
to the given preference vector.
@param v1 the first vector
@param v2 the second vector
@param weightVector the preference vector
@return the weighted distance between the two specified vectors according
to the given preference vector
|
[
"Computes",
"the",
"weighted",
"distance",
"between",
"the",
"two",
"specified",
"vectors",
"according",
"to",
"the",
"given",
"preference",
"vector",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java#L601-L608
|
cdk/cdk
|
base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java
|
AtomContainerManipulator.extractSubstructure
|
public static IAtomContainer extractSubstructure(IAtomContainer atomContainer, int... atomIndices)
throws CloneNotSupportedException {
"""
Extract a substructure from an atom container, in the form of a new
cloned atom container with only the atoms with indices in atomIndices and
bonds that connect these atoms.
Note that this may result in a disconnected atom container.
@param atomContainer the source container to extract from
@param atomIndices the indices of the substructure
@return a cloned atom container with a substructure of the source
@throws CloneNotSupportedException if the source container cannot be cloned
"""
IAtomContainer substructure = (IAtomContainer) atomContainer.clone();
int numberOfAtoms = substructure.getAtomCount();
IAtom[] atoms = new IAtom[numberOfAtoms];
for (int atomIndex = 0; atomIndex < numberOfAtoms; atomIndex++) {
atoms[atomIndex] = substructure.getAtom(atomIndex);
}
Arrays.sort(atomIndices);
for (int index = 0; index < numberOfAtoms; index++) {
if (Arrays.binarySearch(atomIndices, index) < 0) {
IAtom atom = atoms[index];
substructure.removeAtom(atom);
}
}
return substructure;
}
|
java
|
public static IAtomContainer extractSubstructure(IAtomContainer atomContainer, int... atomIndices)
throws CloneNotSupportedException {
IAtomContainer substructure = (IAtomContainer) atomContainer.clone();
int numberOfAtoms = substructure.getAtomCount();
IAtom[] atoms = new IAtom[numberOfAtoms];
for (int atomIndex = 0; atomIndex < numberOfAtoms; atomIndex++) {
atoms[atomIndex] = substructure.getAtom(atomIndex);
}
Arrays.sort(atomIndices);
for (int index = 0; index < numberOfAtoms; index++) {
if (Arrays.binarySearch(atomIndices, index) < 0) {
IAtom atom = atoms[index];
substructure.removeAtom(atom);
}
}
return substructure;
}
|
[
"public",
"static",
"IAtomContainer",
"extractSubstructure",
"(",
"IAtomContainer",
"atomContainer",
",",
"int",
"...",
"atomIndices",
")",
"throws",
"CloneNotSupportedException",
"{",
"IAtomContainer",
"substructure",
"=",
"(",
"IAtomContainer",
")",
"atomContainer",
".",
"clone",
"(",
")",
";",
"int",
"numberOfAtoms",
"=",
"substructure",
".",
"getAtomCount",
"(",
")",
";",
"IAtom",
"[",
"]",
"atoms",
"=",
"new",
"IAtom",
"[",
"numberOfAtoms",
"]",
";",
"for",
"(",
"int",
"atomIndex",
"=",
"0",
";",
"atomIndex",
"<",
"numberOfAtoms",
";",
"atomIndex",
"++",
")",
"{",
"atoms",
"[",
"atomIndex",
"]",
"=",
"substructure",
".",
"getAtom",
"(",
"atomIndex",
")",
";",
"}",
"Arrays",
".",
"sort",
"(",
"atomIndices",
")",
";",
"for",
"(",
"int",
"index",
"=",
"0",
";",
"index",
"<",
"numberOfAtoms",
";",
"index",
"++",
")",
"{",
"if",
"(",
"Arrays",
".",
"binarySearch",
"(",
"atomIndices",
",",
"index",
")",
"<",
"0",
")",
"{",
"IAtom",
"atom",
"=",
"atoms",
"[",
"index",
"]",
";",
"substructure",
".",
"removeAtom",
"(",
"atom",
")",
";",
"}",
"}",
"return",
"substructure",
";",
"}"
] |
Extract a substructure from an atom container, in the form of a new
cloned atom container with only the atoms with indices in atomIndices and
bonds that connect these atoms.
Note that this may result in a disconnected atom container.
@param atomContainer the source container to extract from
@param atomIndices the indices of the substructure
@return a cloned atom container with a substructure of the source
@throws CloneNotSupportedException if the source container cannot be cloned
|
[
"Extract",
"a",
"substructure",
"from",
"an",
"atom",
"container",
"in",
"the",
"form",
"of",
"a",
"new",
"cloned",
"atom",
"container",
"with",
"only",
"the",
"atoms",
"with",
"indices",
"in",
"atomIndices",
"and",
"bonds",
"that",
"connect",
"these",
"atoms",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/tools/manipulator/AtomContainerManipulator.java#L138-L156
|
alkacon/opencms-core
|
src/org/opencms/ui/components/categoryselect/CmsCategorySelectDialog.java
|
CmsCategorySelectDialog.filterTree
|
void filterTree(String filter) {
"""
Adds a filter to the category tree container.<p>
@param filter the filter to add
"""
HierarchicalContainer container = (HierarchicalContainer)m_tree.getContainerDataSource();
container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
final String lowerCaseFilter = filter.toLowerCase();
container.addContainerFilter(new Filter() {
private static final long serialVersionUID = 1L;
public boolean appliesToProperty(Object propertyId) {
return true;
}
public boolean passesFilter(Object itemId, Item item) throws UnsupportedOperationException {
CmsCategory cat = (CmsCategory)itemId;
return cat.getPath().toLowerCase().contains(lowerCaseFilter)
|| ((cat.getTitle() != null) && cat.getTitle().toLowerCase().contains(lowerCaseFilter));
}
});
}
}
|
java
|
void filterTree(String filter) {
HierarchicalContainer container = (HierarchicalContainer)m_tree.getContainerDataSource();
container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
final String lowerCaseFilter = filter.toLowerCase();
container.addContainerFilter(new Filter() {
private static final long serialVersionUID = 1L;
public boolean appliesToProperty(Object propertyId) {
return true;
}
public boolean passesFilter(Object itemId, Item item) throws UnsupportedOperationException {
CmsCategory cat = (CmsCategory)itemId;
return cat.getPath().toLowerCase().contains(lowerCaseFilter)
|| ((cat.getTitle() != null) && cat.getTitle().toLowerCase().contains(lowerCaseFilter));
}
});
}
}
|
[
"void",
"filterTree",
"(",
"String",
"filter",
")",
"{",
"HierarchicalContainer",
"container",
"=",
"(",
"HierarchicalContainer",
")",
"m_tree",
".",
"getContainerDataSource",
"(",
")",
";",
"container",
".",
"removeAllContainerFilters",
"(",
")",
";",
"if",
"(",
"CmsStringUtil",
".",
"isNotEmptyOrWhitespaceOnly",
"(",
"filter",
")",
")",
"{",
"final",
"String",
"lowerCaseFilter",
"=",
"filter",
".",
"toLowerCase",
"(",
")",
";",
"container",
".",
"addContainerFilter",
"(",
"new",
"Filter",
"(",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"public",
"boolean",
"appliesToProperty",
"(",
"Object",
"propertyId",
")",
"{",
"return",
"true",
";",
"}",
"public",
"boolean",
"passesFilter",
"(",
"Object",
"itemId",
",",
"Item",
"item",
")",
"throws",
"UnsupportedOperationException",
"{",
"CmsCategory",
"cat",
"=",
"(",
"CmsCategory",
")",
"itemId",
";",
"return",
"cat",
".",
"getPath",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"contains",
"(",
"lowerCaseFilter",
")",
"||",
"(",
"(",
"cat",
".",
"getTitle",
"(",
")",
"!=",
"null",
")",
"&&",
"cat",
".",
"getTitle",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"contains",
"(",
"lowerCaseFilter",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Adds a filter to the category tree container.<p>
@param filter the filter to add
|
[
"Adds",
"a",
"filter",
"to",
"the",
"category",
"tree",
"container",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/categoryselect/CmsCategorySelectDialog.java#L147-L171
|
EXIficient/exificient-core
|
src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java
|
BitOutputStream.writeDirectBytes
|
protected void writeDirectBytes(byte[] b, int off, int len)
throws IOException {
"""
Ignore current buffer, and write a sequence of bytes directly to the
underlying stream.
@param b
byte array
@param off
byte array offset
@param len
byte array length
@throws IOException
IO exception
"""
ostream.write(b, off, len);
len += len;
}
|
java
|
protected void writeDirectBytes(byte[] b, int off, int len)
throws IOException {
ostream.write(b, off, len);
len += len;
}
|
[
"protected",
"void",
"writeDirectBytes",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"ostream",
".",
"write",
"(",
"b",
",",
"off",
",",
"len",
")",
";",
"len",
"+=",
"len",
";",
"}"
] |
Ignore current buffer, and write a sequence of bytes directly to the
underlying stream.
@param b
byte array
@param off
byte array offset
@param len
byte array length
@throws IOException
IO exception
|
[
"Ignore",
"current",
"buffer",
"and",
"write",
"a",
"sequence",
"of",
"bytes",
"directly",
"to",
"the",
"underlying",
"stream",
"."
] |
train
|
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java#L261-L265
|
looly/hutool
|
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
|
NumberUtil.isGreater
|
public static boolean isGreater(BigDecimal bigNum1, BigDecimal bigNum2) {
"""
比较大小,参数1 > 参数2 返回true
@param bigNum1 数字1
@param bigNum2 数字2
@return 是否大于
@since 3,0.9
"""
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) > 0;
}
|
java
|
public static boolean isGreater(BigDecimal bigNum1, BigDecimal bigNum2) {
Assert.notNull(bigNum1);
Assert.notNull(bigNum2);
return bigNum1.compareTo(bigNum2) > 0;
}
|
[
"public",
"static",
"boolean",
"isGreater",
"(",
"BigDecimal",
"bigNum1",
",",
"BigDecimal",
"bigNum2",
")",
"{",
"Assert",
".",
"notNull",
"(",
"bigNum1",
")",
";",
"Assert",
".",
"notNull",
"(",
"bigNum2",
")",
";",
"return",
"bigNum1",
".",
"compareTo",
"(",
"bigNum2",
")",
">",
"0",
";",
"}"
] |
比较大小,参数1 > 参数2 返回true
@param bigNum1 数字1
@param bigNum2 数字2
@return 是否大于
@since 3,0.9
|
[
"比较大小,参数1",
">",
";",
"参数2",
"返回true"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L1622-L1626
|
youngmonkeys/ezyfox-sfs2x
|
src/main/java/com/tvd12/ezyfox/sfs2x/data/impl/SimpleTransformer.java
|
SimpleTransformer.transformObject
|
protected SFSDataWrapper transformObject(Object value) {
"""
Transform a java pojo object to sfsobject
@param value pojo java object
@return a SFSDataWrapper object
"""
ResponseParamsClass struct = null;
if(context != null) struct = context.getResponseParamsClass(value.getClass());
if(struct == null) struct = new ResponseParamsClass(value.getClass());
ISFSObject sfsObject = new ResponseParamSerializer().object2params(struct, value);
return new SFSDataWrapper(SFSDataType.SFS_OBJECT, sfsObject);
}
|
java
|
protected SFSDataWrapper transformObject(Object value) {
ResponseParamsClass struct = null;
if(context != null) struct = context.getResponseParamsClass(value.getClass());
if(struct == null) struct = new ResponseParamsClass(value.getClass());
ISFSObject sfsObject = new ResponseParamSerializer().object2params(struct, value);
return new SFSDataWrapper(SFSDataType.SFS_OBJECT, sfsObject);
}
|
[
"protected",
"SFSDataWrapper",
"transformObject",
"(",
"Object",
"value",
")",
"{",
"ResponseParamsClass",
"struct",
"=",
"null",
";",
"if",
"(",
"context",
"!=",
"null",
")",
"struct",
"=",
"context",
".",
"getResponseParamsClass",
"(",
"value",
".",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"struct",
"==",
"null",
")",
"struct",
"=",
"new",
"ResponseParamsClass",
"(",
"value",
".",
"getClass",
"(",
")",
")",
";",
"ISFSObject",
"sfsObject",
"=",
"new",
"ResponseParamSerializer",
"(",
")",
".",
"object2params",
"(",
"struct",
",",
"value",
")",
";",
"return",
"new",
"SFSDataWrapper",
"(",
"SFSDataType",
".",
"SFS_OBJECT",
",",
"sfsObject",
")",
";",
"}"
] |
Transform a java pojo object to sfsobject
@param value pojo java object
@return a SFSDataWrapper object
|
[
"Transform",
"a",
"java",
"pojo",
"object",
"to",
"sfsobject"
] |
train
|
https://github.com/youngmonkeys/ezyfox-sfs2x/blob/7e004033a3b551c3ae970a0c8f45db7b1ec144de/src/main/java/com/tvd12/ezyfox/sfs2x/data/impl/SimpleTransformer.java#L128-L134
|
alkacon/opencms-core
|
src/org/opencms/xml/page/CmsXmlPage.java
|
CmsXmlPage.renameValue
|
public void renameValue(String oldValue, String newValue, Locale locale) throws CmsIllegalArgumentException {
"""
Renames the page-element value from the old to the new one.<p>
@param oldValue the old value
@param newValue the new value
@param locale the locale
@throws CmsIllegalArgumentException if the name contains an index ("[<number>]"), the new value for the
given locale already exists in the xmlpage or the the old value does not exist for the locale in the xmlpage.
"""
CmsXmlHtmlValue oldXmlHtmlValue = (CmsXmlHtmlValue)getValue(oldValue, locale);
if (oldXmlHtmlValue == null) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_NO_ELEM_FOR_LANG_2, oldValue, locale));
}
if (hasValue(newValue, locale)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_LANG_ELEM_EXISTS_2, newValue, locale));
}
if (newValue.indexOf('[') >= 0) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_CONTAINS_INDEX_1, newValue));
}
// get the element
Element element = oldXmlHtmlValue.getElement();
// update value of the element attribute 'NAME'
element.addAttribute(ATTRIBUTE_NAME, newValue);
// re-initialize the document to update the bookmarks
initDocument(m_document, m_encoding, getContentDefinition());
}
|
java
|
public void renameValue(String oldValue, String newValue, Locale locale) throws CmsIllegalArgumentException {
CmsXmlHtmlValue oldXmlHtmlValue = (CmsXmlHtmlValue)getValue(oldValue, locale);
if (oldXmlHtmlValue == null) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_NO_ELEM_FOR_LANG_2, oldValue, locale));
}
if (hasValue(newValue, locale)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_LANG_ELEM_EXISTS_2, newValue, locale));
}
if (newValue.indexOf('[') >= 0) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_XML_PAGE_CONTAINS_INDEX_1, newValue));
}
// get the element
Element element = oldXmlHtmlValue.getElement();
// update value of the element attribute 'NAME'
element.addAttribute(ATTRIBUTE_NAME, newValue);
// re-initialize the document to update the bookmarks
initDocument(m_document, m_encoding, getContentDefinition());
}
|
[
"public",
"void",
"renameValue",
"(",
"String",
"oldValue",
",",
"String",
"newValue",
",",
"Locale",
"locale",
")",
"throws",
"CmsIllegalArgumentException",
"{",
"CmsXmlHtmlValue",
"oldXmlHtmlValue",
"=",
"(",
"CmsXmlHtmlValue",
")",
"getValue",
"(",
"oldValue",
",",
"locale",
")",
";",
"if",
"(",
"oldXmlHtmlValue",
"==",
"null",
")",
"{",
"throw",
"new",
"CmsIllegalArgumentException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_XML_PAGE_NO_ELEM_FOR_LANG_2",
",",
"oldValue",
",",
"locale",
")",
")",
";",
"}",
"if",
"(",
"hasValue",
"(",
"newValue",
",",
"locale",
")",
")",
"{",
"throw",
"new",
"CmsIllegalArgumentException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_XML_PAGE_LANG_ELEM_EXISTS_2",
",",
"newValue",
",",
"locale",
")",
")",
";",
"}",
"if",
"(",
"newValue",
".",
"indexOf",
"(",
"'",
"'",
")",
">=",
"0",
")",
"{",
"throw",
"new",
"CmsIllegalArgumentException",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_XML_PAGE_CONTAINS_INDEX_1",
",",
"newValue",
")",
")",
";",
"}",
"// get the element",
"Element",
"element",
"=",
"oldXmlHtmlValue",
".",
"getElement",
"(",
")",
";",
"// update value of the element attribute 'NAME'",
"element",
".",
"addAttribute",
"(",
"ATTRIBUTE_NAME",
",",
"newValue",
")",
";",
"// re-initialize the document to update the bookmarks",
"initDocument",
"(",
"m_document",
",",
"m_encoding",
",",
"getContentDefinition",
"(",
")",
")",
";",
"}"
] |
Renames the page-element value from the old to the new one.<p>
@param oldValue the old value
@param newValue the new value
@param locale the locale
@throws CmsIllegalArgumentException if the name contains an index ("[<number>]"), the new value for the
given locale already exists in the xmlpage or the the old value does not exist for the locale in the xmlpage.
|
[
"Renames",
"the",
"page",
"-",
"element",
"value",
"from",
"the",
"old",
"to",
"the",
"new",
"one",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/page/CmsXmlPage.java#L371-L396
|
yshrsmz/KeyboardVisibilityEvent
|
keyboardvisibilityevent/src/main/java/net/yslibrary/android/keyboardvisibilityevent/util/UIUtil.java
|
UIUtil.showKeyboard
|
public static void showKeyboard(Context context, EditText target) {
"""
Show keyboard and focus to given EditText
@param context Context
@param target EditText to focus
"""
if (context == null || target == null) {
return;
}
InputMethodManager imm = getInputMethodManager(context);
imm.showSoftInput(target, InputMethodManager.SHOW_IMPLICIT);
}
|
java
|
public static void showKeyboard(Context context, EditText target) {
if (context == null || target == null) {
return;
}
InputMethodManager imm = getInputMethodManager(context);
imm.showSoftInput(target, InputMethodManager.SHOW_IMPLICIT);
}
|
[
"public",
"static",
"void",
"showKeyboard",
"(",
"Context",
"context",
",",
"EditText",
"target",
")",
"{",
"if",
"(",
"context",
"==",
"null",
"||",
"target",
"==",
"null",
")",
"{",
"return",
";",
"}",
"InputMethodManager",
"imm",
"=",
"getInputMethodManager",
"(",
"context",
")",
";",
"imm",
".",
"showSoftInput",
"(",
"target",
",",
"InputMethodManager",
".",
"SHOW_IMPLICIT",
")",
";",
"}"
] |
Show keyboard and focus to given EditText
@param context Context
@param target EditText to focus
|
[
"Show",
"keyboard",
"and",
"focus",
"to",
"given",
"EditText"
] |
train
|
https://github.com/yshrsmz/KeyboardVisibilityEvent/blob/fbde29a2c28ff1b2fa44f43cdd1ff3ec1d3321d8/keyboardvisibilityevent/src/main/java/net/yslibrary/android/keyboardvisibilityevent/util/UIUtil.java#L30-L38
|
spring-projects/spring-retry
|
src/main/java/org/springframework/classify/util/MethodInvokerUtils.java
|
MethodInvokerUtils.getMethodInvokerForSingleArgument
|
public static <C, T> MethodInvoker getMethodInvokerForSingleArgument(Object target) {
"""
Create a {@link MethodInvoker} for the delegate from a single public method.
@param target an object to search for an appropriate method
@return a MethodInvoker that calls a method on the delegate
@param <T> the t
@param <C> the C
"""
final AtomicReference<Method> methodHolder = new AtomicReference<Method>();
ReflectionUtils.doWithMethods(target.getClass(),
new ReflectionUtils.MethodCallback() {
public void doWith(Method method)
throws IllegalArgumentException, IllegalAccessException {
if ((method.getModifiers() & Modifier.PUBLIC) == 0
|| method.isBridge()) {
return;
}
if (method.getParameterTypes() == null
|| method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE)
|| ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
}
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);
}
|
java
|
public static <C, T> MethodInvoker getMethodInvokerForSingleArgument(Object target) {
final AtomicReference<Method> methodHolder = new AtomicReference<Method>();
ReflectionUtils.doWithMethods(target.getClass(),
new ReflectionUtils.MethodCallback() {
public void doWith(Method method)
throws IllegalArgumentException, IllegalAccessException {
if ((method.getModifiers() & Modifier.PUBLIC) == 0
|| method.isBridge()) {
return;
}
if (method.getParameterTypes() == null
|| method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE)
|| ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
}
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);
}
|
[
"public",
"static",
"<",
"C",
",",
"T",
">",
"MethodInvoker",
"getMethodInvokerForSingleArgument",
"(",
"Object",
"target",
")",
"{",
"final",
"AtomicReference",
"<",
"Method",
">",
"methodHolder",
"=",
"new",
"AtomicReference",
"<",
"Method",
">",
"(",
")",
";",
"ReflectionUtils",
".",
"doWithMethods",
"(",
"target",
".",
"getClass",
"(",
")",
",",
"new",
"ReflectionUtils",
".",
"MethodCallback",
"(",
")",
"{",
"public",
"void",
"doWith",
"(",
"Method",
"method",
")",
"throws",
"IllegalArgumentException",
",",
"IllegalAccessException",
"{",
"if",
"(",
"(",
"method",
".",
"getModifiers",
"(",
")",
"&",
"Modifier",
".",
"PUBLIC",
")",
"==",
"0",
"||",
"method",
".",
"isBridge",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"method",
".",
"getParameterTypes",
"(",
")",
"==",
"null",
"||",
"method",
".",
"getParameterTypes",
"(",
")",
".",
"length",
"!=",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"method",
".",
"getReturnType",
"(",
")",
".",
"equals",
"(",
"Void",
".",
"TYPE",
")",
"||",
"ReflectionUtils",
".",
"isEqualsMethod",
"(",
"method",
")",
")",
"{",
"return",
";",
"}",
"Assert",
".",
"state",
"(",
"methodHolder",
".",
"get",
"(",
")",
"==",
"null",
",",
"\"More than one non-void public method detected with single argument.\"",
")",
";",
"methodHolder",
".",
"set",
"(",
"method",
")",
";",
"}",
"}",
")",
";",
"Method",
"method",
"=",
"methodHolder",
".",
"get",
"(",
")",
";",
"return",
"new",
"SimpleMethodInvoker",
"(",
"target",
",",
"method",
")",
";",
"}"
] |
Create a {@link MethodInvoker} for the delegate from a single public method.
@param target an object to search for an appropriate method
@return a MethodInvoker that calls a method on the delegate
@param <T> the t
@param <C> the C
|
[
"Create",
"a",
"{"
] |
train
|
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/classify/util/MethodInvokerUtils.java#L212-L237
|
aaberg/sql2o
|
core/src/main/java/org/sql2o/Sql2o.java
|
Sql2o.createQuery
|
@Deprecated
public Query createQuery(String query, boolean returnGeneratedKeys) {
"""
Creates a {@link Query}
@param query the sql query string
@param returnGeneratedKeys boolean value indicating if the database should return any generated keys.
@return the {@link Query} instance
@deprecated create queries with {@link org.sql2o.Connection} class instead, using try-with-resource blocks
<code>
try (Connection con = sql2o.open()) {
return sql2o.createQuery(query, name, returnGeneratedKeys).executeAndFetch(Pojo.class);
}
</code>
"""
return new Connection(this, true).createQuery(query, returnGeneratedKeys);
}
|
java
|
@Deprecated
public Query createQuery(String query, boolean returnGeneratedKeys) {
return new Connection(this, true).createQuery(query, returnGeneratedKeys);
}
|
[
"@",
"Deprecated",
"public",
"Query",
"createQuery",
"(",
"String",
"query",
",",
"boolean",
"returnGeneratedKeys",
")",
"{",
"return",
"new",
"Connection",
"(",
"this",
",",
"true",
")",
".",
"createQuery",
"(",
"query",
",",
"returnGeneratedKeys",
")",
";",
"}"
] |
Creates a {@link Query}
@param query the sql query string
@param returnGeneratedKeys boolean value indicating if the database should return any generated keys.
@return the {@link Query} instance
@deprecated create queries with {@link org.sql2o.Connection} class instead, using try-with-resource blocks
<code>
try (Connection con = sql2o.open()) {
return sql2o.createQuery(query, name, returnGeneratedKeys).executeAndFetch(Pojo.class);
}
</code>
|
[
"Creates",
"a",
"{",
"@link",
"Query",
"}",
"@param",
"query",
"the",
"sql",
"query",
"string",
"@param",
"returnGeneratedKeys",
"boolean",
"value",
"indicating",
"if",
"the",
"database",
"should",
"return",
"any",
"generated",
"keys",
".",
"@return",
"the",
"{",
"@link",
"Query",
"}",
"instance"
] |
train
|
https://github.com/aaberg/sql2o/blob/01d3490a6d2440cf60f973d23508ac4ed57a8e20/core/src/main/java/org/sql2o/Sql2o.java#L167-L170
|
lets-blade/blade
|
src/main/java/com/blade/mvc/ui/template/BladeTemplate.java
|
BladeTemplate.appendParamValue
|
private void appendParamValue(StringBuilder param, StringBuilder result) {
"""
in this case it is obtained by calling recursively the methods on the last obtained object
"""
if (param == null)
throw UncheckedTemplateException.invalidArgumentName(param);
// Object name is the parameter that should be found in the map.
// If it's followed by points, the points remain in the "param" buffer.
final String objectName = takeUntilDotOrEnd(param);
final Object objectValue = arguments.get(objectName);
Object toAppend;
if (param.length() != 0) {
// If this is a chain object.method1.method2.method3
// we recurse
toAppend = valueInChain(objectValue, param);
} else {
// We evaluate if the obejct is an array
// If it's an array we print it nicely
toAppend = evaluateIfArray(objectValue);
}
if (null != toAppend) {
result.append(toAppend);
}
}
|
java
|
private void appendParamValue(StringBuilder param, StringBuilder result) {
if (param == null)
throw UncheckedTemplateException.invalidArgumentName(param);
// Object name is the parameter that should be found in the map.
// If it's followed by points, the points remain in the "param" buffer.
final String objectName = takeUntilDotOrEnd(param);
final Object objectValue = arguments.get(objectName);
Object toAppend;
if (param.length() != 0) {
// If this is a chain object.method1.method2.method3
// we recurse
toAppend = valueInChain(objectValue, param);
} else {
// We evaluate if the obejct is an array
// If it's an array we print it nicely
toAppend = evaluateIfArray(objectValue);
}
if (null != toAppend) {
result.append(toAppend);
}
}
|
[
"private",
"void",
"appendParamValue",
"(",
"StringBuilder",
"param",
",",
"StringBuilder",
"result",
")",
"{",
"if",
"(",
"param",
"==",
"null",
")",
"throw",
"UncheckedTemplateException",
".",
"invalidArgumentName",
"(",
"param",
")",
";",
"// Object name is the parameter that should be found in the map.",
"// If it's followed by points, the points remain in the \"param\" buffer.",
"final",
"String",
"objectName",
"=",
"takeUntilDotOrEnd",
"(",
"param",
")",
";",
"final",
"Object",
"objectValue",
"=",
"arguments",
".",
"get",
"(",
"objectName",
")",
";",
"Object",
"toAppend",
";",
"if",
"(",
"param",
".",
"length",
"(",
")",
"!=",
"0",
")",
"{",
"// If this is a chain object.method1.method2.method3",
"// we recurse",
"toAppend",
"=",
"valueInChain",
"(",
"objectValue",
",",
"param",
")",
";",
"}",
"else",
"{",
"// We evaluate if the obejct is an array",
"// If it's an array we print it nicely",
"toAppend",
"=",
"evaluateIfArray",
"(",
"objectValue",
")",
";",
"}",
"if",
"(",
"null",
"!=",
"toAppend",
")",
"{",
"result",
".",
"append",
"(",
"toAppend",
")",
";",
"}",
"}"
] |
in this case it is obtained by calling recursively the methods on the last obtained object
|
[
"in",
"this",
"case",
"it",
"is",
"obtained",
"by",
"calling",
"recursively",
"the",
"methods",
"on",
"the",
"last",
"obtained",
"object"
] |
train
|
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/mvc/ui/template/BladeTemplate.java#L194-L217
|
haraldk/TwelveMonkeys
|
imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java
|
PICTUtil.readColorTable
|
public static IndexColorModel readColorTable(final DataInput pStream, final int pPixelSize) throws IOException {
"""
/*
http://developer.apple.com/DOCUMENTATION/mac/QuickDraw/QuickDraw-269.html#HEADING269-11
ColorSpec =
RECORD
value: Integer; {index or other value}
rgb: RGBColor; {true color}
END;
ColorTable =
RECORD
ctSeed: LongInt; {unique identifier from table}
ctFlags: Integer; {contains flags describing the ctTable field; }
{ clear for a PixMap record}
ctSize: Integer; {number of entries in the next field minus 1}
ctTable: cSpecArray; {an array of ColorSpec records}
END;
"""
// TODO: Do we need to support these?
/*int seed = */pStream.readInt();
/*int flags = */pStream.readUnsignedShort();
int size = pStream.readUnsignedShort() + 1; // data is size - 1
int[] colors = new int[size];
for (int i = 0; i < size; i++) {
// Read ColorSpec records
/*int index = */pStream.readUnsignedShort();
Color color = readRGBColor(pStream);
colors[i] = color.getRGB();
}
return new IndexColorModel(pPixelSize, size, colors, 0, false, -1, DataBuffer.TYPE_BYTE);
}
|
java
|
public static IndexColorModel readColorTable(final DataInput pStream, final int pPixelSize) throws IOException {
// TODO: Do we need to support these?
/*int seed = */pStream.readInt();
/*int flags = */pStream.readUnsignedShort();
int size = pStream.readUnsignedShort() + 1; // data is size - 1
int[] colors = new int[size];
for (int i = 0; i < size; i++) {
// Read ColorSpec records
/*int index = */pStream.readUnsignedShort();
Color color = readRGBColor(pStream);
colors[i] = color.getRGB();
}
return new IndexColorModel(pPixelSize, size, colors, 0, false, -1, DataBuffer.TYPE_BYTE);
}
|
[
"public",
"static",
"IndexColorModel",
"readColorTable",
"(",
"final",
"DataInput",
"pStream",
",",
"final",
"int",
"pPixelSize",
")",
"throws",
"IOException",
"{",
"// TODO: Do we need to support these?",
"/*int seed = */",
"pStream",
".",
"readInt",
"(",
")",
";",
"/*int flags = */",
"pStream",
".",
"readUnsignedShort",
"(",
")",
";",
"int",
"size",
"=",
"pStream",
".",
"readUnsignedShort",
"(",
")",
"+",
"1",
";",
"// data is size - 1",
"int",
"[",
"]",
"colors",
"=",
"new",
"int",
"[",
"size",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"// Read ColorSpec records",
"/*int index = */",
"pStream",
".",
"readUnsignedShort",
"(",
")",
";",
"Color",
"color",
"=",
"readRGBColor",
"(",
"pStream",
")",
";",
"colors",
"[",
"i",
"]",
"=",
"color",
".",
"getRGB",
"(",
")",
";",
"}",
"return",
"new",
"IndexColorModel",
"(",
"pPixelSize",
",",
"size",
",",
"colors",
",",
"0",
",",
"false",
",",
"-",
"1",
",",
"DataBuffer",
".",
"TYPE_BYTE",
")",
";",
"}"
] |
/*
http://developer.apple.com/DOCUMENTATION/mac/QuickDraw/QuickDraw-269.html#HEADING269-11
ColorSpec =
RECORD
value: Integer; {index or other value}
rgb: RGBColor; {true color}
END;
ColorTable =
RECORD
ctSeed: LongInt; {unique identifier from table}
ctFlags: Integer; {contains flags describing the ctTable field; }
{ clear for a PixMap record}
ctSize: Integer; {number of entries in the next field minus 1}
ctTable: cSpecArray; {an array of ColorSpec records}
END;
|
[
"/",
"*",
"http",
":",
"//",
"developer",
".",
"apple",
".",
"com",
"/",
"DOCUMENTATION",
"/",
"mac",
"/",
"QuickDraw",
"/",
"QuickDraw",
"-",
"269",
".",
"html#HEADING269",
"-",
"11",
"ColorSpec",
"=",
"RECORD",
"value",
":",
"Integer",
";",
"{",
"index",
"or",
"other",
"value",
"}",
"rgb",
":",
"RGBColor",
";",
"{",
"true",
"color",
"}",
"END",
";"
] |
train
|
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L257-L273
|
Deep-Symmetry/beat-link
|
src/main/java/org/deepsymmetry/beatlink/Util.java
|
Util.buildPacket
|
public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {
"""
Build a standard-format UDP packet for sending to port 50001 or 50002 in the protocol.
@param type the type of packet to create.
@param deviceName the 0x14 (twenty) bytes of the device name to send in the packet.
@param payload the remaining bytes which come after the device name.
@return the packet to send.
"""
ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());
content.put(getMagicHeader());
content.put(type.protocolValue);
content.put(deviceName);
content.put(payload);
return new DatagramPacket(content.array(), content.capacity());
}
|
java
|
public static DatagramPacket buildPacket(PacketType type, ByteBuffer deviceName, ByteBuffer payload) {
ByteBuffer content = ByteBuffer.allocate(0x1f + payload.remaining());
content.put(getMagicHeader());
content.put(type.protocolValue);
content.put(deviceName);
content.put(payload);
return new DatagramPacket(content.array(), content.capacity());
}
|
[
"public",
"static",
"DatagramPacket",
"buildPacket",
"(",
"PacketType",
"type",
",",
"ByteBuffer",
"deviceName",
",",
"ByteBuffer",
"payload",
")",
"{",
"ByteBuffer",
"content",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"0x1f",
"+",
"payload",
".",
"remaining",
"(",
")",
")",
";",
"content",
".",
"put",
"(",
"getMagicHeader",
"(",
")",
")",
";",
"content",
".",
"put",
"(",
"type",
".",
"protocolValue",
")",
";",
"content",
".",
"put",
"(",
"deviceName",
")",
";",
"content",
".",
"put",
"(",
"payload",
")",
";",
"return",
"new",
"DatagramPacket",
"(",
"content",
".",
"array",
"(",
")",
",",
"content",
".",
"capacity",
"(",
")",
")",
";",
"}"
] |
Build a standard-format UDP packet for sending to port 50001 or 50002 in the protocol.
@param type the type of packet to create.
@param deviceName the 0x14 (twenty) bytes of the device name to send in the packet.
@param payload the remaining bytes which come after the device name.
@return the packet to send.
|
[
"Build",
"a",
"standard",
"-",
"format",
"UDP",
"packet",
"for",
"sending",
"to",
"port",
"50001",
"or",
"50002",
"in",
"the",
"protocol",
"."
] |
train
|
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/Util.java#L176-L183
|
ontop/ontop
|
mapping/sql/r2rml/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/R2RMLParser.java
|
R2RMLParser.getBodyURIPredicates
|
public List<ImmutableFunctionalTerm> getBodyURIPredicates(PredicateObjectMap pom) {
"""
Get body predicates with templates
@param pom
@return
@throws Exception
"""
List<ImmutableFunctionalTerm> predicateAtoms = new ArrayList<>();
// process PREDICATEMAP
for (PredicateMap pm : pom.getPredicateMaps()) {
String pmConstant = pm.getConstant().toString();
if (pmConstant != null) {
ImmutableFunctionalTerm bodyPredicate = termFactory.getImmutableUriTemplate(termFactory.getConstantLiteral(pmConstant));
predicateAtoms.add(bodyPredicate);
}
Template t = pm.getTemplate();
if (t != null) {
// create uri("...",var)
ImmutableFunctionalTerm predicateAtom = getURIFunction(t.toString());
predicateAtoms.add(predicateAtom);
}
// process column declaration
String c = pm.getColumn();
if (c != null) {
ImmutableFunctionalTerm predicateAtom = getURIFunction(c);
predicateAtoms.add(predicateAtom);
}
}
return predicateAtoms;
}
|
java
|
public List<ImmutableFunctionalTerm> getBodyURIPredicates(PredicateObjectMap pom) {
List<ImmutableFunctionalTerm> predicateAtoms = new ArrayList<>();
// process PREDICATEMAP
for (PredicateMap pm : pom.getPredicateMaps()) {
String pmConstant = pm.getConstant().toString();
if (pmConstant != null) {
ImmutableFunctionalTerm bodyPredicate = termFactory.getImmutableUriTemplate(termFactory.getConstantLiteral(pmConstant));
predicateAtoms.add(bodyPredicate);
}
Template t = pm.getTemplate();
if (t != null) {
// create uri("...",var)
ImmutableFunctionalTerm predicateAtom = getURIFunction(t.toString());
predicateAtoms.add(predicateAtom);
}
// process column declaration
String c = pm.getColumn();
if (c != null) {
ImmutableFunctionalTerm predicateAtom = getURIFunction(c);
predicateAtoms.add(predicateAtom);
}
}
return predicateAtoms;
}
|
[
"public",
"List",
"<",
"ImmutableFunctionalTerm",
">",
"getBodyURIPredicates",
"(",
"PredicateObjectMap",
"pom",
")",
"{",
"List",
"<",
"ImmutableFunctionalTerm",
">",
"predicateAtoms",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// process PREDICATEMAP",
"for",
"(",
"PredicateMap",
"pm",
":",
"pom",
".",
"getPredicateMaps",
"(",
")",
")",
"{",
"String",
"pmConstant",
"=",
"pm",
".",
"getConstant",
"(",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"pmConstant",
"!=",
"null",
")",
"{",
"ImmutableFunctionalTerm",
"bodyPredicate",
"=",
"termFactory",
".",
"getImmutableUriTemplate",
"(",
"termFactory",
".",
"getConstantLiteral",
"(",
"pmConstant",
")",
")",
";",
"predicateAtoms",
".",
"add",
"(",
"bodyPredicate",
")",
";",
"}",
"Template",
"t",
"=",
"pm",
".",
"getTemplate",
"(",
")",
";",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"// create uri(\"...\",var)",
"ImmutableFunctionalTerm",
"predicateAtom",
"=",
"getURIFunction",
"(",
"t",
".",
"toString",
"(",
")",
")",
";",
"predicateAtoms",
".",
"add",
"(",
"predicateAtom",
")",
";",
"}",
"// process column declaration",
"String",
"c",
"=",
"pm",
".",
"getColumn",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"null",
")",
"{",
"ImmutableFunctionalTerm",
"predicateAtom",
"=",
"getURIFunction",
"(",
"c",
")",
";",
"predicateAtoms",
".",
"add",
"(",
"predicateAtom",
")",
";",
"}",
"}",
"return",
"predicateAtoms",
";",
"}"
] |
Get body predicates with templates
@param pom
@return
@throws Exception
|
[
"Get",
"body",
"predicates",
"with",
"templates"
] |
train
|
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/sql/r2rml/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/R2RMLParser.java#L197-L225
|
citrusframework/citrus
|
modules/citrus-core/src/main/java/com/consol/citrus/config/util/BeanDefinitionParserUtils.java
|
BeanDefinitionParserUtils.addConstructorArgReference
|
public static void addConstructorArgReference(BeanDefinitionBuilder builder, String beanReference) {
"""
Sets the property reference on bean definition in case reference
is set properly.
@param builder the bean definition builder to be configured
@param beanReference bean reference to add as constructor arg
"""
if (StringUtils.hasText(beanReference)) {
builder.addConstructorArgReference(beanReference);
}
}
|
java
|
public static void addConstructorArgReference(BeanDefinitionBuilder builder, String beanReference) {
if (StringUtils.hasText(beanReference)) {
builder.addConstructorArgReference(beanReference);
}
}
|
[
"public",
"static",
"void",
"addConstructorArgReference",
"(",
"BeanDefinitionBuilder",
"builder",
",",
"String",
"beanReference",
")",
"{",
"if",
"(",
"StringUtils",
".",
"hasText",
"(",
"beanReference",
")",
")",
"{",
"builder",
".",
"addConstructorArgReference",
"(",
"beanReference",
")",
";",
"}",
"}"
] |
Sets the property reference on bean definition in case reference
is set properly.
@param builder the bean definition builder to be configured
@param beanReference bean reference to add as constructor arg
|
[
"Sets",
"the",
"property",
"reference",
"on",
"bean",
"definition",
"in",
"case",
"reference",
"is",
"set",
"properly",
"."
] |
train
|
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/util/BeanDefinitionParserUtils.java#L88-L92
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.