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
|
---|---|---|---|---|---|---|---|---|---|---|
jronrun/benayn
|
benayn-ustyle/src/main/java/com/benayn/ustyle/Sources.java
|
Sources.asReader
|
public static BufferedReader asReader(InputStream is, Charset charset) {
"""
Convert {@link InputStream} to {@link BufferedReader}
@param is
@return
"""
try {
return new BufferedReader(new InputStreamReader(is, charset.toString()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
java
|
public static BufferedReader asReader(InputStream is, Charset charset) {
try {
return new BufferedReader(new InputStreamReader(is, charset.toString()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
[
"public",
"static",
"BufferedReader",
"asReader",
"(",
"InputStream",
"is",
",",
"Charset",
"charset",
")",
"{",
"try",
"{",
"return",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"is",
",",
"charset",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Convert {@link InputStream} to {@link BufferedReader}
@param is
@return
|
[
"Convert",
"{",
"@link",
"InputStream",
"}",
"to",
"{",
"@link",
"BufferedReader",
"}"
] |
train
|
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Sources.java#L218-L226
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/FeatureDependencyChecker.java
|
FeatureDependencyChecker.toBeUninstalled
|
public boolean toBeUninstalled(String name, List<UninstallAsset> list) {
"""
Verify the name is on the uninstall list
@param name symbolic name of the feature
@param list list of the uninstalling features
@return true if the feature is going to be uninstalled, otherwise, return false.
"""
for (UninstallAsset asset : list) {
String featureName = InstallUtils.getShortName(asset.getProvisioningFeatureDefinition());
if (asset.getName().equals(name) ||
(featureName != null && featureName.equals(name))) {
InstallLogUtils.getInstallLogger().log(Level.FINEST, "The dependent feature is specified to be uninstalled : " + featureName);
return true;
}
}
return false;
}
|
java
|
public boolean toBeUninstalled(String name, List<UninstallAsset> list) {
for (UninstallAsset asset : list) {
String featureName = InstallUtils.getShortName(asset.getProvisioningFeatureDefinition());
if (asset.getName().equals(name) ||
(featureName != null && featureName.equals(name))) {
InstallLogUtils.getInstallLogger().log(Level.FINEST, "The dependent feature is specified to be uninstalled : " + featureName);
return true;
}
}
return false;
}
|
[
"public",
"boolean",
"toBeUninstalled",
"(",
"String",
"name",
",",
"List",
"<",
"UninstallAsset",
">",
"list",
")",
"{",
"for",
"(",
"UninstallAsset",
"asset",
":",
"list",
")",
"{",
"String",
"featureName",
"=",
"InstallUtils",
".",
"getShortName",
"(",
"asset",
".",
"getProvisioningFeatureDefinition",
"(",
")",
")",
";",
"if",
"(",
"asset",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
"||",
"(",
"featureName",
"!=",
"null",
"&&",
"featureName",
".",
"equals",
"(",
"name",
")",
")",
")",
"{",
"InstallLogUtils",
".",
"getInstallLogger",
"(",
")",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"\"The dependent feature is specified to be uninstalled : \"",
"+",
"featureName",
")",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Verify the name is on the uninstall list
@param name symbolic name of the feature
@param list list of the uninstalling features
@return true if the feature is going to be uninstalled, otherwise, return false.
|
[
"Verify",
"the",
"name",
"is",
"on",
"the",
"uninstall",
"list"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/FeatureDependencyChecker.java#L42-L52
|
nguillaumin/slick2d-maven
|
slick2d-core/src/main/java/org/newdawn/slick/openal/AudioLoader.java
|
AudioLoader.getAudio
|
public static Audio getAudio(String format, InputStream in) throws IOException {
"""
Get audio data in a playable state by loading the complete audio into
memory.
@param format The format of the audio to be loaded (something like "XM" or "OGG")
@param in The input stream from which to load the audio data
@return An object representing the audio data
@throws IOException Indicates a failure to access the audio data
"""
init();
if (format.equals(AIF)) {
return SoundStore.get().getAIF(in);
}
if (format.equals(WAV)) {
return SoundStore.get().getWAV(in);
}
if (format.equals(OGG)) {
return SoundStore.get().getOgg(in);
}
throw new IOException("Unsupported format for non-streaming Audio: "+format);
}
|
java
|
public static Audio getAudio(String format, InputStream in) throws IOException {
init();
if (format.equals(AIF)) {
return SoundStore.get().getAIF(in);
}
if (format.equals(WAV)) {
return SoundStore.get().getWAV(in);
}
if (format.equals(OGG)) {
return SoundStore.get().getOgg(in);
}
throw new IOException("Unsupported format for non-streaming Audio: "+format);
}
|
[
"public",
"static",
"Audio",
"getAudio",
"(",
"String",
"format",
",",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"init",
"(",
")",
";",
"if",
"(",
"format",
".",
"equals",
"(",
"AIF",
")",
")",
"{",
"return",
"SoundStore",
".",
"get",
"(",
")",
".",
"getAIF",
"(",
"in",
")",
";",
"}",
"if",
"(",
"format",
".",
"equals",
"(",
"WAV",
")",
")",
"{",
"return",
"SoundStore",
".",
"get",
"(",
")",
".",
"getWAV",
"(",
"in",
")",
";",
"}",
"if",
"(",
"format",
".",
"equals",
"(",
"OGG",
")",
")",
"{",
"return",
"SoundStore",
".",
"get",
"(",
")",
".",
"getOgg",
"(",
"in",
")",
";",
"}",
"throw",
"new",
"IOException",
"(",
"\"Unsupported format for non-streaming Audio: \"",
"+",
"format",
")",
";",
"}"
] |
Get audio data in a playable state by loading the complete audio into
memory.
@param format The format of the audio to be loaded (something like "XM" or "OGG")
@param in The input stream from which to load the audio data
@return An object representing the audio data
@throws IOException Indicates a failure to access the audio data
|
[
"Get",
"audio",
"data",
"in",
"a",
"playable",
"state",
"by",
"loading",
"the",
"complete",
"audio",
"into",
"memory",
"."
] |
train
|
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/openal/AudioLoader.java#L47-L61
|
pravega/pravega
|
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/Ledgers.java
|
Ledgers.readLastAddConfirmed
|
static long readLastAddConfirmed(long ledgerId, BookKeeper bookKeeper, BookKeeperConfig config) throws DurableDataLogException {
"""
Reliably retrieves the LastAddConfirmed for the Ledger with given LedgerId, by opening the Ledger in fencing mode
and getting the value. NOTE: this open-fences the Ledger which will effectively stop any writing action on it.
@param ledgerId The Id of the Ledger to query.
@param bookKeeper A references to the BookKeeper client to use.
@param config Configuration to use.
@return The LastAddConfirmed for the given LedgerId.
@throws DurableDataLogException If an exception occurred. The causing exception is wrapped inside it.
"""
LedgerHandle h = null;
try {
// Here we open the Ledger WITH recovery, to force BookKeeper to reconcile any appends that may have been
// interrupted and not properly acked. Otherwise there is no guarantee we can get an accurate value for
// LastAddConfirmed.
h = openFence(ledgerId, bookKeeper, config);
return h.getLastAddConfirmed();
} finally {
if (h != null) {
close(h);
}
}
}
|
java
|
static long readLastAddConfirmed(long ledgerId, BookKeeper bookKeeper, BookKeeperConfig config) throws DurableDataLogException {
LedgerHandle h = null;
try {
// Here we open the Ledger WITH recovery, to force BookKeeper to reconcile any appends that may have been
// interrupted and not properly acked. Otherwise there is no guarantee we can get an accurate value for
// LastAddConfirmed.
h = openFence(ledgerId, bookKeeper, config);
return h.getLastAddConfirmed();
} finally {
if (h != null) {
close(h);
}
}
}
|
[
"static",
"long",
"readLastAddConfirmed",
"(",
"long",
"ledgerId",
",",
"BookKeeper",
"bookKeeper",
",",
"BookKeeperConfig",
"config",
")",
"throws",
"DurableDataLogException",
"{",
"LedgerHandle",
"h",
"=",
"null",
";",
"try",
"{",
"// Here we open the Ledger WITH recovery, to force BookKeeper to reconcile any appends that may have been",
"// interrupted and not properly acked. Otherwise there is no guarantee we can get an accurate value for",
"// LastAddConfirmed.",
"h",
"=",
"openFence",
"(",
"ledgerId",
",",
"bookKeeper",
",",
"config",
")",
";",
"return",
"h",
".",
"getLastAddConfirmed",
"(",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"h",
"!=",
"null",
")",
"{",
"close",
"(",
"h",
")",
";",
"}",
"}",
"}"
] |
Reliably retrieves the LastAddConfirmed for the Ledger with given LedgerId, by opening the Ledger in fencing mode
and getting the value. NOTE: this open-fences the Ledger which will effectively stop any writing action on it.
@param ledgerId The Id of the Ledger to query.
@param bookKeeper A references to the BookKeeper client to use.
@param config Configuration to use.
@return The LastAddConfirmed for the given LedgerId.
@throws DurableDataLogException If an exception occurred. The causing exception is wrapped inside it.
|
[
"Reliably",
"retrieves",
"the",
"LastAddConfirmed",
"for",
"the",
"Ledger",
"with",
"given",
"LedgerId",
"by",
"opening",
"the",
"Ledger",
"in",
"fencing",
"mode",
"and",
"getting",
"the",
"value",
".",
"NOTE",
":",
"this",
"open",
"-",
"fences",
"the",
"Ledger",
"which",
"will",
"effectively",
"stop",
"any",
"writing",
"action",
"on",
"it",
"."
] |
train
|
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/Ledgers.java#L107-L120
|
sshtools/j2ssh-maverick
|
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java
|
SftpClient.getInputStream
|
public InputStream getInputStream(String remotefile, long position)
throws SftpStatusException, SshException {
"""
Create an InputStream for reading a remote file.
@param remotefile
@param position
@return InputStream
@throws SftpStatusException
@throws SshException
"""
String remotePath = resolveRemotePath(remotefile);
sftp.getAttributes(remotePath);
return new SftpFileInputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_READ), position);
}
|
java
|
public InputStream getInputStream(String remotefile, long position)
throws SftpStatusException, SshException {
String remotePath = resolveRemotePath(remotefile);
sftp.getAttributes(remotePath);
return new SftpFileInputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_READ), position);
}
|
[
"public",
"InputStream",
"getInputStream",
"(",
"String",
"remotefile",
",",
"long",
"position",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"remotePath",
"=",
"resolveRemotePath",
"(",
"remotefile",
")",
";",
"sftp",
".",
"getAttributes",
"(",
"remotePath",
")",
";",
"return",
"new",
"SftpFileInputStream",
"(",
"sftp",
".",
"openFile",
"(",
"remotePath",
",",
"SftpSubsystemChannel",
".",
"OPEN_READ",
")",
",",
"position",
")",
";",
"}"
] |
Create an InputStream for reading a remote file.
@param remotefile
@param position
@return InputStream
@throws SftpStatusException
@throws SshException
|
[
"Create",
"an",
"InputStream",
"for",
"reading",
"a",
"remote",
"file",
"."
] |
train
|
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1519-L1527
|
elki-project/elki
|
elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java
|
MSTSplit.follow
|
private static int follow(int i, int[] partitions) {
"""
Union-find with simple path compression.
@param i Start
@param partitions Partitions array
@return Partition
"""
int next = partitions[i], tmp;
while(i != next) {
tmp = next;
next = partitions[i] = partitions[next];
i = tmp;
}
return i;
}
|
java
|
private static int follow(int i, int[] partitions) {
int next = partitions[i], tmp;
while(i != next) {
tmp = next;
next = partitions[i] = partitions[next];
i = tmp;
}
return i;
}
|
[
"private",
"static",
"int",
"follow",
"(",
"int",
"i",
",",
"int",
"[",
"]",
"partitions",
")",
"{",
"int",
"next",
"=",
"partitions",
"[",
"i",
"]",
",",
"tmp",
";",
"while",
"(",
"i",
"!=",
"next",
")",
"{",
"tmp",
"=",
"next",
";",
"next",
"=",
"partitions",
"[",
"i",
"]",
"=",
"partitions",
"[",
"next",
"]",
";",
"i",
"=",
"tmp",
";",
"}",
"return",
"i",
";",
"}"
] |
Union-find with simple path compression.
@param i Start
@param partitions Partitions array
@return Partition
|
[
"Union",
"-",
"find",
"with",
"simple",
"path",
"compression",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java#L225-L233
|
boncey/Flickr4Java
|
src/main/java/com/flickr4java/flickr/REST.java
|
REST.postMultiPart
|
@Override
public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException {
"""
Invoke an HTTP POST request on a remote host.
@param path The request path
@param metaData The parameters (collection of Parameter objects)
@param payload
@return The Response object
"""
OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path));
Map<String, String> uploadParameters = new HashMap<>(metaData.getUploadParameters());
buildMultipartRequest(uploadParameters, request);
OAuth10aService service = createAndSignRequest(apiKey, sharedSecret, request);
// Ensure all parameters (including oauth) are added to payload so signature matches
uploadParameters.putAll(request.getOauthParameters());
request.addMultipartPayload(String.format("form-data; name=\"photo\"; filename=\"%s\"", metaData.getFilename()), metaData.getFilemimetype(), payload.getPayload());
uploadParameters.entrySet().forEach(e ->
request.addMultipartPayload(String.format("form-data; name=\"%s\"", e.getKey()), null, e.getValue().getBytes()));
try {
return handleResponse(request, service);
} catch (IllegalAccessException | InterruptedException | ExecutionException | InstantiationException | IOException | SAXException | ParserConfigurationException e) {
throw new FlickrRuntimeException(e);
}
}
|
java
|
@Override
public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException {
OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path));
Map<String, String> uploadParameters = new HashMap<>(metaData.getUploadParameters());
buildMultipartRequest(uploadParameters, request);
OAuth10aService service = createAndSignRequest(apiKey, sharedSecret, request);
// Ensure all parameters (including oauth) are added to payload so signature matches
uploadParameters.putAll(request.getOauthParameters());
request.addMultipartPayload(String.format("form-data; name=\"photo\"; filename=\"%s\"", metaData.getFilename()), metaData.getFilemimetype(), payload.getPayload());
uploadParameters.entrySet().forEach(e ->
request.addMultipartPayload(String.format("form-data; name=\"%s\"", e.getKey()), null, e.getValue().getBytes()));
try {
return handleResponse(request, service);
} catch (IllegalAccessException | InterruptedException | ExecutionException | InstantiationException | IOException | SAXException | ParserConfigurationException e) {
throw new FlickrRuntimeException(e);
}
}
|
[
"@",
"Override",
"public",
"com",
".",
"flickr4java",
".",
"flickr",
".",
"Response",
"postMultiPart",
"(",
"String",
"path",
",",
"UploadMetaData",
"metaData",
",",
"Payload",
"payload",
",",
"String",
"apiKey",
",",
"String",
"sharedSecret",
")",
"throws",
"FlickrException",
"{",
"OAuthRequest",
"request",
"=",
"new",
"OAuthRequest",
"(",
"Verb",
".",
"POST",
",",
"buildUrl",
"(",
"path",
")",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"uploadParameters",
"=",
"new",
"HashMap",
"<>",
"(",
"metaData",
".",
"getUploadParameters",
"(",
")",
")",
";",
"buildMultipartRequest",
"(",
"uploadParameters",
",",
"request",
")",
";",
"OAuth10aService",
"service",
"=",
"createAndSignRequest",
"(",
"apiKey",
",",
"sharedSecret",
",",
"request",
")",
";",
"// Ensure all parameters (including oauth) are added to payload so signature matches",
"uploadParameters",
".",
"putAll",
"(",
"request",
".",
"getOauthParameters",
"(",
")",
")",
";",
"request",
".",
"addMultipartPayload",
"(",
"String",
".",
"format",
"(",
"\"form-data; name=\\\"photo\\\"; filename=\\\"%s\\\"\"",
",",
"metaData",
".",
"getFilename",
"(",
")",
")",
",",
"metaData",
".",
"getFilemimetype",
"(",
")",
",",
"payload",
".",
"getPayload",
"(",
")",
")",
";",
"uploadParameters",
".",
"entrySet",
"(",
")",
".",
"forEach",
"(",
"e",
"->",
"request",
".",
"addMultipartPayload",
"(",
"String",
".",
"format",
"(",
"\"form-data; name=\\\"%s\\\"\"",
",",
"e",
".",
"getKey",
"(",
")",
")",
",",
"null",
",",
"e",
".",
"getValue",
"(",
")",
".",
"getBytes",
"(",
")",
")",
")",
";",
"try",
"{",
"return",
"handleResponse",
"(",
"request",
",",
"service",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"|",
"InterruptedException",
"|",
"ExecutionException",
"|",
"InstantiationException",
"|",
"IOException",
"|",
"SAXException",
"|",
"ParserConfigurationException",
"e",
")",
"{",
"throw",
"new",
"FlickrRuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Invoke an HTTP POST request on a remote host.
@param path The request path
@param metaData The parameters (collection of Parameter objects)
@param payload
@return The Response object
|
[
"Invoke",
"an",
"HTTP",
"POST",
"request",
"on",
"a",
"remote",
"host",
"."
] |
train
|
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/REST.java#L201-L223
|
google/j2objc
|
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java
|
Collator.getFunctionalEquivalent
|
public static final ULocale getFunctionalEquivalent(String keyword,
ULocale locID) {
"""
<strong>[icu]</strong> Returns the functionally equivalent locale for the given
requested locale, with respect to given keyword, for the
collation service.
@param keyword a particular keyword as enumerated by
getKeywords.
@param locID The requested locale
@return the locale
@see #getFunctionalEquivalent(String,ULocale,boolean[])
"""
return getFunctionalEquivalent(keyword, locID, null);
}
|
java
|
public static final ULocale getFunctionalEquivalent(String keyword,
ULocale locID) {
return getFunctionalEquivalent(keyword, locID, null);
}
|
[
"public",
"static",
"final",
"ULocale",
"getFunctionalEquivalent",
"(",
"String",
"keyword",
",",
"ULocale",
"locID",
")",
"{",
"return",
"getFunctionalEquivalent",
"(",
"keyword",
",",
"locID",
",",
"null",
")",
";",
"}"
] |
<strong>[icu]</strong> Returns the functionally equivalent locale for the given
requested locale, with respect to given keyword, for the
collation service.
@param keyword a particular keyword as enumerated by
getKeywords.
@param locID The requested locale
@return the locale
@see #getFunctionalEquivalent(String,ULocale,boolean[])
|
[
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"the",
"functionally",
"equivalent",
"locale",
"for",
"the",
"given",
"requested",
"locale",
"with",
"respect",
"to",
"given",
"keyword",
"for",
"the",
"collation",
"service",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/Collator.java#L1048-L1051
|
michael-rapp/AndroidUtil
|
library/src/main/java/de/mrapp/android/util/ThemeUtil.java
|
ThemeUtil.getFloat
|
public static float getFloat(@NonNull final Context context, @AttrRes final int resourceId,
final float defaultValue) {
"""
Obtains the float value, which corresponds to a specific resource id, from a context's
theme.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param resourceId
The resource id of the attribute, which should be obtained, as an {@link Integer}
value. The resource id must corresponds to a valid theme attribute
@param defaultValue
The default value, which should be returned, if the given resource id is invalid, as
a {@link Float} value
@return The float value, which has been obtained, as a {@link Float} value or 0, if the given
resource id is invalid
"""
return getFloat(context, -1, resourceId, defaultValue);
}
|
java
|
public static float getFloat(@NonNull final Context context, @AttrRes final int resourceId,
final float defaultValue) {
return getFloat(context, -1, resourceId, defaultValue);
}
|
[
"public",
"static",
"float",
"getFloat",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"@",
"AttrRes",
"final",
"int",
"resourceId",
",",
"final",
"float",
"defaultValue",
")",
"{",
"return",
"getFloat",
"(",
"context",
",",
"-",
"1",
",",
"resourceId",
",",
"defaultValue",
")",
";",
"}"
] |
Obtains the float value, which corresponds to a specific resource id, from a context's
theme.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param resourceId
The resource id of the attribute, which should be obtained, as an {@link Integer}
value. The resource id must corresponds to a valid theme attribute
@param defaultValue
The default value, which should be returned, if the given resource id is invalid, as
a {@link Float} value
@return The float value, which has been obtained, as a {@link Float} value or 0, if the given
resource id is invalid
|
[
"Obtains",
"the",
"float",
"value",
"which",
"corresponds",
"to",
"a",
"specific",
"resource",
"id",
"from",
"a",
"context",
"s",
"theme",
"."
] |
train
|
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/ThemeUtil.java#L812-L815
|
pgjdbc/pgjdbc
|
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
|
EscapedFunctions2.sqldayofyear
|
public static void sqldayofyear(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
"""
dayofyear translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens
"""
singleArgumentFunctionCall(buf, "extract(doy from ", "dayofyear", parsedArgs);
}
|
java
|
public static void sqldayofyear(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "extract(doy from ", "dayofyear", parsedArgs);
}
|
[
"public",
"static",
"void",
"sqldayofyear",
"(",
"StringBuilder",
"buf",
",",
"List",
"<",
"?",
"extends",
"CharSequence",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"singleArgumentFunctionCall",
"(",
"buf",
",",
"\"extract(doy from \"",
",",
"\"dayofyear\"",
",",
"parsedArgs",
")",
";",
"}"
] |
dayofyear translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens
|
[
"dayofyear",
"translation"
] |
train
|
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L394-L396
|
Azure/azure-sdk-for-java
|
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
|
RedisInner.regenerateKeyAsync
|
public Observable<RedisAccessKeysInner> regenerateKeyAsync(String resourceGroupName, String name, RedisKeyType keyType) {
"""
Regenerate Redis cache's access keys. This operation requires write permission to the cache resource.
@param resourceGroupName The name of the resource group.
@param name The name of the Redis cache.
@param keyType The Redis access key to regenerate. Possible values include: 'Primary', 'Secondary'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisAccessKeysInner object
"""
return regenerateKeyWithServiceResponseAsync(resourceGroupName, name, keyType).map(new Func1<ServiceResponse<RedisAccessKeysInner>, RedisAccessKeysInner>() {
@Override
public RedisAccessKeysInner call(ServiceResponse<RedisAccessKeysInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<RedisAccessKeysInner> regenerateKeyAsync(String resourceGroupName, String name, RedisKeyType keyType) {
return regenerateKeyWithServiceResponseAsync(resourceGroupName, name, keyType).map(new Func1<ServiceResponse<RedisAccessKeysInner>, RedisAccessKeysInner>() {
@Override
public RedisAccessKeysInner call(ServiceResponse<RedisAccessKeysInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"RedisAccessKeysInner",
">",
"regenerateKeyAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"RedisKeyType",
"keyType",
")",
"{",
"return",
"regenerateKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"keyType",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RedisAccessKeysInner",
">",
",",
"RedisAccessKeysInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RedisAccessKeysInner",
"call",
"(",
"ServiceResponse",
"<",
"RedisAccessKeysInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Regenerate Redis cache's access keys. This operation requires write permission to the cache resource.
@param resourceGroupName The name of the resource group.
@param name The name of the Redis cache.
@param keyType The Redis access key to regenerate. Possible values include: 'Primary', 'Secondary'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisAccessKeysInner object
|
[
"Regenerate",
"Redis",
"cache",
"s",
"access",
"keys",
".",
"This",
"operation",
"requires",
"write",
"permission",
"to",
"the",
"cache",
"resource",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1176-L1183
|
advantageous/boon
|
reflekt/src/main/java/io/advantageous/boon/core/reflection/ClassMeta.java
|
ClassMeta.respondsTo
|
public static boolean respondsTo(Object object, String method) {
"""
Checks to see if an object responds to a method.
Helper facade over Reflection library.
@param object object in question
@param method method name in question.
@return true or false
"""
if (object instanceof Class) {
return Reflection.respondsTo((Class) object, method);
} else {
return Reflection.respondsTo(object, method);
}
}
|
java
|
public static boolean respondsTo(Object object, String method) {
if (object instanceof Class) {
return Reflection.respondsTo((Class) object, method);
} else {
return Reflection.respondsTo(object, method);
}
}
|
[
"public",
"static",
"boolean",
"respondsTo",
"(",
"Object",
"object",
",",
"String",
"method",
")",
"{",
"if",
"(",
"object",
"instanceof",
"Class",
")",
"{",
"return",
"Reflection",
".",
"respondsTo",
"(",
"(",
"Class",
")",
"object",
",",
"method",
")",
";",
"}",
"else",
"{",
"return",
"Reflection",
".",
"respondsTo",
"(",
"object",
",",
"method",
")",
";",
"}",
"}"
] |
Checks to see if an object responds to a method.
Helper facade over Reflection library.
@param object object in question
@param method method name in question.
@return true or false
|
[
"Checks",
"to",
"see",
"if",
"an",
"object",
"responds",
"to",
"a",
"method",
".",
"Helper",
"facade",
"over",
"Reflection",
"library",
"."
] |
train
|
https://github.com/advantageous/boon/blob/12712d376761aa3b33223a9f1716720ddb67cb5e/reflekt/src/main/java/io/advantageous/boon/core/reflection/ClassMeta.java#L596-L602
|
alkacon/opencms-core
|
src/org/opencms/gwt/shared/property/CmsClientProperty.java
|
CmsClientProperty.removeEmptyProperties
|
public static void removeEmptyProperties(Map<String, CmsClientProperty> props) {
"""
Helper method for removing empty properties from a map.<p>
@param props the map from which to remove empty properties
"""
Iterator<Map.Entry<String, CmsClientProperty>> iter = props.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, CmsClientProperty> entry = iter.next();
CmsClientProperty value = entry.getValue();
if (value.isEmpty()) {
iter.remove();
}
}
}
|
java
|
public static void removeEmptyProperties(Map<String, CmsClientProperty> props) {
Iterator<Map.Entry<String, CmsClientProperty>> iter = props.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, CmsClientProperty> entry = iter.next();
CmsClientProperty value = entry.getValue();
if (value.isEmpty()) {
iter.remove();
}
}
}
|
[
"public",
"static",
"void",
"removeEmptyProperties",
"(",
"Map",
"<",
"String",
",",
"CmsClientProperty",
">",
"props",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"CmsClientProperty",
">",
">",
"iter",
"=",
"props",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"Map",
".",
"Entry",
"<",
"String",
",",
"CmsClientProperty",
">",
"entry",
"=",
"iter",
".",
"next",
"(",
")",
";",
"CmsClientProperty",
"value",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
".",
"isEmpty",
"(",
")",
")",
"{",
"iter",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] |
Helper method for removing empty properties from a map.<p>
@param props the map from which to remove empty properties
|
[
"Helper",
"method",
"for",
"removing",
"empty",
"properties",
"from",
"a",
"map",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/shared/property/CmsClientProperty.java#L227-L237
|
phax/ph-commons
|
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
|
StringParser.parseLongObj
|
@Nullable
public static Long parseLongObj (@Nullable final String sStr, @Nullable final Long aDefault) {
"""
Parse the given {@link String} as {@link Long} with radix
{@link #DEFAULT_RADIX}.
@param sStr
The string to parse. May be <code>null</code>.
@param aDefault
The default value to be returned if the passed string could not be
converted to a valid value. May be <code>null</code>.
@return <code>aDefault</code> if the string does not represent a valid
value.
"""
return parseLongObj (sStr, DEFAULT_RADIX, aDefault);
}
|
java
|
@Nullable
public static Long parseLongObj (@Nullable final String sStr, @Nullable final Long aDefault)
{
return parseLongObj (sStr, DEFAULT_RADIX, aDefault);
}
|
[
"@",
"Nullable",
"public",
"static",
"Long",
"parseLongObj",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nullable",
"final",
"Long",
"aDefault",
")",
"{",
"return",
"parseLongObj",
"(",
"sStr",
",",
"DEFAULT_RADIX",
",",
"aDefault",
")",
";",
"}"
] |
Parse the given {@link String} as {@link Long} with radix
{@link #DEFAULT_RADIX}.
@param sStr
The string to parse. May be <code>null</code>.
@param aDefault
The default value to be returned if the passed string could not be
converted to a valid value. May be <code>null</code>.
@return <code>aDefault</code> if the string does not represent a valid
value.
|
[
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"{",
"@link",
"Long",
"}",
"with",
"radix",
"{",
"@link",
"#DEFAULT_RADIX",
"}",
"."
] |
train
|
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1133-L1137
|
algolia/algoliasearch-client-java
|
src/main/java/com/algolia/search/saas/Query.java
|
Query.setHighlightingTags
|
public Query setHighlightingTags(String preTag, String postTag) {
"""
/*
Specify the string that is inserted before/after the highlighted parts in
the query result (default to "<em>" / "</em>").
"""
this.highlightPreTag = preTag;
this.highlightPostTag = postTag;
return this;
}
|
java
|
public Query setHighlightingTags(String preTag, String postTag) {
this.highlightPreTag = preTag;
this.highlightPostTag = postTag;
return this;
}
|
[
"public",
"Query",
"setHighlightingTags",
"(",
"String",
"preTag",
",",
"String",
"postTag",
")",
"{",
"this",
".",
"highlightPreTag",
"=",
"preTag",
";",
"this",
".",
"highlightPostTag",
"=",
"postTag",
";",
"return",
"this",
";",
"}"
] |
/*
Specify the string that is inserted before/after the highlighted parts in
the query result (default to "<em>" / "</em>").
|
[
"/",
"*",
"Specify",
"the",
"string",
"that",
"is",
"inserted",
"before",
"/",
"after",
"the",
"highlighted",
"parts",
"in",
"the",
"query",
"result",
"(",
"default",
"to",
"<em",
">",
"/",
"<",
"/",
"em",
">",
")",
"."
] |
train
|
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Query.java#L327-L331
|
CloudSlang/cs-actions
|
cs-date-time/src/main/java/io/cloudslang/content/datetime/services/DateTimeService.java
|
DateTimeService.parseDate
|
public static String parseDate(final String date, final String dateFormat, final String dateLocaleLang,
final String dateLocaleCountry, final String outFormat, final String outLocaleLang,
final String outLocaleCountry) throws Exception {
"""
This operation converts the date input value from one date/time format (specified by dateFormat)
to another date/time format (specified by outFormat) using locale settings (language and country).
You can use the flow "Get Current Date and Time" to check upon the default date/time format from
the Java environment.
@param date the date to parse/convert
@param dateFormat the format of the input date
@param dateLocaleLang the locale language for input dateFormat string. It will be ignored if
dateFormat is empty. default locale language from the Java environment
(which is dependent on the OS locale language)
@param dateLocaleCountry the locale country for input dateFormat string. It will be ignored
if dateFormat is empty or dateLocaleLang is empty. Default locale country
from the Java environment (which is dependent on the OS locale country)
@param outFormat The format of the output date/time. Default date/time format from the Java
environment (which is dependent on the OS date/time format)
@param outLocaleLang The locale language for output string. It will be ignored if outFormat is
empty.
@param outLocaleCountry The locale country for output string. It will be ignored if outFormat
is empty or outLocaleLang is empty.
@return The date in the new format
"""
if (StringUtils.isBlank(date)) {
throw new RuntimeException(Constants.ErrorMessages.DATE_NULL_OR_EMPTY);
}
DateTimeZone timeZone = DateTimeZone.forID(Constants.Miscellaneous.GMT);
DateTime inputDateTime = parseInputDate(date, dateFormat, dateLocaleLang, dateLocaleCountry, timeZone);
return changeFormatForDateTime(inputDateTime, outFormat, outLocaleLang, outLocaleCountry);
}
|
java
|
public static String parseDate(final String date, final String dateFormat, final String dateLocaleLang,
final String dateLocaleCountry, final String outFormat, final String outLocaleLang,
final String outLocaleCountry) throws Exception {
if (StringUtils.isBlank(date)) {
throw new RuntimeException(Constants.ErrorMessages.DATE_NULL_OR_EMPTY);
}
DateTimeZone timeZone = DateTimeZone.forID(Constants.Miscellaneous.GMT);
DateTime inputDateTime = parseInputDate(date, dateFormat, dateLocaleLang, dateLocaleCountry, timeZone);
return changeFormatForDateTime(inputDateTime, outFormat, outLocaleLang, outLocaleCountry);
}
|
[
"public",
"static",
"String",
"parseDate",
"(",
"final",
"String",
"date",
",",
"final",
"String",
"dateFormat",
",",
"final",
"String",
"dateLocaleLang",
",",
"final",
"String",
"dateLocaleCountry",
",",
"final",
"String",
"outFormat",
",",
"final",
"String",
"outLocaleLang",
",",
"final",
"String",
"outLocaleCountry",
")",
"throws",
"Exception",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"date",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"Constants",
".",
"ErrorMessages",
".",
"DATE_NULL_OR_EMPTY",
")",
";",
"}",
"DateTimeZone",
"timeZone",
"=",
"DateTimeZone",
".",
"forID",
"(",
"Constants",
".",
"Miscellaneous",
".",
"GMT",
")",
";",
"DateTime",
"inputDateTime",
"=",
"parseInputDate",
"(",
"date",
",",
"dateFormat",
",",
"dateLocaleLang",
",",
"dateLocaleCountry",
",",
"timeZone",
")",
";",
"return",
"changeFormatForDateTime",
"(",
"inputDateTime",
",",
"outFormat",
",",
"outLocaleLang",
",",
"outLocaleCountry",
")",
";",
"}"
] |
This operation converts the date input value from one date/time format (specified by dateFormat)
to another date/time format (specified by outFormat) using locale settings (language and country).
You can use the flow "Get Current Date and Time" to check upon the default date/time format from
the Java environment.
@param date the date to parse/convert
@param dateFormat the format of the input date
@param dateLocaleLang the locale language for input dateFormat string. It will be ignored if
dateFormat is empty. default locale language from the Java environment
(which is dependent on the OS locale language)
@param dateLocaleCountry the locale country for input dateFormat string. It will be ignored
if dateFormat is empty or dateLocaleLang is empty. Default locale country
from the Java environment (which is dependent on the OS locale country)
@param outFormat The format of the output date/time. Default date/time format from the Java
environment (which is dependent on the OS date/time format)
@param outLocaleLang The locale language for output string. It will be ignored if outFormat is
empty.
@param outLocaleCountry The locale country for output string. It will be ignored if outFormat
is empty or outLocaleLang is empty.
@return The date in the new format
|
[
"This",
"operation",
"converts",
"the",
"date",
"input",
"value",
"from",
"one",
"date",
"/",
"time",
"format",
"(",
"specified",
"by",
"dateFormat",
")",
"to",
"another",
"date",
"/",
"time",
"format",
"(",
"specified",
"by",
"outFormat",
")",
"using",
"locale",
"settings",
"(",
"language",
"and",
"country",
")",
".",
"You",
"can",
"use",
"the",
"flow",
"Get",
"Current",
"Date",
"and",
"Time",
"to",
"check",
"upon",
"the",
"default",
"date",
"/",
"time",
"format",
"from",
"the",
"Java",
"environment",
"."
] |
train
|
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/services/DateTimeService.java#L105-L115
|
querydsl/querydsl
|
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
|
Expressions.stringTemplate
|
public static StringTemplate stringTemplate(String template, Object... args) {
"""
Create a new Template expression
@param template template
@param args template parameters
@return template expression
"""
return stringTemplate(createTemplate(template), ImmutableList.copyOf(args));
}
|
java
|
public static StringTemplate stringTemplate(String template, Object... args) {
return stringTemplate(createTemplate(template), ImmutableList.copyOf(args));
}
|
[
"public",
"static",
"StringTemplate",
"stringTemplate",
"(",
"String",
"template",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"stringTemplate",
"(",
"createTemplate",
"(",
"template",
")",
",",
"ImmutableList",
".",
"copyOf",
"(",
"args",
")",
")",
";",
"}"
] |
Create a new Template expression
@param template template
@param args template parameters
@return template expression
|
[
"Create",
"a",
"new",
"Template",
"expression"
] |
train
|
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L888-L890
|
ravendb/ravendb-jvm-client
|
src/main/java/net/ravendb/client/documents/session/AbstractDocumentQuery.java
|
AbstractDocumentQuery._orderBy
|
public void _orderBy(String field, OrderingType ordering) {
"""
Order the results by the specified fields
The fields are the names of the fields to sort, defaulting to sorting by ascending.
You can prefix a field name with '-' to indicate sorting by descending or '+' to sort by ascending
@param field field to use in order
@param ordering Ordering type
"""
assertNoRawQuery();
String f = ensureValidFieldName(field, false);
orderByTokens.add(OrderByToken.createAscending(f, ordering));
}
|
java
|
public void _orderBy(String field, OrderingType ordering) {
assertNoRawQuery();
String f = ensureValidFieldName(field, false);
orderByTokens.add(OrderByToken.createAscending(f, ordering));
}
|
[
"public",
"void",
"_orderBy",
"(",
"String",
"field",
",",
"OrderingType",
"ordering",
")",
"{",
"assertNoRawQuery",
"(",
")",
";",
"String",
"f",
"=",
"ensureValidFieldName",
"(",
"field",
",",
"false",
")",
";",
"orderByTokens",
".",
"add",
"(",
"OrderByToken",
".",
"createAscending",
"(",
"f",
",",
"ordering",
")",
")",
";",
"}"
] |
Order the results by the specified fields
The fields are the names of the fields to sort, defaulting to sorting by ascending.
You can prefix a field name with '-' to indicate sorting by descending or '+' to sort by ascending
@param field field to use in order
@param ordering Ordering type
|
[
"Order",
"the",
"results",
"by",
"the",
"specified",
"fields",
"The",
"fields",
"are",
"the",
"names",
"of",
"the",
"fields",
"to",
"sort",
"defaulting",
"to",
"sorting",
"by",
"ascending",
".",
"You",
"can",
"prefix",
"a",
"field",
"name",
"with",
"-",
"to",
"indicate",
"sorting",
"by",
"descending",
"or",
"+",
"to",
"sort",
"by",
"ascending"
] |
train
|
https://github.com/ravendb/ravendb-jvm-client/blob/5a45727de507b541d1571e79ddd97c7d88bee787/src/main/java/net/ravendb/client/documents/session/AbstractDocumentQuery.java#L932-L936
|
JDBDT/jdbdt
|
src/main/java/org/jdbdt/JDBDT.java
|
JDBDT.assertDeleted
|
@SafeVarargs
public static void assertDeleted(String message, DataSet... dataSets) throws DBAssertionError {
"""
Assert that database changed by removal of given
data sets (error message variant).
@param message Assertion error message.
@param dataSets Data sets.
@throws DBAssertionError if the assertion fails.
@see #assertDeleted(String,DataSet)
@since 1.2
"""
multipleDeleteAssertions(CallInfo.create(message), dataSets);
}
|
java
|
@SafeVarargs
public static void assertDeleted(String message, DataSet... dataSets) throws DBAssertionError {
multipleDeleteAssertions(CallInfo.create(message), dataSets);
}
|
[
"@",
"SafeVarargs",
"public",
"static",
"void",
"assertDeleted",
"(",
"String",
"message",
",",
"DataSet",
"...",
"dataSets",
")",
"throws",
"DBAssertionError",
"{",
"multipleDeleteAssertions",
"(",
"CallInfo",
".",
"create",
"(",
"message",
")",
",",
"dataSets",
")",
";",
"}"
] |
Assert that database changed by removal of given
data sets (error message variant).
@param message Assertion error message.
@param dataSets Data sets.
@throws DBAssertionError if the assertion fails.
@see #assertDeleted(String,DataSet)
@since 1.2
|
[
"Assert",
"that",
"database",
"changed",
"by",
"removal",
"of",
"given",
"data",
"sets",
"(",
"error",
"message",
"variant",
")",
"."
] |
train
|
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L480-L483
|
ModeShape/modeshape
|
modeshape-schematic/src/main/java/org/modeshape/schematic/internal/document/BasicArray.java
|
BasicArray.removeValues
|
private List<Entry> removeValues( Collection<?> values,
boolean ifMatch ) {
"""
Remove some of the values in this array.
@param values the values to be compared to this array's values
@param ifMatch true if this method should retain all values that match the supplied values, or false if this method should
remove all values that match the supplied values
@return the entries that were removed; never null
"""
LinkedList<Entry> results = null;
// Record the list of entries that are removed, but start at the end of the values (so the indexes are correct)
ListIterator<?> iter = this.values.listIterator(size());
while (iter.hasPrevious()) {
int index = iter.previousIndex();
Object value = iter.previous();
if (ifMatch == values.contains(value)) {
iter.remove();
if (results == null) {
results = new LinkedList<>();
}
results.addFirst(new BasicEntry(index, value));
}
}
return results != null ? results : Collections.<Entry>emptyList();
}
|
java
|
private List<Entry> removeValues( Collection<?> values,
boolean ifMatch ) {
LinkedList<Entry> results = null;
// Record the list of entries that are removed, but start at the end of the values (so the indexes are correct)
ListIterator<?> iter = this.values.listIterator(size());
while (iter.hasPrevious()) {
int index = iter.previousIndex();
Object value = iter.previous();
if (ifMatch == values.contains(value)) {
iter.remove();
if (results == null) {
results = new LinkedList<>();
}
results.addFirst(new BasicEntry(index, value));
}
}
return results != null ? results : Collections.<Entry>emptyList();
}
|
[
"private",
"List",
"<",
"Entry",
">",
"removeValues",
"(",
"Collection",
"<",
"?",
">",
"values",
",",
"boolean",
"ifMatch",
")",
"{",
"LinkedList",
"<",
"Entry",
">",
"results",
"=",
"null",
";",
"// Record the list of entries that are removed, but start at the end of the values (so the indexes are correct)",
"ListIterator",
"<",
"?",
">",
"iter",
"=",
"this",
".",
"values",
".",
"listIterator",
"(",
"size",
"(",
")",
")",
";",
"while",
"(",
"iter",
".",
"hasPrevious",
"(",
")",
")",
"{",
"int",
"index",
"=",
"iter",
".",
"previousIndex",
"(",
")",
";",
"Object",
"value",
"=",
"iter",
".",
"previous",
"(",
")",
";",
"if",
"(",
"ifMatch",
"==",
"values",
".",
"contains",
"(",
"value",
")",
")",
"{",
"iter",
".",
"remove",
"(",
")",
";",
"if",
"(",
"results",
"==",
"null",
")",
"{",
"results",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"}",
"results",
".",
"addFirst",
"(",
"new",
"BasicEntry",
"(",
"index",
",",
"value",
")",
")",
";",
"}",
"}",
"return",
"results",
"!=",
"null",
"?",
"results",
":",
"Collections",
".",
"<",
"Entry",
">",
"emptyList",
"(",
")",
";",
"}"
] |
Remove some of the values in this array.
@param values the values to be compared to this array's values
@param ifMatch true if this method should retain all values that match the supplied values, or false if this method should
remove all values that match the supplied values
@return the entries that were removed; never null
|
[
"Remove",
"some",
"of",
"the",
"values",
"in",
"this",
"array",
"."
] |
train
|
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-schematic/src/main/java/org/modeshape/schematic/internal/document/BasicArray.java#L721-L740
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
|
DataFrameJoiner.leftOuter
|
public Table leftOuter(boolean allowDuplicateColumnNames, Table... tables) {
"""
Joins to the given tables assuming that they have a column of the name we're joining on
@param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column have the same name
if {@code true} the join will succeed and duplicate columns are renamed*
@param tables The tables to join with
@return The resulting table
"""
Table joined = table;
for (Table table2 : tables) {
joined = leftOuter(table2, allowDuplicateColumnNames, columnNames);
}
return joined;
}
|
java
|
public Table leftOuter(boolean allowDuplicateColumnNames, Table... tables) {
Table joined = table;
for (Table table2 : tables) {
joined = leftOuter(table2, allowDuplicateColumnNames, columnNames);
}
return joined;
}
|
[
"public",
"Table",
"leftOuter",
"(",
"boolean",
"allowDuplicateColumnNames",
",",
"Table",
"...",
"tables",
")",
"{",
"Table",
"joined",
"=",
"table",
";",
"for",
"(",
"Table",
"table2",
":",
"tables",
")",
"{",
"joined",
"=",
"leftOuter",
"(",
"table2",
",",
"allowDuplicateColumnNames",
",",
"columnNames",
")",
";",
"}",
"return",
"joined",
";",
"}"
] |
Joins to the given tables assuming that they have a column of the name we're joining on
@param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column have the same name
if {@code true} the join will succeed and duplicate columns are renamed*
@param tables The tables to join with
@return The resulting table
|
[
"Joins",
"to",
"the",
"given",
"tables",
"assuming",
"that",
"they",
"have",
"a",
"column",
"of",
"the",
"name",
"we",
"re",
"joining",
"on"
] |
train
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java#L498-L504
|
overturetool/overture
|
ide/ui/src/main/java/org/overture/ide/ui/VdmPluginImages.java
|
VdmPluginImages.createUnManaged
|
private static ImageDescriptor createUnManaged(String prefix, String name) {
"""
/*
Creates an image descriptor for the given prefix and name in the JDT UI bundle. The path can contain variables
like $NL$. If no image could be found, the 'missing image descriptor' is returned.
"""
return create(prefix, name, true);
}
|
java
|
private static ImageDescriptor createUnManaged(String prefix, String name)
{
return create(prefix, name, true);
}
|
[
"private",
"static",
"ImageDescriptor",
"createUnManaged",
"(",
"String",
"prefix",
",",
"String",
"name",
")",
"{",
"return",
"create",
"(",
"prefix",
",",
"name",
",",
"true",
")",
";",
"}"
] |
/*
Creates an image descriptor for the given prefix and name in the JDT UI bundle. The path can contain variables
like $NL$. If no image could be found, the 'missing image descriptor' is returned.
|
[
"/",
"*",
"Creates",
"an",
"image",
"descriptor",
"for",
"the",
"given",
"prefix",
"and",
"name",
"in",
"the",
"JDT",
"UI",
"bundle",
".",
"The",
"path",
"can",
"contain",
"variables",
"like",
"$NL$",
".",
"If",
"no",
"image",
"could",
"be",
"found",
"the",
"missing",
"image",
"descriptor",
"is",
"returned",
"."
] |
train
|
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/ui/src/main/java/org/overture/ide/ui/VdmPluginImages.java#L793-L796
|
google/error-prone-javac
|
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java
|
MemberSummaryBuilder.buildAnnotationTypeRequiredMemberSummary
|
public void buildAnnotationTypeRequiredMemberSummary(XMLNode node, Content memberSummaryTree) {
"""
Build the summary for the optional members.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added
"""
MemberSummaryWriter writer =
memberSummaryWriters[VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED];
VisibleMemberMap visibleMemberMap =
visibleMemberMaps[VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED];
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
}
|
java
|
public void buildAnnotationTypeRequiredMemberSummary(XMLNode node, Content memberSummaryTree) {
MemberSummaryWriter writer =
memberSummaryWriters[VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED];
VisibleMemberMap visibleMemberMap =
visibleMemberMaps[VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED];
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
}
|
[
"public",
"void",
"buildAnnotationTypeRequiredMemberSummary",
"(",
"XMLNode",
"node",
",",
"Content",
"memberSummaryTree",
")",
"{",
"MemberSummaryWriter",
"writer",
"=",
"memberSummaryWriters",
"[",
"VisibleMemberMap",
".",
"ANNOTATION_TYPE_MEMBER_REQUIRED",
"]",
";",
"VisibleMemberMap",
"visibleMemberMap",
"=",
"visibleMemberMaps",
"[",
"VisibleMemberMap",
".",
"ANNOTATION_TYPE_MEMBER_REQUIRED",
"]",
";",
"addSummary",
"(",
"writer",
",",
"visibleMemberMap",
",",
"false",
",",
"memberSummaryTree",
")",
";",
"}"
] |
Build the summary for the optional members.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added
|
[
"Build",
"the",
"summary",
"for",
"the",
"optional",
"members",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java#L250-L256
|
JosePaumard/streams-utils
|
src/main/java/org/paumard/streams/StreamsUtils.java
|
StreamsUtils.filteringMaxKeys
|
public static <E extends Comparable<? super E>> Stream<E> filteringMaxKeys(Stream<E> stream, int numberOfMaxes) {
"""
<p>Generates a stream composed of the N greatest different values of the provided stream, compared using the
natural order. This method calls the <code>filteringMaxKeys()</code> with the natural order comparator,
please refer to this javadoc for details. </p>
<p>A <code>NullPointerException</code> will be thrown if the provided stream is null. </p>
<p>An <code>IllegalArgumentException</code> is thrown if N is lesser than 1. </p>
@param stream the processed stream
@param numberOfMaxes the number of different max values that should be returned. Note that the total number of
values returned may be larger if there are duplicates in the stream
@param <E> the type of the provided stream
@return the filtered stream
"""
return filteringMaxKeys(stream, numberOfMaxes, Comparator.naturalOrder());
}
|
java
|
public static <E extends Comparable<? super E>> Stream<E> filteringMaxKeys(Stream<E> stream, int numberOfMaxes) {
return filteringMaxKeys(stream, numberOfMaxes, Comparator.naturalOrder());
}
|
[
"public",
"static",
"<",
"E",
"extends",
"Comparable",
"<",
"?",
"super",
"E",
">",
">",
"Stream",
"<",
"E",
">",
"filteringMaxKeys",
"(",
"Stream",
"<",
"E",
">",
"stream",
",",
"int",
"numberOfMaxes",
")",
"{",
"return",
"filteringMaxKeys",
"(",
"stream",
",",
"numberOfMaxes",
",",
"Comparator",
".",
"naturalOrder",
"(",
")",
")",
";",
"}"
] |
<p>Generates a stream composed of the N greatest different values of the provided stream, compared using the
natural order. This method calls the <code>filteringMaxKeys()</code> with the natural order comparator,
please refer to this javadoc for details. </p>
<p>A <code>NullPointerException</code> will be thrown if the provided stream is null. </p>
<p>An <code>IllegalArgumentException</code> is thrown if N is lesser than 1. </p>
@param stream the processed stream
@param numberOfMaxes the number of different max values that should be returned. Note that the total number of
values returned may be larger if there are duplicates in the stream
@param <E> the type of the provided stream
@return the filtered stream
|
[
"<p",
">",
"Generates",
"a",
"stream",
"composed",
"of",
"the",
"N",
"greatest",
"different",
"values",
"of",
"the",
"provided",
"stream",
"compared",
"using",
"the",
"natural",
"order",
".",
"This",
"method",
"calls",
"the",
"<code",
">",
"filteringMaxKeys",
"()",
"<",
"/",
"code",
">",
"with",
"the",
"natural",
"order",
"comparator",
"please",
"refer",
"to",
"this",
"javadoc",
"for",
"details",
".",
"<",
"/",
"p",
">",
"<p",
">",
"A",
"<code",
">",
"NullPointerException<",
"/",
"code",
">",
"will",
"be",
"thrown",
"if",
"the",
"provided",
"stream",
"is",
"null",
".",
"<",
"/",
"p",
">",
"<p",
">",
"An",
"<code",
">",
"IllegalArgumentException<",
"/",
"code",
">",
"is",
"thrown",
"if",
"N",
"is",
"lesser",
"than",
"1",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/JosePaumard/streams-utils/blob/56152574af0aca44c5f679761202a8f90984ab73/src/main/java/org/paumard/streams/StreamsUtils.java#L1056-L1059
|
JOML-CI/JOML
|
src/org/joml/Matrix4x3d.java
|
Matrix4x3d.translateLocal
|
public Matrix4x3d translateLocal(Vector3fc offset, Matrix4x3d dest) {
"""
Pre-multiply a translation to this matrix by translating by the given number of
units in x, y and z and store the result in <code>dest</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation
matrix, then the new matrix will be <code>T * M</code>. So when
transforming a vector <code>v</code> with the new matrix by using
<code>T * M * v</code>, the translation will be applied last!
<p>
In order to set the matrix to a translation transformation without pre-multiplying
it, use {@link #translation(Vector3fc)}.
@see #translation(Vector3fc)
@param offset
the number of units in x, y and z by which to translate
@param dest
will hold the result
@return dest
"""
return translateLocal(offset.x(), offset.y(), offset.z(), dest);
}
|
java
|
public Matrix4x3d translateLocal(Vector3fc offset, Matrix4x3d dest) {
return translateLocal(offset.x(), offset.y(), offset.z(), dest);
}
|
[
"public",
"Matrix4x3d",
"translateLocal",
"(",
"Vector3fc",
"offset",
",",
"Matrix4x3d",
"dest",
")",
"{",
"return",
"translateLocal",
"(",
"offset",
".",
"x",
"(",
")",
",",
"offset",
".",
"y",
"(",
")",
",",
"offset",
".",
"z",
"(",
")",
",",
"dest",
")",
";",
"}"
] |
Pre-multiply a translation to this matrix by translating by the given number of
units in x, y and z and store the result in <code>dest</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>T</code> the translation
matrix, then the new matrix will be <code>T * M</code>. So when
transforming a vector <code>v</code> with the new matrix by using
<code>T * M * v</code>, the translation will be applied last!
<p>
In order to set the matrix to a translation transformation without pre-multiplying
it, use {@link #translation(Vector3fc)}.
@see #translation(Vector3fc)
@param offset
the number of units in x, y and z by which to translate
@param dest
will hold the result
@return dest
|
[
"Pre",
"-",
"multiply",
"a",
"translation",
"to",
"this",
"matrix",
"by",
"translating",
"by",
"the",
"given",
"number",
"of",
"units",
"in",
"x",
"y",
"and",
"z",
"and",
"store",
"the",
"result",
"in",
"<code",
">",
"dest<",
"/",
"code",
">",
".",
"<p",
">",
"If",
"<code",
">",
"M<",
"/",
"code",
">",
"is",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"and",
"<code",
">",
"T<",
"/",
"code",
">",
"the",
"translation",
"matrix",
"then",
"the",
"new",
"matrix",
"will",
"be",
"<code",
">",
"T",
"*",
"M<",
"/",
"code",
">",
".",
"So",
"when",
"transforming",
"a",
"vector",
"<code",
">",
"v<",
"/",
"code",
">",
"with",
"the",
"new",
"matrix",
"by",
"using",
"<code",
">",
"T",
"*",
"M",
"*",
"v<",
"/",
"code",
">",
"the",
"translation",
"will",
"be",
"applied",
"last!",
"<p",
">",
"In",
"order",
"to",
"set",
"the",
"matrix",
"to",
"a",
"translation",
"transformation",
"without",
"pre",
"-",
"multiplying",
"it",
"use",
"{",
"@link",
"#translation",
"(",
"Vector3fc",
")",
"}",
"."
] |
train
|
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L4011-L4013
|
qspin/qtaste
|
kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java
|
TextUtilities.findWordStart
|
public static int findWordStart(String text, int pos, String noWordSep) {
"""
Locates the start of the word at the specified position.
@param text the text
@param pos The position
@param noWordSep Characters that are non-alphanumeric, but
should be treated as word characters anyway
"""
return findWordStart(text, pos, noWordSep, true, false);
}
|
java
|
public static int findWordStart(String text, int pos, String noWordSep) {
return findWordStart(text, pos, noWordSep, true, false);
}
|
[
"public",
"static",
"int",
"findWordStart",
"(",
"String",
"text",
",",
"int",
"pos",
",",
"String",
"noWordSep",
")",
"{",
"return",
"findWordStart",
"(",
"text",
",",
"pos",
",",
"noWordSep",
",",
"true",
",",
"false",
")",
";",
"}"
] |
Locates the start of the word at the specified position.
@param text the text
@param pos The position
@param noWordSep Characters that are non-alphanumeric, but
should be treated as word characters anyway
|
[
"Locates",
"the",
"start",
"of",
"the",
"word",
"at",
"the",
"specified",
"position",
"."
] |
train
|
https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java#L34-L36
|
JavaMoney/jsr354-ri-bp
|
src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java
|
BaseMonetaryCurrenciesSingletonSpi.getCurrency
|
public CurrencyUnit getCurrency(CurrencyQuery query) {
"""
Access a single currency by query.
@param query The currency query, not null.
@return the {@link javax.money.CurrencyUnit} found, never null.
@throws javax.money.MonetaryException if multiple currencies match the query.
"""
Set<CurrencyUnit> currencies = getCurrencies(query);
if (currencies.isEmpty()) {
return null;
}
if (currencies.size() == 1) {
return currencies.iterator().next();
}
throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies);
}
|
java
|
public CurrencyUnit getCurrency(CurrencyQuery query) {
Set<CurrencyUnit> currencies = getCurrencies(query);
if (currencies.isEmpty()) {
return null;
}
if (currencies.size() == 1) {
return currencies.iterator().next();
}
throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies);
}
|
[
"public",
"CurrencyUnit",
"getCurrency",
"(",
"CurrencyQuery",
"query",
")",
"{",
"Set",
"<",
"CurrencyUnit",
">",
"currencies",
"=",
"getCurrencies",
"(",
"query",
")",
";",
"if",
"(",
"currencies",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"currencies",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"return",
"currencies",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
";",
"}",
"throw",
"new",
"MonetaryException",
"(",
"\"Ambiguous request for CurrencyUnit: \"",
"+",
"query",
"+",
"\", found: \"",
"+",
"currencies",
")",
";",
"}"
] |
Access a single currency by query.
@param query The currency query, not null.
@return the {@link javax.money.CurrencyUnit} found, never null.
@throws javax.money.MonetaryException if multiple currencies match the query.
|
[
"Access",
"a",
"single",
"currency",
"by",
"query",
"."
] |
train
|
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java#L144-L153
|
phax/ph-schedule
|
ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java
|
DateBuilder.nextGivenSecondDate
|
public static Date nextGivenSecondDate (final Date date, final int secondBase) {
"""
<p>
Returns a date that is rounded to the next even multiple of the given
minute.
</p>
<p>
The rules for calculating the second are the same as those for calculating
the minute in the method <code>getNextGivenMinuteDate(..)</code>.
</p>
@param date
the Date to round, if <code>null</code> the current time will be
used
@param secondBase
the base-second to set the time on
@return the new rounded date
@see #nextGivenMinuteDate(Date, int)
"""
if (secondBase < 0 || secondBase > 59)
throw new IllegalArgumentException ("secondBase must be >=0 and <= 59");
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date != null ? date : new Date ());
c.setLenient (true);
if (secondBase == 0)
{
c.set (Calendar.MINUTE, c.get (Calendar.MINUTE) + 1);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
final int second = c.get (Calendar.SECOND);
final int arItr = second / secondBase;
final int nextSecondOccurance = secondBase * (arItr + 1);
if (nextSecondOccurance < 60)
{
c.set (Calendar.SECOND, nextSecondOccurance);
c.set (Calendar.MILLISECOND, 0);
}
else
{
c.set (Calendar.MINUTE, c.get (Calendar.MINUTE) + 1);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
}
return c.getTime ();
}
|
java
|
public static Date nextGivenSecondDate (final Date date, final int secondBase)
{
if (secondBase < 0 || secondBase > 59)
throw new IllegalArgumentException ("secondBase must be >=0 and <= 59");
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date != null ? date : new Date ());
c.setLenient (true);
if (secondBase == 0)
{
c.set (Calendar.MINUTE, c.get (Calendar.MINUTE) + 1);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
final int second = c.get (Calendar.SECOND);
final int arItr = second / secondBase;
final int nextSecondOccurance = secondBase * (arItr + 1);
if (nextSecondOccurance < 60)
{
c.set (Calendar.SECOND, nextSecondOccurance);
c.set (Calendar.MILLISECOND, 0);
}
else
{
c.set (Calendar.MINUTE, c.get (Calendar.MINUTE) + 1);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
}
return c.getTime ();
}
|
[
"public",
"static",
"Date",
"nextGivenSecondDate",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"secondBase",
")",
"{",
"if",
"(",
"secondBase",
"<",
"0",
"||",
"secondBase",
">",
"59",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"secondBase must be >=0 and <= 59\"",
")",
";",
"final",
"Calendar",
"c",
"=",
"PDTFactory",
".",
"createCalendar",
"(",
")",
";",
"c",
".",
"setTime",
"(",
"date",
"!=",
"null",
"?",
"date",
":",
"new",
"Date",
"(",
")",
")",
";",
"c",
".",
"setLenient",
"(",
"true",
")",
";",
"if",
"(",
"secondBase",
"==",
"0",
")",
"{",
"c",
".",
"set",
"(",
"Calendar",
".",
"MINUTE",
",",
"c",
".",
"get",
"(",
"Calendar",
".",
"MINUTE",
")",
"+",
"1",
")",
";",
"c",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"0",
")",
";",
"c",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
";",
"}",
"else",
"{",
"final",
"int",
"second",
"=",
"c",
".",
"get",
"(",
"Calendar",
".",
"SECOND",
")",
";",
"final",
"int",
"arItr",
"=",
"second",
"/",
"secondBase",
";",
"final",
"int",
"nextSecondOccurance",
"=",
"secondBase",
"*",
"(",
"arItr",
"+",
"1",
")",
";",
"if",
"(",
"nextSecondOccurance",
"<",
"60",
")",
"{",
"c",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"nextSecondOccurance",
")",
";",
"c",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
";",
"}",
"else",
"{",
"c",
".",
"set",
"(",
"Calendar",
".",
"MINUTE",
",",
"c",
".",
"get",
"(",
"Calendar",
".",
"MINUTE",
")",
"+",
"1",
")",
";",
"c",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"0",
")",
";",
"c",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
";",
"}",
"}",
"return",
"c",
".",
"getTime",
"(",
")",
";",
"}"
] |
<p>
Returns a date that is rounded to the next even multiple of the given
minute.
</p>
<p>
The rules for calculating the second are the same as those for calculating
the minute in the method <code>getNextGivenMinuteDate(..)</code>.
</p>
@param date
the Date to round, if <code>null</code> the current time will be
used
@param secondBase
the base-second to set the time on
@return the new rounded date
@see #nextGivenMinuteDate(Date, int)
|
[
"<p",
">",
"Returns",
"a",
"date",
"that",
"is",
"rounded",
"to",
"the",
"next",
"even",
"multiple",
"of",
"the",
"given",
"minute",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"rules",
"for",
"calculating",
"the",
"second",
"are",
"the",
"same",
"as",
"those",
"for",
"calculating",
"the",
"minute",
"in",
"the",
"method",
"<code",
">",
"getNextGivenMinuteDate",
"(",
"..",
")",
"<",
"/",
"code",
">",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java#L868-L901
|
wisdom-framework/wisdom
|
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ExecUtils.java
|
ExecUtils.findExecutableInDirectory
|
public static File findExecutableInDirectory(String executable, File directory) {
"""
Tries to find the given executable (specified by its name) in the given directory. It checks for a file having
one of the extensions contained in {@link #EXECUTABLE_EXTENSIONS}, and checks that this file is executable.
@param executable the name of the program to find, generally without the extension
@param directory the directory in which the program is searched.
@return the file of the program to be searched for if found. {@code null} otherwise. If the given directory is
{@code null} or not a real directory, it also returns {@code null}.
"""
if (directory == null || !directory.isDirectory()) {
// if the directory is null or not a directory => returning null.
return null;
}
for (String extension : EXECUTABLE_EXTENSIONS) {
File file = new File(directory, executable + extension);
if (file.isFile() && file.canExecute()) {
return file;
}
}
// Not found.
return null;
}
|
java
|
public static File findExecutableInDirectory(String executable, File directory) {
if (directory == null || !directory.isDirectory()) {
// if the directory is null or not a directory => returning null.
return null;
}
for (String extension : EXECUTABLE_EXTENSIONS) {
File file = new File(directory, executable + extension);
if (file.isFile() && file.canExecute()) {
return file;
}
}
// Not found.
return null;
}
|
[
"public",
"static",
"File",
"findExecutableInDirectory",
"(",
"String",
"executable",
",",
"File",
"directory",
")",
"{",
"if",
"(",
"directory",
"==",
"null",
"||",
"!",
"directory",
".",
"isDirectory",
"(",
")",
")",
"{",
"// if the directory is null or not a directory => returning null.",
"return",
"null",
";",
"}",
"for",
"(",
"String",
"extension",
":",
"EXECUTABLE_EXTENSIONS",
")",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"directory",
",",
"executable",
"+",
"extension",
")",
";",
"if",
"(",
"file",
".",
"isFile",
"(",
")",
"&&",
"file",
".",
"canExecute",
"(",
")",
")",
"{",
"return",
"file",
";",
"}",
"}",
"// Not found.",
"return",
"null",
";",
"}"
] |
Tries to find the given executable (specified by its name) in the given directory. It checks for a file having
one of the extensions contained in {@link #EXECUTABLE_EXTENSIONS}, and checks that this file is executable.
@param executable the name of the program to find, generally without the extension
@param directory the directory in which the program is searched.
@return the file of the program to be searched for if found. {@code null} otherwise. If the given directory is
{@code null} or not a real directory, it also returns {@code null}.
|
[
"Tries",
"to",
"find",
"the",
"given",
"executable",
"(",
"specified",
"by",
"its",
"name",
")",
"in",
"the",
"given",
"directory",
".",
"It",
"checks",
"for",
"a",
"file",
"having",
"one",
"of",
"the",
"extensions",
"contained",
"in",
"{",
"@link",
"#EXECUTABLE_EXTENSIONS",
"}",
"and",
"checks",
"that",
"this",
"file",
"is",
"executable",
"."
] |
train
|
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ExecUtils.java#L78-L91
|
xcesco/kripton
|
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/InsertListBeanHelper.java
|
InsertListBeanHelper.generateJavaDoc
|
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
"""
Generate java doc.
@param methodBuilder
the method builder
@param method
the method
@param returnType
the return type
@param listUsedProperty
the list used property
@param primaryKey
the primary key
"""
// transform JQL to SQL
String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnName(String columnName) {
Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);
SQLProperty tempProperty = property.iterator().next();
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
@Override
public String onBindParameter(String bindParameterName, boolean inStatement) {
String resolvedParamName = method.findParameterNameByAlias(bindParameterName);
return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
}
});
// generate javadoc and result
{
String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);
methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
methodBuilder.addJavadoc(
"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
beanNameParameter, primaryKey.getName());
methodBuilder.addJavadoc("\n");
// list of inserted fields
methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
methodBuilder.addJavadoc("<dl>\n");
for (SQLProperty property : listUsedProperty) {
methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
}
methodBuilder.addJavadoc("</dl>\n\n");
// update bean have only one parameter: the bean to update
for (Pair<String, TypeName> param : method.getParameters()) {
methodBuilder.addJavadoc("@param $L", param.value0);
methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
method.findParameterAliasByName(param.value0));
}
InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
}
}
|
java
|
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
// transform JQL to SQL
String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnName(String columnName) {
Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);
SQLProperty tempProperty = property.iterator().next();
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
@Override
public String onBindParameter(String bindParameterName, boolean inStatement) {
String resolvedParamName = method.findParameterNameByAlias(bindParameterName);
return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
}
});
// generate javadoc and result
{
String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);
methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
methodBuilder.addJavadoc(
"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
beanNameParameter, primaryKey.getName());
methodBuilder.addJavadoc("\n");
// list of inserted fields
methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
methodBuilder.addJavadoc("<dl>\n");
for (SQLProperty property : listUsedProperty) {
methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
}
methodBuilder.addJavadoc("</dl>\n\n");
// update bean have only one parameter: the bean to update
for (Pair<String, TypeName> param : method.getParameters()) {
methodBuilder.addJavadoc("@param $L", param.value0);
methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
method.findParameterAliasByName(param.value0));
}
InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
}
}
|
[
"public",
"void",
"generateJavaDoc",
"(",
"MethodSpec",
".",
"Builder",
"methodBuilder",
",",
"final",
"SQLiteModelMethod",
"method",
",",
"TypeName",
"returnType",
",",
"List",
"<",
"SQLProperty",
">",
"listUsedProperty",
",",
"ModelProperty",
"primaryKey",
")",
"{",
"// transform JQL to SQL",
"String",
"sqlInsert",
"=",
"JQLChecker",
".",
"getInstance",
"(",
")",
".",
"replace",
"(",
"method",
",",
"method",
".",
"jql",
",",
"new",
"JQLReplacerListenerImpl",
"(",
"method",
")",
"{",
"@",
"Override",
"public",
"String",
"onColumnName",
"(",
"String",
"columnName",
")",
"{",
"Set",
"<",
"SQLProperty",
">",
"property",
"=",
"currentSchema",
".",
"getPropertyBySimpleName",
"(",
"columnName",
")",
";",
"SQLProperty",
"tempProperty",
"=",
"property",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
";",
"AssertKripton",
".",
"assertTrueOrUnknownPropertyInJQLException",
"(",
"tempProperty",
"!=",
"null",
",",
"method",
",",
"columnName",
")",
";",
"return",
"tempProperty",
".",
"columnName",
";",
"}",
"@",
"Override",
"public",
"String",
"onBindParameter",
"(",
"String",
"bindParameterName",
",",
"boolean",
"inStatement",
")",
"{",
"String",
"resolvedParamName",
"=",
"method",
".",
"findParameterNameByAlias",
"(",
"bindParameterName",
")",
";",
"return",
"SqlAnalyzer",
".",
"PARAM_PREFIX",
"+",
"resolvedParamName",
"+",
"SqlAnalyzer",
".",
"PARAM_SUFFIX",
";",
"}",
"}",
")",
";",
"// generate javadoc and result",
"{",
"String",
"beanNameParameter",
"=",
"method",
".",
"findParameterAliasByName",
"(",
"method",
".",
"getParameters",
"(",
")",
".",
"get",
"(",
"0",
")",
".",
"value0",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<h2>SQL insert</h2>\\n\"",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<pre>$L</pre>\\n\\n\"",
",",
"sqlInsert",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\\n\"",
",",
"beanNameParameter",
",",
"primaryKey",
".",
"getName",
"(",
")",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"\\n\"",
")",
";",
"// list of inserted fields",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<p><strong>Inserted columns:</strong></p>\\n\"",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<dl>\\n\"",
")",
";",
"for",
"(",
"SQLProperty",
"property",
":",
"listUsedProperty",
")",
"{",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"\\t<dt>$L</dt>\"",
",",
"property",
".",
"columnName",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"<dd>is mapped to <strong>$L</strong></dd>\\n\"",
",",
"SqlAnalyzer",
".",
"PARAM_PREFIX",
"+",
"method",
".",
"findParameterAliasByName",
"(",
"method",
".",
"getParameters",
"(",
")",
".",
"get",
"(",
"0",
")",
".",
"value0",
")",
"+",
"\".\"",
"+",
"method",
".",
"findParameterNameByAlias",
"(",
"property",
".",
"getName",
"(",
")",
")",
"+",
"SqlAnalyzer",
".",
"PARAM_SUFFIX",
")",
";",
"}",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"</dl>\\n\\n\"",
")",
";",
"// update bean have only one parameter: the bean to update",
"for",
"(",
"Pair",
"<",
"String",
",",
"TypeName",
">",
"param",
":",
"method",
".",
"getParameters",
"(",
")",
")",
"{",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"@param $L\"",
",",
"param",
".",
"value0",
")",
";",
"methodBuilder",
".",
"addJavadoc",
"(",
"\"\\n\\tis mapped to parameter <strong>$L</strong>\\n\"",
",",
"method",
".",
"findParameterAliasByName",
"(",
"param",
".",
"value0",
")",
")",
";",
"}",
"InsertRawHelper",
".",
"generateJavaDocReturnType",
"(",
"methodBuilder",
",",
"returnType",
")",
";",
"}",
"}"
] |
Generate java doc.
@param methodBuilder
the method builder
@param method
the method
@param returnType
the return type
@param listUsedProperty
the list used property
@param primaryKey
the primary key
|
[
"Generate",
"java",
"doc",
"."
] |
train
|
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/InsertListBeanHelper.java#L208-L263
|
geomajas/geomajas-project-server
|
plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java
|
PdfContext.drawImage
|
public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {
"""
Draws the specified image with the first rectangle's bounds, clipping with the second one.
@param img image
@param rect rectangle
@param clipRect clipping bounds
@param opacity opacity of the image (1 = opaque, 0= transparent)
"""
try {
template.saveState();
// opacity
PdfGState state = new PdfGState();
state.setFillOpacity(opacity);
state.setBlendMode(PdfGState.BM_NORMAL);
template.setGState(state);
// clipping code
if (clipRect != null) {
template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
clipRect.getHeight());
template.clip();
template.newPath();
}
template.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY
+ rect.getBottom());
} catch (DocumentException e) {
log.warn("could not draw image", e);
} finally {
template.restoreState();
}
}
|
java
|
public void drawImage(Image img, Rectangle rect, Rectangle clipRect, float opacity) {
try {
template.saveState();
// opacity
PdfGState state = new PdfGState();
state.setFillOpacity(opacity);
state.setBlendMode(PdfGState.BM_NORMAL);
template.setGState(state);
// clipping code
if (clipRect != null) {
template.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(),
clipRect.getHeight());
template.clip();
template.newPath();
}
template.addImage(img, rect.getWidth(), 0, 0, rect.getHeight(), origX + rect.getLeft(), origY
+ rect.getBottom());
} catch (DocumentException e) {
log.warn("could not draw image", e);
} finally {
template.restoreState();
}
}
|
[
"public",
"void",
"drawImage",
"(",
"Image",
"img",
",",
"Rectangle",
"rect",
",",
"Rectangle",
"clipRect",
",",
"float",
"opacity",
")",
"{",
"try",
"{",
"template",
".",
"saveState",
"(",
")",
";",
"// opacity",
"PdfGState",
"state",
"=",
"new",
"PdfGState",
"(",
")",
";",
"state",
".",
"setFillOpacity",
"(",
"opacity",
")",
";",
"state",
".",
"setBlendMode",
"(",
"PdfGState",
".",
"BM_NORMAL",
")",
";",
"template",
".",
"setGState",
"(",
"state",
")",
";",
"// clipping code",
"if",
"(",
"clipRect",
"!=",
"null",
")",
"{",
"template",
".",
"rectangle",
"(",
"clipRect",
".",
"getLeft",
"(",
")",
"+",
"origX",
",",
"clipRect",
".",
"getBottom",
"(",
")",
"+",
"origY",
",",
"clipRect",
".",
"getWidth",
"(",
")",
",",
"clipRect",
".",
"getHeight",
"(",
")",
")",
";",
"template",
".",
"clip",
"(",
")",
";",
"template",
".",
"newPath",
"(",
")",
";",
"}",
"template",
".",
"addImage",
"(",
"img",
",",
"rect",
".",
"getWidth",
"(",
")",
",",
"0",
",",
"0",
",",
"rect",
".",
"getHeight",
"(",
")",
",",
"origX",
"+",
"rect",
".",
"getLeft",
"(",
")",
",",
"origY",
"+",
"rect",
".",
"getBottom",
"(",
")",
")",
";",
"}",
"catch",
"(",
"DocumentException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"could not draw image\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"template",
".",
"restoreState",
"(",
")",
";",
"}",
"}"
] |
Draws the specified image with the first rectangle's bounds, clipping with the second one.
@param img image
@param rect rectangle
@param clipRect clipping bounds
@param opacity opacity of the image (1 = opaque, 0= transparent)
|
[
"Draws",
"the",
"specified",
"image",
"with",
"the",
"first",
"rectangle",
"s",
"bounds",
"clipping",
"with",
"the",
"second",
"one",
"."
] |
train
|
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java#L401-L423
|
kazocsaba/matrix
|
src/main/java/hu/kazocsaba/math/matrix/immutable/ImmutableMatrixFactory.java
|
ImmutableMatrixFactory.zeros
|
public static ImmutableMatrix zeros(final int rows, final int cols) {
"""
Returns an immutable matrix of the specified size whose elements are all 0.
@param rows the number of rows
@param cols the number of columns
@return a <code>rows</code>×<code>cols</code> matrix whose elements are all 0
@throws IllegalArgumentException if either argument is non-positive
"""
if (rows <= 0 || cols <= 0) throw new IllegalArgumentException("Invalid dimensions");
return create(new ImmutableData(rows, cols) {
@Override
public double getQuick(int row, int col) {
return 0;
}
});
}
|
java
|
public static ImmutableMatrix zeros(final int rows, final int cols) {
if (rows <= 0 || cols <= 0) throw new IllegalArgumentException("Invalid dimensions");
return create(new ImmutableData(rows, cols) {
@Override
public double getQuick(int row, int col) {
return 0;
}
});
}
|
[
"public",
"static",
"ImmutableMatrix",
"zeros",
"(",
"final",
"int",
"rows",
",",
"final",
"int",
"cols",
")",
"{",
"if",
"(",
"rows",
"<=",
"0",
"||",
"cols",
"<=",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid dimensions\"",
")",
";",
"return",
"create",
"(",
"new",
"ImmutableData",
"(",
"rows",
",",
"cols",
")",
"{",
"@",
"Override",
"public",
"double",
"getQuick",
"(",
"int",
"row",
",",
"int",
"col",
")",
"{",
"return",
"0",
";",
"}",
"}",
")",
";",
"}"
] |
Returns an immutable matrix of the specified size whose elements are all 0.
@param rows the number of rows
@param cols the number of columns
@return a <code>rows</code>×<code>cols</code> matrix whose elements are all 0
@throws IllegalArgumentException if either argument is non-positive
|
[
"Returns",
"an",
"immutable",
"matrix",
"of",
"the",
"specified",
"size",
"whose",
"elements",
"are",
"all",
"0",
"."
] |
train
|
https://github.com/kazocsaba/matrix/blob/018570db945fe616b25606fe605fa6e0c180ab5b/src/main/java/hu/kazocsaba/math/matrix/immutable/ImmutableMatrixFactory.java#L223-L231
|
grails/grails-core
|
grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java
|
GrailsMetaClassUtils.getPropertyIfExists
|
public static Object getPropertyIfExists(Object instance, String property) {
"""
Obtains a property of an instance if it exists
@param instance The instance
@param property The property
@return The value of null if non-exists
"""
return getPropertyIfExists(instance, property, Object.class);
}
|
java
|
public static Object getPropertyIfExists(Object instance, String property) {
return getPropertyIfExists(instance, property, Object.class);
}
|
[
"public",
"static",
"Object",
"getPropertyIfExists",
"(",
"Object",
"instance",
",",
"String",
"property",
")",
"{",
"return",
"getPropertyIfExists",
"(",
"instance",
",",
"property",
",",
"Object",
".",
"class",
")",
";",
"}"
] |
Obtains a property of an instance if it exists
@param instance The instance
@param property The property
@return The value of null if non-exists
|
[
"Obtains",
"a",
"property",
"of",
"an",
"instance",
"if",
"it",
"exists"
] |
train
|
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java#L195-L197
|
google/error-prone-javac
|
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java
|
AnnotationTypeFieldBuilder.buildAnnotationTypeMember
|
public void buildAnnotationTypeMember(XMLNode node, Content memberDetailsTree)
throws DocletException {
"""
Build the member documentation.
@param node the XML element that specifies which components to document
@param memberDetailsTree the content tree to which the documentation will be added
@throws DocletException if there is a problem while building the documentation
"""
if (writer == null) {
return;
}
if (hasMembersToDocument()) {
writer.addAnnotationFieldDetailsMarker(memberDetailsTree);
Element lastElement = members.get(members.size() - 1);
for (Element member : members) {
currentMember = member;
Content detailsTree = writer.getMemberTreeHeader();
writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree);
Content annotationDocTree = writer.getAnnotationDocTreeHeader(currentMember,
detailsTree);
buildChildren(node, annotationDocTree);
detailsTree.addContent(writer.getAnnotationDoc(
annotationDocTree, currentMember == lastElement));
memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree));
}
}
}
|
java
|
public void buildAnnotationTypeMember(XMLNode node, Content memberDetailsTree)
throws DocletException {
if (writer == null) {
return;
}
if (hasMembersToDocument()) {
writer.addAnnotationFieldDetailsMarker(memberDetailsTree);
Element lastElement = members.get(members.size() - 1);
for (Element member : members) {
currentMember = member;
Content detailsTree = writer.getMemberTreeHeader();
writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree);
Content annotationDocTree = writer.getAnnotationDocTreeHeader(currentMember,
detailsTree);
buildChildren(node, annotationDocTree);
detailsTree.addContent(writer.getAnnotationDoc(
annotationDocTree, currentMember == lastElement));
memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree));
}
}
}
|
[
"public",
"void",
"buildAnnotationTypeMember",
"(",
"XMLNode",
"node",
",",
"Content",
"memberDetailsTree",
")",
"throws",
"DocletException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"hasMembersToDocument",
"(",
")",
")",
"{",
"writer",
".",
"addAnnotationFieldDetailsMarker",
"(",
"memberDetailsTree",
")",
";",
"Element",
"lastElement",
"=",
"members",
".",
"get",
"(",
"members",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"for",
"(",
"Element",
"member",
":",
"members",
")",
"{",
"currentMember",
"=",
"member",
";",
"Content",
"detailsTree",
"=",
"writer",
".",
"getMemberTreeHeader",
"(",
")",
";",
"writer",
".",
"addAnnotationDetailsTreeHeader",
"(",
"typeElement",
",",
"detailsTree",
")",
";",
"Content",
"annotationDocTree",
"=",
"writer",
".",
"getAnnotationDocTreeHeader",
"(",
"currentMember",
",",
"detailsTree",
")",
";",
"buildChildren",
"(",
"node",
",",
"annotationDocTree",
")",
";",
"detailsTree",
".",
"addContent",
"(",
"writer",
".",
"getAnnotationDoc",
"(",
"annotationDocTree",
",",
"currentMember",
"==",
"lastElement",
")",
")",
";",
"memberDetailsTree",
".",
"addContent",
"(",
"writer",
".",
"getAnnotationDetails",
"(",
"detailsTree",
")",
")",
";",
"}",
"}",
"}"
] |
Build the member documentation.
@param node the XML element that specifies which components to document
@param memberDetailsTree the content tree to which the documentation will be added
@throws DocletException if there is a problem while building the documentation
|
[
"Build",
"the",
"member",
"documentation",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java#L150-L171
|
lessthanoptimal/ejml
|
main/ejml-dsparse/src/org/ejml/sparse/csc/misc/TriangularSolver_DSCC.java
|
TriangularSolver_DSCC.solveU
|
public static void solveU(DMatrixSparseCSC U , double []x ) {
"""
Solves for an upper triangular matrix against a dense vector. U*x = b
@param U Upper triangular matrix. Diagonal elements are assumed to be non-zero
@param x (Input) Solution matrix 'b'. (Output) matrix 'x'
"""
final int N = U.numCols;
int idx1 = U.col_idx[N];
for (int col = N-1; col >= 0; col--) {
int idx0 = U.col_idx[col];
double x_j = x[col] /= U.nz_values[idx1-1];
for (int i = idx0; i < idx1 - 1; i++) {
int row = U.nz_rows[i];
x[row] -= U.nz_values[i] * x_j;
}
idx1 = idx0;
}
}
|
java
|
public static void solveU(DMatrixSparseCSC U , double []x )
{
final int N = U.numCols;
int idx1 = U.col_idx[N];
for (int col = N-1; col >= 0; col--) {
int idx0 = U.col_idx[col];
double x_j = x[col] /= U.nz_values[idx1-1];
for (int i = idx0; i < idx1 - 1; i++) {
int row = U.nz_rows[i];
x[row] -= U.nz_values[i] * x_j;
}
idx1 = idx0;
}
}
|
[
"public",
"static",
"void",
"solveU",
"(",
"DMatrixSparseCSC",
"U",
",",
"double",
"[",
"]",
"x",
")",
"{",
"final",
"int",
"N",
"=",
"U",
".",
"numCols",
";",
"int",
"idx1",
"=",
"U",
".",
"col_idx",
"[",
"N",
"]",
";",
"for",
"(",
"int",
"col",
"=",
"N",
"-",
"1",
";",
"col",
">=",
"0",
";",
"col",
"--",
")",
"{",
"int",
"idx0",
"=",
"U",
".",
"col_idx",
"[",
"col",
"]",
";",
"double",
"x_j",
"=",
"x",
"[",
"col",
"]",
"/=",
"U",
".",
"nz_values",
"[",
"idx1",
"-",
"1",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"idx0",
";",
"i",
"<",
"idx1",
"-",
"1",
";",
"i",
"++",
")",
"{",
"int",
"row",
"=",
"U",
".",
"nz_rows",
"[",
"i",
"]",
";",
"x",
"[",
"row",
"]",
"-=",
"U",
".",
"nz_values",
"[",
"i",
"]",
"*",
"x_j",
";",
"}",
"idx1",
"=",
"idx0",
";",
"}",
"}"
] |
Solves for an upper triangular matrix against a dense vector. U*x = b
@param U Upper triangular matrix. Diagonal elements are assumed to be non-zero
@param x (Input) Solution matrix 'b'. (Output) matrix 'x'
|
[
"Solves",
"for",
"an",
"upper",
"triangular",
"matrix",
"against",
"a",
"dense",
"vector",
".",
"U",
"*",
"x",
"=",
"b"
] |
train
|
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/misc/TriangularSolver_DSCC.java#L86-L102
|
yanzhenjie/AndServer
|
api/src/main/java/com/yanzhenjie/andserver/framework/website/StorageWebsite.java
|
StorageWebsite.findPathResource
|
private File findPathResource(@NonNull String httpPath) {
"""
Find the path specified resource.
@param httpPath path.
@return return if the file is found.
"""
if ("/".equals(httpPath)) {
File indexFile = new File(mRootPath, getIndexFileName());
if (indexFile.exists() && indexFile.isFile()) {
return indexFile;
}
} else {
File sourceFile = new File(mRootPath, httpPath);
if (sourceFile.exists()) {
if (sourceFile.isFile()) {
return sourceFile;
} else {
File childIndexFile = new File(sourceFile, getIndexFileName());
if (childIndexFile.exists() && childIndexFile.isFile()) {
return childIndexFile;
}
}
}
}
return null;
}
|
java
|
private File findPathResource(@NonNull String httpPath) {
if ("/".equals(httpPath)) {
File indexFile = new File(mRootPath, getIndexFileName());
if (indexFile.exists() && indexFile.isFile()) {
return indexFile;
}
} else {
File sourceFile = new File(mRootPath, httpPath);
if (sourceFile.exists()) {
if (sourceFile.isFile()) {
return sourceFile;
} else {
File childIndexFile = new File(sourceFile, getIndexFileName());
if (childIndexFile.exists() && childIndexFile.isFile()) {
return childIndexFile;
}
}
}
}
return null;
}
|
[
"private",
"File",
"findPathResource",
"(",
"@",
"NonNull",
"String",
"httpPath",
")",
"{",
"if",
"(",
"\"/\"",
".",
"equals",
"(",
"httpPath",
")",
")",
"{",
"File",
"indexFile",
"=",
"new",
"File",
"(",
"mRootPath",
",",
"getIndexFileName",
"(",
")",
")",
";",
"if",
"(",
"indexFile",
".",
"exists",
"(",
")",
"&&",
"indexFile",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"indexFile",
";",
"}",
"}",
"else",
"{",
"File",
"sourceFile",
"=",
"new",
"File",
"(",
"mRootPath",
",",
"httpPath",
")",
";",
"if",
"(",
"sourceFile",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"sourceFile",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"sourceFile",
";",
"}",
"else",
"{",
"File",
"childIndexFile",
"=",
"new",
"File",
"(",
"sourceFile",
",",
"getIndexFileName",
"(",
")",
")",
";",
"if",
"(",
"childIndexFile",
".",
"exists",
"(",
")",
"&&",
"childIndexFile",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"childIndexFile",
";",
"}",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find the path specified resource.
@param httpPath path.
@return return if the file is found.
|
[
"Find",
"the",
"path",
"specified",
"resource",
"."
] |
train
|
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/framework/website/StorageWebsite.java#L76-L96
|
Azure/azure-sdk-for-java
|
cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/AccountsInner.java
|
AccountsInner.listSkusAsync
|
public Observable<CognitiveServicesAccountEnumerateSkusResultInner> listSkusAsync(String resourceGroupName, String accountName) {
"""
List available SKUs for the requested Cognitive Services account.
@param resourceGroupName The name of the resource group within the user's subscription.
@param accountName The name of Cognitive Services account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CognitiveServicesAccountEnumerateSkusResultInner object
"""
return listSkusWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner>, CognitiveServicesAccountEnumerateSkusResultInner>() {
@Override
public CognitiveServicesAccountEnumerateSkusResultInner call(ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<CognitiveServicesAccountEnumerateSkusResultInner> listSkusAsync(String resourceGroupName, String accountName) {
return listSkusWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner>, CognitiveServicesAccountEnumerateSkusResultInner>() {
@Override
public CognitiveServicesAccountEnumerateSkusResultInner call(ServiceResponse<CognitiveServicesAccountEnumerateSkusResultInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"CognitiveServicesAccountEnumerateSkusResultInner",
">",
"listSkusAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"listSkusWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"CognitiveServicesAccountEnumerateSkusResultInner",
">",
",",
"CognitiveServicesAccountEnumerateSkusResultInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"CognitiveServicesAccountEnumerateSkusResultInner",
"call",
"(",
"ServiceResponse",
"<",
"CognitiveServicesAccountEnumerateSkusResultInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
List available SKUs for the requested Cognitive Services account.
@param resourceGroupName The name of the resource group within the user's subscription.
@param accountName The name of Cognitive Services account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CognitiveServicesAccountEnumerateSkusResultInner object
|
[
"List",
"available",
"SKUs",
"for",
"the",
"requested",
"Cognitive",
"Services",
"account",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/AccountsInner.java#L1013-L1020
|
netscaler/nitro
|
src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocolhttp_stats.java
|
protocolhttp_stats.get_nitro_response
|
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
"""
<pre>
converts nitro response into object and returns the object array in case of get request.
</pre>
"""
protocolhttp_stats[] resources = new protocolhttp_stats[1];
protocolhttp_response result = (protocolhttp_response) service.get_payload_formatter().string_to_resource(protocolhttp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocolhttp;
return resources;
}
|
java
|
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
protocolhttp_stats[] resources = new protocolhttp_stats[1];
protocolhttp_response result = (protocolhttp_response) service.get_payload_formatter().string_to_resource(protocolhttp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocolhttp;
return resources;
}
|
[
"protected",
"base_resource",
"[",
"]",
"get_nitro_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"protocolhttp_stats",
"[",
"]",
"resources",
"=",
"new",
"protocolhttp_stats",
"[",
"1",
"]",
";",
"protocolhttp_response",
"result",
"=",
"(",
"protocolhttp_response",
")",
"service",
".",
"get_payload_formatter",
"(",
")",
".",
"string_to_resource",
"(",
"protocolhttp_response",
".",
"class",
",",
"response",
")",
";",
"if",
"(",
"result",
".",
"errorcode",
"!=",
"0",
")",
"{",
"if",
"(",
"result",
".",
"errorcode",
"==",
"444",
")",
"{",
"service",
".",
"clear_session",
"(",
")",
";",
"}",
"if",
"(",
"result",
".",
"severity",
"!=",
"null",
")",
"{",
"if",
"(",
"result",
".",
"severity",
".",
"equals",
"(",
"\"ERROR\"",
")",
")",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
")",
";",
"}",
"}",
"resources",
"[",
"0",
"]",
"=",
"result",
".",
"protocolhttp",
";",
"return",
"resources",
";",
"}"
] |
<pre>
converts nitro response into object and returns the object array in case of get request.
</pre>
|
[
"<pre",
">",
"converts",
"nitro",
"response",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocolhttp_stats.java#L567-L586
|
voldemort/voldemort
|
src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java
|
RebalanceBatchPlanProgressBar.completeTask
|
synchronized public void completeTask(int taskId, int partitionStoresMigrated) {
"""
Called whenever a rebalance task completes. This means one task is done
and some number of partition stores have been migrated.
@param taskId
@param partitionStoresMigrated Number of partition stores moved by this
completed task.
"""
tasksInFlight.remove(taskId);
numTasksCompleted++;
numPartitionStoresMigrated += partitionStoresMigrated;
updateProgressBar();
}
|
java
|
synchronized public void completeTask(int taskId, int partitionStoresMigrated) {
tasksInFlight.remove(taskId);
numTasksCompleted++;
numPartitionStoresMigrated += partitionStoresMigrated;
updateProgressBar();
}
|
[
"synchronized",
"public",
"void",
"completeTask",
"(",
"int",
"taskId",
",",
"int",
"partitionStoresMigrated",
")",
"{",
"tasksInFlight",
".",
"remove",
"(",
"taskId",
")",
";",
"numTasksCompleted",
"++",
";",
"numPartitionStoresMigrated",
"+=",
"partitionStoresMigrated",
";",
"updateProgressBar",
"(",
")",
";",
"}"
] |
Called whenever a rebalance task completes. This means one task is done
and some number of partition stores have been migrated.
@param taskId
@param partitionStoresMigrated Number of partition stores moved by this
completed task.
|
[
"Called",
"whenever",
"a",
"rebalance",
"task",
"completes",
".",
"This",
"means",
"one",
"task",
"is",
"done",
"and",
"some",
"number",
"of",
"partition",
"stores",
"have",
"been",
"migrated",
"."
] |
train
|
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalanceBatchPlanProgressBar.java#L82-L89
|
deeplearning4j/deeplearning4j
|
datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java
|
WritableUtils.readString
|
public static String readString(DataInput in) throws IOException {
"""
/*
Read a String as a Network Int n, followed by n Bytes
Alternative to 16 bit read/writeUTF.
Encoding standard is... ?
"""
int length = in.readInt();
if (length == -1)
return null;
byte[] buffer = new byte[length];
in.readFully(buffer); // could/should use readFully(buffer,0,length)?
return new String(buffer, "UTF-8");
}
|
java
|
public static String readString(DataInput in) throws IOException {
int length = in.readInt();
if (length == -1)
return null;
byte[] buffer = new byte[length];
in.readFully(buffer); // could/should use readFully(buffer,0,length)?
return new String(buffer, "UTF-8");
}
|
[
"public",
"static",
"String",
"readString",
"(",
"DataInput",
"in",
")",
"throws",
"IOException",
"{",
"int",
"length",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"if",
"(",
"length",
"==",
"-",
"1",
")",
"return",
"null",
";",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"in",
".",
"readFully",
"(",
"buffer",
")",
";",
"// could/should use readFully(buffer,0,length)?",
"return",
"new",
"String",
"(",
"buffer",
",",
"\"UTF-8\"",
")",
";",
"}"
] |
/*
Read a String as a Network Int n, followed by n Bytes
Alternative to 16 bit read/writeUTF.
Encoding standard is... ?
|
[
"/",
"*",
"Read",
"a",
"String",
"as",
"a",
"Network",
"Int",
"n",
"followed",
"by",
"n",
"Bytes",
"Alternative",
"to",
"16",
"bit",
"read",
"/",
"writeUTF",
".",
"Encoding",
"standard",
"is",
"...",
"?"
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/io/WritableUtils.java#L114-L121
|
Impetus/Kundera
|
src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerFactoryImpl.java
|
EntityManagerFactoryImpl.configurePersistenceUnit
|
private void configurePersistenceUnit(PersistenceUnitInfo puInfo, Map props) {
"""
One time initialization for persistence unit metadata.
@param persistenceUnit
Persistence Unit/ Comma separated persistence units
"""
// Invoke Persistence unit MetaData
if (puInfo.getPersistenceUnitName() == null)
{
throw new KunderaException("Persistence unit name should not be null");
}
if (logger.isInfoEnabled())
{
logger.info("Loading Persistence Unit MetaData For Persistence Unit(s) {}.",
puInfo.getPersistenceUnitName());
}
String[] persistenceUnits = puInfo.getPersistenceUnitName().split(Constants.PERSISTENCE_UNIT_SEPARATOR);
new PersistenceUnitConfiguration(props, kunderaMetadata, persistenceUnits).configure(puInfo);
}
|
java
|
private void configurePersistenceUnit(PersistenceUnitInfo puInfo, Map props)
{
// Invoke Persistence unit MetaData
if (puInfo.getPersistenceUnitName() == null)
{
throw new KunderaException("Persistence unit name should not be null");
}
if (logger.isInfoEnabled())
{
logger.info("Loading Persistence Unit MetaData For Persistence Unit(s) {}.",
puInfo.getPersistenceUnitName());
}
String[] persistenceUnits = puInfo.getPersistenceUnitName().split(Constants.PERSISTENCE_UNIT_SEPARATOR);
new PersistenceUnitConfiguration(props, kunderaMetadata, persistenceUnits).configure(puInfo);
}
|
[
"private",
"void",
"configurePersistenceUnit",
"(",
"PersistenceUnitInfo",
"puInfo",
",",
"Map",
"props",
")",
"{",
"// Invoke Persistence unit MetaData\r",
"if",
"(",
"puInfo",
".",
"getPersistenceUnitName",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"KunderaException",
"(",
"\"Persistence unit name should not be null\"",
")",
";",
"}",
"if",
"(",
"logger",
".",
"isInfoEnabled",
"(",
")",
")",
"{",
"logger",
".",
"info",
"(",
"\"Loading Persistence Unit MetaData For Persistence Unit(s) {}.\"",
",",
"puInfo",
".",
"getPersistenceUnitName",
"(",
")",
")",
";",
"}",
"String",
"[",
"]",
"persistenceUnits",
"=",
"puInfo",
".",
"getPersistenceUnitName",
"(",
")",
".",
"split",
"(",
"Constants",
".",
"PERSISTENCE_UNIT_SEPARATOR",
")",
";",
"new",
"PersistenceUnitConfiguration",
"(",
"props",
",",
"kunderaMetadata",
",",
"persistenceUnits",
")",
".",
"configure",
"(",
"puInfo",
")",
";",
"}"
] |
One time initialization for persistence unit metadata.
@param persistenceUnit
Persistence Unit/ Comma separated persistence units
|
[
"One",
"time",
"initialization",
"for",
"persistence",
"unit",
"metadata",
"."
] |
train
|
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerFactoryImpl.java#L668-L684
|
netty/netty
|
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java
|
WebSocketClientHandshaker08.newHandshakeRequest
|
@Override
protected FullHttpRequest newHandshakeRequest() {
"""
/**
<p>
Sends the opening request to the server:
</p>
<pre>
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 8
</pre>
"""
// Get path
URI wsURL = uri();
String path = rawPath(wsURL);
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug(
"WebSocket version 08 client handshake key: {}, expected response: {}",
key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers();
if (customHeaders != null) {
headers.add(customHeaders);
}
headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.set(HttpHeaderNames.HOST, websocketHostValue(wsURL))
.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
return request;
}
|
java
|
@Override
protected FullHttpRequest newHandshakeRequest() {
// Get path
URI wsURL = uri();
String path = rawPath(wsURL);
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug(
"WebSocket version 08 client handshake key: {}, expected response: {}",
key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
HttpHeaders headers = request.headers();
if (customHeaders != null) {
headers.add(customHeaders);
}
headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.set(HttpHeaderNames.HOST, websocketHostValue(wsURL))
.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
return request;
}
|
[
"@",
"Override",
"protected",
"FullHttpRequest",
"newHandshakeRequest",
"(",
")",
"{",
"// Get path",
"URI",
"wsURL",
"=",
"uri",
"(",
")",
";",
"String",
"path",
"=",
"rawPath",
"(",
"wsURL",
")",
";",
"// Get 16 bit nonce and base 64 encode it",
"byte",
"[",
"]",
"nonce",
"=",
"WebSocketUtil",
".",
"randomBytes",
"(",
"16",
")",
";",
"String",
"key",
"=",
"WebSocketUtil",
".",
"base64",
"(",
"nonce",
")",
";",
"String",
"acceptSeed",
"=",
"key",
"+",
"MAGIC_GUID",
";",
"byte",
"[",
"]",
"sha1",
"=",
"WebSocketUtil",
".",
"sha1",
"(",
"acceptSeed",
".",
"getBytes",
"(",
"CharsetUtil",
".",
"US_ASCII",
")",
")",
";",
"expectedChallengeResponseString",
"=",
"WebSocketUtil",
".",
"base64",
"(",
"sha1",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"WebSocket version 08 client handshake key: {}, expected response: {}\"",
",",
"key",
",",
"expectedChallengeResponseString",
")",
";",
"}",
"// Format request",
"FullHttpRequest",
"request",
"=",
"new",
"DefaultFullHttpRequest",
"(",
"HttpVersion",
".",
"HTTP_1_1",
",",
"HttpMethod",
".",
"GET",
",",
"path",
")",
";",
"HttpHeaders",
"headers",
"=",
"request",
".",
"headers",
"(",
")",
";",
"if",
"(",
"customHeaders",
"!=",
"null",
")",
"{",
"headers",
".",
"add",
"(",
"customHeaders",
")",
";",
"}",
"headers",
".",
"set",
"(",
"HttpHeaderNames",
".",
"UPGRADE",
",",
"HttpHeaderValues",
".",
"WEBSOCKET",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"CONNECTION",
",",
"HttpHeaderValues",
".",
"UPGRADE",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"SEC_WEBSOCKET_KEY",
",",
"key",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"HOST",
",",
"websocketHostValue",
"(",
"wsURL",
")",
")",
".",
"set",
"(",
"HttpHeaderNames",
".",
"SEC_WEBSOCKET_ORIGIN",
",",
"websocketOriginValue",
"(",
"wsURL",
")",
")",
";",
"String",
"expectedSubprotocol",
"=",
"expectedSubprotocol",
"(",
")",
";",
"if",
"(",
"expectedSubprotocol",
"!=",
"null",
"&&",
"!",
"expectedSubprotocol",
".",
"isEmpty",
"(",
")",
")",
"{",
"headers",
".",
"set",
"(",
"HttpHeaderNames",
".",
"SEC_WEBSOCKET_PROTOCOL",
",",
"expectedSubprotocol",
")",
";",
"}",
"headers",
".",
"set",
"(",
"HttpHeaderNames",
".",
"SEC_WEBSOCKET_VERSION",
",",
"\"8\"",
")",
";",
"return",
"request",
";",
"}"
] |
/**
<p>
Sends the opening request to the server:
</p>
<pre>
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 8
</pre>
|
[
"/",
"**",
"<p",
">",
"Sends",
"the",
"opening",
"request",
"to",
"the",
"server",
":",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java#L159-L200
|
primefaces-extensions/core
|
src/main/java/org/primefaces/extensions/model/dynaform/DynaFormRow.java
|
DynaFormRow.addModel
|
public DynaFormModelElement addModel(final DynaFormModel model, final int colspan, final int rowspan) {
"""
*
Adds nested model with given colspan and rowspan.
@param model
@param colspan
@param rowspan
@return DynaFormModelElement added model
"""
final DynaFormModelElement nestedModel = new DynaFormModelElement(model,
colspan,
rowspan,
row,
elements.size() + 1,
dynaFormModel.getControls().size() + 1,
extended);
elements.add(nestedModel);
dynaFormModel.getControls().addAll(model.getControls());
totalColspan = totalColspan + colspan;
return nestedModel;
}
|
java
|
public DynaFormModelElement addModel(final DynaFormModel model, final int colspan, final int rowspan) {
final DynaFormModelElement nestedModel = new DynaFormModelElement(model,
colspan,
rowspan,
row,
elements.size() + 1,
dynaFormModel.getControls().size() + 1,
extended);
elements.add(nestedModel);
dynaFormModel.getControls().addAll(model.getControls());
totalColspan = totalColspan + colspan;
return nestedModel;
}
|
[
"public",
"DynaFormModelElement",
"addModel",
"(",
"final",
"DynaFormModel",
"model",
",",
"final",
"int",
"colspan",
",",
"final",
"int",
"rowspan",
")",
"{",
"final",
"DynaFormModelElement",
"nestedModel",
"=",
"new",
"DynaFormModelElement",
"(",
"model",
",",
"colspan",
",",
"rowspan",
",",
"row",
",",
"elements",
".",
"size",
"(",
")",
"+",
"1",
",",
"dynaFormModel",
".",
"getControls",
"(",
")",
".",
"size",
"(",
")",
"+",
"1",
",",
"extended",
")",
";",
"elements",
".",
"add",
"(",
"nestedModel",
")",
";",
"dynaFormModel",
".",
"getControls",
"(",
")",
".",
"addAll",
"(",
"model",
".",
"getControls",
"(",
")",
")",
";",
"totalColspan",
"=",
"totalColspan",
"+",
"colspan",
";",
"return",
"nestedModel",
";",
"}"
] |
*
Adds nested model with given colspan and rowspan.
@param model
@param colspan
@param rowspan
@return DynaFormModelElement added model
|
[
"*",
"Adds",
"nested",
"model",
"with",
"given",
"colspan",
"and",
"rowspan",
"."
] |
train
|
https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/model/dynaform/DynaFormRow.java#L130-L144
|
ReactiveX/RxJavaAsyncUtil
|
src/main/java/rx/util/async/Async.java
|
Async.deferFuture
|
public static <T> Observable<T> deferFuture(Func0<? extends Future<? extends Observable<? extends T>>> observableFactoryAsync) {
"""
Returns an Observable that starts the specified asynchronous factory function whenever a new observer
subscribes.
<p>
<em>Important note</em> subscribing to the resulting Observable blocks until the future completes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/deferFuture.png" alt="">
@param <T> the result type
@param observableFactoryAsync the asynchronous function to start for each observer
@return the Observable emitting items produced by the asynchronous observer produced by the factory
@see #deferFuture(rx.functions.Func0, rx.Scheduler)
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-deferfuture">RxJava Wiki: deferFuture()</a>
"""
return OperatorDeferFuture.deferFuture(observableFactoryAsync);
}
|
java
|
public static <T> Observable<T> deferFuture(Func0<? extends Future<? extends Observable<? extends T>>> observableFactoryAsync) {
return OperatorDeferFuture.deferFuture(observableFactoryAsync);
}
|
[
"public",
"static",
"<",
"T",
">",
"Observable",
"<",
"T",
">",
"deferFuture",
"(",
"Func0",
"<",
"?",
"extends",
"Future",
"<",
"?",
"extends",
"Observable",
"<",
"?",
"extends",
"T",
">",
">",
">",
"observableFactoryAsync",
")",
"{",
"return",
"OperatorDeferFuture",
".",
"deferFuture",
"(",
"observableFactoryAsync",
")",
";",
"}"
] |
Returns an Observable that starts the specified asynchronous factory function whenever a new observer
subscribes.
<p>
<em>Important note</em> subscribing to the resulting Observable blocks until the future completes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/deferFuture.png" alt="">
@param <T> the result type
@param observableFactoryAsync the asynchronous function to start for each observer
@return the Observable emitting items produced by the asynchronous observer produced by the factory
@see #deferFuture(rx.functions.Func0, rx.Scheduler)
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-deferfuture">RxJava Wiki: deferFuture()</a>
|
[
"Returns",
"an",
"Observable",
"that",
"starts",
"the",
"specified",
"asynchronous",
"factory",
"function",
"whenever",
"a",
"new",
"observer",
"subscribes",
".",
"<p",
">",
"<em",
">",
"Important",
"note<",
"/",
"em",
">",
"subscribing",
"to",
"the",
"resulting",
"Observable",
"blocks",
"until",
"the",
"future",
"completes",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"deferFuture",
".",
"png",
"alt",
"=",
">"
] |
train
|
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L1800-L1802
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
|
ImageModerationsImpl.matchUrlInputAsync
|
public Observable<MatchResponse> matchUrlInputAsync(String contentType, BodyModelModel imageUrl, MatchUrlInputOptionalParameter matchUrlInputOptionalParameter) {
"""
Fuzzily match an image against one of your custom Image Lists. You can create and manage your custom image lists using <a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> API.
Returns ID and tags of matching image.<br/>
<br/>
Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the response.
@param contentType The content type.
@param imageUrl The image url.
@param matchUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the MatchResponse object
"""
return matchUrlInputWithServiceResponseAsync(contentType, imageUrl, matchUrlInputOptionalParameter).map(new Func1<ServiceResponse<MatchResponse>, MatchResponse>() {
@Override
public MatchResponse call(ServiceResponse<MatchResponse> response) {
return response.body();
}
});
}
|
java
|
public Observable<MatchResponse> matchUrlInputAsync(String contentType, BodyModelModel imageUrl, MatchUrlInputOptionalParameter matchUrlInputOptionalParameter) {
return matchUrlInputWithServiceResponseAsync(contentType, imageUrl, matchUrlInputOptionalParameter).map(new Func1<ServiceResponse<MatchResponse>, MatchResponse>() {
@Override
public MatchResponse call(ServiceResponse<MatchResponse> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"MatchResponse",
">",
"matchUrlInputAsync",
"(",
"String",
"contentType",
",",
"BodyModelModel",
"imageUrl",
",",
"MatchUrlInputOptionalParameter",
"matchUrlInputOptionalParameter",
")",
"{",
"return",
"matchUrlInputWithServiceResponseAsync",
"(",
"contentType",
",",
"imageUrl",
",",
"matchUrlInputOptionalParameter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"MatchResponse",
">",
",",
"MatchResponse",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"MatchResponse",
"call",
"(",
"ServiceResponse",
"<",
"MatchResponse",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Fuzzily match an image against one of your custom Image Lists. You can create and manage your custom image lists using <a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe">this</a> API.
Returns ID and tags of matching image.<br/>
<br/>
Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the response.
@param contentType The content type.
@param imageUrl The image url.
@param matchUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the MatchResponse object
|
[
"Fuzzily",
"match",
"an",
"image",
"against",
"one",
"of",
"your",
"custom",
"Image",
"Lists",
".",
"You",
"can",
"create",
"and",
"manage",
"your",
"custom",
"image",
"lists",
"using",
"<",
";",
"a",
"href",
"=",
"/",
"docs",
"/",
"services",
"/",
"578ff44d2703741568569ab9",
"/",
"operations",
"/",
"578ff7b12703741568569abe",
">",
";",
"this<",
";",
"/",
"a>",
";",
"API",
".",
"Returns",
"ID",
"and",
"tags",
"of",
"matching",
"image",
".",
"<",
";",
"br",
"/",
">",
";",
"<",
";",
"br",
"/",
">",
";",
"Note",
":",
"Refresh",
"Index",
"must",
"be",
"run",
"on",
"the",
"corresponding",
"Image",
"List",
"before",
"additions",
"and",
"removals",
"are",
"reflected",
"in",
"the",
"response",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L1786-L1793
|
podio/podio-java
|
src/main/java/com/podio/rating/RatingAPI.java
|
RatingAPI.getRatings
|
public TypeRating getRatings(Reference reference, RatingType type) {
"""
Get the rating average (for fivestar) and totals for the given rating
type on the specified object.
@param reference
The reference to the object to get ratings for
@param type
The type of rating to return
@return The ratings for the type
"""
return getResourceFactory().getApiResource(
"/rating/" + reference.toURLFragment() + type).get(
TypeRating.class);
}
|
java
|
public TypeRating getRatings(Reference reference, RatingType type) {
return getResourceFactory().getApiResource(
"/rating/" + reference.toURLFragment() + type).get(
TypeRating.class);
}
|
[
"public",
"TypeRating",
"getRatings",
"(",
"Reference",
"reference",
",",
"RatingType",
"type",
")",
"{",
"return",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/rating/\"",
"+",
"reference",
".",
"toURLFragment",
"(",
")",
"+",
"type",
")",
".",
"get",
"(",
"TypeRating",
".",
"class",
")",
";",
"}"
] |
Get the rating average (for fivestar) and totals for the given rating
type on the specified object.
@param reference
The reference to the object to get ratings for
@param type
The type of rating to return
@return The ratings for the type
|
[
"Get",
"the",
"rating",
"average",
"(",
"for",
"fivestar",
")",
"and",
"totals",
"for",
"the",
"given",
"rating",
"type",
"on",
"the",
"specified",
"object",
"."
] |
train
|
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/rating/RatingAPI.java#L214-L218
|
Azure/azure-sdk-for-java
|
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingLocatorsInner.java
|
StreamingLocatorsInner.listContentKeys
|
public ListContentKeysResponseInner listContentKeys(String resourceGroupName, String accountName, String streamingLocatorName) {
"""
List Content Keys.
List Content Keys used by this Streaming Locator.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param streamingLocatorName The Streaming Locator name.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ListContentKeysResponseInner object if successful.
"""
return listContentKeysWithServiceResponseAsync(resourceGroupName, accountName, streamingLocatorName).toBlocking().single().body();
}
|
java
|
public ListContentKeysResponseInner listContentKeys(String resourceGroupName, String accountName, String streamingLocatorName) {
return listContentKeysWithServiceResponseAsync(resourceGroupName, accountName, streamingLocatorName).toBlocking().single().body();
}
|
[
"public",
"ListContentKeysResponseInner",
"listContentKeys",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"streamingLocatorName",
")",
"{",
"return",
"listContentKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"streamingLocatorName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
List Content Keys.
List Content Keys used by this Streaming Locator.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@param streamingLocatorName The Streaming Locator name.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ListContentKeysResponseInner object if successful.
|
[
"List",
"Content",
"Keys",
".",
"List",
"Content",
"Keys",
"used",
"by",
"this",
"Streaming",
"Locator",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingLocatorsInner.java#L674-L676
|
looly/hutool
|
hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/AbstractAsymmetricCrypto.java
|
AbstractAsymmetricCrypto.decryptFromBcd
|
public byte[] decryptFromBcd(String data, KeyType keyType, Charset charset) {
"""
分组解密
@param data 数据
@param keyType 密钥类型
@param charset 加密前编码
@return 解密后的密文
@since 4.1.0
"""
final byte[] dataBytes = BCD.ascToBcd(StrUtil.bytes(data, charset));
return decrypt(dataBytes, keyType);
}
|
java
|
public byte[] decryptFromBcd(String data, KeyType keyType, Charset charset) {
final byte[] dataBytes = BCD.ascToBcd(StrUtil.bytes(data, charset));
return decrypt(dataBytes, keyType);
}
|
[
"public",
"byte",
"[",
"]",
"decryptFromBcd",
"(",
"String",
"data",
",",
"KeyType",
"keyType",
",",
"Charset",
"charset",
")",
"{",
"final",
"byte",
"[",
"]",
"dataBytes",
"=",
"BCD",
".",
"ascToBcd",
"(",
"StrUtil",
".",
"bytes",
"(",
"data",
",",
"charset",
")",
")",
";",
"return",
"decrypt",
"(",
"dataBytes",
",",
"keyType",
")",
";",
"}"
] |
分组解密
@param data 数据
@param keyType 密钥类型
@param charset 加密前编码
@return 解密后的密文
@since 4.1.0
|
[
"分组解密"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/AbstractAsymmetricCrypto.java#L296-L299
|
looly/hutool
|
hutool-cron/src/main/java/cn/hutool/cron/Scheduler.java
|
Scheduler.schedule
|
public String schedule(String pattern, Runnable task) {
"""
新增Task,使用随机UUID
@param pattern {@link CronPattern}对应的String表达式
@param task {@link Runnable}
@return ID
"""
return schedule(pattern, new RunnableTask(task));
}
|
java
|
public String schedule(String pattern, Runnable task) {
return schedule(pattern, new RunnableTask(task));
}
|
[
"public",
"String",
"schedule",
"(",
"String",
"pattern",
",",
"Runnable",
"task",
")",
"{",
"return",
"schedule",
"(",
"pattern",
",",
"new",
"RunnableTask",
"(",
"task",
")",
")",
";",
"}"
] |
新增Task,使用随机UUID
@param pattern {@link CronPattern}对应的String表达式
@param task {@link Runnable}
@return ID
|
[
"新增Task,使用随机UUID"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-cron/src/main/java/cn/hutool/cron/Scheduler.java#L206-L208
|
jOOQ/jOOL
|
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
|
Unchecked.doublePredicate
|
public static DoublePredicate doublePredicate(CheckedDoublePredicate function, Consumer<Throwable> handler) {
"""
Wrap a {@link CheckedDoublePredicate} in a {@link DoublePredicate} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
DoubleStream.of(1.0, 2.0, 3.0).filter(Unchecked.doublePredicate(
d -> {
if (d < 0.0)
throw new Exception("Only positive numbers allowed");
return true;
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code>
"""
return d -> {
try {
return function.test(d);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
}
|
java
|
public static DoublePredicate doublePredicate(CheckedDoublePredicate function, Consumer<Throwable> handler) {
return d -> {
try {
return function.test(d);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
}
|
[
"public",
"static",
"DoublePredicate",
"doublePredicate",
"(",
"CheckedDoublePredicate",
"function",
",",
"Consumer",
"<",
"Throwable",
">",
"handler",
")",
"{",
"return",
"d",
"->",
"{",
"try",
"{",
"return",
"function",
".",
"test",
"(",
"d",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"handler",
".",
"accept",
"(",
"e",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"\"Exception handler must throw a RuntimeException\"",
",",
"e",
")",
";",
"}",
"}",
";",
"}"
] |
Wrap a {@link CheckedDoublePredicate} in a {@link DoublePredicate} with a custom handler for checked exceptions.
<p>
Example:
<code><pre>
DoubleStream.of(1.0, 2.0, 3.0).filter(Unchecked.doublePredicate(
d -> {
if (d < 0.0)
throw new Exception("Only positive numbers allowed");
return true;
},
e -> {
throw new IllegalStateException(e);
}
));
</pre></code>
|
[
"Wrap",
"a",
"{",
"@link",
"CheckedDoublePredicate",
"}",
"in",
"a",
"{",
"@link",
"DoublePredicate",
"}",
"with",
"a",
"custom",
"handler",
"for",
"checked",
"exceptions",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"DoubleStream",
".",
"of",
"(",
"1",
".",
"0",
"2",
".",
"0",
"3",
".",
"0",
")",
".",
"filter",
"(",
"Unchecked",
".",
"doublePredicate",
"(",
"d",
"-",
">",
"{",
"if",
"(",
"d",
"<",
";",
"0",
".",
"0",
")",
"throw",
"new",
"Exception",
"(",
"Only",
"positive",
"numbers",
"allowed",
")",
";"
] |
train
|
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1647-L1658
|
albfernandez/itext2
|
src/main/java/com/lowagie/text/pdf/BaseFont.java
|
BaseFont.createFont
|
public static BaseFont createFont() throws DocumentException, IOException {
"""
Creates a new font. This will always be the default Helvetica font (not embedded).
This method is introduced because Helvetica is used in many examples.
@return a BaseFont object (Helvetica, Winansi, not embedded)
@throws IOException This shouldn't occur ever
@throws DocumentException This shouldn't occur ever
@since 2.1.1
"""
return createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
}
|
java
|
public static BaseFont createFont() throws DocumentException, IOException {
return createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
}
|
[
"public",
"static",
"BaseFont",
"createFont",
"(",
")",
"throws",
"DocumentException",
",",
"IOException",
"{",
"return",
"createFont",
"(",
"BaseFont",
".",
"HELVETICA",
",",
"BaseFont",
".",
"WINANSI",
",",
"BaseFont",
".",
"NOT_EMBEDDED",
")",
";",
"}"
] |
Creates a new font. This will always be the default Helvetica font (not embedded).
This method is introduced because Helvetica is used in many examples.
@return a BaseFont object (Helvetica, Winansi, not embedded)
@throws IOException This shouldn't occur ever
@throws DocumentException This shouldn't occur ever
@since 2.1.1
|
[
"Creates",
"a",
"new",
"font",
".",
"This",
"will",
"always",
"be",
"the",
"default",
"Helvetica",
"font",
"(",
"not",
"embedded",
")",
".",
"This",
"method",
"is",
"introduced",
"because",
"Helvetica",
"is",
"used",
"in",
"many",
"examples",
"."
] |
train
|
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/BaseFont.java#L385-L387
|
dbracewell/hermes
|
hermes-core/src/main/java/com/davidbracewell/hermes/HString.java
|
HString.annotationGraph
|
public RelationGraph annotationGraph(@NonNull Tuple relationTypes, @NonNull AnnotationType... annotationTypes) {
"""
<p>Constructs a relation graph with the given relation types as the edges and the given annotation types as the
vertices (the {@link #interleaved(AnnotationType...)} method is used to get the annotations). Relations will be
determine for annotations by including the relations of their sub-annotations (i.e. sub-spans). This allows, for
example, a dependency graph to be built over other annotation types, e.g. phrase chunks.</p>
@param relationTypes the relation types making up the edges
@param annotationTypes annotation types making up the vertices
@return the relation graph
"""
RelationGraph g = new RelationGraph();
List<Annotation> vertices = interleaved(annotationTypes);
Set<RelationType> relationTypeList = Streams
.asStream(relationTypes.iterator())
.filter(r -> r instanceof RelationType)
.map(Cast::<RelationType>as)
.collect(Collectors.toSet());
g.addVertices(vertices);
for (Annotation source : vertices) {
Collection<Relation> relations = source.relations(true);
for (Relation relation : relations) {
if (relationTypeList.contains(relation.getType())) {
relation
.getTarget(document())
.ifPresent(target -> {
target = g.containsVertex(target)
? target
: target
.stream(AnnotationType.ROOT)
.filter(g::containsVertex)
.findFirst()
.orElse(null);
if (target != null) {
if (!g.containsEdge(source, target)) {
RelationEdge edge = g.addEdge(source, target);
edge.setRelation(relation.getValue());
edge.setRelationType(relation.getType());
}
}
});
}
}
}
return g;
}
|
java
|
public RelationGraph annotationGraph(@NonNull Tuple relationTypes, @NonNull AnnotationType... annotationTypes) {
RelationGraph g = new RelationGraph();
List<Annotation> vertices = interleaved(annotationTypes);
Set<RelationType> relationTypeList = Streams
.asStream(relationTypes.iterator())
.filter(r -> r instanceof RelationType)
.map(Cast::<RelationType>as)
.collect(Collectors.toSet());
g.addVertices(vertices);
for (Annotation source : vertices) {
Collection<Relation> relations = source.relations(true);
for (Relation relation : relations) {
if (relationTypeList.contains(relation.getType())) {
relation
.getTarget(document())
.ifPresent(target -> {
target = g.containsVertex(target)
? target
: target
.stream(AnnotationType.ROOT)
.filter(g::containsVertex)
.findFirst()
.orElse(null);
if (target != null) {
if (!g.containsEdge(source, target)) {
RelationEdge edge = g.addEdge(source, target);
edge.setRelation(relation.getValue());
edge.setRelationType(relation.getType());
}
}
});
}
}
}
return g;
}
|
[
"public",
"RelationGraph",
"annotationGraph",
"(",
"@",
"NonNull",
"Tuple",
"relationTypes",
",",
"@",
"NonNull",
"AnnotationType",
"...",
"annotationTypes",
")",
"{",
"RelationGraph",
"g",
"=",
"new",
"RelationGraph",
"(",
")",
";",
"List",
"<",
"Annotation",
">",
"vertices",
"=",
"interleaved",
"(",
"annotationTypes",
")",
";",
"Set",
"<",
"RelationType",
">",
"relationTypeList",
"=",
"Streams",
".",
"asStream",
"(",
"relationTypes",
".",
"iterator",
"(",
")",
")",
".",
"filter",
"(",
"r",
"->",
"r",
"instanceof",
"RelationType",
")",
".",
"map",
"(",
"Cast",
"::",
"<",
"RelationType",
">",
"as",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"g",
".",
"addVertices",
"(",
"vertices",
")",
";",
"for",
"(",
"Annotation",
"source",
":",
"vertices",
")",
"{",
"Collection",
"<",
"Relation",
">",
"relations",
"=",
"source",
".",
"relations",
"(",
"true",
")",
";",
"for",
"(",
"Relation",
"relation",
":",
"relations",
")",
"{",
"if",
"(",
"relationTypeList",
".",
"contains",
"(",
"relation",
".",
"getType",
"(",
")",
")",
")",
"{",
"relation",
".",
"getTarget",
"(",
"document",
"(",
")",
")",
".",
"ifPresent",
"(",
"target",
"->",
"{",
"target",
"=",
"g",
".",
"containsVertex",
"(",
"target",
")",
"?",
"target",
":",
"target",
".",
"stream",
"(",
"AnnotationType",
".",
"ROOT",
")",
".",
"filter",
"(",
"g",
"::",
"containsVertex",
")",
".",
"findFirst",
"(",
")",
".",
"orElse",
"(",
"null",
")",
";",
"if",
"(",
"target",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"g",
".",
"containsEdge",
"(",
"source",
",",
"target",
")",
")",
"{",
"RelationEdge",
"edge",
"=",
"g",
".",
"addEdge",
"(",
"source",
",",
"target",
")",
";",
"edge",
".",
"setRelation",
"(",
"relation",
".",
"getValue",
"(",
")",
")",
";",
"edge",
".",
"setRelationType",
"(",
"relation",
".",
"getType",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
"}",
"return",
"g",
";",
"}"
] |
<p>Constructs a relation graph with the given relation types as the edges and the given annotation types as the
vertices (the {@link #interleaved(AnnotationType...)} method is used to get the annotations). Relations will be
determine for annotations by including the relations of their sub-annotations (i.e. sub-spans). This allows, for
example, a dependency graph to be built over other annotation types, e.g. phrase chunks.</p>
@param relationTypes the relation types making up the edges
@param annotationTypes annotation types making up the vertices
@return the relation graph
|
[
"<p",
">",
"Constructs",
"a",
"relation",
"graph",
"with",
"the",
"given",
"relation",
"types",
"as",
"the",
"edges",
"and",
"the",
"given",
"annotation",
"types",
"as",
"the",
"vertices",
"(",
"the",
"{",
"@link",
"#interleaved",
"(",
"AnnotationType",
"...",
")",
"}",
"method",
"is",
"used",
"to",
"get",
"the",
"annotations",
")",
".",
"Relations",
"will",
"be",
"determine",
"for",
"annotations",
"by",
"including",
"the",
"relations",
"of",
"their",
"sub",
"-",
"annotations",
"(",
"i",
".",
"e",
".",
"sub",
"-",
"spans",
")",
".",
"This",
"allows",
"for",
"example",
"a",
"dependency",
"graph",
"to",
"be",
"built",
"over",
"other",
"annotation",
"types",
"e",
".",
"g",
".",
"phrase",
"chunks",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/HString.java#L132-L167
|
moparisthebest/beehive
|
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/scoping/ScopedServletUtils.java
|
ScopedServletUtils.getScopedRequestAttribute
|
public static Object getScopedRequestAttribute( String attrName, ServletRequest request ) {
"""
Get an attribute from the given request, and if it is a {@link ScopedRequest}, ensure that the attribute
is <strong>not</strong> "showing through" from the outer request, even if the ScopedRequest allows that by
default.
@exclude
"""
if ( request instanceof ScopedRequest )
{
return ( ( ScopedRequest ) request ).getAttribute( attrName, false );
}
return request.getAttribute( attrName );
}
|
java
|
public static Object getScopedRequestAttribute( String attrName, ServletRequest request )
{
if ( request instanceof ScopedRequest )
{
return ( ( ScopedRequest ) request ).getAttribute( attrName, false );
}
return request.getAttribute( attrName );
}
|
[
"public",
"static",
"Object",
"getScopedRequestAttribute",
"(",
"String",
"attrName",
",",
"ServletRequest",
"request",
")",
"{",
"if",
"(",
"request",
"instanceof",
"ScopedRequest",
")",
"{",
"return",
"(",
"(",
"ScopedRequest",
")",
"request",
")",
".",
"getAttribute",
"(",
"attrName",
",",
"false",
")",
";",
"}",
"return",
"request",
".",
"getAttribute",
"(",
"attrName",
")",
";",
"}"
] |
Get an attribute from the given request, and if it is a {@link ScopedRequest}, ensure that the attribute
is <strong>not</strong> "showing through" from the outer request, even if the ScopedRequest allows that by
default.
@exclude
|
[
"Get",
"an",
"attribute",
"from",
"the",
"given",
"request",
"and",
"if",
"it",
"is",
"a",
"{",
"@link",
"ScopedRequest",
"}",
"ensure",
"that",
"the",
"attribute",
"is",
"<strong",
">",
"not<",
"/",
"strong",
">",
"showing",
"through",
"from",
"the",
"outer",
"request",
"even",
"if",
"the",
"ScopedRequest",
"allows",
"that",
"by",
"default",
"."
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/scoping/ScopedServletUtils.java#L358-L366
|
drewnoakes/metadata-extractor
|
Source/com/drew/metadata/xmp/XmpWriter.java
|
XmpWriter.write
|
public static boolean write(OutputStream os, Metadata data) {
"""
Serializes the XmpDirectory component of <code>Metadata</code> into an <code>OutputStream</code>
@param os Destination for the xmp data
@param data populated metadata
@return serialize success
"""
XmpDirectory dir = data.getFirstDirectoryOfType(XmpDirectory.class);
if (dir == null)
return false;
XMPMeta meta = dir.getXMPMeta();
try
{
SerializeOptions so = new SerializeOptions().setOmitPacketWrapper(true);
XMPMetaFactory.serialize(meta, os, so);
}
catch (XMPException e)
{
e.printStackTrace();
return false;
}
return true;
}
|
java
|
public static boolean write(OutputStream os, Metadata data)
{
XmpDirectory dir = data.getFirstDirectoryOfType(XmpDirectory.class);
if (dir == null)
return false;
XMPMeta meta = dir.getXMPMeta();
try
{
SerializeOptions so = new SerializeOptions().setOmitPacketWrapper(true);
XMPMetaFactory.serialize(meta, os, so);
}
catch (XMPException e)
{
e.printStackTrace();
return false;
}
return true;
}
|
[
"public",
"static",
"boolean",
"write",
"(",
"OutputStream",
"os",
",",
"Metadata",
"data",
")",
"{",
"XmpDirectory",
"dir",
"=",
"data",
".",
"getFirstDirectoryOfType",
"(",
"XmpDirectory",
".",
"class",
")",
";",
"if",
"(",
"dir",
"==",
"null",
")",
"return",
"false",
";",
"XMPMeta",
"meta",
"=",
"dir",
".",
"getXMPMeta",
"(",
")",
";",
"try",
"{",
"SerializeOptions",
"so",
"=",
"new",
"SerializeOptions",
"(",
")",
".",
"setOmitPacketWrapper",
"(",
"true",
")",
";",
"XMPMetaFactory",
".",
"serialize",
"(",
"meta",
",",
"os",
",",
"so",
")",
";",
"}",
"catch",
"(",
"XMPException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Serializes the XmpDirectory component of <code>Metadata</code> into an <code>OutputStream</code>
@param os Destination for the xmp data
@param data populated metadata
@return serialize success
|
[
"Serializes",
"the",
"XmpDirectory",
"component",
"of",
"<code",
">",
"Metadata<",
"/",
"code",
">",
"into",
"an",
"<code",
">",
"OutputStream<",
"/",
"code",
">"
] |
train
|
https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/metadata/xmp/XmpWriter.java#L19-L36
|
rometools/rome-propono
|
src/main/java/com/rometools/propono/blogclient/BlogConnectionFactory.java
|
BlogConnectionFactory.getBlogConnection
|
public static BlogConnection getBlogConnection(final String type, final String url, final String username, final String password)
throws BlogClientException {
"""
Create a connection to a blog server.
@param type Connection type, must be "atom" or "metaweblog"
@param url End-point URL to connect to
@param username Username for login to blog server
@param password Password for login to blog server
"""
BlogConnection blogConnection = null;
if (type == null || type.equals("metaweblog")) {
blogConnection = createBlogConnection(METAWEBLOG_IMPL_CLASS, url, username, password);
} else if (type.equals("atom")) {
blogConnection = createBlogConnection(ATOMPROTOCOL_IMPL_CLASS, url, username, password);
} else {
throw new BlogClientException("Type must be 'atom' or 'metaweblog'");
}
return blogConnection;
}
|
java
|
public static BlogConnection getBlogConnection(final String type, final String url, final String username, final String password)
throws BlogClientException {
BlogConnection blogConnection = null;
if (type == null || type.equals("metaweblog")) {
blogConnection = createBlogConnection(METAWEBLOG_IMPL_CLASS, url, username, password);
} else if (type.equals("atom")) {
blogConnection = createBlogConnection(ATOMPROTOCOL_IMPL_CLASS, url, username, password);
} else {
throw new BlogClientException("Type must be 'atom' or 'metaweblog'");
}
return blogConnection;
}
|
[
"public",
"static",
"BlogConnection",
"getBlogConnection",
"(",
"final",
"String",
"type",
",",
"final",
"String",
"url",
",",
"final",
"String",
"username",
",",
"final",
"String",
"password",
")",
"throws",
"BlogClientException",
"{",
"BlogConnection",
"blogConnection",
"=",
"null",
";",
"if",
"(",
"type",
"==",
"null",
"||",
"type",
".",
"equals",
"(",
"\"metaweblog\"",
")",
")",
"{",
"blogConnection",
"=",
"createBlogConnection",
"(",
"METAWEBLOG_IMPL_CLASS",
",",
"url",
",",
"username",
",",
"password",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"atom\"",
")",
")",
"{",
"blogConnection",
"=",
"createBlogConnection",
"(",
"ATOMPROTOCOL_IMPL_CLASS",
",",
"url",
",",
"username",
",",
"password",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"BlogClientException",
"(",
"\"Type must be 'atom' or 'metaweblog'\"",
")",
";",
"}",
"return",
"blogConnection",
";",
"}"
] |
Create a connection to a blog server.
@param type Connection type, must be "atom" or "metaweblog"
@param url End-point URL to connect to
@param username Username for login to blog server
@param password Password for login to blog server
|
[
"Create",
"a",
"connection",
"to",
"a",
"blog",
"server",
"."
] |
train
|
https://github.com/rometools/rome-propono/blob/721de8d5a47998f92969d1ee3db80bdaa3f26fb2/src/main/java/com/rometools/propono/blogclient/BlogConnectionFactory.java#L42-L53
|
networknt/json-schema-validator
|
src/main/java/com/networknt/schema/TypeValidator.java
|
TypeValidator.isNumber
|
public static boolean isNumber(JsonNode node, boolean isTypeLoose) {
"""
Check if the type of the JsonNode's value is number based on the
status of typeLoose flag.
@param node the JsonNode to check
@param isTypeLoose The flag to show whether typeLoose is enabled
@return boolean to indicate if it is a number
"""
if (node.isNumber()) {
return true;
} else if (isTypeLoose) {
if (TypeFactory.getValueNodeType(node) == JsonType.STRING) {
return isNumeric(node.textValue());
}
}
return false;
}
|
java
|
public static boolean isNumber(JsonNode node, boolean isTypeLoose) {
if (node.isNumber()) {
return true;
} else if (isTypeLoose) {
if (TypeFactory.getValueNodeType(node) == JsonType.STRING) {
return isNumeric(node.textValue());
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"isNumber",
"(",
"JsonNode",
"node",
",",
"boolean",
"isTypeLoose",
")",
"{",
"if",
"(",
"node",
".",
"isNumber",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"isTypeLoose",
")",
"{",
"if",
"(",
"TypeFactory",
".",
"getValueNodeType",
"(",
"node",
")",
"==",
"JsonType",
".",
"STRING",
")",
"{",
"return",
"isNumeric",
"(",
"node",
".",
"textValue",
"(",
")",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Check if the type of the JsonNode's value is number based on the
status of typeLoose flag.
@param node the JsonNode to check
@param isTypeLoose The flag to show whether typeLoose is enabled
@return boolean to indicate if it is a number
|
[
"Check",
"if",
"the",
"type",
"of",
"the",
"JsonNode",
"s",
"value",
"is",
"number",
"based",
"on",
"the",
"status",
"of",
"typeLoose",
"flag",
"."
] |
train
|
https://github.com/networknt/json-schema-validator/blob/d2a3a8d2085e72eb5c25c2fd8c8c9e641a62376d/src/main/java/com/networknt/schema/TypeValidator.java#L208-L217
|
h2oai/h2o-3
|
h2o-core/src/main/java/water/parser/DecryptionTool.java
|
DecryptionTool.readSecretKey
|
static SecretKeySpec readSecretKey(DecryptionSetup ds) {
"""
Retrieves a Secret Key using a given Decryption Setup.
@param ds decryption setup
@return SecretKey
"""
Keyed<?> ksObject = DKV.getGet(ds._keystore_id);
ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject);
InputStream ksStream = ksVec.openStream(null /*job key*/);
try {
KeyStore keystore = KeyStore.getInstance(ds._keystore_type);
keystore.load(ksStream, ds._password);
if (! keystore.containsAlias(ds._key_alias)) {
throw new IllegalArgumentException("Alias for key not found");
}
java.security.Key key = keystore.getKey(ds._key_alias, ds._password);
return new SecretKeySpec(key.getEncoded(), key.getAlgorithm());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e);
} catch (IOException e) {
throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e);
}
}
|
java
|
static SecretKeySpec readSecretKey(DecryptionSetup ds) {
Keyed<?> ksObject = DKV.getGet(ds._keystore_id);
ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject);
InputStream ksStream = ksVec.openStream(null /*job key*/);
try {
KeyStore keystore = KeyStore.getInstance(ds._keystore_type);
keystore.load(ksStream, ds._password);
if (! keystore.containsAlias(ds._key_alias)) {
throw new IllegalArgumentException("Alias for key not found");
}
java.security.Key key = keystore.getKey(ds._key_alias, ds._password);
return new SecretKeySpec(key.getEncoded(), key.getAlgorithm());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e);
} catch (IOException e) {
throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e);
}
}
|
[
"static",
"SecretKeySpec",
"readSecretKey",
"(",
"DecryptionSetup",
"ds",
")",
"{",
"Keyed",
"<",
"?",
">",
"ksObject",
"=",
"DKV",
".",
"getGet",
"(",
"ds",
".",
"_keystore_id",
")",
";",
"ByteVec",
"ksVec",
"=",
"(",
"ByteVec",
")",
"(",
"ksObject",
"instanceof",
"Frame",
"?",
"(",
"(",
"Frame",
")",
"ksObject",
")",
".",
"vec",
"(",
"0",
")",
":",
"ksObject",
")",
";",
"InputStream",
"ksStream",
"=",
"ksVec",
".",
"openStream",
"(",
"null",
"/*job key*/",
")",
";",
"try",
"{",
"KeyStore",
"keystore",
"=",
"KeyStore",
".",
"getInstance",
"(",
"ds",
".",
"_keystore_type",
")",
";",
"keystore",
".",
"load",
"(",
"ksStream",
",",
"ds",
".",
"_password",
")",
";",
"if",
"(",
"!",
"keystore",
".",
"containsAlias",
"(",
"ds",
".",
"_key_alias",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Alias for key not found\"",
")",
";",
"}",
"java",
".",
"security",
".",
"Key",
"key",
"=",
"keystore",
".",
"getKey",
"(",
"ds",
".",
"_key_alias",
",",
"ds",
".",
"_password",
")",
";",
"return",
"new",
"SecretKeySpec",
"(",
"key",
".",
"getEncoded",
"(",
")",
",",
"key",
".",
"getAlgorithm",
"(",
")",
")",
";",
"}",
"catch",
"(",
"GeneralSecurityException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to load key \"",
"+",
"ds",
".",
"_key_alias",
"+",
"\" from keystore \"",
"+",
"ds",
".",
"_keystore_id",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to read keystore \"",
"+",
"ds",
".",
"_keystore_id",
",",
"e",
")",
";",
"}",
"}"
] |
Retrieves a Secret Key using a given Decryption Setup.
@param ds decryption setup
@return SecretKey
|
[
"Retrieves",
"a",
"Secret",
"Key",
"using",
"a",
"given",
"Decryption",
"Setup",
"."
] |
train
|
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/parser/DecryptionTool.java#L63-L82
|
mcxiaoke/Android-Next
|
core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java
|
IOUtils.readString
|
public static String readString(File file, Charset charset) throws IOException {
"""
read file
@param file file
@param charset The name of a supported {@link Charset </code>charset<code>}
@return if file not exist, return null, else return content of file
@throws IOException if an error occurs while operator BufferedReader
"""
if (file == null || !file.isFile()) {
return null;
}
StringBuilder fileContent = new StringBuilder();
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charset);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
reader.close();
return fileContent.toString();
} finally {
closeQuietly(reader);
}
}
|
java
|
public static String readString(File file, Charset charset) throws IOException {
if (file == null || !file.isFile()) {
return null;
}
StringBuilder fileContent = new StringBuilder();
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charset);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
reader.close();
return fileContent.toString();
} finally {
closeQuietly(reader);
}
}
|
[
"public",
"static",
"String",
"readString",
"(",
"File",
"file",
",",
"Charset",
"charset",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"!",
"file",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"StringBuilder",
"fileContent",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"BufferedReader",
"reader",
"=",
"null",
";",
"try",
"{",
"InputStreamReader",
"is",
"=",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
",",
"charset",
")",
";",
"reader",
"=",
"new",
"BufferedReader",
"(",
"is",
")",
";",
"String",
"line",
"=",
"null",
";",
"while",
"(",
"(",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"fileContent",
".",
"toString",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"fileContent",
".",
"append",
"(",
"\"\\r\\n\"",
")",
";",
"}",
"fileContent",
".",
"append",
"(",
"line",
")",
";",
"}",
"reader",
".",
"close",
"(",
")",
";",
"return",
"fileContent",
".",
"toString",
"(",
")",
";",
"}",
"finally",
"{",
"closeQuietly",
"(",
"reader",
")",
";",
"}",
"}"
] |
read file
@param file file
@param charset The name of a supported {@link Charset </code>charset<code>}
@return if file not exist, return null, else return content of file
@throws IOException if an error occurs while operator BufferedReader
|
[
"read",
"file"
] |
train
|
https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java#L1121-L1143
|
kuali/ojb-1.0.4
|
src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java
|
JdbcAccessImpl.executeSQL
|
public ResultSetAndStatement executeSQL(
final String sql,
ClassDescriptor cld,
ValueContainer[] values,
boolean scrollable)
throws PersistenceBrokerException {
"""
performs a SQL SELECT statement against RDBMS.
@param sql the query string.
@param cld ClassDescriptor providing meta-information.
"""
if (logger.isDebugEnabled()) logger.debug("executeSQL: " + sql);
final boolean isStoredprocedure = isStoredProcedure(sql);
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
stmt = sm.getPreparedStatement(cld, sql,
scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);
if (isStoredprocedure)
{
// Query implemented as a stored procedure, which must return a result set.
// Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
sm.bindValues(stmt, values, 2);
stmt.execute();
rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
}
else
{
sm.bindValues(stmt, values, 1);
rs = stmt.executeQuery();
}
// as we return the resultset for further operations, we cannot release the statement yet.
// that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)
return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()
{
public Query getQueryInstance()
{
return null;
}
public int getColumnIndex(FieldDescriptor fld)
{
return JdbcType.MIN_INT;
}
public String getStatement()
{
return sql;
}
});
}
catch (PersistenceBrokerException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
logger.error("PersistenceBrokerException during the execution of the SQL query: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);
}
}
|
java
|
public ResultSetAndStatement executeSQL(
final String sql,
ClassDescriptor cld,
ValueContainer[] values,
boolean scrollable)
throws PersistenceBrokerException
{
if (logger.isDebugEnabled()) logger.debug("executeSQL: " + sql);
final boolean isStoredprocedure = isStoredProcedure(sql);
final StatementManagerIF sm = broker.serviceStatementManager();
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
stmt = sm.getPreparedStatement(cld, sql,
scrollable, StatementManagerIF.FETCH_SIZE_NOT_EXPLICITLY_SET, isStoredprocedure);
if (isStoredprocedure)
{
// Query implemented as a stored procedure, which must return a result set.
// Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}
getPlatform().registerOutResultSet((CallableStatement) stmt, 1);
sm.bindValues(stmt, values, 2);
stmt.execute();
rs = (ResultSet) ((CallableStatement) stmt).getObject(1);
}
else
{
sm.bindValues(stmt, values, 1);
rs = stmt.executeQuery();
}
// as we return the resultset for further operations, we cannot release the statement yet.
// that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)
return new ResultSetAndStatement(sm, stmt, rs, new SelectStatement()
{
public Query getQueryInstance()
{
return null;
}
public int getColumnIndex(FieldDescriptor fld)
{
return JdbcType.MIN_INT;
}
public String getStatement()
{
return sql;
}
});
}
catch (PersistenceBrokerException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
logger.error("PersistenceBrokerException during the execution of the SQL query: " + e.getMessage(), e);
throw e;
}
catch (SQLException e)
{
// release resources on exception
sm.closeResources(stmt, rs);
throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);
}
}
|
[
"public",
"ResultSetAndStatement",
"executeSQL",
"(",
"final",
"String",
"sql",
",",
"ClassDescriptor",
"cld",
",",
"ValueContainer",
"[",
"]",
"values",
",",
"boolean",
"scrollable",
")",
"throws",
"PersistenceBrokerException",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"logger",
".",
"debug",
"(",
"\"executeSQL: \"",
"+",
"sql",
")",
";",
"final",
"boolean",
"isStoredprocedure",
"=",
"isStoredProcedure",
"(",
"sql",
")",
";",
"final",
"StatementManagerIF",
"sm",
"=",
"broker",
".",
"serviceStatementManager",
"(",
")",
";",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"ResultSet",
"rs",
"=",
"null",
";",
"try",
"{",
"stmt",
"=",
"sm",
".",
"getPreparedStatement",
"(",
"cld",
",",
"sql",
",",
"scrollable",
",",
"StatementManagerIF",
".",
"FETCH_SIZE_NOT_EXPLICITLY_SET",
",",
"isStoredprocedure",
")",
";",
"if",
"(",
"isStoredprocedure",
")",
"{",
"// Query implemented as a stored procedure, which must return a result set.\r",
"// Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r",
"getPlatform",
"(",
")",
".",
"registerOutResultSet",
"(",
"(",
"CallableStatement",
")",
"stmt",
",",
"1",
")",
";",
"sm",
".",
"bindValues",
"(",
"stmt",
",",
"values",
",",
"2",
")",
";",
"stmt",
".",
"execute",
"(",
")",
";",
"rs",
"=",
"(",
"ResultSet",
")",
"(",
"(",
"CallableStatement",
")",
"stmt",
")",
".",
"getObject",
"(",
"1",
")",
";",
"}",
"else",
"{",
"sm",
".",
"bindValues",
"(",
"stmt",
",",
"values",
",",
"1",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
")",
";",
"}",
"// as we return the resultset for further operations, we cannot release the statement yet.\r",
"// that has to be done by the JdbcAccess-clients (i.e. RsIterator, ProxyRsIterator and PkEnumeration.)\r",
"return",
"new",
"ResultSetAndStatement",
"(",
"sm",
",",
"stmt",
",",
"rs",
",",
"new",
"SelectStatement",
"(",
")",
"{",
"public",
"Query",
"getQueryInstance",
"(",
")",
"{",
"return",
"null",
";",
"}",
"public",
"int",
"getColumnIndex",
"(",
"FieldDescriptor",
"fld",
")",
"{",
"return",
"JdbcType",
".",
"MIN_INT",
";",
"}",
"public",
"String",
"getStatement",
"(",
")",
"{",
"return",
"sql",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"PersistenceBrokerException",
"e",
")",
"{",
"// release resources on exception\r",
"sm",
".",
"closeResources",
"(",
"stmt",
",",
"rs",
")",
";",
"logger",
".",
"error",
"(",
"\"PersistenceBrokerException during the execution of the SQL query: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"// release resources on exception\r",
"sm",
".",
"closeResources",
"(",
"stmt",
",",
"rs",
")",
";",
"throw",
"ExceptionHelper",
".",
"generateException",
"(",
"e",
",",
"sql",
",",
"cld",
",",
"values",
",",
"logger",
",",
"null",
")",
";",
"}",
"}"
] |
performs a SQL SELECT statement against RDBMS.
@param sql the query string.
@param cld ClassDescriptor providing meta-information.
|
[
"performs",
"a",
"SQL",
"SELECT",
"statement",
"against",
"RDBMS",
"."
] |
train
|
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java#L335-L399
|
b3log/latke
|
latke-core/src/main/java/org/b3log/latke/plugin/AbstractPlugin.java
|
AbstractPlugin.fillDefault
|
private void fillDefault(final Map<String, Object> dataModel) {
"""
Fills default values into the specified data model.
<p>
The default data model variable values includes:
<ul>
<li>{@code Keys.SERVER.*}</li>
<li>{@code Keys.RUNTIME.*}</li>
</ul>
</p>
@param dataModel the specified data model
@see Keys#fillServer(java.util.Map)
"""
Keys.fillServer(dataModel);
Keys.fillRuntime(dataModel);
}
|
java
|
private void fillDefault(final Map<String, Object> dataModel) {
Keys.fillServer(dataModel);
Keys.fillRuntime(dataModel);
}
|
[
"private",
"void",
"fillDefault",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"dataModel",
")",
"{",
"Keys",
".",
"fillServer",
"(",
"dataModel",
")",
";",
"Keys",
".",
"fillRuntime",
"(",
"dataModel",
")",
";",
"}"
] |
Fills default values into the specified data model.
<p>
The default data model variable values includes:
<ul>
<li>{@code Keys.SERVER.*}</li>
<li>{@code Keys.RUNTIME.*}</li>
</ul>
</p>
@param dataModel the specified data model
@see Keys#fillServer(java.util.Map)
|
[
"Fills",
"default",
"values",
"into",
"the",
"specified",
"data",
"model",
"."
] |
train
|
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/plugin/AbstractPlugin.java#L344-L347
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanOFactory.java
|
BeanOFactory.create
|
public final BeanO create(EJSContainer c, EJSHome h, boolean reactivate) // d623673.1
throws RemoteException, InvocationTargetException {
"""
Changed EnterpriseBean to Object. d366807.1
"""
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "create: " + h);
BeanO beanO = newInstance(c, h);
boolean success = false;
try
{
beanO.initialize(reactivate);
success = true;
} finally
{
if (!success)
{
beanO.discard();
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "create: " + beanO + ", success=" + success);
}
return beanO;
}
|
java
|
public final BeanO create(EJSContainer c, EJSHome h, boolean reactivate) // d623673.1
throws RemoteException, InvocationTargetException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "create: " + h);
BeanO beanO = newInstance(c, h);
boolean success = false;
try
{
beanO.initialize(reactivate);
success = true;
} finally
{
if (!success)
{
beanO.discard();
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "create: " + beanO + ", success=" + success);
}
return beanO;
}
|
[
"public",
"final",
"BeanO",
"create",
"(",
"EJSContainer",
"c",
",",
"EJSHome",
"h",
",",
"boolean",
"reactivate",
")",
"// d623673.1",
"throws",
"RemoteException",
",",
"InvocationTargetException",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
";",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"create: \"",
"+",
"h",
")",
";",
"BeanO",
"beanO",
"=",
"newInstance",
"(",
"c",
",",
"h",
")",
";",
"boolean",
"success",
"=",
"false",
";",
"try",
"{",
"beanO",
".",
"initialize",
"(",
"reactivate",
")",
";",
"success",
"=",
"true",
";",
"}",
"finally",
"{",
"if",
"(",
"!",
"success",
")",
"{",
"beanO",
".",
"discard",
"(",
")",
";",
"}",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"create: \"",
"+",
"beanO",
"+",
"\", success=\"",
"+",
"success",
")",
";",
"}",
"return",
"beanO",
";",
"}"
] |
Changed EnterpriseBean to Object. d366807.1
|
[
"Changed",
"EnterpriseBean",
"to",
"Object",
".",
"d366807",
".",
"1"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanOFactory.java#L91-L117
|
google/j2objc
|
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/FastStringBuffer.java
|
FastStringBuffer.isWhitespace
|
public boolean isWhitespace(int start, int length) {
"""
@return true if the specified range of characters are all whitespace,
as defined by XMLCharacterRecognizer.
<p>
CURRENTLY DOES NOT CHECK FOR OUT-OF-RANGE.
@param start Offset of first character in the range.
@param length Number of characters to send.
"""
int sourcechunk = start >>> m_chunkBits;
int sourcecolumn = start & m_chunkMask;
int available = m_chunkSize - sourcecolumn;
boolean chunkOK;
while (length > 0)
{
int runlength = (length <= available) ? length : available;
if (sourcechunk == 0 && m_innerFSB != null)
chunkOK = m_innerFSB.isWhitespace(sourcecolumn, runlength);
else
chunkOK = org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(
m_array[sourcechunk], sourcecolumn, runlength);
if (!chunkOK)
return false;
length -= runlength;
++sourcechunk;
sourcecolumn = 0;
available = m_chunkSize;
}
return true;
}
|
java
|
public boolean isWhitespace(int start, int length)
{
int sourcechunk = start >>> m_chunkBits;
int sourcecolumn = start & m_chunkMask;
int available = m_chunkSize - sourcecolumn;
boolean chunkOK;
while (length > 0)
{
int runlength = (length <= available) ? length : available;
if (sourcechunk == 0 && m_innerFSB != null)
chunkOK = m_innerFSB.isWhitespace(sourcecolumn, runlength);
else
chunkOK = org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(
m_array[sourcechunk], sourcecolumn, runlength);
if (!chunkOK)
return false;
length -= runlength;
++sourcechunk;
sourcecolumn = 0;
available = m_chunkSize;
}
return true;
}
|
[
"public",
"boolean",
"isWhitespace",
"(",
"int",
"start",
",",
"int",
"length",
")",
"{",
"int",
"sourcechunk",
"=",
"start",
">>>",
"m_chunkBits",
";",
"int",
"sourcecolumn",
"=",
"start",
"&",
"m_chunkMask",
";",
"int",
"available",
"=",
"m_chunkSize",
"-",
"sourcecolumn",
";",
"boolean",
"chunkOK",
";",
"while",
"(",
"length",
">",
"0",
")",
"{",
"int",
"runlength",
"=",
"(",
"length",
"<=",
"available",
")",
"?",
"length",
":",
"available",
";",
"if",
"(",
"sourcechunk",
"==",
"0",
"&&",
"m_innerFSB",
"!=",
"null",
")",
"chunkOK",
"=",
"m_innerFSB",
".",
"isWhitespace",
"(",
"sourcecolumn",
",",
"runlength",
")",
";",
"else",
"chunkOK",
"=",
"org",
".",
"apache",
".",
"xml",
".",
"utils",
".",
"XMLCharacterRecognizer",
".",
"isWhiteSpace",
"(",
"m_array",
"[",
"sourcechunk",
"]",
",",
"sourcecolumn",
",",
"runlength",
")",
";",
"if",
"(",
"!",
"chunkOK",
")",
"return",
"false",
";",
"length",
"-=",
"runlength",
";",
"++",
"sourcechunk",
";",
"sourcecolumn",
"=",
"0",
";",
"available",
"=",
"m_chunkSize",
";",
"}",
"return",
"true",
";",
"}"
] |
@return true if the specified range of characters are all whitespace,
as defined by XMLCharacterRecognizer.
<p>
CURRENTLY DOES NOT CHECK FOR OUT-OF-RANGE.
@param start Offset of first character in the range.
@param length Number of characters to send.
|
[
"@return",
"true",
"if",
"the",
"specified",
"range",
"of",
"characters",
"are",
"all",
"whitespace",
"as",
"defined",
"by",
"XMLCharacterRecognizer",
".",
"<p",
">",
"CURRENTLY",
"DOES",
"NOT",
"CHECK",
"FOR",
"OUT",
"-",
"OF",
"-",
"RANGE",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/FastStringBuffer.java#L824-L854
|
Jasig/uPortal
|
uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/cache/PortletCacheControlServiceImpl.java
|
PortletCacheControlServiceImpl.cacheElement
|
protected void cacheElement(
Ehcache cache,
Serializable cacheKey,
CachedPortletResultHolder<?> data,
CacheControl cacheControl) {
"""
Construct an appropriate Cache {@link Element} for the cacheKey and data. The element's ttl
will be set depending on whether expiration or validation method is indicated from the
CacheControl and the cache's configuration.
"""
// using validation method, ignore expirationTime and defer to cache configuration
if (cacheControl.getETag() != null) {
final Element element = new Element(cacheKey, data);
cache.put(element);
return;
}
// using expiration method, -1 for CacheControl#expirationTime means "forever" (e.g. ignore
// and defer to cache configuration)
final int expirationTime = cacheControl.getExpirationTime();
if (expirationTime == -1) {
final Element element = new Element(cacheKey, data);
cache.put(element);
return;
}
// using expiration method with a positive expiration, set that value as the element's TTL
// if it is lower than the configured cache TTL
final CacheConfiguration cacheConfiguration = cache.getCacheConfiguration();
final Element element = new Element(cacheKey, data);
final long cacheTTL = cacheConfiguration.getTimeToLiveSeconds();
if (expirationTime < cacheTTL) {
element.setTimeToLive(expirationTime);
}
cache.put(element);
}
|
java
|
protected void cacheElement(
Ehcache cache,
Serializable cacheKey,
CachedPortletResultHolder<?> data,
CacheControl cacheControl) {
// using validation method, ignore expirationTime and defer to cache configuration
if (cacheControl.getETag() != null) {
final Element element = new Element(cacheKey, data);
cache.put(element);
return;
}
// using expiration method, -1 for CacheControl#expirationTime means "forever" (e.g. ignore
// and defer to cache configuration)
final int expirationTime = cacheControl.getExpirationTime();
if (expirationTime == -1) {
final Element element = new Element(cacheKey, data);
cache.put(element);
return;
}
// using expiration method with a positive expiration, set that value as the element's TTL
// if it is lower than the configured cache TTL
final CacheConfiguration cacheConfiguration = cache.getCacheConfiguration();
final Element element = new Element(cacheKey, data);
final long cacheTTL = cacheConfiguration.getTimeToLiveSeconds();
if (expirationTime < cacheTTL) {
element.setTimeToLive(expirationTime);
}
cache.put(element);
}
|
[
"protected",
"void",
"cacheElement",
"(",
"Ehcache",
"cache",
",",
"Serializable",
"cacheKey",
",",
"CachedPortletResultHolder",
"<",
"?",
">",
"data",
",",
"CacheControl",
"cacheControl",
")",
"{",
"// using validation method, ignore expirationTime and defer to cache configuration",
"if",
"(",
"cacheControl",
".",
"getETag",
"(",
")",
"!=",
"null",
")",
"{",
"final",
"Element",
"element",
"=",
"new",
"Element",
"(",
"cacheKey",
",",
"data",
")",
";",
"cache",
".",
"put",
"(",
"element",
")",
";",
"return",
";",
"}",
"// using expiration method, -1 for CacheControl#expirationTime means \"forever\" (e.g. ignore",
"// and defer to cache configuration)",
"final",
"int",
"expirationTime",
"=",
"cacheControl",
".",
"getExpirationTime",
"(",
")",
";",
"if",
"(",
"expirationTime",
"==",
"-",
"1",
")",
"{",
"final",
"Element",
"element",
"=",
"new",
"Element",
"(",
"cacheKey",
",",
"data",
")",
";",
"cache",
".",
"put",
"(",
"element",
")",
";",
"return",
";",
"}",
"// using expiration method with a positive expiration, set that value as the element's TTL",
"// if it is lower than the configured cache TTL",
"final",
"CacheConfiguration",
"cacheConfiguration",
"=",
"cache",
".",
"getCacheConfiguration",
"(",
")",
";",
"final",
"Element",
"element",
"=",
"new",
"Element",
"(",
"cacheKey",
",",
"data",
")",
";",
"final",
"long",
"cacheTTL",
"=",
"cacheConfiguration",
".",
"getTimeToLiveSeconds",
"(",
")",
";",
"if",
"(",
"expirationTime",
"<",
"cacheTTL",
")",
"{",
"element",
".",
"setTimeToLive",
"(",
"expirationTime",
")",
";",
"}",
"cache",
".",
"put",
"(",
"element",
")",
";",
"}"
] |
Construct an appropriate Cache {@link Element} for the cacheKey and data. The element's ttl
will be set depending on whether expiration or validation method is indicated from the
CacheControl and the cache's configuration.
|
[
"Construct",
"an",
"appropriate",
"Cache",
"{"
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/cache/PortletCacheControlServiceImpl.java#L517-L547
|
arquillian/arquillian-cube
|
docker/reporter/src/main/java/org/arquillian/cube/docker/impl/client/reporter/TakeVncDroneVideo.java
|
TakeVncDroneVideo.reportScreencastRecording
|
public void reportScreencastRecording(@Observes AfterVideoRecorded event, ReporterConfiguration reporterConfiguration) {
"""
Executes after drone recording has finished and file is generated
"""
Path videoLocation = event.getVideoLocation();
if (videoLocation != null) {
videoLocation = Paths.get(videoLocation.toString().replace("flv", "mp4"));
final Path rootDir = Paths.get(reporterConfiguration.getRootDirectory());
final Path relativize = rootDir.relativize(videoLocation);
final Method testMethod = getTestMethod(event);
Reporter.createReport(new TestMethodReport(testMethod.getName()))
.addKeyValueEntry(DockerEnvironmentReportKey.VIDEO_PATH, new FileEntry(relativize))
.inSection(new TestMethodSection(testMethod))
.fire(reportEvent);
}
}
|
java
|
public void reportScreencastRecording(@Observes AfterVideoRecorded event, ReporterConfiguration reporterConfiguration) {
Path videoLocation = event.getVideoLocation();
if (videoLocation != null) {
videoLocation = Paths.get(videoLocation.toString().replace("flv", "mp4"));
final Path rootDir = Paths.get(reporterConfiguration.getRootDirectory());
final Path relativize = rootDir.relativize(videoLocation);
final Method testMethod = getTestMethod(event);
Reporter.createReport(new TestMethodReport(testMethod.getName()))
.addKeyValueEntry(DockerEnvironmentReportKey.VIDEO_PATH, new FileEntry(relativize))
.inSection(new TestMethodSection(testMethod))
.fire(reportEvent);
}
}
|
[
"public",
"void",
"reportScreencastRecording",
"(",
"@",
"Observes",
"AfterVideoRecorded",
"event",
",",
"ReporterConfiguration",
"reporterConfiguration",
")",
"{",
"Path",
"videoLocation",
"=",
"event",
".",
"getVideoLocation",
"(",
")",
";",
"if",
"(",
"videoLocation",
"!=",
"null",
")",
"{",
"videoLocation",
"=",
"Paths",
".",
"get",
"(",
"videoLocation",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"\"flv\"",
",",
"\"mp4\"",
")",
")",
";",
"final",
"Path",
"rootDir",
"=",
"Paths",
".",
"get",
"(",
"reporterConfiguration",
".",
"getRootDirectory",
"(",
")",
")",
";",
"final",
"Path",
"relativize",
"=",
"rootDir",
".",
"relativize",
"(",
"videoLocation",
")",
";",
"final",
"Method",
"testMethod",
"=",
"getTestMethod",
"(",
"event",
")",
";",
"Reporter",
".",
"createReport",
"(",
"new",
"TestMethodReport",
"(",
"testMethod",
".",
"getName",
"(",
")",
")",
")",
".",
"addKeyValueEntry",
"(",
"DockerEnvironmentReportKey",
".",
"VIDEO_PATH",
",",
"new",
"FileEntry",
"(",
"relativize",
")",
")",
".",
"inSection",
"(",
"new",
"TestMethodSection",
"(",
"testMethod",
")",
")",
".",
"fire",
"(",
"reportEvent",
")",
";",
"}",
"}"
] |
Executes after drone recording has finished and file is generated
|
[
"Executes",
"after",
"drone",
"recording",
"has",
"finished",
"and",
"file",
"is",
"generated"
] |
train
|
https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/reporter/src/main/java/org/arquillian/cube/docker/impl/client/reporter/TakeVncDroneVideo.java#L24-L42
|
spotbugs/spotbugs
|
spotbugs/src/gui/main/edu/umd/cs/findbugs/sourceViewer/NavigableTextPane.java
|
NavigableTextPane.scrollLineToVisible
|
public void scrollLineToVisible(int line, int margin) {
"""
scroll the specified line into view, with a margin of 'margin' pixels
above and below
"""
int maxMargin = (parentHeight() - 20) / 2;
if (margin > maxMargin) {
margin = Math.max(0, maxMargin);
}
scrollLineToVisibleImpl(line, margin);
}
|
java
|
public void scrollLineToVisible(int line, int margin) {
int maxMargin = (parentHeight() - 20) / 2;
if (margin > maxMargin) {
margin = Math.max(0, maxMargin);
}
scrollLineToVisibleImpl(line, margin);
}
|
[
"public",
"void",
"scrollLineToVisible",
"(",
"int",
"line",
",",
"int",
"margin",
")",
"{",
"int",
"maxMargin",
"=",
"(",
"parentHeight",
"(",
")",
"-",
"20",
")",
"/",
"2",
";",
"if",
"(",
"margin",
">",
"maxMargin",
")",
"{",
"margin",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"maxMargin",
")",
";",
"}",
"scrollLineToVisibleImpl",
"(",
"line",
",",
"margin",
")",
";",
"}"
] |
scroll the specified line into view, with a margin of 'margin' pixels
above and below
|
[
"scroll",
"the",
"specified",
"line",
"into",
"view",
"with",
"a",
"margin",
"of",
"margin",
"pixels",
"above",
"and",
"below"
] |
train
|
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/gui/main/edu/umd/cs/findbugs/sourceViewer/NavigableTextPane.java#L111-L117
|
carewebframework/carewebframework-core
|
org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java
|
LayoutParser.parseTrigger
|
private void parseTrigger(Element node, LayoutElement parent) {
"""
Parse a trigger node.
@param node The DOM node.
@param parent The parent layout element.
"""
LayoutTrigger trigger = new LayoutTrigger();
parent.getTriggers().add(trigger);
parseChildren(node, trigger, Tag.CONDITION, Tag.ACTION);
}
|
java
|
private void parseTrigger(Element node, LayoutElement parent) {
LayoutTrigger trigger = new LayoutTrigger();
parent.getTriggers().add(trigger);
parseChildren(node, trigger, Tag.CONDITION, Tag.ACTION);
}
|
[
"private",
"void",
"parseTrigger",
"(",
"Element",
"node",
",",
"LayoutElement",
"parent",
")",
"{",
"LayoutTrigger",
"trigger",
"=",
"new",
"LayoutTrigger",
"(",
")",
";",
"parent",
".",
"getTriggers",
"(",
")",
".",
"add",
"(",
"trigger",
")",
";",
"parseChildren",
"(",
"node",
",",
"trigger",
",",
"Tag",
".",
"CONDITION",
",",
"Tag",
".",
"ACTION",
")",
";",
"}"
] |
Parse a trigger node.
@param node The DOM node.
@param parent The parent layout element.
|
[
"Parse",
"a",
"trigger",
"node",
"."
] |
train
|
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java#L302-L306
|
MariaDB/mariadb-connector-j
|
src/main/java/org/mariadb/jdbc/internal/util/exceptions/ExceptionMapper.java
|
ExceptionMapper.get
|
public static SQLException get(final String message, String sqlState, int errorCode,
final Throwable exception, boolean timeout) {
"""
Helper to decorate exception with associate subclass of {@link SQLException} exception.
@param message exception message
@param sqlState sqlstate
@param errorCode errorCode
@param exception cause
@param timeout was timeout on query
@return SQLException exception
"""
final SqlStates state = SqlStates.fromString(sqlState);
switch (state) {
case DATA_EXCEPTION:
return new SQLDataException(message, sqlState, errorCode, exception);
case FEATURE_NOT_SUPPORTED:
return new SQLFeatureNotSupportedException(message, sqlState, errorCode, exception);
case CONSTRAINT_VIOLATION:
return new SQLIntegrityConstraintViolationException(message, sqlState, errorCode,
exception);
case INVALID_AUTHORIZATION:
return new SQLInvalidAuthorizationSpecException(message, sqlState, errorCode, exception);
case CONNECTION_EXCEPTION:
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
case SYNTAX_ERROR_ACCESS_RULE:
return new SQLSyntaxErrorException(message, sqlState, errorCode, exception);
case TRANSACTION_ROLLBACK:
return new SQLTransactionRollbackException(message, sqlState, errorCode, exception);
case WARNING:
return new SQLWarning(message, sqlState, errorCode, exception);
case INTERRUPTED_EXCEPTION:
if (timeout && "70100".equals(sqlState)) {
return new SQLTimeoutException(message, sqlState, errorCode, exception);
}
if (exception instanceof SQLNonTransientConnectionException) {
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
}
return new SQLTransientException(message, sqlState, errorCode, exception);
case TIMEOUT_EXCEPTION:
return new SQLTimeoutException(message, sqlState, errorCode, exception);
case UNDEFINED_SQLSTATE:
if (exception instanceof SQLNonTransientConnectionException) {
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
}
return new SQLException(message, sqlState, errorCode, exception);
default:
// DISTRIBUTED_TRANSACTION_ERROR,
return new SQLException(message, sqlState, errorCode, exception);
}
}
|
java
|
public static SQLException get(final String message, String sqlState, int errorCode,
final Throwable exception, boolean timeout) {
final SqlStates state = SqlStates.fromString(sqlState);
switch (state) {
case DATA_EXCEPTION:
return new SQLDataException(message, sqlState, errorCode, exception);
case FEATURE_NOT_SUPPORTED:
return new SQLFeatureNotSupportedException(message, sqlState, errorCode, exception);
case CONSTRAINT_VIOLATION:
return new SQLIntegrityConstraintViolationException(message, sqlState, errorCode,
exception);
case INVALID_AUTHORIZATION:
return new SQLInvalidAuthorizationSpecException(message, sqlState, errorCode, exception);
case CONNECTION_EXCEPTION:
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
case SYNTAX_ERROR_ACCESS_RULE:
return new SQLSyntaxErrorException(message, sqlState, errorCode, exception);
case TRANSACTION_ROLLBACK:
return new SQLTransactionRollbackException(message, sqlState, errorCode, exception);
case WARNING:
return new SQLWarning(message, sqlState, errorCode, exception);
case INTERRUPTED_EXCEPTION:
if (timeout && "70100".equals(sqlState)) {
return new SQLTimeoutException(message, sqlState, errorCode, exception);
}
if (exception instanceof SQLNonTransientConnectionException) {
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
}
return new SQLTransientException(message, sqlState, errorCode, exception);
case TIMEOUT_EXCEPTION:
return new SQLTimeoutException(message, sqlState, errorCode, exception);
case UNDEFINED_SQLSTATE:
if (exception instanceof SQLNonTransientConnectionException) {
return new SQLNonTransientConnectionException(message, sqlState, errorCode, exception);
}
return new SQLException(message, sqlState, errorCode, exception);
default:
// DISTRIBUTED_TRANSACTION_ERROR,
return new SQLException(message, sqlState, errorCode, exception);
}
}
|
[
"public",
"static",
"SQLException",
"get",
"(",
"final",
"String",
"message",
",",
"String",
"sqlState",
",",
"int",
"errorCode",
",",
"final",
"Throwable",
"exception",
",",
"boolean",
"timeout",
")",
"{",
"final",
"SqlStates",
"state",
"=",
"SqlStates",
".",
"fromString",
"(",
"sqlState",
")",
";",
"switch",
"(",
"state",
")",
"{",
"case",
"DATA_EXCEPTION",
":",
"return",
"new",
"SQLDataException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"FEATURE_NOT_SUPPORTED",
":",
"return",
"new",
"SQLFeatureNotSupportedException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"CONSTRAINT_VIOLATION",
":",
"return",
"new",
"SQLIntegrityConstraintViolationException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"INVALID_AUTHORIZATION",
":",
"return",
"new",
"SQLInvalidAuthorizationSpecException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"CONNECTION_EXCEPTION",
":",
"return",
"new",
"SQLNonTransientConnectionException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"SYNTAX_ERROR_ACCESS_RULE",
":",
"return",
"new",
"SQLSyntaxErrorException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"TRANSACTION_ROLLBACK",
":",
"return",
"new",
"SQLTransactionRollbackException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"WARNING",
":",
"return",
"new",
"SQLWarning",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"INTERRUPTED_EXCEPTION",
":",
"if",
"(",
"timeout",
"&&",
"\"70100\"",
".",
"equals",
"(",
"sqlState",
")",
")",
"{",
"return",
"new",
"SQLTimeoutException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"}",
"if",
"(",
"exception",
"instanceof",
"SQLNonTransientConnectionException",
")",
"{",
"return",
"new",
"SQLNonTransientConnectionException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"}",
"return",
"new",
"SQLTransientException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"TIMEOUT_EXCEPTION",
":",
"return",
"new",
"SQLTimeoutException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"case",
"UNDEFINED_SQLSTATE",
":",
"if",
"(",
"exception",
"instanceof",
"SQLNonTransientConnectionException",
")",
"{",
"return",
"new",
"SQLNonTransientConnectionException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"}",
"return",
"new",
"SQLException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"default",
":",
"// DISTRIBUTED_TRANSACTION_ERROR,",
"return",
"new",
"SQLException",
"(",
"message",
",",
"sqlState",
",",
"errorCode",
",",
"exception",
")",
";",
"}",
"}"
] |
Helper to decorate exception with associate subclass of {@link SQLException} exception.
@param message exception message
@param sqlState sqlstate
@param errorCode errorCode
@param exception cause
@param timeout was timeout on query
@return SQLException exception
|
[
"Helper",
"to",
"decorate",
"exception",
"with",
"associate",
"subclass",
"of",
"{",
"@link",
"SQLException",
"}",
"exception",
"."
] |
train
|
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/exceptions/ExceptionMapper.java#L226-L266
|
jenetics/jenetics
|
jenetics/src/main/java/io/jenetics/engine/Codecs.java
|
Codecs.ofMapping
|
public static <A, B> Codec<Map<A, B>, EnumGene<Integer>>
ofMapping(final ISeq<? extends A> source, final ISeq<? extends B> target) {
"""
Create a codec, which creates a a mapping from the elements given in the
{@code source} sequence to the elements given in the {@code target}
sequence. The returned mapping can be seen as a function which maps every
element of the {@code target} set to an element of the {@code source} set.
<pre>{@code
final ISeq<Integer> numbers = ISeq.of(1, 2, 3, 4, 5);
final ISeq<String> strings = ISeq.of("1", "2", "3");
final Codec<Map<Integer, String>, EnumGene<Integer>> codec =
Codecs.ofMapping(numbers, strings);
}</pre>
If {@code source.size() > target.size()}, the created mapping is
<a href="https://en.wikipedia.org/wiki/Surjective_function">surjective</a>,
if {@code source.size() < target.size()}, the mapping is
<a href="https://en.wikipedia.org/wiki/Injective_function">injective</a>
and if both sets have the same size, the returned mapping is
<a href="https://en.wikipedia.org/wiki/Bijection">bijective</a>.
@since 4.3
@param source the source elements. Will be the <em>keys</em> of the
encoded {@code Map}.
@param target the target elements. Will be the <em>values</em> of the
encoded {@code Map}.
@param <A> the type of the source elements
@param <B> the type of the target elements
@return a new mapping codec
@throws IllegalArgumentException if the {@code target} sequences are empty
@throws NullPointerException if one of the argument is {@code null}
"""
return ofMapping(source, target, HashMap::new);
}
|
java
|
public static <A, B> Codec<Map<A, B>, EnumGene<Integer>>
ofMapping(final ISeq<? extends A> source, final ISeq<? extends B> target) {
return ofMapping(source, target, HashMap::new);
}
|
[
"public",
"static",
"<",
"A",
",",
"B",
">",
"Codec",
"<",
"Map",
"<",
"A",
",",
"B",
">",
",",
"EnumGene",
"<",
"Integer",
">",
">",
"ofMapping",
"(",
"final",
"ISeq",
"<",
"?",
"extends",
"A",
">",
"source",
",",
"final",
"ISeq",
"<",
"?",
"extends",
"B",
">",
"target",
")",
"{",
"return",
"ofMapping",
"(",
"source",
",",
"target",
",",
"HashMap",
"::",
"new",
")",
";",
"}"
] |
Create a codec, which creates a a mapping from the elements given in the
{@code source} sequence to the elements given in the {@code target}
sequence. The returned mapping can be seen as a function which maps every
element of the {@code target} set to an element of the {@code source} set.
<pre>{@code
final ISeq<Integer> numbers = ISeq.of(1, 2, 3, 4, 5);
final ISeq<String> strings = ISeq.of("1", "2", "3");
final Codec<Map<Integer, String>, EnumGene<Integer>> codec =
Codecs.ofMapping(numbers, strings);
}</pre>
If {@code source.size() > target.size()}, the created mapping is
<a href="https://en.wikipedia.org/wiki/Surjective_function">surjective</a>,
if {@code source.size() < target.size()}, the mapping is
<a href="https://en.wikipedia.org/wiki/Injective_function">injective</a>
and if both sets have the same size, the returned mapping is
<a href="https://en.wikipedia.org/wiki/Bijection">bijective</a>.
@since 4.3
@param source the source elements. Will be the <em>keys</em> of the
encoded {@code Map}.
@param target the target elements. Will be the <em>values</em> of the
encoded {@code Map}.
@param <A> the type of the source elements
@param <B> the type of the target elements
@return a new mapping codec
@throws IllegalArgumentException if the {@code target} sequences are empty
@throws NullPointerException if one of the argument is {@code null}
|
[
"Create",
"a",
"codec",
"which",
"creates",
"a",
"a",
"mapping",
"from",
"the",
"elements",
"given",
"in",
"the",
"{",
"@code",
"source",
"}",
"sequence",
"to",
"the",
"elements",
"given",
"in",
"the",
"{",
"@code",
"target",
"}",
"sequence",
".",
"The",
"returned",
"mapping",
"can",
"be",
"seen",
"as",
"a",
"function",
"which",
"maps",
"every",
"element",
"of",
"the",
"{",
"@code",
"target",
"}",
"set",
"to",
"an",
"element",
"of",
"the",
"{",
"@code",
"source",
"}",
"set",
"."
] |
train
|
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Codecs.java#L725-L728
|
alkacon/opencms-core
|
src/org/opencms/workplace/CmsWorkplace.java
|
CmsWorkplace.decodeParamValue
|
protected String decodeParamValue(String paramName, String paramValue) {
"""
Decodes an individual parameter value.<p>
In special cases some parameters might require a different-from-default
encoding. This is the case if the content of the parameter was
encoded using the JavaScript encodeURIComponent() method on the client,
which always encodes in UTF-8.<p>
@param paramName the name of the parameter
@param paramValue the unencoded value of the parameter
@return the encoded value of the parameter
"""
if ((paramName != null) && (paramValue != null)) {
return CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding());
} else {
return null;
}
}
|
java
|
protected String decodeParamValue(String paramName, String paramValue) {
if ((paramName != null) && (paramValue != null)) {
return CmsEncoder.decode(paramValue, getCms().getRequestContext().getEncoding());
} else {
return null;
}
}
|
[
"protected",
"String",
"decodeParamValue",
"(",
"String",
"paramName",
",",
"String",
"paramValue",
")",
"{",
"if",
"(",
"(",
"paramName",
"!=",
"null",
")",
"&&",
"(",
"paramValue",
"!=",
"null",
")",
")",
"{",
"return",
"CmsEncoder",
".",
"decode",
"(",
"paramValue",
",",
"getCms",
"(",
")",
".",
"getRequestContext",
"(",
")",
".",
"getEncoding",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] |
Decodes an individual parameter value.<p>
In special cases some parameters might require a different-from-default
encoding. This is the case if the content of the parameter was
encoded using the JavaScript encodeURIComponent() method on the client,
which always encodes in UTF-8.<p>
@param paramName the name of the parameter
@param paramValue the unencoded value of the parameter
@return the encoded value of the parameter
|
[
"Decodes",
"an",
"individual",
"parameter",
"value",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L2252-L2259
|
fhoeben/hsac-fitnesse-fixtures
|
src/main/java/nl/hsac/fitnesse/fixture/util/selenium/JavascriptHelper.java
|
JavascriptHelper.executeScript
|
public static Object executeScript(JavascriptExecutor jse, String script, Object... parameters) {
"""
Executes Javascript in browser. If script contains the magic variable 'arguments'
the parameters will also be passed to the statement. In the latter case the parameters
must be a number, a boolean, a String, WebElement, or a List of any combination of the above.
@link http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html#executeScript(java.lang.String,%20java.lang.Object...)
@param script javascript to run.
@param parameters parameters for the script.
@return return value from statement.
"""
Object result;
try {
result = jse.executeScript(script, parameters);
} catch (WebDriverException e) {
String msg = e.getMessage();
if (msg != null && msg.contains("Detected a page unload event; script execution does not work across page loads.")) {
// page reloaded while script ran, retry it once
result = jse.executeScript(script, parameters);
} else {
throw e;
}
}
return result;
}
|
java
|
public static Object executeScript(JavascriptExecutor jse, String script, Object... parameters) {
Object result;
try {
result = jse.executeScript(script, parameters);
} catch (WebDriverException e) {
String msg = e.getMessage();
if (msg != null && msg.contains("Detected a page unload event; script execution does not work across page loads.")) {
// page reloaded while script ran, retry it once
result = jse.executeScript(script, parameters);
} else {
throw e;
}
}
return result;
}
|
[
"public",
"static",
"Object",
"executeScript",
"(",
"JavascriptExecutor",
"jse",
",",
"String",
"script",
",",
"Object",
"...",
"parameters",
")",
"{",
"Object",
"result",
";",
"try",
"{",
"result",
"=",
"jse",
".",
"executeScript",
"(",
"script",
",",
"parameters",
")",
";",
"}",
"catch",
"(",
"WebDriverException",
"e",
")",
"{",
"String",
"msg",
"=",
"e",
".",
"getMessage",
"(",
")",
";",
"if",
"(",
"msg",
"!=",
"null",
"&&",
"msg",
".",
"contains",
"(",
"\"Detected a page unload event; script execution does not work across page loads.\"",
")",
")",
"{",
"// page reloaded while script ran, retry it once",
"result",
"=",
"jse",
".",
"executeScript",
"(",
"script",
",",
"parameters",
")",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Executes Javascript in browser. If script contains the magic variable 'arguments'
the parameters will also be passed to the statement. In the latter case the parameters
must be a number, a boolean, a String, WebElement, or a List of any combination of the above.
@link http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/JavascriptExecutor.html#executeScript(java.lang.String,%20java.lang.Object...)
@param script javascript to run.
@param parameters parameters for the script.
@return return value from statement.
|
[
"Executes",
"Javascript",
"in",
"browser",
".",
"If",
"script",
"contains",
"the",
"magic",
"variable",
"arguments",
"the",
"parameters",
"will",
"also",
"be",
"passed",
"to",
"the",
"statement",
".",
"In",
"the",
"latter",
"case",
"the",
"parameters",
"must",
"be",
"a",
"number",
"a",
"boolean",
"a",
"String",
"WebElement",
"or",
"a",
"List",
"of",
"any",
"combination",
"of",
"the",
"above",
"."
] |
train
|
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/selenium/JavascriptHelper.java#L48-L62
|
alkacon/opencms-core
|
src-modules/org/opencms/workplace/commons/CmsPreferences.java
|
CmsPreferences.buildSelect
|
String buildSelect(String htmlAttributes, SelectOptions options) {
"""
Builds the HTML code for a select widget given a bean containing the select options
@param htmlAttributes html attributes for the select widget
@param options the bean containing the select options
@return the HTML for the select box
"""
return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());
}
|
java
|
String buildSelect(String htmlAttributes, SelectOptions options) {
return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());
}
|
[
"String",
"buildSelect",
"(",
"String",
"htmlAttributes",
",",
"SelectOptions",
"options",
")",
"{",
"return",
"buildSelect",
"(",
"htmlAttributes",
",",
"options",
".",
"getOptions",
"(",
")",
",",
"options",
".",
"getValues",
"(",
")",
",",
"options",
".",
"getSelectedIndex",
"(",
")",
")",
";",
"}"
] |
Builds the HTML code for a select widget given a bean containing the select options
@param htmlAttributes html attributes for the select widget
@param options the bean containing the select options
@return the HTML for the select box
|
[
"Builds",
"the",
"HTML",
"code",
"for",
"a",
"select",
"widget",
"given",
"a",
"bean",
"containing",
"the",
"select",
"options"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPreferences.java#L2257-L2260
|
mirage-sql/mirage
|
src/main/java/com/miragesql/miragesql/util/MirageUtil.java
|
MirageUtil.buildSelectSQL
|
public static String buildSelectSQL(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> clazz, NameConverter nameConverter) {
"""
Builds select (by primary keys) SQL from the entity class.
@param beanDescFactory the bean descriptor factory
@param entityOperator the entity operator
@param clazz the entity class to select
@param nameConverter the name converter
@return Select SQL
@throws RuntimeException the entity class has no primary keys
@deprecated use {@link #buildSelectSQL(String, BeanDescFactory, EntityOperator, Class, NameConverter)} instead
"""
StringBuilder sb = new StringBuilder();
BeanDesc beanDesc = beanDescFactory.getBeanDesc(clazz);
sb.append("SELECT * FROM ");
sb.append(MirageUtil.getTableName(clazz, nameConverter));
sb.append(" WHERE ");
int count = 0;
for(int i=0; i<beanDesc.getPropertyDescSize(); i++){
PropertyDesc pd = beanDesc.getPropertyDesc(i);
PrimaryKeyInfo primaryKey = entityOperator.getPrimaryKeyInfo(clazz, pd, nameConverter);
if(primaryKey != null){
if(count != 0){
sb.append(" AND ");
}
sb.append(MirageUtil.getColumnName(entityOperator, clazz, pd, nameConverter));
sb.append(" = ?");
count++;
}
}
if(count == 0){
throw new RuntimeException(
"Primary key is not found: " + clazz.getName());
}
return sb.toString();
}
|
java
|
public static String buildSelectSQL(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> clazz, NameConverter nameConverter){
StringBuilder sb = new StringBuilder();
BeanDesc beanDesc = beanDescFactory.getBeanDesc(clazz);
sb.append("SELECT * FROM ");
sb.append(MirageUtil.getTableName(clazz, nameConverter));
sb.append(" WHERE ");
int count = 0;
for(int i=0; i<beanDesc.getPropertyDescSize(); i++){
PropertyDesc pd = beanDesc.getPropertyDesc(i);
PrimaryKeyInfo primaryKey = entityOperator.getPrimaryKeyInfo(clazz, pd, nameConverter);
if(primaryKey != null){
if(count != 0){
sb.append(" AND ");
}
sb.append(MirageUtil.getColumnName(entityOperator, clazz, pd, nameConverter));
sb.append(" = ?");
count++;
}
}
if(count == 0){
throw new RuntimeException(
"Primary key is not found: " + clazz.getName());
}
return sb.toString();
}
|
[
"public",
"static",
"String",
"buildSelectSQL",
"(",
"BeanDescFactory",
"beanDescFactory",
",",
"EntityOperator",
"entityOperator",
",",
"Class",
"<",
"?",
">",
"clazz",
",",
"NameConverter",
"nameConverter",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"BeanDesc",
"beanDesc",
"=",
"beanDescFactory",
".",
"getBeanDesc",
"(",
"clazz",
")",
";",
"sb",
".",
"append",
"(",
"\"SELECT * FROM \"",
")",
";",
"sb",
".",
"append",
"(",
"MirageUtil",
".",
"getTableName",
"(",
"clazz",
",",
"nameConverter",
")",
")",
";",
"sb",
".",
"append",
"(",
"\" WHERE \"",
")",
";",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"beanDesc",
".",
"getPropertyDescSize",
"(",
")",
";",
"i",
"++",
")",
"{",
"PropertyDesc",
"pd",
"=",
"beanDesc",
".",
"getPropertyDesc",
"(",
"i",
")",
";",
"PrimaryKeyInfo",
"primaryKey",
"=",
"entityOperator",
".",
"getPrimaryKeyInfo",
"(",
"clazz",
",",
"pd",
",",
"nameConverter",
")",
";",
"if",
"(",
"primaryKey",
"!=",
"null",
")",
"{",
"if",
"(",
"count",
"!=",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\" AND \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"MirageUtil",
".",
"getColumnName",
"(",
"entityOperator",
",",
"clazz",
",",
"pd",
",",
"nameConverter",
")",
")",
";",
"sb",
".",
"append",
"(",
"\" = ?\"",
")",
";",
"count",
"++",
";",
"}",
"}",
"if",
"(",
"count",
"==",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Primary key is not found: \"",
"+",
"clazz",
".",
"getName",
"(",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Builds select (by primary keys) SQL from the entity class.
@param beanDescFactory the bean descriptor factory
@param entityOperator the entity operator
@param clazz the entity class to select
@param nameConverter the name converter
@return Select SQL
@throws RuntimeException the entity class has no primary keys
@deprecated use {@link #buildSelectSQL(String, BeanDescFactory, EntityOperator, Class, NameConverter)} instead
|
[
"Builds",
"select",
"(",
"by",
"primary",
"keys",
")",
"SQL",
"from",
"the",
"entity",
"class",
"."
] |
train
|
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/util/MirageUtil.java#L124-L152
|
protostuff/protostuff
|
protostuff-parser/src/main/java/io/protostuff/parser/DefaultProtoLoader.java
|
DefaultProtoLoader.getResource
|
public static URL getResource(String resource, Class<?> context, boolean checkParent) {
"""
Loads a {@link URL} resource from the classloader; If not found, the classloader of the {@code context} class
specified will be used. If the flag {@code checkParent} is true, the classloader's parent is included in the
lookup.
"""
URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
if (url != null)
return url;
if (context != null)
{
ClassLoader loader = context.getClassLoader();
while (loader != null)
{
url = loader.getResource(resource);
if (url != null)
return url;
loader = checkParent ? loader.getParent() : null;
}
}
return ClassLoader.getSystemResource(resource);
}
|
java
|
public static URL getResource(String resource, Class<?> context, boolean checkParent)
{
URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
if (url != null)
return url;
if (context != null)
{
ClassLoader loader = context.getClassLoader();
while (loader != null)
{
url = loader.getResource(resource);
if (url != null)
return url;
loader = checkParent ? loader.getParent() : null;
}
}
return ClassLoader.getSystemResource(resource);
}
|
[
"public",
"static",
"URL",
"getResource",
"(",
"String",
"resource",
",",
"Class",
"<",
"?",
">",
"context",
",",
"boolean",
"checkParent",
")",
"{",
"URL",
"url",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
".",
"getResource",
"(",
"resource",
")",
";",
"if",
"(",
"url",
"!=",
"null",
")",
"return",
"url",
";",
"if",
"(",
"context",
"!=",
"null",
")",
"{",
"ClassLoader",
"loader",
"=",
"context",
".",
"getClassLoader",
"(",
")",
";",
"while",
"(",
"loader",
"!=",
"null",
")",
"{",
"url",
"=",
"loader",
".",
"getResource",
"(",
"resource",
")",
";",
"if",
"(",
"url",
"!=",
"null",
")",
"return",
"url",
";",
"loader",
"=",
"checkParent",
"?",
"loader",
".",
"getParent",
"(",
")",
":",
"null",
";",
"}",
"}",
"return",
"ClassLoader",
".",
"getSystemResource",
"(",
"resource",
")",
";",
"}"
] |
Loads a {@link URL} resource from the classloader; If not found, the classloader of the {@code context} class
specified will be used. If the flag {@code checkParent} is true, the classloader's parent is included in the
lookup.
|
[
"Loads",
"a",
"{"
] |
train
|
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-parser/src/main/java/io/protostuff/parser/DefaultProtoLoader.java#L299-L318
|
knowm/XChange
|
xchange-bankera/src/main/java/org/knowm/xchange/bankera/BankeraAdapters.java
|
BankeraAdapters.adaptTicker
|
public static Ticker adaptTicker(BankeraTickerResponse ticker, CurrencyPair currencyPair) {
"""
Adapts Bankera BankeraTickerResponse to a Ticker
@param ticker Specific ticker
@param currencyPair BankeraCurrency pair (e.g. ETH/BTC)
@return Ticker
"""
BigDecimal high = new BigDecimal(ticker.getTicker().getHigh());
BigDecimal low = new BigDecimal(ticker.getTicker().getLow());
BigDecimal bid = new BigDecimal(ticker.getTicker().getBid());
BigDecimal ask = new BigDecimal(ticker.getTicker().getAsk());
BigDecimal last = new BigDecimal(ticker.getTicker().getLast());
BigDecimal volume = new BigDecimal(ticker.getTicker().getVolume());
Date timestamp = new Date(ticker.getTicker().getTimestamp());
return new Ticker.Builder()
.currencyPair(currencyPair)
.high(high)
.low(low)
.bid(bid)
.ask(ask)
.last(last)
.volume(volume)
.timestamp(timestamp)
.build();
}
|
java
|
public static Ticker adaptTicker(BankeraTickerResponse ticker, CurrencyPair currencyPair) {
BigDecimal high = new BigDecimal(ticker.getTicker().getHigh());
BigDecimal low = new BigDecimal(ticker.getTicker().getLow());
BigDecimal bid = new BigDecimal(ticker.getTicker().getBid());
BigDecimal ask = new BigDecimal(ticker.getTicker().getAsk());
BigDecimal last = new BigDecimal(ticker.getTicker().getLast());
BigDecimal volume = new BigDecimal(ticker.getTicker().getVolume());
Date timestamp = new Date(ticker.getTicker().getTimestamp());
return new Ticker.Builder()
.currencyPair(currencyPair)
.high(high)
.low(low)
.bid(bid)
.ask(ask)
.last(last)
.volume(volume)
.timestamp(timestamp)
.build();
}
|
[
"public",
"static",
"Ticker",
"adaptTicker",
"(",
"BankeraTickerResponse",
"ticker",
",",
"CurrencyPair",
"currencyPair",
")",
"{",
"BigDecimal",
"high",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getHigh",
"(",
")",
")",
";",
"BigDecimal",
"low",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getLow",
"(",
")",
")",
";",
"BigDecimal",
"bid",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getBid",
"(",
")",
")",
";",
"BigDecimal",
"ask",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getAsk",
"(",
")",
")",
";",
"BigDecimal",
"last",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getLast",
"(",
")",
")",
";",
"BigDecimal",
"volume",
"=",
"new",
"BigDecimal",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getVolume",
"(",
")",
")",
";",
"Date",
"timestamp",
"=",
"new",
"Date",
"(",
"ticker",
".",
"getTicker",
"(",
")",
".",
"getTimestamp",
"(",
")",
")",
";",
"return",
"new",
"Ticker",
".",
"Builder",
"(",
")",
".",
"currencyPair",
"(",
"currencyPair",
")",
".",
"high",
"(",
"high",
")",
".",
"low",
"(",
"low",
")",
".",
"bid",
"(",
"bid",
")",
".",
"ask",
"(",
"ask",
")",
".",
"last",
"(",
"last",
")",
".",
"volume",
"(",
"volume",
")",
".",
"timestamp",
"(",
"timestamp",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Adapts Bankera BankeraTickerResponse to a Ticker
@param ticker Specific ticker
@param currencyPair BankeraCurrency pair (e.g. ETH/BTC)
@return Ticker
|
[
"Adapts",
"Bankera",
"BankeraTickerResponse",
"to",
"a",
"Ticker"
] |
train
|
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bankera/src/main/java/org/knowm/xchange/bankera/BankeraAdapters.java#L69-L89
|
stratosphere/stratosphere
|
stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/sort/FixedLengthRecordSorter.java
|
FixedLengthRecordSorter.writeToOutput
|
@Override
public void writeToOutput(final ChannelWriterOutputView output, final int start, int num) throws IOException {
"""
Writes a subset of the records in this buffer in their logical order to the given output.
@param output The output view to write the records to.
@param start The logical start position of the subset.
@param len The number of elements to write.
@throws IOException Thrown, if an I/O exception occurred writing to the output view.
"""
final TypeComparator<T> comparator = this.comparator;
final TypeSerializer<T> serializer = this.serializer;
T record = this.recordInstance;
final SingleSegmentInputView inView = this.inView;
final int recordsPerSegment = this.recordsPerSegment;
int currentMemSeg = start / recordsPerSegment;
int offset = (start % recordsPerSegment) * this.recordSize;
while (num > 0) {
final MemorySegment currentIndexSegment = this.sortBuffer.get(currentMemSeg++);
inView.set(currentIndexSegment, offset);
// check whether we have a full or partially full segment
if (num >= recordsPerSegment && offset == 0) {
// full segment
for (int numInMemSeg = 0; numInMemSeg < recordsPerSegment; numInMemSeg++) {
record = comparator.readWithKeyDenormalization(record, inView);
serializer.serialize(record, output);
}
num -= recordsPerSegment;
} else {
// partially filled segment
for (; num > 0; num--) {
record = comparator.readWithKeyDenormalization(record, inView);
serializer.serialize(record, output);
}
}
}
}
|
java
|
@Override
public void writeToOutput(final ChannelWriterOutputView output, final int start, int num) throws IOException {
final TypeComparator<T> comparator = this.comparator;
final TypeSerializer<T> serializer = this.serializer;
T record = this.recordInstance;
final SingleSegmentInputView inView = this.inView;
final int recordsPerSegment = this.recordsPerSegment;
int currentMemSeg = start / recordsPerSegment;
int offset = (start % recordsPerSegment) * this.recordSize;
while (num > 0) {
final MemorySegment currentIndexSegment = this.sortBuffer.get(currentMemSeg++);
inView.set(currentIndexSegment, offset);
// check whether we have a full or partially full segment
if (num >= recordsPerSegment && offset == 0) {
// full segment
for (int numInMemSeg = 0; numInMemSeg < recordsPerSegment; numInMemSeg++) {
record = comparator.readWithKeyDenormalization(record, inView);
serializer.serialize(record, output);
}
num -= recordsPerSegment;
} else {
// partially filled segment
for (; num > 0; num--) {
record = comparator.readWithKeyDenormalization(record, inView);
serializer.serialize(record, output);
}
}
}
}
|
[
"@",
"Override",
"public",
"void",
"writeToOutput",
"(",
"final",
"ChannelWriterOutputView",
"output",
",",
"final",
"int",
"start",
",",
"int",
"num",
")",
"throws",
"IOException",
"{",
"final",
"TypeComparator",
"<",
"T",
">",
"comparator",
"=",
"this",
".",
"comparator",
";",
"final",
"TypeSerializer",
"<",
"T",
">",
"serializer",
"=",
"this",
".",
"serializer",
";",
"T",
"record",
"=",
"this",
".",
"recordInstance",
";",
"final",
"SingleSegmentInputView",
"inView",
"=",
"this",
".",
"inView",
";",
"final",
"int",
"recordsPerSegment",
"=",
"this",
".",
"recordsPerSegment",
";",
"int",
"currentMemSeg",
"=",
"start",
"/",
"recordsPerSegment",
";",
"int",
"offset",
"=",
"(",
"start",
"%",
"recordsPerSegment",
")",
"*",
"this",
".",
"recordSize",
";",
"while",
"(",
"num",
">",
"0",
")",
"{",
"final",
"MemorySegment",
"currentIndexSegment",
"=",
"this",
".",
"sortBuffer",
".",
"get",
"(",
"currentMemSeg",
"++",
")",
";",
"inView",
".",
"set",
"(",
"currentIndexSegment",
",",
"offset",
")",
";",
"// check whether we have a full or partially full segment",
"if",
"(",
"num",
">=",
"recordsPerSegment",
"&&",
"offset",
"==",
"0",
")",
"{",
"// full segment",
"for",
"(",
"int",
"numInMemSeg",
"=",
"0",
";",
"numInMemSeg",
"<",
"recordsPerSegment",
";",
"numInMemSeg",
"++",
")",
"{",
"record",
"=",
"comparator",
".",
"readWithKeyDenormalization",
"(",
"record",
",",
"inView",
")",
";",
"serializer",
".",
"serialize",
"(",
"record",
",",
"output",
")",
";",
"}",
"num",
"-=",
"recordsPerSegment",
";",
"}",
"else",
"{",
"// partially filled segment",
"for",
"(",
";",
"num",
">",
"0",
";",
"num",
"--",
")",
"{",
"record",
"=",
"comparator",
".",
"readWithKeyDenormalization",
"(",
"record",
",",
"inView",
")",
";",
"serializer",
".",
"serialize",
"(",
"record",
",",
"output",
")",
";",
"}",
"}",
"}",
"}"
] |
Writes a subset of the records in this buffer in their logical order to the given output.
@param output The output view to write the records to.
@param start The logical start position of the subset.
@param len The number of elements to write.
@throws IOException Thrown, if an I/O exception occurred writing to the output view.
|
[
"Writes",
"a",
"subset",
"of",
"the",
"records",
"in",
"this",
"buffer",
"in",
"their",
"logical",
"order",
"to",
"the",
"given",
"output",
"."
] |
train
|
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/sort/FixedLengthRecordSorter.java#L410-L442
|
apache/groovy
|
src/main/groovy/groovy/lang/ExpandoMetaClass.java
|
ExpandoMetaClass.setProperty
|
public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) {
"""
Overrides default implementation just in case setProperty method has been overridden by ExpandoMetaClass
@see MetaClassImpl#setProperty(Class, Object, String, Object, boolean, boolean)
"""
if (setPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && getJavaClass().isInstance(object)) {
setPropertyMethod.invoke(object, new Object[]{name, newValue});
return;
}
super.setProperty(sender, object, name, newValue, useSuper, fromInsideClass);
}
|
java
|
public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) {
if (setPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && getJavaClass().isInstance(object)) {
setPropertyMethod.invoke(object, new Object[]{name, newValue});
return;
}
super.setProperty(sender, object, name, newValue, useSuper, fromInsideClass);
}
|
[
"public",
"void",
"setProperty",
"(",
"Class",
"sender",
",",
"Object",
"object",
",",
"String",
"name",
",",
"Object",
"newValue",
",",
"boolean",
"useSuper",
",",
"boolean",
"fromInsideClass",
")",
"{",
"if",
"(",
"setPropertyMethod",
"!=",
"null",
"&&",
"!",
"name",
".",
"equals",
"(",
"META_CLASS_PROPERTY",
")",
"&&",
"getJavaClass",
"(",
")",
".",
"isInstance",
"(",
"object",
")",
")",
"{",
"setPropertyMethod",
".",
"invoke",
"(",
"object",
",",
"new",
"Object",
"[",
"]",
"{",
"name",
",",
"newValue",
"}",
")",
";",
"return",
";",
"}",
"super",
".",
"setProperty",
"(",
"sender",
",",
"object",
",",
"name",
",",
"newValue",
",",
"useSuper",
",",
"fromInsideClass",
")",
";",
"}"
] |
Overrides default implementation just in case setProperty method has been overridden by ExpandoMetaClass
@see MetaClassImpl#setProperty(Class, Object, String, Object, boolean, boolean)
|
[
"Overrides",
"default",
"implementation",
"just",
"in",
"case",
"setProperty",
"method",
"has",
"been",
"overridden",
"by",
"ExpandoMetaClass"
] |
train
|
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/ExpandoMetaClass.java#L1180-L1186
|
ManfredTremmel/gwt-commons-lang3
|
src/main/java/org/apache/commons/lang3/Range.java
|
Range.intersectionWith
|
public Range<T> intersectionWith(final Range<T> other) {
"""
Calculate the intersection of {@code this} and an overlapping Range.
@param other overlapping Range
@return range representing the intersection of {@code this} and {@code other} ({@code this} if equal)
@throws IllegalArgumentException if {@code other} does not overlap {@code this}
@since 3.0.1
"""
if (!this.isOverlappedBy(other)) {
throw new IllegalArgumentException(StringUtils.simpleFormat(
"Cannot calculate intersection with non-overlapping range %s", other));
}
if (this.equals(other)) {
return this;
}
final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
return between(min, max, getComparator());
}
|
java
|
public Range<T> intersectionWith(final Range<T> other) {
if (!this.isOverlappedBy(other)) {
throw new IllegalArgumentException(StringUtils.simpleFormat(
"Cannot calculate intersection with non-overlapping range %s", other));
}
if (this.equals(other)) {
return this;
}
final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum;
final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum;
return between(min, max, getComparator());
}
|
[
"public",
"Range",
"<",
"T",
">",
"intersectionWith",
"(",
"final",
"Range",
"<",
"T",
">",
"other",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isOverlappedBy",
"(",
"other",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"StringUtils",
".",
"simpleFormat",
"(",
"\"Cannot calculate intersection with non-overlapping range %s\"",
",",
"other",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"equals",
"(",
"other",
")",
")",
"{",
"return",
"this",
";",
"}",
"final",
"T",
"min",
"=",
"getComparator",
"(",
")",
".",
"compare",
"(",
"minimum",
",",
"other",
".",
"minimum",
")",
"<",
"0",
"?",
"other",
".",
"minimum",
":",
"minimum",
";",
"final",
"T",
"max",
"=",
"getComparator",
"(",
")",
".",
"compare",
"(",
"maximum",
",",
"other",
".",
"maximum",
")",
"<",
"0",
"?",
"maximum",
":",
"other",
".",
"maximum",
";",
"return",
"between",
"(",
"min",
",",
"max",
",",
"getComparator",
"(",
")",
")",
";",
"}"
] |
Calculate the intersection of {@code this} and an overlapping Range.
@param other overlapping Range
@return range representing the intersection of {@code this} and {@code other} ({@code this} if equal)
@throws IllegalArgumentException if {@code other} does not overlap {@code this}
@since 3.0.1
|
[
"Calculate",
"the",
"intersection",
"of",
"{"
] |
train
|
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Range.java#L381-L392
|
lessthanoptimal/ejml
|
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
|
CommonOps_DDF2.elementDiv
|
public static void elementDiv( DMatrix2 a , DMatrix2 b , DMatrix2 c ) {
"""
<p>Performs an element by element division operation:<br>
<br>
c<sub>i</sub> = a<sub>i</sub> / b<sub>i</sub> <br>
</p>
@param a The left vector in the division operation. Not modified.
@param b The right vector in the division operation. Not modified.
@param c Where the results of the operation are stored. Modified.
"""
c.a1 = a.a1/b.a1;
c.a2 = a.a2/b.a2;
}
|
java
|
public static void elementDiv( DMatrix2 a , DMatrix2 b , DMatrix2 c ) {
c.a1 = a.a1/b.a1;
c.a2 = a.a2/b.a2;
}
|
[
"public",
"static",
"void",
"elementDiv",
"(",
"DMatrix2",
"a",
",",
"DMatrix2",
"b",
",",
"DMatrix2",
"c",
")",
"{",
"c",
".",
"a1",
"=",
"a",
".",
"a1",
"/",
"b",
".",
"a1",
";",
"c",
".",
"a2",
"=",
"a",
".",
"a2",
"/",
"b",
".",
"a2",
";",
"}"
] |
<p>Performs an element by element division operation:<br>
<br>
c<sub>i</sub> = a<sub>i</sub> / b<sub>i</sub> <br>
</p>
@param a The left vector in the division operation. Not modified.
@param b The right vector in the division operation. Not modified.
@param c Where the results of the operation are stored. Modified.
|
[
"<p",
">",
"Performs",
"an",
"element",
"by",
"element",
"division",
"operation",
":",
"<br",
">",
"<br",
">",
"c<sub",
">",
"i<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"i<",
"/",
"sub",
">",
"/",
"b<sub",
">",
"i<",
"/",
"sub",
">",
"<br",
">",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L961-L964
|
ralscha/wampspring
|
src/main/java/ch/rasc/wampspring/EventMessenger.java
|
EventMessenger.sendTo
|
public void sendTo(String topicURI, Object event, String eligibleWebSocketSessionId) {
"""
Send an {@link EventMessage} to one client that is subscribed to the given
topicURI. If the client with the given WebSocket session id is not subscribed to
the topicURI nothing happens.
@param topicURI the name of the topic
@param event the payload of the {@link EventMessage}
@param eligibleWebSocketSessionId only the client with the WebSocket session id
listed here will receive the EVENT message
"""
sendTo(topicURI, event, Collections.singleton(eligibleWebSocketSessionId));
}
|
java
|
public void sendTo(String topicURI, Object event, String eligibleWebSocketSessionId) {
sendTo(topicURI, event, Collections.singleton(eligibleWebSocketSessionId));
}
|
[
"public",
"void",
"sendTo",
"(",
"String",
"topicURI",
",",
"Object",
"event",
",",
"String",
"eligibleWebSocketSessionId",
")",
"{",
"sendTo",
"(",
"topicURI",
",",
"event",
",",
"Collections",
".",
"singleton",
"(",
"eligibleWebSocketSessionId",
")",
")",
";",
"}"
] |
Send an {@link EventMessage} to one client that is subscribed to the given
topicURI. If the client with the given WebSocket session id is not subscribed to
the topicURI nothing happens.
@param topicURI the name of the topic
@param event the payload of the {@link EventMessage}
@param eligibleWebSocketSessionId only the client with the WebSocket session id
listed here will receive the EVENT message
|
[
"Send",
"an",
"{",
"@link",
"EventMessage",
"}",
"to",
"one",
"client",
"that",
"is",
"subscribed",
"to",
"the",
"given",
"topicURI",
".",
"If",
"the",
"client",
"with",
"the",
"given",
"WebSocket",
"session",
"id",
"is",
"not",
"subscribed",
"to",
"the",
"topicURI",
"nothing",
"happens",
"."
] |
train
|
https://github.com/ralscha/wampspring/blob/7571bb6773b848c580b29890587eb35397bfe5b5/src/main/java/ch/rasc/wampspring/EventMessenger.java#L133-L135
|
wcm-io/wcm-io-wcm
|
ui/granite/src/main/java/io/wcm/wcm/ui/granite/util/GraniteUi.java
|
GraniteUi.getExistingResourceType
|
public static @Nullable String getExistingResourceType(@NotNull ResourceResolver resourceResolver, @NotNull String @NotNull... resourceTypes) {
"""
From the list of resource types get the first one that exists.
@param resourceResolver Resource resolver
@param resourceTypes ResourceTypes
@return Existing resource type
"""
for (String path : resourceTypes) {
if (resourceResolver.getResource(path) != null) {
return path;
}
}
return null;
}
|
java
|
public static @Nullable String getExistingResourceType(@NotNull ResourceResolver resourceResolver, @NotNull String @NotNull... resourceTypes) {
for (String path : resourceTypes) {
if (resourceResolver.getResource(path) != null) {
return path;
}
}
return null;
}
|
[
"public",
"static",
"@",
"Nullable",
"String",
"getExistingResourceType",
"(",
"@",
"NotNull",
"ResourceResolver",
"resourceResolver",
",",
"@",
"NotNull",
"String",
"@",
"NotNull",
".",
".",
".",
"resourceTypes",
")",
"{",
"for",
"(",
"String",
"path",
":",
"resourceTypes",
")",
"{",
"if",
"(",
"resourceResolver",
".",
"getResource",
"(",
"path",
")",
"!=",
"null",
")",
"{",
"return",
"path",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
From the list of resource types get the first one that exists.
@param resourceResolver Resource resolver
@param resourceTypes ResourceTypes
@return Existing resource type
|
[
"From",
"the",
"list",
"of",
"resource",
"types",
"get",
"the",
"first",
"one",
"that",
"exists",
"."
] |
train
|
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/ui/granite/src/main/java/io/wcm/wcm/ui/granite/util/GraniteUi.java#L99-L106
|
vipshop/vjtools
|
vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java
|
Formats.shortName
|
public static String shortName(String str, int length, int rightLength) {
"""
shortName("123456789", 8, 3) = "12...789"
shortName("123456789", 8, 2) = "123...89"
"""
if (str.length() > length) {
int leftIndex = length - 3 - rightLength;
str = str.substring(0, Math.max(0, leftIndex)) + "..."
+ str.substring(Math.max(0, str.length() - rightLength), str.length());
}
return str;
}
|
java
|
public static String shortName(String str, int length, int rightLength) {
if (str.length() > length) {
int leftIndex = length - 3 - rightLength;
str = str.substring(0, Math.max(0, leftIndex)) + "..."
+ str.substring(Math.max(0, str.length() - rightLength), str.length());
}
return str;
}
|
[
"public",
"static",
"String",
"shortName",
"(",
"String",
"str",
",",
"int",
"length",
",",
"int",
"rightLength",
")",
"{",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"length",
")",
"{",
"int",
"leftIndex",
"=",
"length",
"-",
"3",
"-",
"rightLength",
";",
"str",
"=",
"str",
".",
"substring",
"(",
"0",
",",
"Math",
".",
"max",
"(",
"0",
",",
"leftIndex",
")",
")",
"+",
"\"...\"",
"+",
"str",
".",
"substring",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"str",
".",
"length",
"(",
")",
"-",
"rightLength",
")",
",",
"str",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"str",
";",
"}"
] |
shortName("123456789", 8, 3) = "12...789"
shortName("123456789", 8, 2) = "123...89"
|
[
"shortName",
"(",
"123456789",
"8",
"3",
")",
"=",
"12",
"...",
"789"
] |
train
|
https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java#L201-L208
|
redbox-mint/redbox
|
plugins/transformer/vital-fedora2/src/main/java/com/googlecode/fascinator/redbox/VitalTransformer.java
|
VitalTransformer.createNewObject
|
private String createNewObject(FedoraClient fedora, String oid)
throws Exception {
"""
Create a new VITAL object and return the PID.
@param fedora An instantiated fedora client
@param oid The ID of the ReDBox object we will store here. For logging
@return String The new VITAL PID that was just created
"""
InputStream in = null;
byte[] template = null;
// Start by reading our FOXML template into memory
try {
if (foxmlTemplate != null) {
// We have a user provided template
in = new FileInputStream(foxmlTemplate);
template = IOUtils.toByteArray(in);
} else {
// Use the built in template
in = getClass().getResourceAsStream("/foxml_template.xml");
template = IOUtils.toByteArray(in);
}
} catch (IOException ex) {
throw new Exception(
"Error accessing FOXML Template, please check system configuration!");
} finally {
if (in != null) {
in.close();
}
}
String vitalPid = fedora.getAPIM().ingest(template,
Strings.FOXML_VERSION,
"ReDBox creating new object: '" + oid + "'");
log.info("New VITAL PID: '{}'", vitalPid);
return vitalPid;
}
|
java
|
private String createNewObject(FedoraClient fedora, String oid)
throws Exception {
InputStream in = null;
byte[] template = null;
// Start by reading our FOXML template into memory
try {
if (foxmlTemplate != null) {
// We have a user provided template
in = new FileInputStream(foxmlTemplate);
template = IOUtils.toByteArray(in);
} else {
// Use the built in template
in = getClass().getResourceAsStream("/foxml_template.xml");
template = IOUtils.toByteArray(in);
}
} catch (IOException ex) {
throw new Exception(
"Error accessing FOXML Template, please check system configuration!");
} finally {
if (in != null) {
in.close();
}
}
String vitalPid = fedora.getAPIM().ingest(template,
Strings.FOXML_VERSION,
"ReDBox creating new object: '" + oid + "'");
log.info("New VITAL PID: '{}'", vitalPid);
return vitalPid;
}
|
[
"private",
"String",
"createNewObject",
"(",
"FedoraClient",
"fedora",
",",
"String",
"oid",
")",
"throws",
"Exception",
"{",
"InputStream",
"in",
"=",
"null",
";",
"byte",
"[",
"]",
"template",
"=",
"null",
";",
"// Start by reading our FOXML template into memory",
"try",
"{",
"if",
"(",
"foxmlTemplate",
"!=",
"null",
")",
"{",
"// We have a user provided template",
"in",
"=",
"new",
"FileInputStream",
"(",
"foxmlTemplate",
")",
";",
"template",
"=",
"IOUtils",
".",
"toByteArray",
"(",
"in",
")",
";",
"}",
"else",
"{",
"// Use the built in template",
"in",
"=",
"getClass",
"(",
")",
".",
"getResourceAsStream",
"(",
"\"/foxml_template.xml\"",
")",
";",
"template",
"=",
"IOUtils",
".",
"toByteArray",
"(",
"in",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Error accessing FOXML Template, please check system configuration!\"",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"in",
"!=",
"null",
")",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"}",
"String",
"vitalPid",
"=",
"fedora",
".",
"getAPIM",
"(",
")",
".",
"ingest",
"(",
"template",
",",
"Strings",
".",
"FOXML_VERSION",
",",
"\"ReDBox creating new object: '\"",
"+",
"oid",
"+",
"\"'\"",
")",
";",
"log",
".",
"info",
"(",
"\"New VITAL PID: '{}'\"",
",",
"vitalPid",
")",
";",
"return",
"vitalPid",
";",
"}"
] |
Create a new VITAL object and return the PID.
@param fedora An instantiated fedora client
@param oid The ID of the ReDBox object we will store here. For logging
@return String The new VITAL PID that was just created
|
[
"Create",
"a",
"new",
"VITAL",
"object",
"and",
"return",
"the",
"PID",
"."
] |
train
|
https://github.com/redbox-mint/redbox/blob/1db230f218031b85c48c8603cbb04fce7ac6de0c/plugins/transformer/vital-fedora2/src/main/java/com/googlecode/fascinator/redbox/VitalTransformer.java#L667-L696
|
google/closure-compiler
|
src/com/google/javascript/jscomp/TypeCheck.java
|
TypeCheck.checkCallConventions
|
private void checkCallConventions(NodeTraversal t, Node n) {
"""
Validate class-defining calls.
Because JS has no 'native' syntax for defining classes, we need
to do this manually.
"""
SubclassRelationship relationship =
compiler.getCodingConvention().getClassesDefinedByCall(n);
TypedScope scope = t.getTypedScope();
if (relationship != null) {
ObjectType superClass =
TypeValidator.getInstanceOfCtor(
scope.lookupQualifiedName(QualifiedName.of(relationship.superclassName)));
ObjectType subClass =
TypeValidator.getInstanceOfCtor(
scope.lookupQualifiedName(QualifiedName.of(relationship.subclassName)));
if (relationship.type == SubclassType.INHERITS
&& superClass != null
&& !superClass.isEmptyType()
&& subClass != null
&& !subClass.isEmptyType()) {
validator.expectSuperType(n, superClass, subClass);
}
}
}
|
java
|
private void checkCallConventions(NodeTraversal t, Node n) {
SubclassRelationship relationship =
compiler.getCodingConvention().getClassesDefinedByCall(n);
TypedScope scope = t.getTypedScope();
if (relationship != null) {
ObjectType superClass =
TypeValidator.getInstanceOfCtor(
scope.lookupQualifiedName(QualifiedName.of(relationship.superclassName)));
ObjectType subClass =
TypeValidator.getInstanceOfCtor(
scope.lookupQualifiedName(QualifiedName.of(relationship.subclassName)));
if (relationship.type == SubclassType.INHERITS
&& superClass != null
&& !superClass.isEmptyType()
&& subClass != null
&& !subClass.isEmptyType()) {
validator.expectSuperType(n, superClass, subClass);
}
}
}
|
[
"private",
"void",
"checkCallConventions",
"(",
"NodeTraversal",
"t",
",",
"Node",
"n",
")",
"{",
"SubclassRelationship",
"relationship",
"=",
"compiler",
".",
"getCodingConvention",
"(",
")",
".",
"getClassesDefinedByCall",
"(",
"n",
")",
";",
"TypedScope",
"scope",
"=",
"t",
".",
"getTypedScope",
"(",
")",
";",
"if",
"(",
"relationship",
"!=",
"null",
")",
"{",
"ObjectType",
"superClass",
"=",
"TypeValidator",
".",
"getInstanceOfCtor",
"(",
"scope",
".",
"lookupQualifiedName",
"(",
"QualifiedName",
".",
"of",
"(",
"relationship",
".",
"superclassName",
")",
")",
")",
";",
"ObjectType",
"subClass",
"=",
"TypeValidator",
".",
"getInstanceOfCtor",
"(",
"scope",
".",
"lookupQualifiedName",
"(",
"QualifiedName",
".",
"of",
"(",
"relationship",
".",
"subclassName",
")",
")",
")",
";",
"if",
"(",
"relationship",
".",
"type",
"==",
"SubclassType",
".",
"INHERITS",
"&&",
"superClass",
"!=",
"null",
"&&",
"!",
"superClass",
".",
"isEmptyType",
"(",
")",
"&&",
"subClass",
"!=",
"null",
"&&",
"!",
"subClass",
".",
"isEmptyType",
"(",
")",
")",
"{",
"validator",
".",
"expectSuperType",
"(",
"n",
",",
"superClass",
",",
"subClass",
")",
";",
"}",
"}",
"}"
] |
Validate class-defining calls.
Because JS has no 'native' syntax for defining classes, we need
to do this manually.
|
[
"Validate",
"class",
"-",
"defining",
"calls",
".",
"Because",
"JS",
"has",
"no",
"native",
"syntax",
"for",
"defining",
"classes",
"we",
"need",
"to",
"do",
"this",
"manually",
"."
] |
train
|
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeCheck.java#L2506-L2525
|
jhunters/jprotobuf
|
jprotobuf-precompile-plugin/src/main/java/com/baidu/jprotobuf/mojo/PreCompileMojo.java
|
PreCompileMojo.addRelevantPluginDependenciesToClasspath
|
private void addRelevantPluginDependenciesToClasspath( List<URL> path )
throws MojoExecutionException {
"""
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and
ExecutableDependency into consideration.
@param path classpath of {@link java.net.URL} objects
@throws MojoExecutionException if a problem happens
"""
if ( hasCommandlineArgs() )
{
arguments = parseCommandlineArgs();
}
try
{
for ( Artifact classPathElement : this.determineRelevantPluginDependencies() )
{
getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId()
+ " to classpath" );
path.add( classPathElement.getFile().toURI().toURL() );
}
}
catch ( MalformedURLException e )
{
throw new MojoExecutionException( "Error during setting up classpath", e );
}
}
|
java
|
private void addRelevantPluginDependenciesToClasspath( List<URL> path )
throws MojoExecutionException
{
if ( hasCommandlineArgs() )
{
arguments = parseCommandlineArgs();
}
try
{
for ( Artifact classPathElement : this.determineRelevantPluginDependencies() )
{
getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId()
+ " to classpath" );
path.add( classPathElement.getFile().toURI().toURL() );
}
}
catch ( MalformedURLException e )
{
throw new MojoExecutionException( "Error during setting up classpath", e );
}
}
|
[
"private",
"void",
"addRelevantPluginDependenciesToClasspath",
"(",
"List",
"<",
"URL",
">",
"path",
")",
"throws",
"MojoExecutionException",
"{",
"if",
"(",
"hasCommandlineArgs",
"(",
")",
")",
"{",
"arguments",
"=",
"parseCommandlineArgs",
"(",
")",
";",
"}",
"try",
"{",
"for",
"(",
"Artifact",
"classPathElement",
":",
"this",
".",
"determineRelevantPluginDependencies",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Adding plugin dependency artifact: \"",
"+",
"classPathElement",
".",
"getArtifactId",
"(",
")",
"+",
"\" to classpath\"",
")",
";",
"path",
".",
"add",
"(",
"classPathElement",
".",
"getFile",
"(",
")",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Error during setting up classpath\"",
",",
"e",
")",
";",
"}",
"}"
] |
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and
ExecutableDependency into consideration.
@param path classpath of {@link java.net.URL} objects
@throws MojoExecutionException if a problem happens
|
[
"Add",
"any",
"relevant",
"project",
"dependencies",
"to",
"the",
"classpath",
".",
"Indirectly",
"takes",
"includePluginDependencies",
"and",
"ExecutableDependency",
"into",
"consideration",
"."
] |
train
|
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/jprotobuf-precompile-plugin/src/main/java/com/baidu/jprotobuf/mojo/PreCompileMojo.java#L608-L630
|
tumblr/jumblr
|
src/main/java/com/tumblr/jumblr/JumblrClient.java
|
JumblrClient.postReblog
|
public Post postReblog(String blogName, Long postId, String reblogKey) {
"""
Reblog a given post
@param blogName the name of the blog to post to
@param postId the id of the post
@param reblogKey the reblog_key of the post
@return The created reblog Post or null
"""
return this.postReblog(blogName, postId, reblogKey, null);
}
|
java
|
public Post postReblog(String blogName, Long postId, String reblogKey) {
return this.postReblog(blogName, postId, reblogKey, null);
}
|
[
"public",
"Post",
"postReblog",
"(",
"String",
"blogName",
",",
"Long",
"postId",
",",
"String",
"reblogKey",
")",
"{",
"return",
"this",
".",
"postReblog",
"(",
"blogName",
",",
"postId",
",",
"reblogKey",
",",
"null",
")",
";",
"}"
] |
Reblog a given post
@param blogName the name of the blog to post to
@param postId the id of the post
@param reblogKey the reblog_key of the post
@return The created reblog Post or null
|
[
"Reblog",
"a",
"given",
"post"
] |
train
|
https://github.com/tumblr/jumblr/blob/373629fd545defb016e227ea758f092507fbd624/src/main/java/com/tumblr/jumblr/JumblrClient.java#L360-L362
|
elki-project/elki
|
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java
|
BitsUtil.previousSetBit
|
public static int previousSetBit(long[] v, int start) {
"""
Find the previous set bit.
@param v Values to process
@param start Start position (inclusive)
@return Position of previous set bit, or -1.
"""
if(start < 0) {
return -1;
}
int wordindex = start >>> LONG_LOG2_SIZE;
if(wordindex >= v.length) {
return magnitude(v) - 1;
}
// Initial word
final int off = 63 - (start & LONG_LOG2_MASK);
long cur = v[wordindex] & (LONG_ALL_BITS >>> off);
for(;;) {
if(cur != 0) {
return wordindex * Long.SIZE + 63 - ((cur == LONG_ALL_BITS) ? 0 : Long.numberOfLeadingZeros(cur));
}
if(wordindex == 0) {
return -1;
}
cur = v[--wordindex];
}
}
|
java
|
public static int previousSetBit(long[] v, int start) {
if(start < 0) {
return -1;
}
int wordindex = start >>> LONG_LOG2_SIZE;
if(wordindex >= v.length) {
return magnitude(v) - 1;
}
// Initial word
final int off = 63 - (start & LONG_LOG2_MASK);
long cur = v[wordindex] & (LONG_ALL_BITS >>> off);
for(;;) {
if(cur != 0) {
return wordindex * Long.SIZE + 63 - ((cur == LONG_ALL_BITS) ? 0 : Long.numberOfLeadingZeros(cur));
}
if(wordindex == 0) {
return -1;
}
cur = v[--wordindex];
}
}
|
[
"public",
"static",
"int",
"previousSetBit",
"(",
"long",
"[",
"]",
"v",
",",
"int",
"start",
")",
"{",
"if",
"(",
"start",
"<",
"0",
")",
"{",
"return",
"-",
"1",
";",
"}",
"int",
"wordindex",
"=",
"start",
">>>",
"LONG_LOG2_SIZE",
";",
"if",
"(",
"wordindex",
">=",
"v",
".",
"length",
")",
"{",
"return",
"magnitude",
"(",
"v",
")",
"-",
"1",
";",
"}",
"// Initial word",
"final",
"int",
"off",
"=",
"63",
"-",
"(",
"start",
"&",
"LONG_LOG2_MASK",
")",
";",
"long",
"cur",
"=",
"v",
"[",
"wordindex",
"]",
"&",
"(",
"LONG_ALL_BITS",
">>>",
"off",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"if",
"(",
"cur",
"!=",
"0",
")",
"{",
"return",
"wordindex",
"*",
"Long",
".",
"SIZE",
"+",
"63",
"-",
"(",
"(",
"cur",
"==",
"LONG_ALL_BITS",
")",
"?",
"0",
":",
"Long",
".",
"numberOfLeadingZeros",
"(",
"cur",
")",
")",
";",
"}",
"if",
"(",
"wordindex",
"==",
"0",
")",
"{",
"return",
"-",
"1",
";",
"}",
"cur",
"=",
"v",
"[",
"--",
"wordindex",
"]",
";",
"}",
"}"
] |
Find the previous set bit.
@param v Values to process
@param start Start position (inclusive)
@return Position of previous set bit, or -1.
|
[
"Find",
"the",
"previous",
"set",
"bit",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java#L1233-L1253
|
phax/ph-web
|
ph-web/src/main/java/com/helger/web/fileupload/parse/FileItemHeaders.java
|
FileItemHeaders.addHeader
|
public void addHeader (@Nonnull final String sName, @Nullable final String sValue) {
"""
Method to add header values to this instance.
@param sName
name of this header
@param sValue
value of this header
"""
ValueEnforcer.notNull (sName, "HeaderName");
final String sNameLower = sName.toLowerCase (Locale.US);
m_aRWLock.writeLocked ( () -> {
ICommonsList <String> aHeaderValueList = m_aHeaderNameToValueListMap.get (sNameLower);
if (aHeaderValueList == null)
{
aHeaderValueList = new CommonsArrayList <> ();
m_aHeaderNameToValueListMap.put (sNameLower, aHeaderValueList);
m_aHeaderNameList.add (sNameLower);
}
aHeaderValueList.add (sValue);
});
}
|
java
|
public void addHeader (@Nonnull final String sName, @Nullable final String sValue)
{
ValueEnforcer.notNull (sName, "HeaderName");
final String sNameLower = sName.toLowerCase (Locale.US);
m_aRWLock.writeLocked ( () -> {
ICommonsList <String> aHeaderValueList = m_aHeaderNameToValueListMap.get (sNameLower);
if (aHeaderValueList == null)
{
aHeaderValueList = new CommonsArrayList <> ();
m_aHeaderNameToValueListMap.put (sNameLower, aHeaderValueList);
m_aHeaderNameList.add (sNameLower);
}
aHeaderValueList.add (sValue);
});
}
|
[
"public",
"void",
"addHeader",
"(",
"@",
"Nonnull",
"final",
"String",
"sName",
",",
"@",
"Nullable",
"final",
"String",
"sValue",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"sName",
",",
"\"HeaderName\"",
")",
";",
"final",
"String",
"sNameLower",
"=",
"sName",
".",
"toLowerCase",
"(",
"Locale",
".",
"US",
")",
";",
"m_aRWLock",
".",
"writeLocked",
"(",
"(",
")",
"->",
"{",
"ICommonsList",
"<",
"String",
">",
"aHeaderValueList",
"=",
"m_aHeaderNameToValueListMap",
".",
"get",
"(",
"sNameLower",
")",
";",
"if",
"(",
"aHeaderValueList",
"==",
"null",
")",
"{",
"aHeaderValueList",
"=",
"new",
"CommonsArrayList",
"<>",
"(",
")",
";",
"m_aHeaderNameToValueListMap",
".",
"put",
"(",
"sNameLower",
",",
"aHeaderValueList",
")",
";",
"m_aHeaderNameList",
".",
"add",
"(",
"sNameLower",
")",
";",
"}",
"aHeaderValueList",
".",
"add",
"(",
"sValue",
")",
";",
"}",
")",
";",
"}"
] |
Method to add header values to this instance.
@param sName
name of this header
@param sValue
value of this header
|
[
"Method",
"to",
"add",
"header",
"values",
"to",
"this",
"instance",
"."
] |
train
|
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/fileupload/parse/FileItemHeaders.java#L123-L139
|
JetBrains/xodus
|
vfs/src/main/java/jetbrains/exodus/vfs/VirtualFileSystem.java
|
VirtualFileSystem.createUniqueFile
|
public File createUniqueFile(@NotNull final Transaction txn, @NotNull final String pathPrefix) {
"""
Creates new {@linkplain File} with unique auto-generated path starting with specified {@code pathPrefix}.
@param txn {@linkplain Transaction} instance
@param pathPrefix prefix which the path of the {@linkplain File result} will start from
@return new {@linkplain File}
@see File
@see File#getPath()
"""
while (true) {
try {
return createFile(txn, pathPrefix + new Object().hashCode());
} catch (FileExistsException ignored) {
}
}
}
|
java
|
public File createUniqueFile(@NotNull final Transaction txn, @NotNull final String pathPrefix) {
while (true) {
try {
return createFile(txn, pathPrefix + new Object().hashCode());
} catch (FileExistsException ignored) {
}
}
}
|
[
"public",
"File",
"createUniqueFile",
"(",
"@",
"NotNull",
"final",
"Transaction",
"txn",
",",
"@",
"NotNull",
"final",
"String",
"pathPrefix",
")",
"{",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"return",
"createFile",
"(",
"txn",
",",
"pathPrefix",
"+",
"new",
"Object",
"(",
")",
".",
"hashCode",
"(",
")",
")",
";",
"}",
"catch",
"(",
"FileExistsException",
"ignored",
")",
"{",
"}",
"}",
"}"
] |
Creates new {@linkplain File} with unique auto-generated path starting with specified {@code pathPrefix}.
@param txn {@linkplain Transaction} instance
@param pathPrefix prefix which the path of the {@linkplain File result} will start from
@return new {@linkplain File}
@see File
@see File#getPath()
|
[
"Creates",
"new",
"{",
"@linkplain",
"File",
"}",
"with",
"unique",
"auto",
"-",
"generated",
"path",
"starting",
"with",
"specified",
"{",
"@code",
"pathPrefix",
"}",
"."
] |
train
|
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/vfs/src/main/java/jetbrains/exodus/vfs/VirtualFileSystem.java#L245-L252
|
Jasig/uPortal
|
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/GroupMemberImpl.java
|
GroupMemberImpl.getParentGroups
|
@Override
public Set<IEntityGroup> getParentGroups() throws GroupsException {
"""
Returns an <code>Iterator</code> over this <code>IGroupMember's</code> parent groups.
Synchronize the collection of keys with adds and removes.
@return Iterator
"""
final EntityIdentifier cacheKey = getUnderlyingEntityIdentifier();
Element element = parentGroupsCache.get(cacheKey);
if (element == null) {
final Set<IEntityGroup> groups = buildParentGroupsSet();
element = new Element(cacheKey, groups);
parentGroupsCache.put(element);
}
@SuppressWarnings("unchecked")
final Set<IEntityGroup> rslt = (Set<IEntityGroup>) element.getObjectValue();
return rslt;
}
|
java
|
@Override
public Set<IEntityGroup> getParentGroups() throws GroupsException {
final EntityIdentifier cacheKey = getUnderlyingEntityIdentifier();
Element element = parentGroupsCache.get(cacheKey);
if (element == null) {
final Set<IEntityGroup> groups = buildParentGroupsSet();
element = new Element(cacheKey, groups);
parentGroupsCache.put(element);
}
@SuppressWarnings("unchecked")
final Set<IEntityGroup> rslt = (Set<IEntityGroup>) element.getObjectValue();
return rslt;
}
|
[
"@",
"Override",
"public",
"Set",
"<",
"IEntityGroup",
">",
"getParentGroups",
"(",
")",
"throws",
"GroupsException",
"{",
"final",
"EntityIdentifier",
"cacheKey",
"=",
"getUnderlyingEntityIdentifier",
"(",
")",
";",
"Element",
"element",
"=",
"parentGroupsCache",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"element",
"==",
"null",
")",
"{",
"final",
"Set",
"<",
"IEntityGroup",
">",
"groups",
"=",
"buildParentGroupsSet",
"(",
")",
";",
"element",
"=",
"new",
"Element",
"(",
"cacheKey",
",",
"groups",
")",
";",
"parentGroupsCache",
".",
"put",
"(",
"element",
")",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"final",
"Set",
"<",
"IEntityGroup",
">",
"rslt",
"=",
"(",
"Set",
"<",
"IEntityGroup",
">",
")",
"element",
".",
"getObjectValue",
"(",
")",
";",
"return",
"rslt",
";",
"}"
] |
Returns an <code>Iterator</code> over this <code>IGroupMember's</code> parent groups.
Synchronize the collection of keys with adds and removes.
@return Iterator
|
[
"Returns",
"an",
"<code",
">",
"Iterator<",
"/",
"code",
">",
"over",
"this",
"<code",
">",
"IGroupMember",
"s<",
"/",
"code",
">",
"parent",
"groups",
".",
"Synchronize",
"the",
"collection",
"of",
"keys",
"with",
"adds",
"and",
"removes",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/GroupMemberImpl.java#L83-L98
|
js-lib-com/net-client
|
src/main/java/js/net/client/HttpRmiTransaction.java
|
HttpRmiTransaction.setHeader
|
public void setHeader(String name, String value) {
"""
Set HTTP header value or remove named header if <code>value</code> is null.
@param name HTTP header name,
@param value HTTP header value, possible null.
@since 1.9
"""
if (headers == null) {
headers = new HashMap<String, String>();
}
if (value != null) {
headers.put(name, value);
} else {
headers.remove(name);
}
}
|
java
|
public void setHeader(String name, String value) {
if (headers == null) {
headers = new HashMap<String, String>();
}
if (value != null) {
headers.put(name, value);
} else {
headers.remove(name);
}
}
|
[
"public",
"void",
"setHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"headers",
"==",
"null",
")",
"{",
"headers",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"}",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"headers",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}",
"else",
"{",
"headers",
".",
"remove",
"(",
"name",
")",
";",
"}",
"}"
] |
Set HTTP header value or remove named header if <code>value</code> is null.
@param name HTTP header name,
@param value HTTP header value, possible null.
@since 1.9
|
[
"Set",
"HTTP",
"header",
"value",
"or",
"remove",
"named",
"header",
"if",
"<code",
">",
"value<",
"/",
"code",
">",
"is",
"null",
"."
] |
train
|
https://github.com/js-lib-com/net-client/blob/0489f85d8baa1be1ff115aa79929e0cf05d4c72d/src/main/java/js/net/client/HttpRmiTransaction.java#L314-L323
|
js-lib-com/template.xhtml
|
src/main/java/js/template/xhtml/Content.java
|
Content.isEmpty
|
boolean isEmpty(Object scope, String propertyPath) throws TemplateException {
"""
Test if value is empty. Delegates {@link #getValue(Object, String)} and returns true if found value fulfill one of
the next conditions:
<ul>
<li>null
<li>boolean false
<li>number equals with 0
<li>empty string
<li>array of length 0
<li>collection of size 0
<li>map of size 0
<li>undefined character
</ul>
Note that undefined value, that is, field or method getter not found, is not considered empty value.
@param scope scope object,
@param propertyPath property path.
@return true if value is empty.
@throws TemplateException if requested value is undefined.
"""
return Types.asBoolean(getValue(scope, propertyPath)) == false;
}
|
java
|
boolean isEmpty(Object scope, String propertyPath) throws TemplateException
{
return Types.asBoolean(getValue(scope, propertyPath)) == false;
}
|
[
"boolean",
"isEmpty",
"(",
"Object",
"scope",
",",
"String",
"propertyPath",
")",
"throws",
"TemplateException",
"{",
"return",
"Types",
".",
"asBoolean",
"(",
"getValue",
"(",
"scope",
",",
"propertyPath",
")",
")",
"==",
"false",
";",
"}"
] |
Test if value is empty. Delegates {@link #getValue(Object, String)} and returns true if found value fulfill one of
the next conditions:
<ul>
<li>null
<li>boolean false
<li>number equals with 0
<li>empty string
<li>array of length 0
<li>collection of size 0
<li>map of size 0
<li>undefined character
</ul>
Note that undefined value, that is, field or method getter not found, is not considered empty value.
@param scope scope object,
@param propertyPath property path.
@return true if value is empty.
@throws TemplateException if requested value is undefined.
|
[
"Test",
"if",
"value",
"is",
"empty",
".",
"Delegates",
"{",
"@link",
"#getValue",
"(",
"Object",
"String",
")",
"}",
"and",
"returns",
"true",
"if",
"found",
"value",
"fulfill",
"one",
"of",
"the",
"next",
"conditions",
":",
"<ul",
">",
"<li",
">",
"null",
"<li",
">",
"boolean",
"false",
"<li",
">",
"number",
"equals",
"with",
"0",
"<li",
">",
"empty",
"string",
"<li",
">",
"array",
"of",
"length",
"0",
"<li",
">",
"collection",
"of",
"size",
"0",
"<li",
">",
"map",
"of",
"size",
"0",
"<li",
">",
"undefined",
"character",
"<",
"/",
"ul",
">",
"Note",
"that",
"undefined",
"value",
"that",
"is",
"field",
"or",
"method",
"getter",
"not",
"found",
"is",
"not",
"considered",
"empty",
"value",
"."
] |
train
|
https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/Content.java#L215-L218
|
apache/flink
|
flink-core/src/main/java/org/apache/flink/types/Record.java
|
Record.getField
|
@SuppressWarnings("unchecked")
public <T extends Value> T getField(int fieldNum, T target) {
"""
Gets the field at the given position. The method tries to deserialize the fields into the given target value.
If the fields has been changed since the last (de)serialization, or is null, them the target value is left
unchanged and the changed value (or null) is returned.
<p>
In all cases, the returned value contains the correct data (or is correctly null).
@param fieldNum The position of the field.
@param target The value to deserialize the field into.
@return The value with the contents of the requested field, or null, if the field is null.
"""
// range check
if (fieldNum < 0 || fieldNum >= this.numFields) {
throw new IndexOutOfBoundsException();
}
if (target == null) {
throw new NullPointerException("The target object may not be null");
}
// get offset and check for null
final int offset = this.offsets[fieldNum];
if (offset == NULL_INDICATOR_OFFSET) {
return null;
}
else if (offset == MODIFIED_INDICATOR_OFFSET) {
// value that has been set is new or modified
// bring the binary in sync so that the deserialization gives the correct result
return (T) this.writeFields[fieldNum];
}
final int limit = offset + this.lengths[fieldNum];
deserialize(target, offset, limit, fieldNum);
return target;
}
|
java
|
@SuppressWarnings("unchecked")
public <T extends Value> T getField(int fieldNum, T target) {
// range check
if (fieldNum < 0 || fieldNum >= this.numFields) {
throw new IndexOutOfBoundsException();
}
if (target == null) {
throw new NullPointerException("The target object may not be null");
}
// get offset and check for null
final int offset = this.offsets[fieldNum];
if (offset == NULL_INDICATOR_OFFSET) {
return null;
}
else if (offset == MODIFIED_INDICATOR_OFFSET) {
// value that has been set is new or modified
// bring the binary in sync so that the deserialization gives the correct result
return (T) this.writeFields[fieldNum];
}
final int limit = offset + this.lengths[fieldNum];
deserialize(target, offset, limit, fieldNum);
return target;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"Value",
">",
"T",
"getField",
"(",
"int",
"fieldNum",
",",
"T",
"target",
")",
"{",
"// range check",
"if",
"(",
"fieldNum",
"<",
"0",
"||",
"fieldNum",
">=",
"this",
".",
"numFields",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"The target object may not be null\"",
")",
";",
"}",
"// get offset and check for null",
"final",
"int",
"offset",
"=",
"this",
".",
"offsets",
"[",
"fieldNum",
"]",
";",
"if",
"(",
"offset",
"==",
"NULL_INDICATOR_OFFSET",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"offset",
"==",
"MODIFIED_INDICATOR_OFFSET",
")",
"{",
"// value that has been set is new or modified",
"// bring the binary in sync so that the deserialization gives the correct result",
"return",
"(",
"T",
")",
"this",
".",
"writeFields",
"[",
"fieldNum",
"]",
";",
"}",
"final",
"int",
"limit",
"=",
"offset",
"+",
"this",
".",
"lengths",
"[",
"fieldNum",
"]",
";",
"deserialize",
"(",
"target",
",",
"offset",
",",
"limit",
",",
"fieldNum",
")",
";",
"return",
"target",
";",
"}"
] |
Gets the field at the given position. The method tries to deserialize the fields into the given target value.
If the fields has been changed since the last (de)serialization, or is null, them the target value is left
unchanged and the changed value (or null) is returned.
<p>
In all cases, the returned value contains the correct data (or is correctly null).
@param fieldNum The position of the field.
@param target The value to deserialize the field into.
@return The value with the contents of the requested field, or null, if the field is null.
|
[
"Gets",
"the",
"field",
"at",
"the",
"given",
"position",
".",
"The",
"method",
"tries",
"to",
"deserialize",
"the",
"fields",
"into",
"the",
"given",
"target",
"value",
".",
"If",
"the",
"fields",
"has",
"been",
"changed",
"since",
"the",
"last",
"(",
"de",
")",
"serialization",
"or",
"is",
"null",
"them",
"the",
"target",
"value",
"is",
"left",
"unchanged",
"and",
"the",
"changed",
"value",
"(",
"or",
"null",
")",
"is",
"returned",
".",
"<p",
">",
"In",
"all",
"cases",
"the",
"returned",
"value",
"contains",
"the",
"correct",
"data",
"(",
"or",
"is",
"correctly",
"null",
")",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/Record.java#L269-L293
|
unbescape/unbescape
|
src/main/java/org/unbescape/xml/XmlEscape.java
|
XmlEscape.unescapeXml
|
public static void unescapeXml(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
"""
<p>
Perform an XML <strong>unescape</strong> operation on a <tt>char[]</tt> input.
</p>
<p>
No additional configuration arguments are required. Unescape operations
will always perform <em>complete</em> XML 1.0/1.1 unescape of CERs, decimal
and hexadecimal references.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the unescape operation should start.
@param len the number of characters in <tt>text</tt> that should be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
"""
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
final int textLen = (text == null? 0 : text.length);
if (offset < 0 || offset > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
if (len < 0 || (offset + len) > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
// The chosen symbols (1.0 or 1.1) don't really matter, as both contain the same CERs
XmlEscapeUtil.unescape(text, offset, len, writer, XmlEscapeSymbols.XML11_SYMBOLS);
}
|
java
|
public static void unescapeXml(final char[] text, final int offset, final int len, final Writer writer)
throws IOException{
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
final int textLen = (text == null? 0 : text.length);
if (offset < 0 || offset > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
if (len < 0 || (offset + len) > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
// The chosen symbols (1.0 or 1.1) don't really matter, as both contain the same CERs
XmlEscapeUtil.unescape(text, offset, len, writer, XmlEscapeSymbols.XML11_SYMBOLS);
}
|
[
"public",
"static",
"void",
"unescapeXml",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' cannot be null\"",
")",
";",
"}",
"final",
"int",
"textLen",
"=",
"(",
"text",
"==",
"null",
"?",
"0",
":",
"text",
".",
"length",
")",
";",
"if",
"(",
"offset",
"<",
"0",
"||",
"offset",
">",
"textLen",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid (offset, len). offset=\"",
"+",
"offset",
"+",
"\", len=\"",
"+",
"len",
"+",
"\", text.length=\"",
"+",
"textLen",
")",
";",
"}",
"if",
"(",
"len",
"<",
"0",
"||",
"(",
"offset",
"+",
"len",
")",
">",
"textLen",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid (offset, len). offset=\"",
"+",
"offset",
"+",
"\", len=\"",
"+",
"len",
"+",
"\", text.length=\"",
"+",
"textLen",
")",
";",
"}",
"// The chosen symbols (1.0 or 1.1) don't really matter, as both contain the same CERs",
"XmlEscapeUtil",
".",
"unescape",
"(",
"text",
",",
"offset",
",",
"len",
",",
"writer",
",",
"XmlEscapeSymbols",
".",
"XML11_SYMBOLS",
")",
";",
"}"
] |
<p>
Perform an XML <strong>unescape</strong> operation on a <tt>char[]</tt> input.
</p>
<p>
No additional configuration arguments are required. Unescape operations
will always perform <em>complete</em> XML 1.0/1.1 unescape of CERs, decimal
and hexadecimal references.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the unescape operation should start.
@param len the number of characters in <tt>text</tt> that should be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
|
[
"<p",
">",
"Perform",
"an",
"XML",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"No",
"additional",
"configuration",
"arguments",
"are",
"required",
".",
"Unescape",
"operations",
"will",
"always",
"perform",
"<em",
">",
"complete<",
"/",
"em",
">",
"XML",
"1",
".",
"0",
"/",
"1",
".",
"1",
"unescape",
"of",
"CERs",
"decimal",
"and",
"hexadecimal",
"references",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"is",
"<strong",
">",
"thread",
"-",
"safe<",
"/",
"strong",
">",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L2423-L2445
|
lessthanoptimal/BoofCV
|
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/RefinePolyLineCorner.java
|
RefinePolyLineCorner.createLine
|
private void createLine( int index0 , int index1 , List<Point2D_I32> contour , LineGeneral2D_F64 line ) {
"""
Given segment information create a line in general notation which has been normalized
"""
if( index1 < 0 )
System.out.println("SHIT");
Point2D_I32 p0 = contour.get(index0);
Point2D_I32 p1 = contour.get(index1);
// System.out.println("createLine "+p0+" "+p1);
work.a.set(p0.x, p0.y);
work.b.set(p1.x, p1.y);
UtilLine2D_F64.convert(work,line);
// ensure A*A + B*B = 1
line.normalize();
}
|
java
|
private void createLine( int index0 , int index1 , List<Point2D_I32> contour , LineGeneral2D_F64 line )
{
if( index1 < 0 )
System.out.println("SHIT");
Point2D_I32 p0 = contour.get(index0);
Point2D_I32 p1 = contour.get(index1);
// System.out.println("createLine "+p0+" "+p1);
work.a.set(p0.x, p0.y);
work.b.set(p1.x, p1.y);
UtilLine2D_F64.convert(work,line);
// ensure A*A + B*B = 1
line.normalize();
}
|
[
"private",
"void",
"createLine",
"(",
"int",
"index0",
",",
"int",
"index1",
",",
"List",
"<",
"Point2D_I32",
">",
"contour",
",",
"LineGeneral2D_F64",
"line",
")",
"{",
"if",
"(",
"index1",
"<",
"0",
")",
"System",
".",
"out",
".",
"println",
"(",
"\"SHIT\"",
")",
";",
"Point2D_I32",
"p0",
"=",
"contour",
".",
"get",
"(",
"index0",
")",
";",
"Point2D_I32",
"p1",
"=",
"contour",
".",
"get",
"(",
"index1",
")",
";",
"//\t\tSystem.out.println(\"createLine \"+p0+\" \"+p1);",
"work",
".",
"a",
".",
"set",
"(",
"p0",
".",
"x",
",",
"p0",
".",
"y",
")",
";",
"work",
".",
"b",
".",
"set",
"(",
"p1",
".",
"x",
",",
"p1",
".",
"y",
")",
";",
"UtilLine2D_F64",
".",
"convert",
"(",
"work",
",",
"line",
")",
";",
"// ensure A*A + B*B = 1",
"line",
".",
"normalize",
"(",
")",
";",
"}"
] |
Given segment information create a line in general notation which has been normalized
|
[
"Given",
"segment",
"information",
"create",
"a",
"line",
"in",
"general",
"notation",
"which",
"has",
"been",
"normalized"
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/RefinePolyLineCorner.java#L217-L233
|
j-a-w-r/jawr-main-repo
|
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/handler/ResourceBundlesHandlerImpl.java
|
ResourceBundlesHandlerImpl.joinAndPostProcessBundle
|
private void joinAndPostProcessBundle(CompositeResourceBundle composite, BundleProcessingStatus status) {
"""
Joins and post process the variant composite bundle
@param composite
the composite bundle
@param status
the status
@param compositeBundleVariants
the variants
"""
JoinableResourceBundleContent store;
stopProcessIfNeeded();
List<Map<String, String>> allVariants = VariantUtils.getAllVariants(composite.getVariants());
// Add the default bundle variant (the non variant one)
allVariants.add(null);
// Process all variants
for (Map<String, String> variants : allVariants) {
status.setBundleVariants(variants);
store = new JoinableResourceBundleContent();
for (JoinableResourceBundle childbundle : composite.getChildBundles()) {
if (!childbundle.getInclusionPattern().isIncludeOnlyOnDebug()) {
JoinableResourceBundleContent childContent = joinAndPostprocessBundle(childbundle, variants,
status);
// Do unitary postprocessing.
status.setProcessingType(BundleProcessingStatus.FILE_PROCESSING_TYPE);
StringBuffer content = executeUnitaryPostProcessing(composite, status, childContent.getContent(),
this.unitaryCompositePostProcessor);
childContent.setContent(content);
store.append(childContent);
}
}
// Post process composite bundle as needed
store = postProcessJoinedCompositeBundle(composite, store.getContent(), status);
String variantKey = VariantUtils.getVariantKey(variants);
String name = VariantUtils.getVariantBundleName(composite.getId(), variantKey, false);
storeBundle(name, store);
initBundleDataHashcode(composite, store, variantKey);
}
}
|
java
|
private void joinAndPostProcessBundle(CompositeResourceBundle composite, BundleProcessingStatus status) {
JoinableResourceBundleContent store;
stopProcessIfNeeded();
List<Map<String, String>> allVariants = VariantUtils.getAllVariants(composite.getVariants());
// Add the default bundle variant (the non variant one)
allVariants.add(null);
// Process all variants
for (Map<String, String> variants : allVariants) {
status.setBundleVariants(variants);
store = new JoinableResourceBundleContent();
for (JoinableResourceBundle childbundle : composite.getChildBundles()) {
if (!childbundle.getInclusionPattern().isIncludeOnlyOnDebug()) {
JoinableResourceBundleContent childContent = joinAndPostprocessBundle(childbundle, variants,
status);
// Do unitary postprocessing.
status.setProcessingType(BundleProcessingStatus.FILE_PROCESSING_TYPE);
StringBuffer content = executeUnitaryPostProcessing(composite, status, childContent.getContent(),
this.unitaryCompositePostProcessor);
childContent.setContent(content);
store.append(childContent);
}
}
// Post process composite bundle as needed
store = postProcessJoinedCompositeBundle(composite, store.getContent(), status);
String variantKey = VariantUtils.getVariantKey(variants);
String name = VariantUtils.getVariantBundleName(composite.getId(), variantKey, false);
storeBundle(name, store);
initBundleDataHashcode(composite, store, variantKey);
}
}
|
[
"private",
"void",
"joinAndPostProcessBundle",
"(",
"CompositeResourceBundle",
"composite",
",",
"BundleProcessingStatus",
"status",
")",
"{",
"JoinableResourceBundleContent",
"store",
";",
"stopProcessIfNeeded",
"(",
")",
";",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"allVariants",
"=",
"VariantUtils",
".",
"getAllVariants",
"(",
"composite",
".",
"getVariants",
"(",
")",
")",
";",
"// Add the default bundle variant (the non variant one)",
"allVariants",
".",
"add",
"(",
"null",
")",
";",
"// Process all variants",
"for",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"variants",
":",
"allVariants",
")",
"{",
"status",
".",
"setBundleVariants",
"(",
"variants",
")",
";",
"store",
"=",
"new",
"JoinableResourceBundleContent",
"(",
")",
";",
"for",
"(",
"JoinableResourceBundle",
"childbundle",
":",
"composite",
".",
"getChildBundles",
"(",
")",
")",
"{",
"if",
"(",
"!",
"childbundle",
".",
"getInclusionPattern",
"(",
")",
".",
"isIncludeOnlyOnDebug",
"(",
")",
")",
"{",
"JoinableResourceBundleContent",
"childContent",
"=",
"joinAndPostprocessBundle",
"(",
"childbundle",
",",
"variants",
",",
"status",
")",
";",
"// Do unitary postprocessing.",
"status",
".",
"setProcessingType",
"(",
"BundleProcessingStatus",
".",
"FILE_PROCESSING_TYPE",
")",
";",
"StringBuffer",
"content",
"=",
"executeUnitaryPostProcessing",
"(",
"composite",
",",
"status",
",",
"childContent",
".",
"getContent",
"(",
")",
",",
"this",
".",
"unitaryCompositePostProcessor",
")",
";",
"childContent",
".",
"setContent",
"(",
"content",
")",
";",
"store",
".",
"append",
"(",
"childContent",
")",
";",
"}",
"}",
"// Post process composite bundle as needed",
"store",
"=",
"postProcessJoinedCompositeBundle",
"(",
"composite",
",",
"store",
".",
"getContent",
"(",
")",
",",
"status",
")",
";",
"String",
"variantKey",
"=",
"VariantUtils",
".",
"getVariantKey",
"(",
"variants",
")",
";",
"String",
"name",
"=",
"VariantUtils",
".",
"getVariantBundleName",
"(",
"composite",
".",
"getId",
"(",
")",
",",
"variantKey",
",",
"false",
")",
";",
"storeBundle",
"(",
"name",
",",
"store",
")",
";",
"initBundleDataHashcode",
"(",
"composite",
",",
"store",
",",
"variantKey",
")",
";",
"}",
"}"
] |
Joins and post process the variant composite bundle
@param composite
the composite bundle
@param status
the status
@param compositeBundleVariants
the variants
|
[
"Joins",
"and",
"post",
"process",
"the",
"variant",
"composite",
"bundle"
] |
train
|
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/handler/ResourceBundlesHandlerImpl.java#L1087-L1120
|
alkacon/opencms-core
|
src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java
|
CmsSitemapController.getPath
|
protected String getPath(CmsClientSitemapEntry entry, String newUrlName) {
"""
Helper method for getting the full path of a sitemap entry whose URL name is being edited.<p>
@param entry the sitemap entry
@param newUrlName the new url name of the sitemap entry
@return the new full site path of the sitemap entry
"""
if (newUrlName.equals("")) {
return entry.getSitePath();
}
return CmsResource.getParentFolder(entry.getSitePath()) + newUrlName + "/";
}
|
java
|
protected String getPath(CmsClientSitemapEntry entry, String newUrlName) {
if (newUrlName.equals("")) {
return entry.getSitePath();
}
return CmsResource.getParentFolder(entry.getSitePath()) + newUrlName + "/";
}
|
[
"protected",
"String",
"getPath",
"(",
"CmsClientSitemapEntry",
"entry",
",",
"String",
"newUrlName",
")",
"{",
"if",
"(",
"newUrlName",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"return",
"entry",
".",
"getSitePath",
"(",
")",
";",
"}",
"return",
"CmsResource",
".",
"getParentFolder",
"(",
"entry",
".",
"getSitePath",
"(",
")",
")",
"+",
"newUrlName",
"+",
"\"/\"",
";",
"}"
] |
Helper method for getting the full path of a sitemap entry whose URL name is being edited.<p>
@param entry the sitemap entry
@param newUrlName the new url name of the sitemap entry
@return the new full site path of the sitemap entry
|
[
"Helper",
"method",
"for",
"getting",
"the",
"full",
"path",
"of",
"a",
"sitemap",
"entry",
"whose",
"URL",
"name",
"is",
"being",
"edited",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L2228-L2234
|
elki-project/elki
|
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java
|
CASH.determineMinMaxDistance
|
private double[] determineMinMaxDistance(Relation<ParameterizationFunction> relation, int dimensionality) {
"""
Determines the minimum and maximum function value of all parameterization
functions stored in the specified database.
@param relation the database containing the parameterization functions.
@param dimensionality the dimensionality of the database
@return an array containing the minimum and maximum function value of all
parameterization functions stored in the specified database
"""
double[] min = new double[dimensionality - 1];
double[] max = new double[dimensionality - 1];
Arrays.fill(max, Math.PI);
HyperBoundingBox box = new HyperBoundingBox(min, max);
double d_min = Double.POSITIVE_INFINITY, d_max = Double.NEGATIVE_INFINITY;
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
ParameterizationFunction f = relation.get(iditer);
HyperBoundingBox minMax = f.determineAlphaMinMax(box);
double f_min = f.function(SpatialUtil.getMin(minMax));
double f_max = f.function(SpatialUtil.getMax(minMax));
d_min = Math.min(d_min, f_min);
d_max = Math.max(d_max, f_max);
}
return new double[] { d_min, d_max };
}
|
java
|
private double[] determineMinMaxDistance(Relation<ParameterizationFunction> relation, int dimensionality) {
double[] min = new double[dimensionality - 1];
double[] max = new double[dimensionality - 1];
Arrays.fill(max, Math.PI);
HyperBoundingBox box = new HyperBoundingBox(min, max);
double d_min = Double.POSITIVE_INFINITY, d_max = Double.NEGATIVE_INFINITY;
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
ParameterizationFunction f = relation.get(iditer);
HyperBoundingBox minMax = f.determineAlphaMinMax(box);
double f_min = f.function(SpatialUtil.getMin(minMax));
double f_max = f.function(SpatialUtil.getMax(minMax));
d_min = Math.min(d_min, f_min);
d_max = Math.max(d_max, f_max);
}
return new double[] { d_min, d_max };
}
|
[
"private",
"double",
"[",
"]",
"determineMinMaxDistance",
"(",
"Relation",
"<",
"ParameterizationFunction",
">",
"relation",
",",
"int",
"dimensionality",
")",
"{",
"double",
"[",
"]",
"min",
"=",
"new",
"double",
"[",
"dimensionality",
"-",
"1",
"]",
";",
"double",
"[",
"]",
"max",
"=",
"new",
"double",
"[",
"dimensionality",
"-",
"1",
"]",
";",
"Arrays",
".",
"fill",
"(",
"max",
",",
"Math",
".",
"PI",
")",
";",
"HyperBoundingBox",
"box",
"=",
"new",
"HyperBoundingBox",
"(",
"min",
",",
"max",
")",
";",
"double",
"d_min",
"=",
"Double",
".",
"POSITIVE_INFINITY",
",",
"d_max",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"for",
"(",
"DBIDIter",
"iditer",
"=",
"relation",
".",
"iterDBIDs",
"(",
")",
";",
"iditer",
".",
"valid",
"(",
")",
";",
"iditer",
".",
"advance",
"(",
")",
")",
"{",
"ParameterizationFunction",
"f",
"=",
"relation",
".",
"get",
"(",
"iditer",
")",
";",
"HyperBoundingBox",
"minMax",
"=",
"f",
".",
"determineAlphaMinMax",
"(",
"box",
")",
";",
"double",
"f_min",
"=",
"f",
".",
"function",
"(",
"SpatialUtil",
".",
"getMin",
"(",
"minMax",
")",
")",
";",
"double",
"f_max",
"=",
"f",
".",
"function",
"(",
"SpatialUtil",
".",
"getMax",
"(",
"minMax",
")",
")",
";",
"d_min",
"=",
"Math",
".",
"min",
"(",
"d_min",
",",
"f_min",
")",
";",
"d_max",
"=",
"Math",
".",
"max",
"(",
"d_max",
",",
"f_max",
")",
";",
"}",
"return",
"new",
"double",
"[",
"]",
"{",
"d_min",
",",
"d_max",
"}",
";",
"}"
] |
Determines the minimum and maximum function value of all parameterization
functions stored in the specified database.
@param relation the database containing the parameterization functions.
@param dimensionality the dimensionality of the database
@return an array containing the minimum and maximum function value of all
parameterization functions stored in the specified database
|
[
"Determines",
"the",
"minimum",
"and",
"maximum",
"function",
"value",
"of",
"all",
"parameterization",
"functions",
"stored",
"in",
"the",
"specified",
"database",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java#L595-L612
|
baasbox/Android-SDK
|
library/src/main/java/com/baasbox/android/BaasUser.java
|
BaasUser.fetchAll
|
public static RequestToken fetchAll(BaasQuery.Criteria filter, int flags, BaasHandler<List<BaasUser>> handler) {
"""
Asynchronously fetches the list of users from the server.
@param flags {@link RequestOptions}
@param handler an handler to be invoked upon completion of the request
@return a {@link com.baasbox.android.RequestToken} to manage the request
"""
BaasBox box = BaasBox.getDefaultChecked();
FetchUsers users = new FetchUsers(box, "users", null, filter, flags, handler);
return box.submitAsync(users);
}
|
java
|
public static RequestToken fetchAll(BaasQuery.Criteria filter, int flags, BaasHandler<List<BaasUser>> handler) {
BaasBox box = BaasBox.getDefaultChecked();
FetchUsers users = new FetchUsers(box, "users", null, filter, flags, handler);
return box.submitAsync(users);
}
|
[
"public",
"static",
"RequestToken",
"fetchAll",
"(",
"BaasQuery",
".",
"Criteria",
"filter",
",",
"int",
"flags",
",",
"BaasHandler",
"<",
"List",
"<",
"BaasUser",
">",
">",
"handler",
")",
"{",
"BaasBox",
"box",
"=",
"BaasBox",
".",
"getDefaultChecked",
"(",
")",
";",
"FetchUsers",
"users",
"=",
"new",
"FetchUsers",
"(",
"box",
",",
"\"users\"",
",",
"null",
",",
"filter",
",",
"flags",
",",
"handler",
")",
";",
"return",
"box",
".",
"submitAsync",
"(",
"users",
")",
";",
"}"
] |
Asynchronously fetches the list of users from the server.
@param flags {@link RequestOptions}
@param handler an handler to be invoked upon completion of the request
@return a {@link com.baasbox.android.RequestToken} to manage the request
|
[
"Asynchronously",
"fetches",
"the",
"list",
"of",
"users",
"from",
"the",
"server",
"."
] |
train
|
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L472-L476
|
centic9/commons-dost
|
src/main/java/org/dstadler/commons/svn/SVNCommands.java
|
SVNCommands.branchExists
|
public static boolean branchExists(String branch, String baseUrl) {
"""
Check if the given branch already exists
@param branch The name of the branch including the path to the branch, e.g. branches/4.2.x
@param baseUrl The SVN url to connect to
@return true if the branch already exists, false otherwise.
"""
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument(CMD_LOG);
cmdLine.addArgument(OPT_XML);
addDefaultArguments(cmdLine, null, null);
cmdLine.addArgument("-r");
cmdLine.addArgument("HEAD:HEAD");
cmdLine.addArgument(baseUrl + branch);
try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
return true;
} catch (IOException e) {
log.log(Level.FINE, "Branch " + branch + " not found or other error", e);
return false;
}
}
|
java
|
public static boolean branchExists(String branch, String baseUrl) {
CommandLine cmdLine = new CommandLine(SVN_CMD);
cmdLine.addArgument(CMD_LOG);
cmdLine.addArgument(OPT_XML);
addDefaultArguments(cmdLine, null, null);
cmdLine.addArgument("-r");
cmdLine.addArgument("HEAD:HEAD");
cmdLine.addArgument(baseUrl + branch);
try (InputStream inStr = ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000)) {
return true;
} catch (IOException e) {
log.log(Level.FINE, "Branch " + branch + " not found or other error", e);
return false;
}
}
|
[
"public",
"static",
"boolean",
"branchExists",
"(",
"String",
"branch",
",",
"String",
"baseUrl",
")",
"{",
"CommandLine",
"cmdLine",
"=",
"new",
"CommandLine",
"(",
"SVN_CMD",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"CMD_LOG",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"OPT_XML",
")",
";",
"addDefaultArguments",
"(",
"cmdLine",
",",
"null",
",",
"null",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"\"-r\"",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"\"HEAD:HEAD\"",
")",
";",
"cmdLine",
".",
"addArgument",
"(",
"baseUrl",
"+",
"branch",
")",
";",
"try",
"(",
"InputStream",
"inStr",
"=",
"ExecutionHelper",
".",
"getCommandResult",
"(",
"cmdLine",
",",
"new",
"File",
"(",
"\".\"",
")",
",",
"0",
",",
"120000",
")",
")",
"{",
"return",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Branch \"",
"+",
"branch",
"+",
"\" not found or other error\"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Check if the given branch already exists
@param branch The name of the branch including the path to the branch, e.g. branches/4.2.x
@param baseUrl The SVN url to connect to
@return true if the branch already exists, false otherwise.
|
[
"Check",
"if",
"the",
"given",
"branch",
"already",
"exists"
] |
train
|
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L248-L263
|
Azure/azure-sdk-for-java
|
devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java
|
ControllersInner.beginCreateAsync
|
public Observable<ControllerInner> beginCreateAsync(String resourceGroupName, String name, ControllerInner controller) {
"""
Creates an Azure Dev Spaces Controller.
Creates an Azure Dev Spaces Controller with the specified create parameters.
@param resourceGroupName Resource group to which the resource belongs.
@param name Name of the resource.
@param controller Controller create parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ControllerInner object
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, name, controller).map(new Func1<ServiceResponse<ControllerInner>, ControllerInner>() {
@Override
public ControllerInner call(ServiceResponse<ControllerInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<ControllerInner> beginCreateAsync(String resourceGroupName, String name, ControllerInner controller) {
return beginCreateWithServiceResponseAsync(resourceGroupName, name, controller).map(new Func1<ServiceResponse<ControllerInner>, ControllerInner>() {
@Override
public ControllerInner call(ServiceResponse<ControllerInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"ControllerInner",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"ControllerInner",
"controller",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"controller",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ControllerInner",
">",
",",
"ControllerInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ControllerInner",
"call",
"(",
"ServiceResponse",
"<",
"ControllerInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Creates an Azure Dev Spaces Controller.
Creates an Azure Dev Spaces Controller with the specified create parameters.
@param resourceGroupName Resource group to which the resource belongs.
@param name Name of the resource.
@param controller Controller create parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ControllerInner object
|
[
"Creates",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
".",
"Creates",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
"with",
"the",
"specified",
"create",
"parameters",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java#L329-L336
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.