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
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java | SecurityRulesInner.beginCreateOrUpdate | public SecurityRuleInner beginCreateOrUpdate(String resourceGroupName, String networkSecurityGroupName, String securityRuleName, SecurityRuleInner securityRuleParameters) {
"""
Creates or updates a security rule in the specified network security group.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param securityRuleName The name of the security rule.
@param securityRuleParameters Parameters supplied to the create or update network security rule operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SecurityRuleInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).toBlocking().single().body();
} | java | public SecurityRuleInner beginCreateOrUpdate(String resourceGroupName, String networkSecurityGroupName, String securityRuleName, SecurityRuleInner securityRuleParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).toBlocking().single().body();
} | [
"public",
"SecurityRuleInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkSecurityGroupName",
",",
"String",
"securityRuleName",
",",
"SecurityRuleInner",
"securityRuleParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkSecurityGroupName",
",",
"securityRuleName",
",",
"securityRuleParameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Creates or updates a security rule in the specified network security group.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param securityRuleName The name of the security rule.
@param securityRuleParameters Parameters supplied to the create or update network security rule operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SecurityRuleInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"security",
"rule",
"in",
"the",
"specified",
"network",
"security",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java#L444-L446 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigRational.java | BigRational.valueOf | public static BigRational valueOf(BigDecimal value) {
"""
Creates a rational number of the specified {@link BigDecimal} value.
@param value the double value
@return the rational number
"""
if (value.compareTo(BigDecimal.ZERO) == 0) {
return ZERO;
}
if (value.compareTo(BigDecimal.ONE) == 0) {
return ONE;
}
int scale = value.scale();
if (scale == 0) {
return new BigRational(value, BigDecimal.ONE);
} else if (scale < 0) {
BigDecimal n = new BigDecimal(value.unscaledValue()).multiply(BigDecimal.ONE.movePointLeft(value.scale()));
return new BigRational(n, BigDecimal.ONE);
}
else {
BigDecimal n = new BigDecimal(value.unscaledValue());
BigDecimal d = BigDecimal.ONE.movePointRight(value.scale());
return new BigRational(n, d);
}
} | java | public static BigRational valueOf(BigDecimal value) {
if (value.compareTo(BigDecimal.ZERO) == 0) {
return ZERO;
}
if (value.compareTo(BigDecimal.ONE) == 0) {
return ONE;
}
int scale = value.scale();
if (scale == 0) {
return new BigRational(value, BigDecimal.ONE);
} else if (scale < 0) {
BigDecimal n = new BigDecimal(value.unscaledValue()).multiply(BigDecimal.ONE.movePointLeft(value.scale()));
return new BigRational(n, BigDecimal.ONE);
}
else {
BigDecimal n = new BigDecimal(value.unscaledValue());
BigDecimal d = BigDecimal.ONE.movePointRight(value.scale());
return new BigRational(n, d);
}
} | [
"public",
"static",
"BigRational",
"valueOf",
"(",
"BigDecimal",
"value",
")",
"{",
"if",
"(",
"value",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ZERO",
")",
"==",
"0",
")",
"{",
"return",
"ZERO",
";",
"}",
"if",
"(",
"value",
".",
"compareTo",
"(",
"BigDecimal",
".",
"ONE",
")",
"==",
"0",
")",
"{",
"return",
"ONE",
";",
"}",
"int",
"scale",
"=",
"value",
".",
"scale",
"(",
")",
";",
"if",
"(",
"scale",
"==",
"0",
")",
"{",
"return",
"new",
"BigRational",
"(",
"value",
",",
"BigDecimal",
".",
"ONE",
")",
";",
"}",
"else",
"if",
"(",
"scale",
"<",
"0",
")",
"{",
"BigDecimal",
"n",
"=",
"new",
"BigDecimal",
"(",
"value",
".",
"unscaledValue",
"(",
")",
")",
".",
"multiply",
"(",
"BigDecimal",
".",
"ONE",
".",
"movePointLeft",
"(",
"value",
".",
"scale",
"(",
")",
")",
")",
";",
"return",
"new",
"BigRational",
"(",
"n",
",",
"BigDecimal",
".",
"ONE",
")",
";",
"}",
"else",
"{",
"BigDecimal",
"n",
"=",
"new",
"BigDecimal",
"(",
"value",
".",
"unscaledValue",
"(",
")",
")",
";",
"BigDecimal",
"d",
"=",
"BigDecimal",
".",
"ONE",
".",
"movePointRight",
"(",
"value",
".",
"scale",
"(",
")",
")",
";",
"return",
"new",
"BigRational",
"(",
"n",
",",
"d",
")",
";",
"}",
"}"
] | Creates a rational number of the specified {@link BigDecimal} value.
@param value the double value
@return the rational number | [
"Creates",
"a",
"rational",
"number",
"of",
"the",
"specified",
"{",
"@link",
"BigDecimal",
"}",
"value",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigRational.java#L911-L931 |
vatbub/common | updater/src/main/java/com/github/vatbub/common/updater/UpdateChecker.java | UpdateChecker.getMavenMetadata | private static Document getMavenMetadata(URL repoBaseURL, String mavenGroupID, String mavenArtifactID)
throws JDOMException, IOException {
"""
Get a DOM of mavens {@code maven-metadata.xml}-file of the specified
artifact.
@param repoBaseURL The base url where the repo can be reached. For Maven Central,
this is <a href="http://repo1.maven.org/maven/">http://repo1.maven.org/maven/</a>
@param mavenGroupID The groupID of the artifact to be looked up.
@param mavenArtifactID The artifactId of the artifact to be looked up.
@return A JDOM {@link Document} representation of mavens
{@code maven-metadata.xml}
@throws JDOMException If mavens {@code maven-metadata.xml} is not parseable (Which
will never be the case unless you don't modify it manually).
@throws IOException In case mavens {@code maven-metadata.xml} cannot be retrieved
for any other reason.
"""
return new SAXBuilder().build(new URL(repoBaseURL.toString() + "/" + mavenGroupID.replace('.', '/')
+ "/" + mavenArtifactID + "/maven-metadata.xml"));
} | java | private static Document getMavenMetadata(URL repoBaseURL, String mavenGroupID, String mavenArtifactID)
throws JDOMException, IOException {
return new SAXBuilder().build(new URL(repoBaseURL.toString() + "/" + mavenGroupID.replace('.', '/')
+ "/" + mavenArtifactID + "/maven-metadata.xml"));
} | [
"private",
"static",
"Document",
"getMavenMetadata",
"(",
"URL",
"repoBaseURL",
",",
"String",
"mavenGroupID",
",",
"String",
"mavenArtifactID",
")",
"throws",
"JDOMException",
",",
"IOException",
"{",
"return",
"new",
"SAXBuilder",
"(",
")",
".",
"build",
"(",
"new",
"URL",
"(",
"repoBaseURL",
".",
"toString",
"(",
")",
"+",
"\"/\"",
"+",
"mavenGroupID",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
"+",
"\"/\"",
"+",
"mavenArtifactID",
"+",
"\"/maven-metadata.xml\"",
")",
")",
";",
"}"
] | Get a DOM of mavens {@code maven-metadata.xml}-file of the specified
artifact.
@param repoBaseURL The base url where the repo can be reached. For Maven Central,
this is <a href="http://repo1.maven.org/maven/">http://repo1.maven.org/maven/</a>
@param mavenGroupID The groupID of the artifact to be looked up.
@param mavenArtifactID The artifactId of the artifact to be looked up.
@return A JDOM {@link Document} representation of mavens
{@code maven-metadata.xml}
@throws JDOMException If mavens {@code maven-metadata.xml} is not parseable (Which
will never be the case unless you don't modify it manually).
@throws IOException In case mavens {@code maven-metadata.xml} cannot be retrieved
for any other reason. | [
"Get",
"a",
"DOM",
"of",
"mavens",
"{",
"@code",
"maven",
"-",
"metadata",
".",
"xml",
"}",
"-",
"file",
"of",
"the",
"specified",
"artifact",
"."
] | train | https://github.com/vatbub/common/blob/8b9fd2ece0a23d520ce53b66c84cbd094e378443/updater/src/main/java/com/github/vatbub/common/updater/UpdateChecker.java#L369-L373 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/sjavac/server/JavacServer.java | JavacServer.startServer | public static int startServer(String settings, PrintStream err) {
"""
Start a server using a settings string. Typically: "--startserver:portfile=/tmp/myserver,poolsize=3" and the string "portfile=/tmp/myserver,poolsize=3"
is sent as the settings parameter. Returns 0 on success, -1 on failure.
"""
try {
String portfile = Util.extractStringOption("portfile", settings);
// The log file collects more javac server specific log information.
String logfile = Util.extractStringOption("logfile", settings);
// The stdouterr file collects all the System.out and System.err writes to disk.
String stdouterrfile = Util.extractStringOption("stdouterrfile", settings);
// We could perhaps use System.setOut and setErr here.
// But for the moment we rely on the client to spawn a shell where stdout
// and stderr are redirected already.
// The pool size is a limit the number of concurrent compiler threads used.
// The server might use less than these to avoid memory problems.
int poolsize = Util.extractIntOption("poolsize", settings);
if (poolsize <= 0) {
// If not set, default to the number of cores.
poolsize = Runtime.getRuntime().availableProcessors();
}
// How many seconds of inactivity will the server accept before quitting?
int keepalive = Util.extractIntOption("keepalive", settings);
if (keepalive <= 0) {
keepalive = 120;
}
// The port file is locked and the server port and cookie is written into it.
PortFile portFile = getPortFile(portfile);
JavacServer s;
synchronized (portFile) {
portFile.lock();
portFile.getValues();
if (portFile.containsPortInfo()) {
err.println("Javac server not started because portfile exists!");
portFile.unlock();
return -1;
}
s = new JavacServer(poolsize, logfile);
portFile.setValues(s.getPort(), s.getCookie());
portFile.unlock();
}
// Run the server. Will delete the port file when shutting down.
// It will shut down automatically when no new requests have come in
// during the last 125 seconds.
s.run(portFile, err, keepalive);
// The run loop for the server has exited.
return 0;
} catch (Exception e) {
e.printStackTrace(err);
return -1;
}
} | java | public static int startServer(String settings, PrintStream err) {
try {
String portfile = Util.extractStringOption("portfile", settings);
// The log file collects more javac server specific log information.
String logfile = Util.extractStringOption("logfile", settings);
// The stdouterr file collects all the System.out and System.err writes to disk.
String stdouterrfile = Util.extractStringOption("stdouterrfile", settings);
// We could perhaps use System.setOut and setErr here.
// But for the moment we rely on the client to spawn a shell where stdout
// and stderr are redirected already.
// The pool size is a limit the number of concurrent compiler threads used.
// The server might use less than these to avoid memory problems.
int poolsize = Util.extractIntOption("poolsize", settings);
if (poolsize <= 0) {
// If not set, default to the number of cores.
poolsize = Runtime.getRuntime().availableProcessors();
}
// How many seconds of inactivity will the server accept before quitting?
int keepalive = Util.extractIntOption("keepalive", settings);
if (keepalive <= 0) {
keepalive = 120;
}
// The port file is locked and the server port and cookie is written into it.
PortFile portFile = getPortFile(portfile);
JavacServer s;
synchronized (portFile) {
portFile.lock();
portFile.getValues();
if (portFile.containsPortInfo()) {
err.println("Javac server not started because portfile exists!");
portFile.unlock();
return -1;
}
s = new JavacServer(poolsize, logfile);
portFile.setValues(s.getPort(), s.getCookie());
portFile.unlock();
}
// Run the server. Will delete the port file when shutting down.
// It will shut down automatically when no new requests have come in
// during the last 125 seconds.
s.run(portFile, err, keepalive);
// The run loop for the server has exited.
return 0;
} catch (Exception e) {
e.printStackTrace(err);
return -1;
}
} | [
"public",
"static",
"int",
"startServer",
"(",
"String",
"settings",
",",
"PrintStream",
"err",
")",
"{",
"try",
"{",
"String",
"portfile",
"=",
"Util",
".",
"extractStringOption",
"(",
"\"portfile\"",
",",
"settings",
")",
";",
"// The log file collects more javac server specific log information.",
"String",
"logfile",
"=",
"Util",
".",
"extractStringOption",
"(",
"\"logfile\"",
",",
"settings",
")",
";",
"// The stdouterr file collects all the System.out and System.err writes to disk.",
"String",
"stdouterrfile",
"=",
"Util",
".",
"extractStringOption",
"(",
"\"stdouterrfile\"",
",",
"settings",
")",
";",
"// We could perhaps use System.setOut and setErr here.",
"// But for the moment we rely on the client to spawn a shell where stdout",
"// and stderr are redirected already.",
"// The pool size is a limit the number of concurrent compiler threads used.",
"// The server might use less than these to avoid memory problems.",
"int",
"poolsize",
"=",
"Util",
".",
"extractIntOption",
"(",
"\"poolsize\"",
",",
"settings",
")",
";",
"if",
"(",
"poolsize",
"<=",
"0",
")",
"{",
"// If not set, default to the number of cores.",
"poolsize",
"=",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"availableProcessors",
"(",
")",
";",
"}",
"// How many seconds of inactivity will the server accept before quitting?",
"int",
"keepalive",
"=",
"Util",
".",
"extractIntOption",
"(",
"\"keepalive\"",
",",
"settings",
")",
";",
"if",
"(",
"keepalive",
"<=",
"0",
")",
"{",
"keepalive",
"=",
"120",
";",
"}",
"// The port file is locked and the server port and cookie is written into it.",
"PortFile",
"portFile",
"=",
"getPortFile",
"(",
"portfile",
")",
";",
"JavacServer",
"s",
";",
"synchronized",
"(",
"portFile",
")",
"{",
"portFile",
".",
"lock",
"(",
")",
";",
"portFile",
".",
"getValues",
"(",
")",
";",
"if",
"(",
"portFile",
".",
"containsPortInfo",
"(",
")",
")",
"{",
"err",
".",
"println",
"(",
"\"Javac server not started because portfile exists!\"",
")",
";",
"portFile",
".",
"unlock",
"(",
")",
";",
"return",
"-",
"1",
";",
"}",
"s",
"=",
"new",
"JavacServer",
"(",
"poolsize",
",",
"logfile",
")",
";",
"portFile",
".",
"setValues",
"(",
"s",
".",
"getPort",
"(",
")",
",",
"s",
".",
"getCookie",
"(",
")",
")",
";",
"portFile",
".",
"unlock",
"(",
")",
";",
"}",
"// Run the server. Will delete the port file when shutting down.",
"// It will shut down automatically when no new requests have come in",
"// during the last 125 seconds.",
"s",
".",
"run",
"(",
"portFile",
",",
"err",
",",
"keepalive",
")",
";",
"// The run loop for the server has exited.",
"return",
"0",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
"err",
")",
";",
"return",
"-",
"1",
";",
"}",
"}"
] | Start a server using a settings string. Typically: "--startserver:portfile=/tmp/myserver,poolsize=3" and the string "portfile=/tmp/myserver,poolsize=3"
is sent as the settings parameter. Returns 0 on success, -1 on failure. | [
"Start",
"a",
"server",
"using",
"a",
"settings",
"string",
".",
"Typically",
":",
"--",
"startserver",
":",
"portfile",
"=",
"/",
"tmp",
"/",
"myserver",
"poolsize",
"=",
"3",
"and",
"the",
"string",
"portfile",
"=",
"/",
"tmp",
"/",
"myserver",
"poolsize",
"=",
"3",
"is",
"sent",
"as",
"the",
"settings",
"parameter",
".",
"Returns",
"0",
"on",
"success",
"-",
"1",
"on",
"failure",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/server/JavacServer.java#L159-L209 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/QueryRecord.java | QueryRecord.setGridFile | public int setGridFile(Record record, String keyAreaName) {
"""
Mark the main grid file and key order.<p>
Included as a utility for backward compatibility (Use SetupKeys now).
Basically, this method clones the key area for this record.
@param record The record in my list to get the key area from.
@param iKeyNo The key area in the record to retrieve.
@param The index of this key area.
"""
KeyArea recordKeyArea = record.getKeyArea(keyAreaName);
KeyArea newKeyArea = this.makeIndex(recordKeyArea.getUniqueKeyCode(), recordKeyArea.getKeyName());
for (int iKeyField = 0; iKeyField < recordKeyArea.getKeyFields(); iKeyField++)
{
BaseField field = recordKeyArea.getField(iKeyField);
boolean bOrder = recordKeyArea.getKeyOrder(iKeyField);
newKeyArea.addKeyField(field, bOrder);
}
return this.getKeyAreaCount() - 1; // Index of new key area
} | java | public int setGridFile(Record record, String keyAreaName)
{
KeyArea recordKeyArea = record.getKeyArea(keyAreaName);
KeyArea newKeyArea = this.makeIndex(recordKeyArea.getUniqueKeyCode(), recordKeyArea.getKeyName());
for (int iKeyField = 0; iKeyField < recordKeyArea.getKeyFields(); iKeyField++)
{
BaseField field = recordKeyArea.getField(iKeyField);
boolean bOrder = recordKeyArea.getKeyOrder(iKeyField);
newKeyArea.addKeyField(field, bOrder);
}
return this.getKeyAreaCount() - 1; // Index of new key area
} | [
"public",
"int",
"setGridFile",
"(",
"Record",
"record",
",",
"String",
"keyAreaName",
")",
"{",
"KeyArea",
"recordKeyArea",
"=",
"record",
".",
"getKeyArea",
"(",
"keyAreaName",
")",
";",
"KeyArea",
"newKeyArea",
"=",
"this",
".",
"makeIndex",
"(",
"recordKeyArea",
".",
"getUniqueKeyCode",
"(",
")",
",",
"recordKeyArea",
".",
"getKeyName",
"(",
")",
")",
";",
"for",
"(",
"int",
"iKeyField",
"=",
"0",
";",
"iKeyField",
"<",
"recordKeyArea",
".",
"getKeyFields",
"(",
")",
";",
"iKeyField",
"++",
")",
"{",
"BaseField",
"field",
"=",
"recordKeyArea",
".",
"getField",
"(",
"iKeyField",
")",
";",
"boolean",
"bOrder",
"=",
"recordKeyArea",
".",
"getKeyOrder",
"(",
"iKeyField",
")",
";",
"newKeyArea",
".",
"addKeyField",
"(",
"field",
",",
"bOrder",
")",
";",
"}",
"return",
"this",
".",
"getKeyAreaCount",
"(",
")",
"-",
"1",
";",
"// Index of new key area",
"}"
] | Mark the main grid file and key order.<p>
Included as a utility for backward compatibility (Use SetupKeys now).
Basically, this method clones the key area for this record.
@param record The record in my list to get the key area from.
@param iKeyNo The key area in the record to retrieve.
@param The index of this key area. | [
"Mark",
"the",
"main",
"grid",
"file",
"and",
"key",
"order",
".",
"<p",
">",
"Included",
"as",
"a",
"utility",
"for",
"backward",
"compatibility",
"(",
"Use",
"SetupKeys",
"now",
")",
".",
"Basically",
"this",
"method",
"clones",
"the",
"key",
"area",
"for",
"this",
"record",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/QueryRecord.java#L534-L545 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/spacefillingcurves/BinarySplitSpatialSorter.java | BinarySplitSpatialSorter.binarySplitSort | private void binarySplitSort(List<? extends SpatialComparable> objs, final int start, final int end, int depth, final int numdim, int[] dims, Sorter comp) {
"""
Sort the array using a binary split in dimension curdim, then recurse with
the next dimension.
@param objs List of objects
@param start Interval start
@param end Interval end (exclusive)
@param depth Recursion depth
@param numdim Number of dimensions
@param dims Dimension indexes to sort by.
@param comp Comparator to use
"""
final int mid = start + ((end - start) >>> 1);
// Make invariant
comp.setDimension(dims != null ? dims[depth] : depth);
QuickSelect.quickSelect(objs, comp, start, end, mid);
// Recurse
final int nextdim = (depth + 1) % numdim;
if(start < mid - 1) {
binarySplitSort(objs, start, mid, nextdim, numdim, dims, comp);
}
if(mid + 2 < end) {
binarySplitSort(objs, mid + 1, end, nextdim, numdim, dims, comp);
}
} | java | private void binarySplitSort(List<? extends SpatialComparable> objs, final int start, final int end, int depth, final int numdim, int[] dims, Sorter comp) {
final int mid = start + ((end - start) >>> 1);
// Make invariant
comp.setDimension(dims != null ? dims[depth] : depth);
QuickSelect.quickSelect(objs, comp, start, end, mid);
// Recurse
final int nextdim = (depth + 1) % numdim;
if(start < mid - 1) {
binarySplitSort(objs, start, mid, nextdim, numdim, dims, comp);
}
if(mid + 2 < end) {
binarySplitSort(objs, mid + 1, end, nextdim, numdim, dims, comp);
}
} | [
"private",
"void",
"binarySplitSort",
"(",
"List",
"<",
"?",
"extends",
"SpatialComparable",
">",
"objs",
",",
"final",
"int",
"start",
",",
"final",
"int",
"end",
",",
"int",
"depth",
",",
"final",
"int",
"numdim",
",",
"int",
"[",
"]",
"dims",
",",
"Sorter",
"comp",
")",
"{",
"final",
"int",
"mid",
"=",
"start",
"+",
"(",
"(",
"end",
"-",
"start",
")",
">>>",
"1",
")",
";",
"// Make invariant",
"comp",
".",
"setDimension",
"(",
"dims",
"!=",
"null",
"?",
"dims",
"[",
"depth",
"]",
":",
"depth",
")",
";",
"QuickSelect",
".",
"quickSelect",
"(",
"objs",
",",
"comp",
",",
"start",
",",
"end",
",",
"mid",
")",
";",
"// Recurse",
"final",
"int",
"nextdim",
"=",
"(",
"depth",
"+",
"1",
")",
"%",
"numdim",
";",
"if",
"(",
"start",
"<",
"mid",
"-",
"1",
")",
"{",
"binarySplitSort",
"(",
"objs",
",",
"start",
",",
"mid",
",",
"nextdim",
",",
"numdim",
",",
"dims",
",",
"comp",
")",
";",
"}",
"if",
"(",
"mid",
"+",
"2",
"<",
"end",
")",
"{",
"binarySplitSort",
"(",
"objs",
",",
"mid",
"+",
"1",
",",
"end",
",",
"nextdim",
",",
"numdim",
",",
"dims",
",",
"comp",
")",
";",
"}",
"}"
] | Sort the array using a binary split in dimension curdim, then recurse with
the next dimension.
@param objs List of objects
@param start Interval start
@param end Interval end (exclusive)
@param depth Recursion depth
@param numdim Number of dimensions
@param dims Dimension indexes to sort by.
@param comp Comparator to use | [
"Sort",
"the",
"array",
"using",
"a",
"binary",
"split",
"in",
"dimension",
"curdim",
"then",
"recurse",
"with",
"the",
"next",
"dimension",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/spacefillingcurves/BinarySplitSpatialSorter.java#L86-L99 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java | ContentBasedLocalBundleRepository.selectBundle | public File selectBundle(String baseLocation, final String symbolicName, final VersionRange versionRange) {
"""
This method selects bundles based on the input criteria. The first parameter is the baseLocation. This
can be null, the empty string, a directory, a comma separated list of directories, or a file path relative
to the install. If it is a file path then that exact bundle is returned irrespective of other selection
parameters. If it is null or the empty string it is assumed to be a bundle in lib dir. If it is a directory,
or a comma separated directory then the subsequent matching rules will be used to choose a matching bundle
in the specified directories.
<p>Assuming a baseLocation of "dev/,lib/" a symbolic name of "a.b" and a version range of "[1,1.0.100)" then all
bundles in dev and lib will be searched looking for the highest versioned bundle with a symbolic name of a.b. Note
highest versioned excludes iFixes where the iFix base version is not located. So given identified bundles:
<ol>
<li>a.b/1.0.0</li>
<li>a.b/1.0.1.v1</li>
<li>a.b/1.0.2.v2</li>
</ol>
The middle bundle will be chosen.
</p>
@param baseLocation The base location.
@param symbolicName The desired symbolic name.
@param versionRange The range of versions that can be selected.
@return The file representing the chosen bundle.
"""
readCache();
return selectResource(baseLocation, symbolicName, versionRange);
} | java | public File selectBundle(String baseLocation, final String symbolicName, final VersionRange versionRange) {
readCache();
return selectResource(baseLocation, symbolicName, versionRange);
} | [
"public",
"File",
"selectBundle",
"(",
"String",
"baseLocation",
",",
"final",
"String",
"symbolicName",
",",
"final",
"VersionRange",
"versionRange",
")",
"{",
"readCache",
"(",
")",
";",
"return",
"selectResource",
"(",
"baseLocation",
",",
"symbolicName",
",",
"versionRange",
")",
";",
"}"
] | This method selects bundles based on the input criteria. The first parameter is the baseLocation. This
can be null, the empty string, a directory, a comma separated list of directories, or a file path relative
to the install. If it is a file path then that exact bundle is returned irrespective of other selection
parameters. If it is null or the empty string it is assumed to be a bundle in lib dir. If it is a directory,
or a comma separated directory then the subsequent matching rules will be used to choose a matching bundle
in the specified directories.
<p>Assuming a baseLocation of "dev/,lib/" a symbolic name of "a.b" and a version range of "[1,1.0.100)" then all
bundles in dev and lib will be searched looking for the highest versioned bundle with a symbolic name of a.b. Note
highest versioned excludes iFixes where the iFix base version is not located. So given identified bundles:
<ol>
<li>a.b/1.0.0</li>
<li>a.b/1.0.1.v1</li>
<li>a.b/1.0.2.v2</li>
</ol>
The middle bundle will be chosen.
</p>
@param baseLocation The base location.
@param symbolicName The desired symbolic name.
@param versionRange The range of versions that can be selected.
@return The file representing the chosen bundle. | [
"This",
"method",
"selects",
"bundles",
"based",
"on",
"the",
"input",
"criteria",
".",
"The",
"first",
"parameter",
"is",
"the",
"baseLocation",
".",
"This",
"can",
"be",
"null",
"the",
"empty",
"string",
"a",
"directory",
"a",
"comma",
"separated",
"list",
"of",
"directories",
"or",
"a",
"file",
"path",
"relative",
"to",
"the",
"install",
".",
"If",
"it",
"is",
"a",
"file",
"path",
"then",
"that",
"exact",
"bundle",
"is",
"returned",
"irrespective",
"of",
"other",
"selection",
"parameters",
".",
"If",
"it",
"is",
"null",
"or",
"the",
"empty",
"string",
"it",
"is",
"assumed",
"to",
"be",
"a",
"bundle",
"in",
"lib",
"dir",
".",
"If",
"it",
"is",
"a",
"directory",
"or",
"a",
"comma",
"separated",
"directory",
"then",
"the",
"subsequent",
"matching",
"rules",
"will",
"be",
"used",
"to",
"choose",
"a",
"matching",
"bundle",
"in",
"the",
"specified",
"directories",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/ContentBasedLocalBundleRepository.java#L326-L329 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/util/url/UrlOperations.java | UrlOperations.resolveUrl | public static String resolveUrl(String baseUrl, String url, String defaultValue) {
"""
Resolve a possibly relative url argument against a base URL.
@param baseUrl the base URL against which the url should be resolved
@param url the URL, possibly relative, to make absolute.
@param defaultValue The default value to return if the supplied values can't be resolved.
@return url resolved against baseUrl, unless it is absolute already, and
further transformed by whatever escaping normally takes place with a
UsableURI.
In case of error, return the defaultValue
"""
for(final String scheme : ALL_SCHEMES) {
if(url.startsWith(scheme)) {
try {
return UsableURIFactory.getInstance(url).getEscapedURI();
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
// can't let a space exist... send back close to whatever came
// in...
return defaultValue;
}
}
}
UsableURI absBaseURI;
UsableURI resolvedURI = null;
try {
absBaseURI = UsableURIFactory.getInstance(baseUrl);
resolvedURI = UsableURIFactory.getInstance(absBaseURI, url);
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
return defaultValue;
}
return resolvedURI.getEscapedURI();
} | java | public static String resolveUrl(String baseUrl, String url, String defaultValue) {
for(final String scheme : ALL_SCHEMES) {
if(url.startsWith(scheme)) {
try {
return UsableURIFactory.getInstance(url).getEscapedURI();
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
// can't let a space exist... send back close to whatever came
// in...
return defaultValue;
}
}
}
UsableURI absBaseURI;
UsableURI resolvedURI = null;
try {
absBaseURI = UsableURIFactory.getInstance(baseUrl);
resolvedURI = UsableURIFactory.getInstance(absBaseURI, url);
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
return defaultValue;
}
return resolvedURI.getEscapedURI();
} | [
"public",
"static",
"String",
"resolveUrl",
"(",
"String",
"baseUrl",
",",
"String",
"url",
",",
"String",
"defaultValue",
")",
"{",
"for",
"(",
"final",
"String",
"scheme",
":",
"ALL_SCHEMES",
")",
"{",
"if",
"(",
"url",
".",
"startsWith",
"(",
"scheme",
")",
")",
"{",
"try",
"{",
"return",
"UsableURIFactory",
".",
"getInstance",
"(",
"url",
")",
".",
"getEscapedURI",
"(",
")",
";",
"}",
"catch",
"(",
"URIException",
"e",
")",
"{",
"LOGGER",
".",
"warning",
"(",
"e",
".",
"getLocalizedMessage",
"(",
")",
"+",
"\": \"",
"+",
"url",
")",
";",
"// can't let a space exist... send back close to whatever came",
"// in...",
"return",
"defaultValue",
";",
"}",
"}",
"}",
"UsableURI",
"absBaseURI",
";",
"UsableURI",
"resolvedURI",
"=",
"null",
";",
"try",
"{",
"absBaseURI",
"=",
"UsableURIFactory",
".",
"getInstance",
"(",
"baseUrl",
")",
";",
"resolvedURI",
"=",
"UsableURIFactory",
".",
"getInstance",
"(",
"absBaseURI",
",",
"url",
")",
";",
"}",
"catch",
"(",
"URIException",
"e",
")",
"{",
"LOGGER",
".",
"warning",
"(",
"e",
".",
"getLocalizedMessage",
"(",
")",
"+",
"\": \"",
"+",
"url",
")",
";",
"return",
"defaultValue",
";",
"}",
"return",
"resolvedURI",
".",
"getEscapedURI",
"(",
")",
";",
"}"
] | Resolve a possibly relative url argument against a base URL.
@param baseUrl the base URL against which the url should be resolved
@param url the URL, possibly relative, to make absolute.
@param defaultValue The default value to return if the supplied values can't be resolved.
@return url resolved against baseUrl, unless it is absolute already, and
further transformed by whatever escaping normally takes place with a
UsableURI.
In case of error, return the defaultValue | [
"Resolve",
"a",
"possibly",
"relative",
"url",
"argument",
"against",
"a",
"base",
"URL",
"."
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/url/UrlOperations.java#L182-L207 |
opencb/biodata | biodata-tools/src/main/java/org/opencb/biodata/tools/variant/stats/VariantStatsCalculator.java | VariantStatsCalculator.calculateStatsForVariantsList | public static void calculateStatsForVariantsList(List<Variant> variants, Pedigree ped) {
"""
Calculates the statistics for some variants read from a set of files, and
optionally given pedigree information. Some statistics like inheritance
patterns can only be calculated if pedigree information is provided.
@param variants The variants whose statistics will be calculated
@param ped Optional pedigree information to calculate some statistics
"""
for (Variant variant : variants) {
for (StudyEntry entry : variant.getStudies()) {
VariantStats stats = calculate(variant, entry);
entry.setStats(StudyEntry.DEFAULT_COHORT, stats);
}
}
} | java | public static void calculateStatsForVariantsList(List<Variant> variants, Pedigree ped) {
for (Variant variant : variants) {
for (StudyEntry entry : variant.getStudies()) {
VariantStats stats = calculate(variant, entry);
entry.setStats(StudyEntry.DEFAULT_COHORT, stats);
}
}
} | [
"public",
"static",
"void",
"calculateStatsForVariantsList",
"(",
"List",
"<",
"Variant",
">",
"variants",
",",
"Pedigree",
"ped",
")",
"{",
"for",
"(",
"Variant",
"variant",
":",
"variants",
")",
"{",
"for",
"(",
"StudyEntry",
"entry",
":",
"variant",
".",
"getStudies",
"(",
")",
")",
"{",
"VariantStats",
"stats",
"=",
"calculate",
"(",
"variant",
",",
"entry",
")",
";",
"entry",
".",
"setStats",
"(",
"StudyEntry",
".",
"DEFAULT_COHORT",
",",
"stats",
")",
";",
"}",
"}",
"}"
] | Calculates the statistics for some variants read from a set of files, and
optionally given pedigree information. Some statistics like inheritance
patterns can only be calculated if pedigree information is provided.
@param variants The variants whose statistics will be calculated
@param ped Optional pedigree information to calculate some statistics | [
"Calculates",
"the",
"statistics",
"for",
"some",
"variants",
"read",
"from",
"a",
"set",
"of",
"files",
"and",
"optionally",
"given",
"pedigree",
"information",
".",
"Some",
"statistics",
"like",
"inheritance",
"patterns",
"can",
"only",
"be",
"calculated",
"if",
"pedigree",
"information",
"is",
"provided",
"."
] | train | https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/variant/stats/VariantStatsCalculator.java#L189-L196 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java | JavaCompiler.resolveBinaryNameOrIdent | public Symbol resolveBinaryNameOrIdent(ModuleSymbol msym, String name) {
"""
Resolve an identifier which may be the binary name of a class or
the Java name of a class or package.
@param msym The module in which the search should be performed
@param name The name to resolve
"""
try {
Name flatname = names.fromString(name.replace("/", "."));
return finder.loadClass(msym, flatname);
} catch (CompletionFailure ignore) {
return resolveIdent(msym, name);
}
} | java | public Symbol resolveBinaryNameOrIdent(ModuleSymbol msym, String name) {
try {
Name flatname = names.fromString(name.replace("/", "."));
return finder.loadClass(msym, flatname);
} catch (CompletionFailure ignore) {
return resolveIdent(msym, name);
}
} | [
"public",
"Symbol",
"resolveBinaryNameOrIdent",
"(",
"ModuleSymbol",
"msym",
",",
"String",
"name",
")",
"{",
"try",
"{",
"Name",
"flatname",
"=",
"names",
".",
"fromString",
"(",
"name",
".",
"replace",
"(",
"\"/\"",
",",
"\".\"",
")",
")",
";",
"return",
"finder",
".",
"loadClass",
"(",
"msym",
",",
"flatname",
")",
";",
"}",
"catch",
"(",
"CompletionFailure",
"ignore",
")",
"{",
"return",
"resolveIdent",
"(",
"msym",
",",
"name",
")",
";",
"}",
"}"
] | Resolve an identifier which may be the binary name of a class or
the Java name of a class or package.
@param msym The module in which the search should be performed
@param name The name to resolve | [
"Resolve",
"an",
"identifier",
"which",
"may",
"be",
"the",
"binary",
"name",
"of",
"a",
"class",
"or",
"the",
"Java",
"name",
"of",
"a",
"class",
"or",
"package",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java#L700-L707 |
passwordmaker/java-passwordmaker-lib | src/main/java/org/daveware/passwordmaker/Database.java | Database.removeAccount | private void removeAccount(Account parent, Account child) {
"""
Internal routine to remove a child from a parent.
Notifies the listeners of the removal
@param parent - The parent to remove the child from
@param child - The child to remove from parent
"""
parent.getChildren().remove(child);
sendAccountRemoved(parent, child);
} | java | private void removeAccount(Account parent, Account child) {
parent.getChildren().remove(child);
sendAccountRemoved(parent, child);
} | [
"private",
"void",
"removeAccount",
"(",
"Account",
"parent",
",",
"Account",
"child",
")",
"{",
"parent",
".",
"getChildren",
"(",
")",
".",
"remove",
"(",
"child",
")",
";",
"sendAccountRemoved",
"(",
"parent",
",",
"child",
")",
";",
"}"
] | Internal routine to remove a child from a parent.
Notifies the listeners of the removal
@param parent - The parent to remove the child from
@param child - The child to remove from parent | [
"Internal",
"routine",
"to",
"remove",
"a",
"child",
"from",
"a",
"parent",
".",
"Notifies",
"the",
"listeners",
"of",
"the",
"removal"
] | train | https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/Database.java#L152-L155 |
undertow-io/undertow | core/src/main/java/io/undertow/websockets/core/WebSockets.java | WebSockets.sendBinary | public static void sendBinary(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
"""
Sends a complete binary message, invoking the callback when complete
Automatically frees the pooled byte buffer when done.
@param pooledData The data to send, it will be freed when done
@param wsChannel The web socket channel
@param callback The callback to invoke on completion
"""
sendInternal(pooledData, WebSocketFrameType.BINARY, wsChannel, callback, null, -1);
} | java | public static void sendBinary(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(pooledData, WebSocketFrameType.BINARY, wsChannel, callback, null, -1);
} | [
"public",
"static",
"void",
"sendBinary",
"(",
"final",
"PooledByteBuffer",
"pooledData",
",",
"final",
"WebSocketChannel",
"wsChannel",
",",
"final",
"WebSocketCallback",
"<",
"Void",
">",
"callback",
")",
"{",
"sendInternal",
"(",
"pooledData",
",",
"WebSocketFrameType",
".",
"BINARY",
",",
"wsChannel",
",",
"callback",
",",
"null",
",",
"-",
"1",
")",
";",
"}"
] | Sends a complete binary message, invoking the callback when complete
Automatically frees the pooled byte buffer when done.
@param pooledData The data to send, it will be freed when done
@param wsChannel The web socket channel
@param callback The callback to invoke on completion | [
"Sends",
"a",
"complete",
"binary",
"message",
"invoking",
"the",
"callback",
"when",
"complete",
"Automatically",
"frees",
"the",
"pooled",
"byte",
"buffer",
"when",
"done",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L686-L688 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java | LogRecordBrowser.restartRecordsInProcess | private OnePidRecordListImpl restartRecordsInProcess(final RepositoryPointer after, long max, final IInternalRecordFilter recFilter) {
"""
continue the list of the records in the process filtered with <code>recFilter</code>
"""
if (!(after instanceof RepositoryPointerImpl)) {
throw new IllegalArgumentException("Specified location does not belong to this repository.");
}
return new OnePidRecordListLocationImpl((RepositoryPointerImpl)after, max, recFilter);
} | java | private OnePidRecordListImpl restartRecordsInProcess(final RepositoryPointer after, long max, final IInternalRecordFilter recFilter) {
if (!(after instanceof RepositoryPointerImpl)) {
throw new IllegalArgumentException("Specified location does not belong to this repository.");
}
return new OnePidRecordListLocationImpl((RepositoryPointerImpl)after, max, recFilter);
} | [
"private",
"OnePidRecordListImpl",
"restartRecordsInProcess",
"(",
"final",
"RepositoryPointer",
"after",
",",
"long",
"max",
",",
"final",
"IInternalRecordFilter",
"recFilter",
")",
"{",
"if",
"(",
"!",
"(",
"after",
"instanceof",
"RepositoryPointerImpl",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Specified location does not belong to this repository.\"",
")",
";",
"}",
"return",
"new",
"OnePidRecordListLocationImpl",
"(",
"(",
"RepositoryPointerImpl",
")",
"after",
",",
"max",
",",
"recFilter",
")",
";",
"}"
] | continue the list of the records in the process filtered with <code>recFilter</code> | [
"continue",
"the",
"list",
"of",
"the",
"records",
"in",
"the",
"process",
"filtered",
"with",
"<code",
">",
"recFilter<",
"/",
"code",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java#L172-L177 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java | JacksonDBCollection.ensureIndex | public void ensureIndex(final DBObject keys, final DBObject optionsIN) throws MongoException {
"""
Creates an index on a set of fields, if one does not already exist.
@param keys an object with a key set of the fields desired for the index
@param optionsIN options for the index (name, unique, etc)
@throws MongoException If an error occurred
"""
dbCollection.ensureIndex(keys, optionsIN);
} | java | public void ensureIndex(final DBObject keys, final DBObject optionsIN) throws MongoException {
dbCollection.ensureIndex(keys, optionsIN);
} | [
"public",
"void",
"ensureIndex",
"(",
"final",
"DBObject",
"keys",
",",
"final",
"DBObject",
"optionsIN",
")",
"throws",
"MongoException",
"{",
"dbCollection",
".",
"ensureIndex",
"(",
"keys",
",",
"optionsIN",
")",
";",
"}"
] | Creates an index on a set of fields, if one does not already exist.
@param keys an object with a key set of the fields desired for the index
@param optionsIN options for the index (name, unique, etc)
@throws MongoException If an error occurred | [
"Creates",
"an",
"index",
"on",
"a",
"set",
"of",
"fields",
"if",
"one",
"does",
"not",
"already",
"exist",
"."
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/JacksonDBCollection.java#L733-L735 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/LocaleUtils.java | LocaleUtils.parseLocale | private static Locale parseLocale(final String str) {
"""
Tries to parse a locale from the given String.
@param str the String to parse a locale from.
@return a Locale instance parsed from the given String.
@throws IllegalArgumentException if the given String can not be parsed.
"""
if (isISO639LanguageCode(str)) {
return new Locale(str);
}
final String[] segments = str.split("_", -1);
final String language = segments[0];
if (segments.length == 2) {
final String country = segments[1];
if (isISO639LanguageCode(language) && isISO3166CountryCode(country) ||
isNumericAreaCode(country)) {
return new Locale(language, country);
}
} else if (segments.length == 3) {
final String country = segments[1];
final String variant = segments[2];
if (isISO639LanguageCode(language) &&
(country.length() == 0 || isISO3166CountryCode(country) || isNumericAreaCode(country)) &&
variant.length() > 0) {
return new Locale(language, country, variant);
}
}
throw new IllegalArgumentException("Invalid locale format: " + str);
} | java | private static Locale parseLocale(final String str) {
if (isISO639LanguageCode(str)) {
return new Locale(str);
}
final String[] segments = str.split("_", -1);
final String language = segments[0];
if (segments.length == 2) {
final String country = segments[1];
if (isISO639LanguageCode(language) && isISO3166CountryCode(country) ||
isNumericAreaCode(country)) {
return new Locale(language, country);
}
} else if (segments.length == 3) {
final String country = segments[1];
final String variant = segments[2];
if (isISO639LanguageCode(language) &&
(country.length() == 0 || isISO3166CountryCode(country) || isNumericAreaCode(country)) &&
variant.length() > 0) {
return new Locale(language, country, variant);
}
}
throw new IllegalArgumentException("Invalid locale format: " + str);
} | [
"private",
"static",
"Locale",
"parseLocale",
"(",
"final",
"String",
"str",
")",
"{",
"if",
"(",
"isISO639LanguageCode",
"(",
"str",
")",
")",
"{",
"return",
"new",
"Locale",
"(",
"str",
")",
";",
"}",
"final",
"String",
"[",
"]",
"segments",
"=",
"str",
".",
"split",
"(",
"\"_\"",
",",
"-",
"1",
")",
";",
"final",
"String",
"language",
"=",
"segments",
"[",
"0",
"]",
";",
"if",
"(",
"segments",
".",
"length",
"==",
"2",
")",
"{",
"final",
"String",
"country",
"=",
"segments",
"[",
"1",
"]",
";",
"if",
"(",
"isISO639LanguageCode",
"(",
"language",
")",
"&&",
"isISO3166CountryCode",
"(",
"country",
")",
"||",
"isNumericAreaCode",
"(",
"country",
")",
")",
"{",
"return",
"new",
"Locale",
"(",
"language",
",",
"country",
")",
";",
"}",
"}",
"else",
"if",
"(",
"segments",
".",
"length",
"==",
"3",
")",
"{",
"final",
"String",
"country",
"=",
"segments",
"[",
"1",
"]",
";",
"final",
"String",
"variant",
"=",
"segments",
"[",
"2",
"]",
";",
"if",
"(",
"isISO639LanguageCode",
"(",
"language",
")",
"&&",
"(",
"country",
".",
"length",
"(",
")",
"==",
"0",
"||",
"isISO3166CountryCode",
"(",
"country",
")",
"||",
"isNumericAreaCode",
"(",
"country",
")",
")",
"&&",
"variant",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"Locale",
"(",
"language",
",",
"country",
",",
"variant",
")",
";",
"}",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid locale format: \"",
"+",
"str",
")",
";",
"}"
] | Tries to parse a locale from the given String.
@param str the String to parse a locale from.
@return a Locale instance parsed from the given String.
@throws IllegalArgumentException if the given String can not be parsed. | [
"Tries",
"to",
"parse",
"a",
"locale",
"from",
"the",
"given",
"String",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/LocaleUtils.java#L139-L162 |
GenesysPureEngage/provisioning-client-java | src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java | SamlSettingsApi.setEnabledAsync | public com.squareup.okhttp.Call setEnabledAsync(Boolean saMLEnabled, final ApiCallback<SetEnabledResponse> callback) throws ApiException {
"""
Set SAML state. (asynchronously)
Change current SAML state.
@param saMLEnabled Value that define SAML state. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object
"""
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = setEnabledValidateBeforeCall(saMLEnabled, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<SetEnabledResponse>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call setEnabledAsync(Boolean saMLEnabled, final ApiCallback<SetEnabledResponse> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = setEnabledValidateBeforeCall(saMLEnabled, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<SetEnabledResponse>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"setEnabledAsync",
"(",
"Boolean",
"saMLEnabled",
",",
"final",
"ApiCallback",
"<",
"SetEnabledResponse",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseBody",
".",
"ProgressListener",
"progressListener",
"=",
"null",
";",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"progressRequestListener",
"=",
"null",
";",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"progressListener",
"=",
"new",
"ProgressResponseBody",
".",
"ProgressListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"update",
"(",
"long",
"bytesRead",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onDownloadProgress",
"(",
"bytesRead",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"progressRequestListener",
"=",
"new",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onRequestProgress",
"(",
"long",
"bytesWritten",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onUploadProgress",
"(",
"bytesWritten",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"}",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"setEnabledValidateBeforeCall",
"(",
"saMLEnabled",
",",
"progressListener",
",",
"progressRequestListener",
")",
";",
"Type",
"localVarReturnType",
"=",
"new",
"TypeToken",
"<",
"SetEnabledResponse",
">",
"(",
")",
"{",
"}",
".",
"getType",
"(",
")",
";",
"apiClient",
".",
"executeAsync",
"(",
"call",
",",
"localVarReturnType",
",",
"callback",
")",
";",
"return",
"call",
";",
"}"
] | Set SAML state. (asynchronously)
Change current SAML state.
@param saMLEnabled Value that define SAML state. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Set",
"SAML",
"state",
".",
"(",
"asynchronously",
")",
"Change",
"current",
"SAML",
"state",
"."
] | train | https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/SamlSettingsApi.java#L1270-L1295 |
allengeorge/libraft | libraft-agent/src/main/java/io/libraft/agent/protocol/RaftRPC.java | RaftRPC.setupJacksonAnnotatedCommandSerializationAndDeserialization | public static <T extends Command> void setupJacksonAnnotatedCommandSerializationAndDeserialization(ObjectMapper mapper, Class<T> commandSubclassKlass) {
"""
Setup serialization and deserialization for Jackson-annotated {@link Command} subclasses.
All Jackson-annotated {@code Command} subclasses <strong>must</strong> derive from a single base class.
<p/>
The following <strong>is</strong> supported:
<pre>
Object
+-- CMD_BASE
+-- CMD_0
+-- CMD_1
</pre>
And the following is <strong>not</strong> supported:
<pre>
Object
+-- CMD_0
+-- CMD_1
</pre>
See {@code RaftAgent} for more on which {@code Command} types are supported.
@param mapper instance of {@code ObjectMapper} with which the serialization/deserialization mapping is registered
@param commandSubclassKlass the base class of all the Jackson-annotated {@code Command} classes
@see io.libraft.agent.RaftAgent
"""
SimpleModule module = new SimpleModule("raftrpc-jackson-command-module", new Version(0, 0, 0, "inline", "io.libraft", "raftrpc-jackson-command-module"));
module.addAbstractTypeMapping(Command.class, commandSubclassKlass);
module.addDeserializer(commandSubclassKlass, new RaftRPCCommand.PassThroughDeserializer<T>(commandSubclassKlass));
mapper.registerModule(module);
} | java | public static <T extends Command> void setupJacksonAnnotatedCommandSerializationAndDeserialization(ObjectMapper mapper, Class<T> commandSubclassKlass) {
SimpleModule module = new SimpleModule("raftrpc-jackson-command-module", new Version(0, 0, 0, "inline", "io.libraft", "raftrpc-jackson-command-module"));
module.addAbstractTypeMapping(Command.class, commandSubclassKlass);
module.addDeserializer(commandSubclassKlass, new RaftRPCCommand.PassThroughDeserializer<T>(commandSubclassKlass));
mapper.registerModule(module);
} | [
"public",
"static",
"<",
"T",
"extends",
"Command",
">",
"void",
"setupJacksonAnnotatedCommandSerializationAndDeserialization",
"(",
"ObjectMapper",
"mapper",
",",
"Class",
"<",
"T",
">",
"commandSubclassKlass",
")",
"{",
"SimpleModule",
"module",
"=",
"new",
"SimpleModule",
"(",
"\"raftrpc-jackson-command-module\"",
",",
"new",
"Version",
"(",
"0",
",",
"0",
",",
"0",
",",
"\"inline\"",
",",
"\"io.libraft\"",
",",
"\"raftrpc-jackson-command-module\"",
")",
")",
";",
"module",
".",
"addAbstractTypeMapping",
"(",
"Command",
".",
"class",
",",
"commandSubclassKlass",
")",
";",
"module",
".",
"addDeserializer",
"(",
"commandSubclassKlass",
",",
"new",
"RaftRPCCommand",
".",
"PassThroughDeserializer",
"<",
"T",
">",
"(",
"commandSubclassKlass",
")",
")",
";",
"mapper",
".",
"registerModule",
"(",
"module",
")",
";",
"}"
] | Setup serialization and deserialization for Jackson-annotated {@link Command} subclasses.
All Jackson-annotated {@code Command} subclasses <strong>must</strong> derive from a single base class.
<p/>
The following <strong>is</strong> supported:
<pre>
Object
+-- CMD_BASE
+-- CMD_0
+-- CMD_1
</pre>
And the following is <strong>not</strong> supported:
<pre>
Object
+-- CMD_0
+-- CMD_1
</pre>
See {@code RaftAgent} for more on which {@code Command} types are supported.
@param mapper instance of {@code ObjectMapper} with which the serialization/deserialization mapping is registered
@param commandSubclassKlass the base class of all the Jackson-annotated {@code Command} classes
@see io.libraft.agent.RaftAgent | [
"Setup",
"serialization",
"and",
"deserialization",
"for",
"Jackson",
"-",
"annotated",
"{",
"@link",
"Command",
"}",
"subclasses",
".",
"All",
"Jackson",
"-",
"annotated",
"{",
"@code",
"Command",
"}",
"subclasses",
"<strong",
">",
"must<",
"/",
"strong",
">",
"derive",
"from",
"a",
"single",
"base",
"class",
".",
"<p",
"/",
">",
"The",
"following",
"<strong",
">",
"is<",
"/",
"strong",
">",
"supported",
":",
"<pre",
">",
"Object",
"+",
"--",
"CMD_BASE",
"+",
"--",
"CMD_0",
"+",
"--",
"CMD_1",
"<",
"/",
"pre",
">",
"And",
"the",
"following",
"is",
"<strong",
">",
"not<",
"/",
"strong",
">",
"supported",
":",
"<pre",
">",
"Object",
"+",
"--",
"CMD_0",
"+",
"--",
"CMD_1",
"<",
"/",
"pre",
">",
"See",
"{",
"@code",
"RaftAgent",
"}",
"for",
"more",
"on",
"which",
"{",
"@code",
"Command",
"}",
"types",
"are",
"supported",
"."
] | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-agent/src/main/java/io/libraft/agent/protocol/RaftRPC.java#L93-L100 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/event/DisableOnFieldHandler.java | DisableOnFieldHandler.init | public void init(BaseField field, BaseField fieldToDisable, String strCompareString, boolean bDisableIfMatch) {
"""
Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param fieldToDisable The field to disable when this listener's owner matches the target string.
@param strCompareString The string to compare to this listener's owner.
@param bDisableIfMatch If true, disables if the string matches, if false, enables on match.
"""
super.init(field);
m_fldToDisable = fieldToDisable;
m_strCompareString = strCompareString;
m_bDisableIfMatch = bDisableIfMatch;
if (m_fldToDisable != null)
m_fldToDisable.addListener(new FieldRemoveBOnCloseHandler(this)); // Remove this listener if closed
} | java | public void init(BaseField field, BaseField fieldToDisable, String strCompareString, boolean bDisableIfMatch)
{
super.init(field);
m_fldToDisable = fieldToDisable;
m_strCompareString = strCompareString;
m_bDisableIfMatch = bDisableIfMatch;
if (m_fldToDisable != null)
m_fldToDisable.addListener(new FieldRemoveBOnCloseHandler(this)); // Remove this listener if closed
} | [
"public",
"void",
"init",
"(",
"BaseField",
"field",
",",
"BaseField",
"fieldToDisable",
",",
"String",
"strCompareString",
",",
"boolean",
"bDisableIfMatch",
")",
"{",
"super",
".",
"init",
"(",
"field",
")",
";",
"m_fldToDisable",
"=",
"fieldToDisable",
";",
"m_strCompareString",
"=",
"strCompareString",
";",
"m_bDisableIfMatch",
"=",
"bDisableIfMatch",
";",
"if",
"(",
"m_fldToDisable",
"!=",
"null",
")",
"m_fldToDisable",
".",
"addListener",
"(",
"new",
"FieldRemoveBOnCloseHandler",
"(",
"this",
")",
")",
";",
"// Remove this listener if closed",
"}"
] | Constructor.
@param field The basefield owner of this listener (usually null and set on setOwner()).
@param fieldToDisable The field to disable when this listener's owner matches the target string.
@param strCompareString The string to compare to this listener's owner.
@param bDisableIfMatch If true, disables if the string matches, if false, enables on match. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/DisableOnFieldHandler.java#L63-L71 |
foundation-runtime/service-directory | 2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java | WebSocketSerializer.getProtocolSerializer | public static ProtocolSerializer getProtocolSerializer(ProtocolHeader header, Protocol protocol) throws JsonGenerationException, JsonMappingException, IOException {
"""
Serialize the Protocol.
@param header
the ProtocolHeader.
@param protocol
the Protocol.
@return
the ProtocolSerializer.
@throws JsonGenerationException
@throws JsonMappingException
@throws IOException
"""
final String s = serializeProtocol(header, protocol);
return new ProtocolSerializer(){
@Override
public String serializerAsString() {
return s;
}
};
} | java | public static ProtocolSerializer getProtocolSerializer(ProtocolHeader header, Protocol protocol) throws JsonGenerationException, JsonMappingException, IOException{
final String s = serializeProtocol(header, protocol);
return new ProtocolSerializer(){
@Override
public String serializerAsString() {
return s;
}
};
} | [
"public",
"static",
"ProtocolSerializer",
"getProtocolSerializer",
"(",
"ProtocolHeader",
"header",
",",
"Protocol",
"protocol",
")",
"throws",
"JsonGenerationException",
",",
"JsonMappingException",
",",
"IOException",
"{",
"final",
"String",
"s",
"=",
"serializeProtocol",
"(",
"header",
",",
"protocol",
")",
";",
"return",
"new",
"ProtocolSerializer",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"serializerAsString",
"(",
")",
"{",
"return",
"s",
";",
"}",
"}",
";",
"}"
] | Serialize the Protocol.
@param header
the ProtocolHeader.
@param protocol
the Protocol.
@return
the ProtocolSerializer.
@throws JsonGenerationException
@throws JsonMappingException
@throws IOException | [
"Serialize",
"the",
"Protocol",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java#L79-L89 |
cdk/cdk | tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java | MolecularFormulaManipulator.correctMass | private static double correctMass(double mass, Integer charge) {
"""
Correct the mass according the charge of the IMmoleculeFormula.
Negative charge will add the mass of one electron to the mass.
@param mass The mass to correct
@param charge The charge
@return The mass with the correction
"""
if (charge == null)
return mass;
double massE = 0.00054857990927;
if (charge > 0)
mass -= massE * charge;
else if (charge < 0) mass += massE * Math.abs(charge);
return mass;
} | java | private static double correctMass(double mass, Integer charge) {
if (charge == null)
return mass;
double massE = 0.00054857990927;
if (charge > 0)
mass -= massE * charge;
else if (charge < 0) mass += massE * Math.abs(charge);
return mass;
} | [
"private",
"static",
"double",
"correctMass",
"(",
"double",
"mass",
",",
"Integer",
"charge",
")",
"{",
"if",
"(",
"charge",
"==",
"null",
")",
"return",
"mass",
";",
"double",
"massE",
"=",
"0.00054857990927",
";",
"if",
"(",
"charge",
">",
"0",
")",
"mass",
"-=",
"massE",
"*",
"charge",
";",
"else",
"if",
"(",
"charge",
"<",
"0",
")",
"mass",
"+=",
"massE",
"*",
"Math",
".",
"abs",
"(",
"charge",
")",
";",
"return",
"mass",
";",
"}"
] | Correct the mass according the charge of the IMmoleculeFormula.
Negative charge will add the mass of one electron to the mass.
@param mass The mass to correct
@param charge The charge
@return The mass with the correction | [
"Correct",
"the",
"mass",
"according",
"the",
"charge",
"of",
"the",
"IMmoleculeFormula",
".",
"Negative",
"charge",
"will",
"add",
"the",
"mass",
"of",
"one",
"electron",
"to",
"the",
"mass",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L825-L833 |
liferay/com-liferay-commerce | commerce-payment-api/src/main/java/com/liferay/commerce/payment/model/CommercePaymentMethodGroupRelWrapper.java | CommercePaymentMethodGroupRelWrapper.getDescription | @Override
public String getDescription(String languageId, boolean useDefault) {
"""
Returns the localized description of this commerce payment method group rel in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized description of this commerce payment method group rel
"""
return _commercePaymentMethodGroupRel.getDescription(languageId,
useDefault);
} | java | @Override
public String getDescription(String languageId, boolean useDefault) {
return _commercePaymentMethodGroupRel.getDescription(languageId,
useDefault);
} | [
"@",
"Override",
"public",
"String",
"getDescription",
"(",
"String",
"languageId",
",",
"boolean",
"useDefault",
")",
"{",
"return",
"_commercePaymentMethodGroupRel",
".",
"getDescription",
"(",
"languageId",
",",
"useDefault",
")",
";",
"}"
] | Returns the localized description of this commerce payment method group rel in the language, optionally using the default language if no localization exists for the requested language.
@param languageId the ID of the language
@param useDefault whether to use the default language if no localization exists for the requested language
@return the localized description of this commerce payment method group rel | [
"Returns",
"the",
"localized",
"description",
"of",
"this",
"commerce",
"payment",
"method",
"group",
"rel",
"in",
"the",
"language",
"optionally",
"using",
"the",
"default",
"language",
"if",
"no",
"localization",
"exists",
"for",
"the",
"requested",
"language",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-payment-api/src/main/java/com/liferay/commerce/payment/model/CommercePaymentMethodGroupRelWrapper.java#L275-L279 |
irmen/Pyrolite | java/src/main/java/net/razorvine/pickle/PickleUtils.java | PickleUtils.str2bytes | public static byte[] str2bytes(String str) throws IOException {
"""
Convert a string to a byte array, no encoding is used. String must only contain characters <256.
"""
byte[] b=new byte[str.length()];
for(int i=0; i<str.length(); ++i) {
char c=str.charAt(i);
if(c>255) throw new UnsupportedEncodingException("string contained a char > 255, cannot convert to bytes");
b[i]=(byte)c;
}
return b;
} | java | public static byte[] str2bytes(String str) throws IOException {
byte[] b=new byte[str.length()];
for(int i=0; i<str.length(); ++i) {
char c=str.charAt(i);
if(c>255) throw new UnsupportedEncodingException("string contained a char > 255, cannot convert to bytes");
b[i]=(byte)c;
}
return b;
} | [
"public",
"static",
"byte",
"[",
"]",
"str2bytes",
"(",
"String",
"str",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"b",
"=",
"new",
"byte",
"[",
"str",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"str",
".",
"length",
"(",
")",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"c",
">",
"255",
")",
"throw",
"new",
"UnsupportedEncodingException",
"(",
"\"string contained a char > 255, cannot convert to bytes\"",
")",
";",
"b",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"c",
";",
"}",
"return",
"b",
";",
"}"
] | Convert a string to a byte array, no encoding is used. String must only contain characters <256. | [
"Convert",
"a",
"string",
"to",
"a",
"byte",
"array",
"no",
"encoding",
"is",
"used",
".",
"String",
"must",
"only",
"contain",
"characters",
"<256",
"."
] | train | https://github.com/irmen/Pyrolite/blob/060bc3c9069cd31560b6da4f67280736fb2cdf63/java/src/main/java/net/razorvine/pickle/PickleUtils.java#L300-L308 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/XMLUtils.java | XMLUtils.extractXML | public static String extractXML(Node node, int start, int length) {
"""
Extracts a well-formed XML fragment from the given DOM tree.
@param node the root of the DOM tree where the extraction takes place
@param start the index of the first character
@param length the maximum number of characters in text nodes to include in the returned fragment
@return a well-formed XML fragment starting at the given character index and having up to the specified length,
summing only the characters in text nodes
@since 1.6M2
"""
ExtractHandler handler = null;
try {
handler = new ExtractHandler(start, length);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(node), new SAXResult(handler));
return handler.getResult();
} catch (Throwable t) {
if (handler != null && handler.isFinished()) {
return handler.getResult();
} else {
throw new RuntimeException("Failed to extract XML", t);
}
}
} | java | public static String extractXML(Node node, int start, int length)
{
ExtractHandler handler = null;
try {
handler = new ExtractHandler(start, length);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(node), new SAXResult(handler));
return handler.getResult();
} catch (Throwable t) {
if (handler != null && handler.isFinished()) {
return handler.getResult();
} else {
throw new RuntimeException("Failed to extract XML", t);
}
}
} | [
"public",
"static",
"String",
"extractXML",
"(",
"Node",
"node",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"ExtractHandler",
"handler",
"=",
"null",
";",
"try",
"{",
"handler",
"=",
"new",
"ExtractHandler",
"(",
"start",
",",
"length",
")",
";",
"Transformer",
"xformer",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
".",
"newTransformer",
"(",
")",
";",
"xformer",
".",
"transform",
"(",
"new",
"DOMSource",
"(",
"node",
")",
",",
"new",
"SAXResult",
"(",
"handler",
")",
")",
";",
"return",
"handler",
".",
"getResult",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
"handler",
"!=",
"null",
"&&",
"handler",
".",
"isFinished",
"(",
")",
")",
"{",
"return",
"handler",
".",
"getResult",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to extract XML\"",
",",
"t",
")",
";",
"}",
"}",
"}"
] | Extracts a well-formed XML fragment from the given DOM tree.
@param node the root of the DOM tree where the extraction takes place
@param start the index of the first character
@param length the maximum number of characters in text nodes to include in the returned fragment
@return a well-formed XML fragment starting at the given character index and having up to the specified length,
summing only the characters in text nodes
@since 1.6M2 | [
"Extracts",
"a",
"well",
"-",
"formed",
"XML",
"fragment",
"from",
"the",
"given",
"DOM",
"tree",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/XMLUtils.java#L137-L152 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | StrBuilder.midString | public String midString(int index, final int length) {
"""
Extracts some characters from the middle of the string builder without
throwing an exception.
<p>
This method extracts <code>length</code> characters from the builder
at the specified index.
If the index is negative it is treated as zero.
If the index is greater than the builder size, it is treated as the builder size.
If the length is negative, the empty string is returned.
If insufficient characters are available in the builder, as much as possible is returned.
Thus the returned string may be shorter than the length requested.
@param index the index to start at, negative means zero
@param length the number of characters to extract, negative returns empty string
@return the new string
"""
if (index < 0) {
index = 0;
}
if (length <= 0 || index >= size) {
return StringUtils.EMPTY;
}
if (size <= index + length) {
return new String(buffer, index, size - index);
}
return new String(buffer, index, length);
} | java | public String midString(int index, final int length) {
if (index < 0) {
index = 0;
}
if (length <= 0 || index >= size) {
return StringUtils.EMPTY;
}
if (size <= index + length) {
return new String(buffer, index, size - index);
}
return new String(buffer, index, length);
} | [
"public",
"String",
"midString",
"(",
"int",
"index",
",",
"final",
"int",
"length",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"index",
"=",
"0",
";",
"}",
"if",
"(",
"length",
"<=",
"0",
"||",
"index",
">=",
"size",
")",
"{",
"return",
"StringUtils",
".",
"EMPTY",
";",
"}",
"if",
"(",
"size",
"<=",
"index",
"+",
"length",
")",
"{",
"return",
"new",
"String",
"(",
"buffer",
",",
"index",
",",
"size",
"-",
"index",
")",
";",
"}",
"return",
"new",
"String",
"(",
"buffer",
",",
"index",
",",
"length",
")",
";",
"}"
] | Extracts some characters from the middle of the string builder without
throwing an exception.
<p>
This method extracts <code>length</code> characters from the builder
at the specified index.
If the index is negative it is treated as zero.
If the index is greater than the builder size, it is treated as the builder size.
If the length is negative, the empty string is returned.
If insufficient characters are available in the builder, as much as possible is returned.
Thus the returned string may be shorter than the length requested.
@param index the index to start at, negative means zero
@param length the number of characters to extract, negative returns empty string
@return the new string | [
"Extracts",
"some",
"characters",
"from",
"the",
"middle",
"of",
"the",
"string",
"builder",
"without",
"throwing",
"an",
"exception",
".",
"<p",
">",
"This",
"method",
"extracts",
"<code",
">",
"length<",
"/",
"code",
">",
"characters",
"from",
"the",
"builder",
"at",
"the",
"specified",
"index",
".",
"If",
"the",
"index",
"is",
"negative",
"it",
"is",
"treated",
"as",
"zero",
".",
"If",
"the",
"index",
"is",
"greater",
"than",
"the",
"builder",
"size",
"it",
"is",
"treated",
"as",
"the",
"builder",
"size",
".",
"If",
"the",
"length",
"is",
"negative",
"the",
"empty",
"string",
"is",
"returned",
".",
"If",
"insufficient",
"characters",
"are",
"available",
"in",
"the",
"builder",
"as",
"much",
"as",
"possible",
"is",
"returned",
".",
"Thus",
"the",
"returned",
"string",
"may",
"be",
"shorter",
"than",
"the",
"length",
"requested",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L2344-L2355 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/helpers/DateHelper.java | DateHelper.getUTCMilliseconds | public static long getUTCMilliseconds(@NonNull final String dateStr) {
"""
Gets the UTC time in milliseconds from 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'' formatted date string.
@param dateStr 'yyyy-MM-dd'T'HH:mm:ss.SSSz' formatted date string.
@return UTC time in milliseconds.
"""
if (!TextUtils.isEmpty(dateStr)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
return date.getTime();
}
}
return -1;
} | java | public static long getUTCMilliseconds(@NonNull final String dateStr) {
if (!TextUtils.isEmpty(dateStr)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
return date.getTime();
}
}
return -1;
} | [
"public",
"static",
"long",
"getUTCMilliseconds",
"(",
"@",
"NonNull",
"final",
"String",
"dateStr",
")",
"{",
"if",
"(",
"!",
"TextUtils",
".",
"isEmpty",
"(",
"dateStr",
")",
")",
"{",
"DateFormat",
"sdf",
"=",
"new",
"SimpleDateFormat",
"(",
"\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"",
",",
"Locale",
".",
"ENGLISH",
")",
";",
"sdf",
".",
"setTimeZone",
"(",
"TimeZone",
".",
"getTimeZone",
"(",
"\"UTC\"",
")",
")",
";",
"Date",
"date",
"=",
"null",
";",
"try",
"{",
"date",
"=",
"sdf",
".",
"parse",
"(",
"dateStr",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"if",
"(",
"date",
"!=",
"null",
")",
"{",
"return",
"date",
".",
"getTime",
"(",
")",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Gets the UTC time in milliseconds from 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'' formatted date string.
@param dateStr 'yyyy-MM-dd'T'HH:mm:ss.SSSz' formatted date string.
@return UTC time in milliseconds. | [
"Gets",
"the",
"UTC",
"time",
"in",
"milliseconds",
"from",
"yyyy",
"-",
"MM",
"-",
"dd",
"T",
"HH",
":",
"mm",
":",
"ss",
".",
"SSS",
"Z",
"formatted",
"date",
"string",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/helpers/DateHelper.java#L59-L78 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java | SchemaService.deleteApplication | public void deleteApplication(ApplicationDefinition appDef, String key) {
"""
Delete the application with the given definition, including all of its data. The
given {@link ApplicationDefinition} must define the tenant in which the application
resides. If the given application doesn't exist, the call is a no-op. If the
application exists, the given key must match the current key, if one is defined, or
be null/empty if no key is defined.
@param appDef {@link ApplicationDefinition} of application to delete.
@param key Application key of existing application, if any.
"""
checkServiceState();
String appKey = appDef.getKey();
if (Utils.isEmpty(appKey)) {
Utils.require(Utils.isEmpty(key), "Application key does not match: %s", key);
} else {
Utils.require(appKey.equals(key), "Application key does not match: %s", key);
}
assert Tenant.getTenant(appDef) != null;
// Delete storage service-specific data first.
m_logger.info("Deleting application: {}", appDef.getAppName());
StorageService storageService = getStorageService(appDef);
storageService.deleteApplication(appDef);
TaskManagerService.instance().deleteApplicationTasks(appDef);
deleteAppProperties(appDef);
} | java | public void deleteApplication(ApplicationDefinition appDef, String key) {
checkServiceState();
String appKey = appDef.getKey();
if (Utils.isEmpty(appKey)) {
Utils.require(Utils.isEmpty(key), "Application key does not match: %s", key);
} else {
Utils.require(appKey.equals(key), "Application key does not match: %s", key);
}
assert Tenant.getTenant(appDef) != null;
// Delete storage service-specific data first.
m_logger.info("Deleting application: {}", appDef.getAppName());
StorageService storageService = getStorageService(appDef);
storageService.deleteApplication(appDef);
TaskManagerService.instance().deleteApplicationTasks(appDef);
deleteAppProperties(appDef);
} | [
"public",
"void",
"deleteApplication",
"(",
"ApplicationDefinition",
"appDef",
",",
"String",
"key",
")",
"{",
"checkServiceState",
"(",
")",
";",
"String",
"appKey",
"=",
"appDef",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"Utils",
".",
"isEmpty",
"(",
"appKey",
")",
")",
"{",
"Utils",
".",
"require",
"(",
"Utils",
".",
"isEmpty",
"(",
"key",
")",
",",
"\"Application key does not match: %s\"",
",",
"key",
")",
";",
"}",
"else",
"{",
"Utils",
".",
"require",
"(",
"appKey",
".",
"equals",
"(",
"key",
")",
",",
"\"Application key does not match: %s\"",
",",
"key",
")",
";",
"}",
"assert",
"Tenant",
".",
"getTenant",
"(",
"appDef",
")",
"!=",
"null",
";",
"// Delete storage service-specific data first.\r",
"m_logger",
".",
"info",
"(",
"\"Deleting application: {}\"",
",",
"appDef",
".",
"getAppName",
"(",
")",
")",
";",
"StorageService",
"storageService",
"=",
"getStorageService",
"(",
"appDef",
")",
";",
"storageService",
".",
"deleteApplication",
"(",
"appDef",
")",
";",
"TaskManagerService",
".",
"instance",
"(",
")",
".",
"deleteApplicationTasks",
"(",
"appDef",
")",
";",
"deleteAppProperties",
"(",
"appDef",
")",
";",
"}"
] | Delete the application with the given definition, including all of its data. The
given {@link ApplicationDefinition} must define the tenant in which the application
resides. If the given application doesn't exist, the call is a no-op. If the
application exists, the given key must match the current key, if one is defined, or
be null/empty if no key is defined.
@param appDef {@link ApplicationDefinition} of application to delete.
@param key Application key of existing application, if any. | [
"Delete",
"the",
"application",
"with",
"the",
"given",
"definition",
"including",
"all",
"of",
"its",
"data",
".",
"The",
"given",
"{",
"@link",
"ApplicationDefinition",
"}",
"must",
"define",
"the",
"tenant",
"in",
"which",
"the",
"application",
"resides",
".",
"If",
"the",
"given",
"application",
"doesn",
"t",
"exist",
"the",
"call",
"is",
"a",
"no",
"-",
"op",
".",
"If",
"the",
"application",
"exists",
"the",
"given",
"key",
"must",
"match",
"the",
"current",
"key",
"if",
"one",
"is",
"defined",
"or",
"be",
"null",
"/",
"empty",
"if",
"no",
"key",
"is",
"defined",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/schema/SchemaService.java#L262-L278 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/validation/repeater/RepeaterExample.java | RepeaterExample.preparePaintComponent | @Override
protected void preparePaintComponent(final Request request) {
"""
Override preparepaint to initialise the data on first acecss by a user.
@param request the request being responded to.
"""
if (!isInitialised()) {
MyDataBean myBean = new MyDataBean();
myBean.setName("My Bean");
myBean.addBean(new SomeDataBean("blah", "more blah"));
myBean.addBean(new SomeDataBean());
repeaterFields.setData(myBean);
setInitialised(true);
}
} | java | @Override
protected void preparePaintComponent(final Request request) {
if (!isInitialised()) {
MyDataBean myBean = new MyDataBean();
myBean.setName("My Bean");
myBean.addBean(new SomeDataBean("blah", "more blah"));
myBean.addBean(new SomeDataBean());
repeaterFields.setData(myBean);
setInitialised(true);
}
} | [
"@",
"Override",
"protected",
"void",
"preparePaintComponent",
"(",
"final",
"Request",
"request",
")",
"{",
"if",
"(",
"!",
"isInitialised",
"(",
")",
")",
"{",
"MyDataBean",
"myBean",
"=",
"new",
"MyDataBean",
"(",
")",
";",
"myBean",
".",
"setName",
"(",
"\"My Bean\"",
")",
";",
"myBean",
".",
"addBean",
"(",
"new",
"SomeDataBean",
"(",
"\"blah\"",
",",
"\"more blah\"",
")",
")",
";",
"myBean",
".",
"addBean",
"(",
"new",
"SomeDataBean",
"(",
")",
")",
";",
"repeaterFields",
".",
"setData",
"(",
"myBean",
")",
";",
"setInitialised",
"(",
"true",
")",
";",
"}",
"}"
] | Override preparepaint to initialise the data on first acecss by a user.
@param request the request being responded to. | [
"Override",
"preparepaint",
"to",
"initialise",
"the",
"data",
"on",
"first",
"acecss",
"by",
"a",
"user",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/validation/repeater/RepeaterExample.java#L90-L103 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java | ParseUtils.requireNamespace | public static void requireNamespace(final XMLExtendedStreamReader reader, final Namespace requiredNs) throws XMLStreamException {
"""
Require that the namespace of the current element matches the required namespace.
@param reader the reader
@param requiredNs the namespace required
@throws XMLStreamException if the current namespace does not match the required namespace
"""
Namespace actualNs = Namespace.forUri(reader.getNamespaceURI());
if (actualNs != requiredNs) {
throw unexpectedElement(reader);
}
} | java | public static void requireNamespace(final XMLExtendedStreamReader reader, final Namespace requiredNs) throws XMLStreamException {
Namespace actualNs = Namespace.forUri(reader.getNamespaceURI());
if (actualNs != requiredNs) {
throw unexpectedElement(reader);
}
} | [
"public",
"static",
"void",
"requireNamespace",
"(",
"final",
"XMLExtendedStreamReader",
"reader",
",",
"final",
"Namespace",
"requiredNs",
")",
"throws",
"XMLStreamException",
"{",
"Namespace",
"actualNs",
"=",
"Namespace",
".",
"forUri",
"(",
"reader",
".",
"getNamespaceURI",
"(",
")",
")",
";",
"if",
"(",
"actualNs",
"!=",
"requiredNs",
")",
"{",
"throw",
"unexpectedElement",
"(",
"reader",
")",
";",
"}",
"}"
] | Require that the namespace of the current element matches the required namespace.
@param reader the reader
@param requiredNs the namespace required
@throws XMLStreamException if the current namespace does not match the required namespace | [
"Require",
"that",
"the",
"namespace",
"of",
"the",
"current",
"element",
"matches",
"the",
"required",
"namespace",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/parsing/ParseUtils.java#L333-L338 |
GoogleCloudPlatform/bigdata-interop | bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/DynamicFileListRecordReader.java | DynamicFileListRecordReader.parseFileIndex | private int parseFileIndex(String fileName) {
"""
Parses the numerical index out of a String which matches exportPattern; the exportPattern
should have been compiled from a regex that looks like "data-(\d+).json".
@throws IndexOutOfBoundsException if the parsed value is greater than Integer.MAX_VALUE.
"""
Matcher match = null;
String indexString = null;
try {
match = exportPattern.matcher(fileName);
match.find();
indexString = match.group(1);
} catch (Exception e) {
throw new IllegalStateException(String.format("Failed to parse file '%s'", fileName), e);
}
long longValue = Long.parseLong(indexString);
if (longValue > Integer.MAX_VALUE) {
throw new IndexOutOfBoundsException(String.format(
"Invalid fileName '%s'; max allowable index is %d, got %d instead",
fileName, Integer.MAX_VALUE, longValue));
}
return (int) longValue;
} | java | private int parseFileIndex(String fileName) {
Matcher match = null;
String indexString = null;
try {
match = exportPattern.matcher(fileName);
match.find();
indexString = match.group(1);
} catch (Exception e) {
throw new IllegalStateException(String.format("Failed to parse file '%s'", fileName), e);
}
long longValue = Long.parseLong(indexString);
if (longValue > Integer.MAX_VALUE) {
throw new IndexOutOfBoundsException(String.format(
"Invalid fileName '%s'; max allowable index is %d, got %d instead",
fileName, Integer.MAX_VALUE, longValue));
}
return (int) longValue;
} | [
"private",
"int",
"parseFileIndex",
"(",
"String",
"fileName",
")",
"{",
"Matcher",
"match",
"=",
"null",
";",
"String",
"indexString",
"=",
"null",
";",
"try",
"{",
"match",
"=",
"exportPattern",
".",
"matcher",
"(",
"fileName",
")",
";",
"match",
".",
"find",
"(",
")",
";",
"indexString",
"=",
"match",
".",
"group",
"(",
"1",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"Failed to parse file '%s'\"",
",",
"fileName",
")",
",",
"e",
")",
";",
"}",
"long",
"longValue",
"=",
"Long",
".",
"parseLong",
"(",
"indexString",
")",
";",
"if",
"(",
"longValue",
">",
"Integer",
".",
"MAX_VALUE",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"String",
".",
"format",
"(",
"\"Invalid fileName '%s'; max allowable index is %d, got %d instead\"",
",",
"fileName",
",",
"Integer",
".",
"MAX_VALUE",
",",
"longValue",
")",
")",
";",
"}",
"return",
"(",
"int",
")",
"longValue",
";",
"}"
] | Parses the numerical index out of a String which matches exportPattern; the exportPattern
should have been compiled from a regex that looks like "data-(\d+).json".
@throws IndexOutOfBoundsException if the parsed value is greater than Integer.MAX_VALUE. | [
"Parses",
"the",
"numerical",
"index",
"out",
"of",
"a",
"String",
"which",
"matches",
"exportPattern",
";",
"the",
"exportPattern",
"should",
"have",
"been",
"compiled",
"from",
"a",
"regex",
"that",
"looks",
"like",
"data",
"-",
"(",
"\\",
"d",
"+",
")",
".",
"json",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/bigquery/src/main/java/com/google/cloud/hadoop/io/bigquery/DynamicFileListRecordReader.java#L309-L326 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java | MethodUtils.getMethodsWithAnnotation | public static Method[] getMethodsWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls) {
"""
Gets all class level public methods of the given class that are annotated with the given annotation.
@param cls
the {@link Class} to query
@param annotationCls
the {@link java.lang.annotation.Annotation} that must be present on a method to be matched
@return an array of Methods (possibly empty).
@throws IllegalArgumentException
if the class or annotation are {@code null}
@since 3.4
"""
return getMethodsWithAnnotation(cls, annotationCls, false, false);
} | java | public static Method[] getMethodsWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls) {
return getMethodsWithAnnotation(cls, annotationCls, false, false);
} | [
"public",
"static",
"Method",
"[",
"]",
"getMethodsWithAnnotation",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationCls",
")",
"{",
"return",
"getMethodsWithAnnotation",
"(",
"cls",
",",
"annotationCls",
",",
"false",
",",
"false",
")",
";",
"}"
] | Gets all class level public methods of the given class that are annotated with the given annotation.
@param cls
the {@link Class} to query
@param annotationCls
the {@link java.lang.annotation.Annotation} that must be present on a method to be matched
@return an array of Methods (possibly empty).
@throws IllegalArgumentException
if the class or annotation are {@code null}
@since 3.4 | [
"Gets",
"all",
"class",
"level",
"public",
"methods",
"of",
"the",
"given",
"class",
"that",
"are",
"annotated",
"with",
"the",
"given",
"annotation",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java#L846-L848 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/style/ColorUtils.java | ColorUtils.toColorWithAlpha | public static int toColorWithAlpha(int red, int green, int blue, int alpha) {
"""
Convert the RBGA values to a color integer
@param red
red integer color inclusively between 0 and 255
@param green
green integer color inclusively between 0 and 255
@param blue
blue integer color inclusively between 0 and 255
@param alpha
alpha integer color inclusively between 0 and 255, -1 to not
include alpha
@return integer color
"""
validateRGB(red);
validateRGB(green);
validateRGB(blue);
int color = (red & 0xff) << 16 | (green & 0xff) << 8 | (blue & 0xff);
if (alpha != -1) {
validateRGB(alpha);
color = (alpha & 0xff) << 24 | color;
}
return color;
} | java | public static int toColorWithAlpha(int red, int green, int blue, int alpha) {
validateRGB(red);
validateRGB(green);
validateRGB(blue);
int color = (red & 0xff) << 16 | (green & 0xff) << 8 | (blue & 0xff);
if (alpha != -1) {
validateRGB(alpha);
color = (alpha & 0xff) << 24 | color;
}
return color;
} | [
"public",
"static",
"int",
"toColorWithAlpha",
"(",
"int",
"red",
",",
"int",
"green",
",",
"int",
"blue",
",",
"int",
"alpha",
")",
"{",
"validateRGB",
"(",
"red",
")",
";",
"validateRGB",
"(",
"green",
")",
";",
"validateRGB",
"(",
"blue",
")",
";",
"int",
"color",
"=",
"(",
"red",
"&",
"0xff",
")",
"<<",
"16",
"|",
"(",
"green",
"&",
"0xff",
")",
"<<",
"8",
"|",
"(",
"blue",
"&",
"0xff",
")",
";",
"if",
"(",
"alpha",
"!=",
"-",
"1",
")",
"{",
"validateRGB",
"(",
"alpha",
")",
";",
"color",
"=",
"(",
"alpha",
"&",
"0xff",
")",
"<<",
"24",
"|",
"color",
";",
"}",
"return",
"color",
";",
"}"
] | Convert the RBGA values to a color integer
@param red
red integer color inclusively between 0 and 255
@param green
green integer color inclusively between 0 and 255
@param blue
blue integer color inclusively between 0 and 255
@param alpha
alpha integer color inclusively between 0 and 255, -1 to not
include alpha
@return integer color | [
"Convert",
"the",
"RBGA",
"values",
"to",
"a",
"color",
"integer"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/style/ColorUtils.java#L196-L206 |
google/closure-compiler | src/com/google/javascript/jscomp/SymbolTable.java | SymbolTable.isAnySymbolDeclared | private Symbol isAnySymbolDeclared(String name, Node declNode, SymbolScope scope) {
"""
Checks if any symbol is already declared at the given node and scope for the given name. If so,
returns it.
"""
Symbol sym = symbols.get(declNode, name);
if (sym == null) {
// Sometimes, our symbol tables will disagree on where the
// declaration node should be. In the rare case where this happens,
// trust the existing symbol.
// See SymbolTableTest#testDeclarationDisagreement.
return scope.ownSymbols.get(name);
}
return sym;
} | java | private Symbol isAnySymbolDeclared(String name, Node declNode, SymbolScope scope) {
Symbol sym = symbols.get(declNode, name);
if (sym == null) {
// Sometimes, our symbol tables will disagree on where the
// declaration node should be. In the rare case where this happens,
// trust the existing symbol.
// See SymbolTableTest#testDeclarationDisagreement.
return scope.ownSymbols.get(name);
}
return sym;
} | [
"private",
"Symbol",
"isAnySymbolDeclared",
"(",
"String",
"name",
",",
"Node",
"declNode",
",",
"SymbolScope",
"scope",
")",
"{",
"Symbol",
"sym",
"=",
"symbols",
".",
"get",
"(",
"declNode",
",",
"name",
")",
";",
"if",
"(",
"sym",
"==",
"null",
")",
"{",
"// Sometimes, our symbol tables will disagree on where the",
"// declaration node should be. In the rare case where this happens,",
"// trust the existing symbol.",
"// See SymbolTableTest#testDeclarationDisagreement.",
"return",
"scope",
".",
"ownSymbols",
".",
"get",
"(",
"name",
")",
";",
"}",
"return",
"sym",
";",
"}"
] | Checks if any symbol is already declared at the given node and scope for the given name. If so,
returns it. | [
"Checks",
"if",
"any",
"symbol",
"is",
"already",
"declared",
"at",
"the",
"given",
"node",
"and",
"scope",
"for",
"the",
"given",
"name",
".",
"If",
"so",
"returns",
"it",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/SymbolTable.java#L562-L572 |
HeidelTime/heideltime | src/de/unihd/dbs/uima/annotator/heideltime/ProcessorManager.java | ProcessorManager.registerProcessor | public void registerProcessor(String processor, Priority prio) {
"""
method to register a processor
@param processor processor to be registered in the processormanager's list
@param p priority for the process to take
"""
this.processorNames.get(prio).add(processor);
} | java | public void registerProcessor(String processor, Priority prio) {
this.processorNames.get(prio).add(processor);
} | [
"public",
"void",
"registerProcessor",
"(",
"String",
"processor",
",",
"Priority",
"prio",
")",
"{",
"this",
".",
"processorNames",
".",
"get",
"(",
"prio",
")",
".",
"add",
"(",
"processor",
")",
";",
"}"
] | method to register a processor
@param processor processor to be registered in the processormanager's list
@param p priority for the process to take | [
"method",
"to",
"register",
"a",
"processor"
] | train | https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/ProcessorManager.java#L51-L53 |
pravega/pravega | client/src/main/java/io/pravega/client/admin/impl/StreamCutHelper.java | StreamCutHelper.fetchHeadStreamCut | public CompletableFuture<StreamCut> fetchHeadStreamCut(final Stream stream) {
"""
Obtain the {@link StreamCut} pointing to the current HEAD of the Stream.
@param stream The Stream.
@return {@link StreamCut} pointing to the HEAD of the Stream.
"""
//Fetch segments pointing to the current HEAD of the stream.
return controller.getSegmentsAtTime(new StreamImpl(stream.getScope(), stream.getStreamName()), 0L)
.thenApply( s -> new StreamCutImpl(stream, s));
} | java | public CompletableFuture<StreamCut> fetchHeadStreamCut(final Stream stream) {
//Fetch segments pointing to the current HEAD of the stream.
return controller.getSegmentsAtTime(new StreamImpl(stream.getScope(), stream.getStreamName()), 0L)
.thenApply( s -> new StreamCutImpl(stream, s));
} | [
"public",
"CompletableFuture",
"<",
"StreamCut",
">",
"fetchHeadStreamCut",
"(",
"final",
"Stream",
"stream",
")",
"{",
"//Fetch segments pointing to the current HEAD of the stream.",
"return",
"controller",
".",
"getSegmentsAtTime",
"(",
"new",
"StreamImpl",
"(",
"stream",
".",
"getScope",
"(",
")",
",",
"stream",
".",
"getStreamName",
"(",
")",
")",
",",
"0L",
")",
".",
"thenApply",
"(",
"s",
"->",
"new",
"StreamCutImpl",
"(",
"stream",
",",
"s",
")",
")",
";",
"}"
] | Obtain the {@link StreamCut} pointing to the current HEAD of the Stream.
@param stream The Stream.
@return {@link StreamCut} pointing to the HEAD of the Stream. | [
"Obtain",
"the",
"{"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/admin/impl/StreamCutHelper.java#L51-L55 |
apereo/cas | core/cas-server-core-configuration-metadata-repository/src/main/java/org/springframework/boot/configurationmetadata/CasConfigurationMetadataRepositoryJsonBuilder.java | CasConfigurationMetadataRepositoryJsonBuilder.withJsonResource | public CasConfigurationMetadataRepositoryJsonBuilder withJsonResource(final InputStream inputStream, final Charset charset) {
"""
Add the content of a {@link ConfigurationMetadataRepository} defined by the
specified {@link InputStream} json document using the specified {@link Charset}. If
this metadata repository holds items that were loaded previously, these are
ignored.
<p>
Leaves the stream open when done.
@param inputStream the source input stream
@param charset the charset of the input
@return this builder
"""
if (inputStream == null) {
throw new IllegalArgumentException("InputStream must not be null.");
}
this.repositories.add(add(inputStream, charset));
return this;
} | java | public CasConfigurationMetadataRepositoryJsonBuilder withJsonResource(final InputStream inputStream, final Charset charset) {
if (inputStream == null) {
throw new IllegalArgumentException("InputStream must not be null.");
}
this.repositories.add(add(inputStream, charset));
return this;
} | [
"public",
"CasConfigurationMetadataRepositoryJsonBuilder",
"withJsonResource",
"(",
"final",
"InputStream",
"inputStream",
",",
"final",
"Charset",
"charset",
")",
"{",
"if",
"(",
"inputStream",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"InputStream must not be null.\"",
")",
";",
"}",
"this",
".",
"repositories",
".",
"add",
"(",
"add",
"(",
"inputStream",
",",
"charset",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add the content of a {@link ConfigurationMetadataRepository} defined by the
specified {@link InputStream} json document using the specified {@link Charset}. If
this metadata repository holds items that were loaded previously, these are
ignored.
<p>
Leaves the stream open when done.
@param inputStream the source input stream
@param charset the charset of the input
@return this builder | [
"Add",
"the",
"content",
"of",
"a",
"{",
"@link",
"ConfigurationMetadataRepository",
"}",
"defined",
"by",
"the",
"specified",
"{",
"@link",
"InputStream",
"}",
"json",
"document",
"using",
"the",
"specified",
"{",
"@link",
"Charset",
"}",
".",
"If",
"this",
"metadata",
"repository",
"holds",
"items",
"that",
"were",
"loaded",
"previously",
"these",
"are",
"ignored",
".",
"<p",
">",
"Leaves",
"the",
"stream",
"open",
"when",
"done",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-configuration-metadata-repository/src/main/java/org/springframework/boot/configurationmetadata/CasConfigurationMetadataRepositoryJsonBuilder.java#L58-L64 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/ImageBuffer.java | ImageBuffer.setRGBA | public void setRGBA(int x, int y, int r, int g, int b, int a) {
"""
Set a pixel in the image buffer
@param x The x position of the pixel to set
@param y The y position of the pixel to set
@param r The red component to set (0->255)
@param g The green component to set (0->255)
@param b The blue component to set (0->255)
@param a The alpha component to set (0->255)
"""
if ((x < 0) || (x >= width) || (y < 0) || (y >= height)) {
throw new RuntimeException("Specified location: "+x+","+y+" outside of image");
}
int ofs = ((x + (y * texWidth)) * 4);
if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
rawData[ofs] = (byte) b;
rawData[ofs + 1] = (byte) g;
rawData[ofs + 2] = (byte) r;
rawData[ofs + 3] = (byte) a;
} else {
rawData[ofs] = (byte) r;
rawData[ofs + 1] = (byte) g;
rawData[ofs + 2] = (byte) b;
rawData[ofs + 3] = (byte) a;
}
} | java | public void setRGBA(int x, int y, int r, int g, int b, int a) {
if ((x < 0) || (x >= width) || (y < 0) || (y >= height)) {
throw new RuntimeException("Specified location: "+x+","+y+" outside of image");
}
int ofs = ((x + (y * texWidth)) * 4);
if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) {
rawData[ofs] = (byte) b;
rawData[ofs + 1] = (byte) g;
rawData[ofs + 2] = (byte) r;
rawData[ofs + 3] = (byte) a;
} else {
rawData[ofs] = (byte) r;
rawData[ofs + 1] = (byte) g;
rawData[ofs + 2] = (byte) b;
rawData[ofs + 3] = (byte) a;
}
} | [
"public",
"void",
"setRGBA",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
",",
"int",
"a",
")",
"{",
"if",
"(",
"(",
"x",
"<",
"0",
")",
"||",
"(",
"x",
">=",
"width",
")",
"||",
"(",
"y",
"<",
"0",
")",
"||",
"(",
"y",
">=",
"height",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Specified location: \"",
"+",
"x",
"+",
"\",\"",
"+",
"y",
"+",
"\" outside of image\"",
")",
";",
"}",
"int",
"ofs",
"=",
"(",
"(",
"x",
"+",
"(",
"y",
"*",
"texWidth",
")",
")",
"*",
"4",
")",
";",
"if",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
"==",
"ByteOrder",
".",
"BIG_ENDIAN",
")",
"{",
"rawData",
"[",
"ofs",
"]",
"=",
"(",
"byte",
")",
"b",
";",
"rawData",
"[",
"ofs",
"+",
"1",
"]",
"=",
"(",
"byte",
")",
"g",
";",
"rawData",
"[",
"ofs",
"+",
"2",
"]",
"=",
"(",
"byte",
")",
"r",
";",
"rawData",
"[",
"ofs",
"+",
"3",
"]",
"=",
"(",
"byte",
")",
"a",
";",
"}",
"else",
"{",
"rawData",
"[",
"ofs",
"]",
"=",
"(",
"byte",
")",
"r",
";",
"rawData",
"[",
"ofs",
"+",
"1",
"]",
"=",
"(",
"byte",
")",
"g",
";",
"rawData",
"[",
"ofs",
"+",
"2",
"]",
"=",
"(",
"byte",
")",
"b",
";",
"rawData",
"[",
"ofs",
"+",
"3",
"]",
"=",
"(",
"byte",
")",
"a",
";",
"}",
"}"
] | Set a pixel in the image buffer
@param x The x position of the pixel to set
@param y The y position of the pixel to set
@param r The red component to set (0->255)
@param g The green component to set (0->255)
@param b The blue component to set (0->255)
@param a The alpha component to set (0->255) | [
"Set",
"a",
"pixel",
"in",
"the",
"image",
"buffer"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/ImageBuffer.java#L114-L132 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java | KMLWriterDriver.getKMLType | private static String getKMLType(int sqlTypeId, String sqlTypeName) throws SQLException {
"""
Return the kml type representation from SQL data type
@param sqlTypeId
@param sqlTypeName
@return
@throws SQLException
"""
switch (sqlTypeId) {
case Types.BOOLEAN:
return "bool";
case Types.DOUBLE:
return "double";
case Types.FLOAT:
return "float";
case Types.INTEGER:
case Types.BIGINT:
return "int";
case Types.SMALLINT:
return "short";
case Types.DATE:
case Types.VARCHAR:
case Types.NCHAR:
case Types.CHAR:
return "string";
default:
throw new SQLException("Field type not supported by KML : " + sqlTypeName);
}
} | java | private static String getKMLType(int sqlTypeId, String sqlTypeName) throws SQLException {
switch (sqlTypeId) {
case Types.BOOLEAN:
return "bool";
case Types.DOUBLE:
return "double";
case Types.FLOAT:
return "float";
case Types.INTEGER:
case Types.BIGINT:
return "int";
case Types.SMALLINT:
return "short";
case Types.DATE:
case Types.VARCHAR:
case Types.NCHAR:
case Types.CHAR:
return "string";
default:
throw new SQLException("Field type not supported by KML : " + sqlTypeName);
}
} | [
"private",
"static",
"String",
"getKMLType",
"(",
"int",
"sqlTypeId",
",",
"String",
"sqlTypeName",
")",
"throws",
"SQLException",
"{",
"switch",
"(",
"sqlTypeId",
")",
"{",
"case",
"Types",
".",
"BOOLEAN",
":",
"return",
"\"bool\"",
";",
"case",
"Types",
".",
"DOUBLE",
":",
"return",
"\"double\"",
";",
"case",
"Types",
".",
"FLOAT",
":",
"return",
"\"float\"",
";",
"case",
"Types",
".",
"INTEGER",
":",
"case",
"Types",
".",
"BIGINT",
":",
"return",
"\"int\"",
";",
"case",
"Types",
".",
"SMALLINT",
":",
"return",
"\"short\"",
";",
"case",
"Types",
".",
"DATE",
":",
"case",
"Types",
".",
"VARCHAR",
":",
"case",
"Types",
".",
"NCHAR",
":",
"case",
"Types",
".",
"CHAR",
":",
"return",
"\"string\"",
";",
"default",
":",
"throw",
"new",
"SQLException",
"(",
"\"Field type not supported by KML : \"",
"+",
"sqlTypeName",
")",
";",
"}",
"}"
] | Return the kml type representation from SQL data type
@param sqlTypeId
@param sqlTypeName
@return
@throws SQLException | [
"Return",
"the",
"kml",
"type",
"representation",
"from",
"SQL",
"data",
"type"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java#L377-L398 |
jqno/equalsverifier | src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java | ConditionalInstantiator.callFactory | public <T> T callFactory(String factoryMethod, Class<?>[] paramTypes, Object[] paramValues) {
"""
Attempts to call a static factory method on the type.
@param <T>
The return type of the factory method.
@param factoryMethod
The name of the factory method.
@param paramTypes
The types of the parameters of the specific overload of the
factory method we want to call.
@param paramValues
The values that we want to pass into the factory method.
@return An instance of the type given by the factory method with the
given parameter values, or null of the type does not exist.
@throws ReflectionException
If the call to the factory method fails.
"""
return callFactory(fullyQualifiedClassName, factoryMethod, paramTypes, paramValues);
} | java | public <T> T callFactory(String factoryMethod, Class<?>[] paramTypes, Object[] paramValues) {
return callFactory(fullyQualifiedClassName, factoryMethod, paramTypes, paramValues);
} | [
"public",
"<",
"T",
">",
"T",
"callFactory",
"(",
"String",
"factoryMethod",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
",",
"Object",
"[",
"]",
"paramValues",
")",
"{",
"return",
"callFactory",
"(",
"fullyQualifiedClassName",
",",
"factoryMethod",
",",
"paramTypes",
",",
"paramValues",
")",
";",
"}"
] | Attempts to call a static factory method on the type.
@param <T>
The return type of the factory method.
@param factoryMethod
The name of the factory method.
@param paramTypes
The types of the parameters of the specific overload of the
factory method we want to call.
@param paramValues
The values that we want to pass into the factory method.
@return An instance of the type given by the factory method with the
given parameter values, or null of the type does not exist.
@throws ReflectionException
If the call to the factory method fails. | [
"Attempts",
"to",
"call",
"a",
"static",
"factory",
"method",
"on",
"the",
"type",
"."
] | train | https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java#L102-L104 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java | PropertyBuilder.getInstance | public static PropertyBuilder getInstance(Context context,
TypeElement typeElement,
PropertyWriter writer) {
"""
Construct a new PropertyBuilder.
@param context the build context.
@param typeElement the class whoses members are being documented.
@param writer the doclet specific writer.
@return the new PropertyBuilder
"""
return new PropertyBuilder(context, typeElement, writer);
} | java | public static PropertyBuilder getInstance(Context context,
TypeElement typeElement,
PropertyWriter writer) {
return new PropertyBuilder(context, typeElement, writer);
} | [
"public",
"static",
"PropertyBuilder",
"getInstance",
"(",
"Context",
"context",
",",
"TypeElement",
"typeElement",
",",
"PropertyWriter",
"writer",
")",
"{",
"return",
"new",
"PropertyBuilder",
"(",
"context",
",",
"typeElement",
",",
"writer",
")",
";",
"}"
] | Construct a new PropertyBuilder.
@param context the build context.
@param typeElement the class whoses members are being documented.
@param writer the doclet specific writer.
@return the new PropertyBuilder | [
"Construct",
"a",
"new",
"PropertyBuilder",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java#L106-L110 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.subtractEquals | public static void subtractEquals(DMatrixD1 a, DMatrixD1 b) {
"""
<p>Performs the following subtraction operation:<br>
<br>
a = a - b <br>
a<sub>ij</sub> = a<sub>ij</sub> - b<sub>ij</sub>
</p>
@param a A Matrix. Modified.
@param b A Matrix. Not modified.
"""
if( a.numCols != b.numCols || a.numRows != b.numRows ) {
throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions");
}
final int length = a.getNumElements();
for( int i = 0; i < length; i++ ) {
a.data[i] -= b.data[i];
}
} | java | public static void subtractEquals(DMatrixD1 a, DMatrixD1 b)
{
if( a.numCols != b.numCols || a.numRows != b.numRows ) {
throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions");
}
final int length = a.getNumElements();
for( int i = 0; i < length; i++ ) {
a.data[i] -= b.data[i];
}
} | [
"public",
"static",
"void",
"subtractEquals",
"(",
"DMatrixD1",
"a",
",",
"DMatrixD1",
"b",
")",
"{",
"if",
"(",
"a",
".",
"numCols",
"!=",
"b",
".",
"numCols",
"||",
"a",
".",
"numRows",
"!=",
"b",
".",
"numRows",
")",
"{",
"throw",
"new",
"MatrixDimensionException",
"(",
"\"The 'a' and 'b' matrices do not have compatible dimensions\"",
")",
";",
"}",
"final",
"int",
"length",
"=",
"a",
".",
"getNumElements",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"a",
".",
"data",
"[",
"i",
"]",
"-=",
"b",
".",
"data",
"[",
"i",
"]",
";",
"}",
"}"
] | <p>Performs the following subtraction operation:<br>
<br>
a = a - b <br>
a<sub>ij</sub> = a<sub>ij</sub> - b<sub>ij</sub>
</p>
@param a A Matrix. Modified.
@param b A Matrix. Not modified. | [
"<p",
">",
"Performs",
"the",
"following",
"subtraction",
"operation",
":",
"<br",
">",
"<br",
">",
"a",
"=",
"a",
"-",
"b",
"<br",
">",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"-",
"b<sub",
">",
"ij<",
"/",
"sub",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L2307-L2318 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/spillover/spilloveraction.java | spilloveraction.get | public static spilloveraction get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch spilloveraction resource of given name .
"""
spilloveraction obj = new spilloveraction();
obj.set_name(name);
spilloveraction response = (spilloveraction) obj.get_resource(service);
return response;
} | java | public static spilloveraction get(nitro_service service, String name) throws Exception{
spilloveraction obj = new spilloveraction();
obj.set_name(name);
spilloveraction response = (spilloveraction) obj.get_resource(service);
return response;
} | [
"public",
"static",
"spilloveraction",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"spilloveraction",
"obj",
"=",
"new",
"spilloveraction",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"spilloveraction",
"response",
"=",
"(",
"spilloveraction",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] | Use this API to fetch spilloveraction resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"spilloveraction",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/spillover/spilloveraction.java#L265-L270 |
alkacon/opencms-core | src/org/opencms/workplace/CmsWorkplaceMessages.java | CmsWorkplaceMessages.getResourceTypeName | public static String getResourceTypeName(Locale locale, String name) {
"""
Returns the localized name of the given resource type name.<p>
If this key is not found, the value of the name input will be returned.<p>
@param locale the right locale to use
@param name the resource type name to generate the nice name for
@return the localized name of the given resource type name
"""
// try to find the localized key
CmsExplorerTypeSettings typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name);
if (typeSettings == null) {
return name;
}
String key = typeSettings.getKey();
return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name);
} | java | public static String getResourceTypeName(Locale locale, String name) {
// try to find the localized key
CmsExplorerTypeSettings typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name);
if (typeSettings == null) {
return name;
}
String key = typeSettings.getKey();
return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name);
} | [
"public",
"static",
"String",
"getResourceTypeName",
"(",
"Locale",
"locale",
",",
"String",
"name",
")",
"{",
"// try to find the localized key",
"CmsExplorerTypeSettings",
"typeSettings",
"=",
"OpenCms",
".",
"getWorkplaceManager",
"(",
")",
".",
"getExplorerTypeSetting",
"(",
"name",
")",
";",
"if",
"(",
"typeSettings",
"==",
"null",
")",
"{",
"return",
"name",
";",
"}",
"String",
"key",
"=",
"typeSettings",
".",
"getKey",
"(",
")",
";",
"return",
"OpenCms",
".",
"getWorkplaceManager",
"(",
")",
".",
"getMessages",
"(",
"locale",
")",
".",
"keyDefault",
"(",
"key",
",",
"name",
")",
";",
"}"
] | Returns the localized name of the given resource type name.<p>
If this key is not found, the value of the name input will be returned.<p>
@param locale the right locale to use
@param name the resource type name to generate the nice name for
@return the localized name of the given resource type name | [
"Returns",
"the",
"localized",
"name",
"of",
"the",
"given",
"resource",
"type",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplaceMessages.java#L193-L202 |
jglobus/JGlobus | gram/src/main/java/org/globus/gram/Gram.java | Gram.jobSignal | public static int jobSignal(GramJob job, int signal, String arg)
throws GramException, GSSException {
"""
This function sends a signal to a job.
@throws GramException if an error occurs during cancel
@param job the signaled job
@param signal type of the signal
@param arg argument of the signal
"""
GlobusURL jobURL = job.getID();
GSSCredential cred = getJobCredentials(job);
String msg = GRAMProtocol.SIGNAL(jobURL.getURL(),
jobURL.getHost(),
signal,
arg);
GatekeeperReply hd = null;
hd = jmConnect(cred, jobURL, msg);
switch(signal) {
case GramJob.SIGNAL_PRIORITY:
return hd.failureCode;
case GramJob.SIGNAL_STDIO_SIZE:
case GramJob.SIGNAL_STDIO_UPDATE:
case GramJob.SIGNAL_COMMIT_REQUEST:
case GramJob.SIGNAL_COMMIT_EXTEND:
case GramJob.SIGNAL_COMMIT_END:
case GramJob.SIGNAL_STOP_MANAGER:
if (hd.failureCode != 0 && hd.status == GramJob.STATUS_FAILED) {
throw new GramException(hd.failureCode);
} else if (hd.failureCode == 0 && hd.jobFailureCode != 0) {
job.setError( hd.jobFailureCode );
job.setStatus(GramJob.STATUS_FAILED);
return hd.failureCode;
} else {
job.setStatus(hd.status);
return 0;
}
default:
job.setStatus( hd.status );
job.setError( hd.failureCode );
return 0;
}
} | java | public static int jobSignal(GramJob job, int signal, String arg)
throws GramException, GSSException {
GlobusURL jobURL = job.getID();
GSSCredential cred = getJobCredentials(job);
String msg = GRAMProtocol.SIGNAL(jobURL.getURL(),
jobURL.getHost(),
signal,
arg);
GatekeeperReply hd = null;
hd = jmConnect(cred, jobURL, msg);
switch(signal) {
case GramJob.SIGNAL_PRIORITY:
return hd.failureCode;
case GramJob.SIGNAL_STDIO_SIZE:
case GramJob.SIGNAL_STDIO_UPDATE:
case GramJob.SIGNAL_COMMIT_REQUEST:
case GramJob.SIGNAL_COMMIT_EXTEND:
case GramJob.SIGNAL_COMMIT_END:
case GramJob.SIGNAL_STOP_MANAGER:
if (hd.failureCode != 0 && hd.status == GramJob.STATUS_FAILED) {
throw new GramException(hd.failureCode);
} else if (hd.failureCode == 0 && hd.jobFailureCode != 0) {
job.setError( hd.jobFailureCode );
job.setStatus(GramJob.STATUS_FAILED);
return hd.failureCode;
} else {
job.setStatus(hd.status);
return 0;
}
default:
job.setStatus( hd.status );
job.setError( hd.failureCode );
return 0;
}
} | [
"public",
"static",
"int",
"jobSignal",
"(",
"GramJob",
"job",
",",
"int",
"signal",
",",
"String",
"arg",
")",
"throws",
"GramException",
",",
"GSSException",
"{",
"GlobusURL",
"jobURL",
"=",
"job",
".",
"getID",
"(",
")",
";",
"GSSCredential",
"cred",
"=",
"getJobCredentials",
"(",
"job",
")",
";",
"String",
"msg",
"=",
"GRAMProtocol",
".",
"SIGNAL",
"(",
"jobURL",
".",
"getURL",
"(",
")",
",",
"jobURL",
".",
"getHost",
"(",
")",
",",
"signal",
",",
"arg",
")",
";",
"GatekeeperReply",
"hd",
"=",
"null",
";",
"hd",
"=",
"jmConnect",
"(",
"cred",
",",
"jobURL",
",",
"msg",
")",
";",
"switch",
"(",
"signal",
")",
"{",
"case",
"GramJob",
".",
"SIGNAL_PRIORITY",
":",
"return",
"hd",
".",
"failureCode",
";",
"case",
"GramJob",
".",
"SIGNAL_STDIO_SIZE",
":",
"case",
"GramJob",
".",
"SIGNAL_STDIO_UPDATE",
":",
"case",
"GramJob",
".",
"SIGNAL_COMMIT_REQUEST",
":",
"case",
"GramJob",
".",
"SIGNAL_COMMIT_EXTEND",
":",
"case",
"GramJob",
".",
"SIGNAL_COMMIT_END",
":",
"case",
"GramJob",
".",
"SIGNAL_STOP_MANAGER",
":",
"if",
"(",
"hd",
".",
"failureCode",
"!=",
"0",
"&&",
"hd",
".",
"status",
"==",
"GramJob",
".",
"STATUS_FAILED",
")",
"{",
"throw",
"new",
"GramException",
"(",
"hd",
".",
"failureCode",
")",
";",
"}",
"else",
"if",
"(",
"hd",
".",
"failureCode",
"==",
"0",
"&&",
"hd",
".",
"jobFailureCode",
"!=",
"0",
")",
"{",
"job",
".",
"setError",
"(",
"hd",
".",
"jobFailureCode",
")",
";",
"job",
".",
"setStatus",
"(",
"GramJob",
".",
"STATUS_FAILED",
")",
";",
"return",
"hd",
".",
"failureCode",
";",
"}",
"else",
"{",
"job",
".",
"setStatus",
"(",
"hd",
".",
"status",
")",
";",
"return",
"0",
";",
"}",
"default",
":",
"job",
".",
"setStatus",
"(",
"hd",
".",
"status",
")",
";",
"job",
".",
"setError",
"(",
"hd",
".",
"failureCode",
")",
";",
"return",
"0",
";",
"}",
"}"
] | This function sends a signal to a job.
@throws GramException if an error occurs during cancel
@param job the signaled job
@param signal type of the signal
@param arg argument of the signal | [
"This",
"function",
"sends",
"a",
"signal",
"to",
"a",
"job",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gram/src/main/java/org/globus/gram/Gram.java#L686-L725 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/TaskModel.java | TaskModel.update | public void update(Record record, boolean isText) throws MPXJException {
"""
This method populates the task model from data read from an MPX file.
@param record data read from an MPX file
@param isText flag indicating whether the textual or numeric data is being supplied
"""
int length = record.getLength();
for (int i = 0; i < length; i++)
{
if (isText == true)
{
add(getTaskCode(record.getString(i)));
}
else
{
add(record.getInteger(i).intValue());
}
}
} | java | public void update(Record record, boolean isText) throws MPXJException
{
int length = record.getLength();
for (int i = 0; i < length; i++)
{
if (isText == true)
{
add(getTaskCode(record.getString(i)));
}
else
{
add(record.getInteger(i).intValue());
}
}
} | [
"public",
"void",
"update",
"(",
"Record",
"record",
",",
"boolean",
"isText",
")",
"throws",
"MPXJException",
"{",
"int",
"length",
"=",
"record",
".",
"getLength",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isText",
"==",
"true",
")",
"{",
"add",
"(",
"getTaskCode",
"(",
"record",
".",
"getString",
"(",
"i",
")",
")",
")",
";",
"}",
"else",
"{",
"add",
"(",
"record",
".",
"getInteger",
"(",
"i",
")",
".",
"intValue",
"(",
")",
")",
";",
"}",
"}",
"}"
] | This method populates the task model from data read from an MPX file.
@param record data read from an MPX file
@param isText flag indicating whether the textual or numeric data is being supplied | [
"This",
"method",
"populates",
"the",
"task",
"model",
"from",
"data",
"read",
"from",
"an",
"MPX",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/TaskModel.java#L99-L114 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java | InnerClasses.registerInnerClassWithGeneratedName | public TypeInfo registerInnerClassWithGeneratedName(String simpleName, int accessModifiers) {
"""
Register the name (or a simpl mangling of it) as an inner class with the given access
modifiers.
@return A {@link TypeInfo} with the full (possibly mangled) class name
"""
simpleName = classNames.generateName(simpleName);
TypeInfo innerClass = outer.innerClass(simpleName);
innerClassesAccessModifiers.put(innerClass, accessModifiers);
return innerClass;
} | java | public TypeInfo registerInnerClassWithGeneratedName(String simpleName, int accessModifiers) {
simpleName = classNames.generateName(simpleName);
TypeInfo innerClass = outer.innerClass(simpleName);
innerClassesAccessModifiers.put(innerClass, accessModifiers);
return innerClass;
} | [
"public",
"TypeInfo",
"registerInnerClassWithGeneratedName",
"(",
"String",
"simpleName",
",",
"int",
"accessModifiers",
")",
"{",
"simpleName",
"=",
"classNames",
".",
"generateName",
"(",
"simpleName",
")",
";",
"TypeInfo",
"innerClass",
"=",
"outer",
".",
"innerClass",
"(",
"simpleName",
")",
";",
"innerClassesAccessModifiers",
".",
"put",
"(",
"innerClass",
",",
"accessModifiers",
")",
";",
"return",
"innerClass",
";",
"}"
] | Register the name (or a simpl mangling of it) as an inner class with the given access
modifiers.
@return A {@link TypeInfo} with the full (possibly mangled) class name | [
"Register",
"the",
"name",
"(",
"or",
"a",
"simpl",
"mangling",
"of",
"it",
")",
"as",
"an",
"inner",
"class",
"with",
"the",
"given",
"access",
"modifiers",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/internal/InnerClasses.java#L64-L69 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/termofuse/TermOfUsePanel.java | TermOfUsePanel.newDataProtectionPanel | protected Component newDataProtectionPanel(final String id,
final IModel<HeaderContentListModelBean> model) {
"""
Factory method for creating the new {@link Component} for the data protection. This method is
invoked in the constructor from the derived classes and can be overridden so users can
provide their own version of a new {@link Component} for the data protection.
@param id
the id
@param model
the model
@return the new {@link Component} for the data protection
"""
return new DataProtectionPanel(id, Model.of(model.getObject()));
} | java | protected Component newDataProtectionPanel(final String id,
final IModel<HeaderContentListModelBean> model)
{
return new DataProtectionPanel(id, Model.of(model.getObject()));
} | [
"protected",
"Component",
"newDataProtectionPanel",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"HeaderContentListModelBean",
">",
"model",
")",
"{",
"return",
"new",
"DataProtectionPanel",
"(",
"id",
",",
"Model",
".",
"of",
"(",
"model",
".",
"getObject",
"(",
")",
")",
")",
";",
"}"
] | Factory method for creating the new {@link Component} for the data protection. This method is
invoked in the constructor from the derived classes and can be overridden so users can
provide their own version of a new {@link Component} for the data protection.
@param id
the id
@param model
the model
@return the new {@link Component} for the data protection | [
"Factory",
"method",
"for",
"creating",
"the",
"new",
"{",
"@link",
"Component",
"}",
"for",
"the",
"data",
"protection",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
"so",
"users",
"can",
"provide",
"their",
"own",
"version",
"of",
"a",
"new",
"{",
"@link",
"Component",
"}",
"for",
"the",
"data",
"protection",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/termofuse/TermOfUsePanel.java#L225-L229 |
galan/verjson | src/main/java/de/galan/verjson/util/Transformations.java | Transformations.getArrayAndRemove | public static ArrayNode getArrayAndRemove(ObjectNode obj, String fieldName) {
"""
Removes the field from a ObjectNode and returns it as ArrayNode
"""
ArrayNode result = null;
if (obj != null) {
result = array(remove(obj, fieldName));
}
return result;
} | java | public static ArrayNode getArrayAndRemove(ObjectNode obj, String fieldName) {
ArrayNode result = null;
if (obj != null) {
result = array(remove(obj, fieldName));
}
return result;
} | [
"public",
"static",
"ArrayNode",
"getArrayAndRemove",
"(",
"ObjectNode",
"obj",
",",
"String",
"fieldName",
")",
"{",
"ArrayNode",
"result",
"=",
"null",
";",
"if",
"(",
"obj",
"!=",
"null",
")",
"{",
"result",
"=",
"array",
"(",
"remove",
"(",
"obj",
",",
"fieldName",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Removes the field from a ObjectNode and returns it as ArrayNode | [
"Removes",
"the",
"field",
"from",
"a",
"ObjectNode",
"and",
"returns",
"it",
"as",
"ArrayNode"
] | train | https://github.com/galan/verjson/blob/4db610fb5198fde913114ed628234f957e1c19d5/src/main/java/de/galan/verjson/util/Transformations.java#L80-L86 |
carewebframework/carewebframework-vista | org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java | BrokerSession.callRPC | public String callRPC(String name, boolean async, int timeout, RPCParameters params) {
"""
Performs a remote procedure call.
@param name Name of the remote procedure. This has the format:
<p>
<pre>
<remote procedure name>[:<remote procedure version>][:<calling context>]
</pre>
<p>
where only the remote procedure name is required. If the server supports multiple
versions of a remote procedure, an explicit version specifier may be added. If a
different calling context is desired, this may be specified to override the
default. For example:
<p>
<pre>
GET LAB RESULTS:2.4:LR CONTEXT
</pre>
@param async If true, the remote procedure call will be executed asynchronously. In this
case, the value returned by the method will be the unique handle for the
asynchronous request.
@param timeout The timeout, in milliseconds, to wait for remote procedure completion.
@param params Parameters to be passed to the remote procedure. This may be null.
@return The data returned by the remote procedure called if called synchronously, or the
unique handle of the request, if call asynchronously.
"""
ensureConnection();
String version = "";
String context = connectionParams.getAppid();
if (name.contains(":")) {
String pcs[] = StrUtil.split(name, ":", 3, true);
name = pcs[0];
version = pcs[1];
context = pcs[2].isEmpty() ? context : pcs[2];
}
Request request = new Request(Action.RPC);
request.addParameter("UID", id);
request.addParameter("CTX", context);
request.addParameter("VER", version);
request.addParameter("RPC", name);
request.addParameter("ASY", async);
if (params != null) {
request.addParameters(params);
}
Response response = netCall(request, timeout);
return response.getData();
} | java | public String callRPC(String name, boolean async, int timeout, RPCParameters params) {
ensureConnection();
String version = "";
String context = connectionParams.getAppid();
if (name.contains(":")) {
String pcs[] = StrUtil.split(name, ":", 3, true);
name = pcs[0];
version = pcs[1];
context = pcs[2].isEmpty() ? context : pcs[2];
}
Request request = new Request(Action.RPC);
request.addParameter("UID", id);
request.addParameter("CTX", context);
request.addParameter("VER", version);
request.addParameter("RPC", name);
request.addParameter("ASY", async);
if (params != null) {
request.addParameters(params);
}
Response response = netCall(request, timeout);
return response.getData();
} | [
"public",
"String",
"callRPC",
"(",
"String",
"name",
",",
"boolean",
"async",
",",
"int",
"timeout",
",",
"RPCParameters",
"params",
")",
"{",
"ensureConnection",
"(",
")",
";",
"String",
"version",
"=",
"\"\"",
";",
"String",
"context",
"=",
"connectionParams",
".",
"getAppid",
"(",
")",
";",
"if",
"(",
"name",
".",
"contains",
"(",
"\":\"",
")",
")",
"{",
"String",
"pcs",
"[",
"]",
"=",
"StrUtil",
".",
"split",
"(",
"name",
",",
"\":\"",
",",
"3",
",",
"true",
")",
";",
"name",
"=",
"pcs",
"[",
"0",
"]",
";",
"version",
"=",
"pcs",
"[",
"1",
"]",
";",
"context",
"=",
"pcs",
"[",
"2",
"]",
".",
"isEmpty",
"(",
")",
"?",
"context",
":",
"pcs",
"[",
"2",
"]",
";",
"}",
"Request",
"request",
"=",
"new",
"Request",
"(",
"Action",
".",
"RPC",
")",
";",
"request",
".",
"addParameter",
"(",
"\"UID\"",
",",
"id",
")",
";",
"request",
".",
"addParameter",
"(",
"\"CTX\"",
",",
"context",
")",
";",
"request",
".",
"addParameter",
"(",
"\"VER\"",
",",
"version",
")",
";",
"request",
".",
"addParameter",
"(",
"\"RPC\"",
",",
"name",
")",
";",
"request",
".",
"addParameter",
"(",
"\"ASY\"",
",",
"async",
")",
";",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"request",
".",
"addParameters",
"(",
"params",
")",
";",
"}",
"Response",
"response",
"=",
"netCall",
"(",
"request",
",",
"timeout",
")",
";",
"return",
"response",
".",
"getData",
"(",
")",
";",
"}"
] | Performs a remote procedure call.
@param name Name of the remote procedure. This has the format:
<p>
<pre>
<remote procedure name>[:<remote procedure version>][:<calling context>]
</pre>
<p>
where only the remote procedure name is required. If the server supports multiple
versions of a remote procedure, an explicit version specifier may be added. If a
different calling context is desired, this may be specified to override the
default. For example:
<p>
<pre>
GET LAB RESULTS:2.4:LR CONTEXT
</pre>
@param async If true, the remote procedure call will be executed asynchronously. In this
case, the value returned by the method will be the unique handle for the
asynchronous request.
@param timeout The timeout, in milliseconds, to wait for remote procedure completion.
@param params Parameters to be passed to the remote procedure. This may be null.
@return The data returned by the remote procedure called if called synchronously, or the
unique handle of the request, if call asynchronously. | [
"Performs",
"a",
"remote",
"procedure",
"call",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java#L288-L313 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java | DataStream.writeAsCsv | @PublicEvolving
public DataStreamSink<T> writeAsCsv(String path) {
"""
Writes a DataStream to the file specified by the path parameter.
<p>For every field of an element of the DataStream the result of {@link Object#toString()}
is written. This method can only be used on data streams of tuples.
@param path
the path pointing to the location the text file is written to
@return the closed DataStream
"""
return writeAsCsv(path, null, CsvOutputFormat.DEFAULT_LINE_DELIMITER, CsvOutputFormat.DEFAULT_FIELD_DELIMITER);
} | java | @PublicEvolving
public DataStreamSink<T> writeAsCsv(String path) {
return writeAsCsv(path, null, CsvOutputFormat.DEFAULT_LINE_DELIMITER, CsvOutputFormat.DEFAULT_FIELD_DELIMITER);
} | [
"@",
"PublicEvolving",
"public",
"DataStreamSink",
"<",
"T",
">",
"writeAsCsv",
"(",
"String",
"path",
")",
"{",
"return",
"writeAsCsv",
"(",
"path",
",",
"null",
",",
"CsvOutputFormat",
".",
"DEFAULT_LINE_DELIMITER",
",",
"CsvOutputFormat",
".",
"DEFAULT_FIELD_DELIMITER",
")",
";",
"}"
] | Writes a DataStream to the file specified by the path parameter.
<p>For every field of an element of the DataStream the result of {@link Object#toString()}
is written. This method can only be used on data streams of tuples.
@param path
the path pointing to the location the text file is written to
@return the closed DataStream | [
"Writes",
"a",
"DataStream",
"to",
"the",
"file",
"specified",
"by",
"the",
"path",
"parameter",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStream.java#L1060-L1063 |
zaproxy/zaproxy | src/org/zaproxy/zap/spider/SpiderController.java | SpiderController.arrayKeyValueExists | private boolean arrayKeyValueExists(String key, String value) {
"""
Checks whether the value exists in an ArrayList of certain key.
@param key the string of the uri
@param value the request body of the uri
@return true or false depending whether the uri and request body have already been processed
"""
if (visitedPost.containsKey(key)) {
for(String s : visitedPost.get(key)) {
if(s.equals(value)) {
return true;
}
}
}
return false;
} | java | private boolean arrayKeyValueExists(String key, String value) {
if (visitedPost.containsKey(key)) {
for(String s : visitedPost.get(key)) {
if(s.equals(value)) {
return true;
}
}
}
return false;
} | [
"private",
"boolean",
"arrayKeyValueExists",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"visitedPost",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"for",
"(",
"String",
"s",
":",
"visitedPost",
".",
"get",
"(",
"key",
")",
")",
"{",
"if",
"(",
"s",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks whether the value exists in an ArrayList of certain key.
@param key the string of the uri
@param value the request body of the uri
@return true or false depending whether the uri and request body have already been processed | [
"Checks",
"whether",
"the",
"value",
"exists",
"in",
"an",
"ArrayList",
"of",
"certain",
"key",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/spider/SpiderController.java#L358-L369 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java | KerasTokenizer.fromJson | public static KerasTokenizer fromJson(String jsonFileName) throws IOException, InvalidKerasConfigurationException {
"""
Import Keras Tokenizer from JSON file created with `tokenizer.to_json()` in Python.
@param jsonFileName Full path of the JSON file to load
@return Keras Tokenizer instance loaded from JSON
@throws IOException I/O exception
@throws InvalidKerasConfigurationException Invalid Keras configuration
"""
String json = new String(Files.readAllBytes(Paths.get(jsonFileName)));
Map<String, Object> tokenizerBaseConfig = parseJsonString(json);
Map<String, Object> tokenizerConfig;
if (tokenizerBaseConfig.containsKey("config"))
tokenizerConfig = (Map<String, Object>) tokenizerBaseConfig.get("config");
else
throw new InvalidKerasConfigurationException("No configuration found for Keras tokenizer");
Integer numWords = (Integer) tokenizerConfig.get("num_words");
String filters = (String) tokenizerConfig.get("filters");
Boolean lower = (Boolean) tokenizerConfig.get("lower");
String split = (String) tokenizerConfig.get("split");
Boolean charLevel = (Boolean) tokenizerConfig.get("char_level");
String oovToken = (String) tokenizerConfig.get("oov_token");
Integer documentCount = (Integer) tokenizerConfig.get("document_count");
@SuppressWarnings("unchecked")
Map<String, Integer> wordCounts = (Map) parseJsonString((String) tokenizerConfig.get("word_counts"));
@SuppressWarnings("unchecked")
Map<String, Integer> wordDocs = (Map) parseJsonString((String) tokenizerConfig.get("word_docs"));
@SuppressWarnings("unchecked")
Map<String, Integer> wordIndex = (Map) parseJsonString((String) tokenizerConfig.get("word_index"));
@SuppressWarnings("unchecked")
Map<Integer, String> indexWord = (Map) parseJsonString((String) tokenizerConfig.get("index_word"));
@SuppressWarnings("unchecked")
Map<Integer, Integer> indexDocs = (Map) parseJsonString((String) tokenizerConfig.get("index_docs"));
KerasTokenizer tokenizer = new KerasTokenizer(numWords, filters, lower, split, charLevel, oovToken);
tokenizer.setDocumentCount(documentCount);
tokenizer.setWordCounts(wordCounts);
tokenizer.setWordDocs(new HashMap<>(wordDocs));
tokenizer.setWordIndex(wordIndex);
tokenizer.setIndexWord(indexWord);
tokenizer.setIndexDocs(indexDocs);
return tokenizer;
} | java | public static KerasTokenizer fromJson(String jsonFileName) throws IOException, InvalidKerasConfigurationException {
String json = new String(Files.readAllBytes(Paths.get(jsonFileName)));
Map<String, Object> tokenizerBaseConfig = parseJsonString(json);
Map<String, Object> tokenizerConfig;
if (tokenizerBaseConfig.containsKey("config"))
tokenizerConfig = (Map<String, Object>) tokenizerBaseConfig.get("config");
else
throw new InvalidKerasConfigurationException("No configuration found for Keras tokenizer");
Integer numWords = (Integer) tokenizerConfig.get("num_words");
String filters = (String) tokenizerConfig.get("filters");
Boolean lower = (Boolean) tokenizerConfig.get("lower");
String split = (String) tokenizerConfig.get("split");
Boolean charLevel = (Boolean) tokenizerConfig.get("char_level");
String oovToken = (String) tokenizerConfig.get("oov_token");
Integer documentCount = (Integer) tokenizerConfig.get("document_count");
@SuppressWarnings("unchecked")
Map<String, Integer> wordCounts = (Map) parseJsonString((String) tokenizerConfig.get("word_counts"));
@SuppressWarnings("unchecked")
Map<String, Integer> wordDocs = (Map) parseJsonString((String) tokenizerConfig.get("word_docs"));
@SuppressWarnings("unchecked")
Map<String, Integer> wordIndex = (Map) parseJsonString((String) tokenizerConfig.get("word_index"));
@SuppressWarnings("unchecked")
Map<Integer, String> indexWord = (Map) parseJsonString((String) tokenizerConfig.get("index_word"));
@SuppressWarnings("unchecked")
Map<Integer, Integer> indexDocs = (Map) parseJsonString((String) tokenizerConfig.get("index_docs"));
KerasTokenizer tokenizer = new KerasTokenizer(numWords, filters, lower, split, charLevel, oovToken);
tokenizer.setDocumentCount(documentCount);
tokenizer.setWordCounts(wordCounts);
tokenizer.setWordDocs(new HashMap<>(wordDocs));
tokenizer.setWordIndex(wordIndex);
tokenizer.setIndexWord(indexWord);
tokenizer.setIndexDocs(indexDocs);
return tokenizer;
} | [
"public",
"static",
"KerasTokenizer",
"fromJson",
"(",
"String",
"jsonFileName",
")",
"throws",
"IOException",
",",
"InvalidKerasConfigurationException",
"{",
"String",
"json",
"=",
"new",
"String",
"(",
"Files",
".",
"readAllBytes",
"(",
"Paths",
".",
"get",
"(",
"jsonFileName",
")",
")",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"tokenizerBaseConfig",
"=",
"parseJsonString",
"(",
"json",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"tokenizerConfig",
";",
"if",
"(",
"tokenizerBaseConfig",
".",
"containsKey",
"(",
"\"config\"",
")",
")",
"tokenizerConfig",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"tokenizerBaseConfig",
".",
"get",
"(",
"\"config\"",
")",
";",
"else",
"throw",
"new",
"InvalidKerasConfigurationException",
"(",
"\"No configuration found for Keras tokenizer\"",
")",
";",
"Integer",
"numWords",
"=",
"(",
"Integer",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"num_words\"",
")",
";",
"String",
"filters",
"=",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"filters\"",
")",
";",
"Boolean",
"lower",
"=",
"(",
"Boolean",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"lower\"",
")",
";",
"String",
"split",
"=",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"split\"",
")",
";",
"Boolean",
"charLevel",
"=",
"(",
"Boolean",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"char_level\"",
")",
";",
"String",
"oovToken",
"=",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"oov_token\"",
")",
";",
"Integer",
"documentCount",
"=",
"(",
"Integer",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"document_count\"",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"String",
",",
"Integer",
">",
"wordCounts",
"=",
"(",
"Map",
")",
"parseJsonString",
"(",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"word_counts\"",
")",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"String",
",",
"Integer",
">",
"wordDocs",
"=",
"(",
"Map",
")",
"parseJsonString",
"(",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"word_docs\"",
")",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"String",
",",
"Integer",
">",
"wordIndex",
"=",
"(",
"Map",
")",
"parseJsonString",
"(",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"word_index\"",
")",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"Integer",
",",
"String",
">",
"indexWord",
"=",
"(",
"Map",
")",
"parseJsonString",
"(",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"index_word\"",
")",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"indexDocs",
"=",
"(",
"Map",
")",
"parseJsonString",
"(",
"(",
"String",
")",
"tokenizerConfig",
".",
"get",
"(",
"\"index_docs\"",
")",
")",
";",
"KerasTokenizer",
"tokenizer",
"=",
"new",
"KerasTokenizer",
"(",
"numWords",
",",
"filters",
",",
"lower",
",",
"split",
",",
"charLevel",
",",
"oovToken",
")",
";",
"tokenizer",
".",
"setDocumentCount",
"(",
"documentCount",
")",
";",
"tokenizer",
".",
"setWordCounts",
"(",
"wordCounts",
")",
";",
"tokenizer",
".",
"setWordDocs",
"(",
"new",
"HashMap",
"<>",
"(",
"wordDocs",
")",
")",
";",
"tokenizer",
".",
"setWordIndex",
"(",
"wordIndex",
")",
";",
"tokenizer",
".",
"setIndexWord",
"(",
"indexWord",
")",
";",
"tokenizer",
".",
"setIndexDocs",
"(",
"indexDocs",
")",
";",
"return",
"tokenizer",
";",
"}"
] | Import Keras Tokenizer from JSON file created with `tokenizer.to_json()` in Python.
@param jsonFileName Full path of the JSON file to load
@return Keras Tokenizer instance loaded from JSON
@throws IOException I/O exception
@throws InvalidKerasConfigurationException Invalid Keras configuration | [
"Import",
"Keras",
"Tokenizer",
"from",
"JSON",
"file",
"created",
"with",
"tokenizer",
".",
"to_json",
"()",
"in",
"Python",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java#L107-L145 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/TypedStreamReader.java | TypedStreamReader.createStreamReader | public static TypedStreamReader createStreamReader
(BranchingReaderSource input, ReaderCreator owner, ReaderConfig cfg,
InputBootstrapper bs, boolean forER)
throws XMLStreamException {
"""
Factory method for constructing readers.
@param owner "Owner" of this reader, factory that created the reader;
needed for returning updated symbol table information after parsing.
@param input Input source used to read the XML document.
@param cfg Object that contains reader configuration info.
"""
TypedStreamReader sr = new TypedStreamReader
(bs, input, owner, cfg, createElementStack(cfg), forER);
return sr;
} | java | public static TypedStreamReader createStreamReader
(BranchingReaderSource input, ReaderCreator owner, ReaderConfig cfg,
InputBootstrapper bs, boolean forER)
throws XMLStreamException
{
TypedStreamReader sr = new TypedStreamReader
(bs, input, owner, cfg, createElementStack(cfg), forER);
return sr;
} | [
"public",
"static",
"TypedStreamReader",
"createStreamReader",
"(",
"BranchingReaderSource",
"input",
",",
"ReaderCreator",
"owner",
",",
"ReaderConfig",
"cfg",
",",
"InputBootstrapper",
"bs",
",",
"boolean",
"forER",
")",
"throws",
"XMLStreamException",
"{",
"TypedStreamReader",
"sr",
"=",
"new",
"TypedStreamReader",
"(",
"bs",
",",
"input",
",",
"owner",
",",
"cfg",
",",
"createElementStack",
"(",
"cfg",
")",
",",
"forER",
")",
";",
"return",
"sr",
";",
"}"
] | Factory method for constructing readers.
@param owner "Owner" of this reader, factory that created the reader;
needed for returning updated symbol table information after parsing.
@param input Input source used to read the XML document.
@param cfg Object that contains reader configuration info. | [
"Factory",
"method",
"for",
"constructing",
"readers",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/TypedStreamReader.java#L105-L114 |
GoogleCloudPlatform/bigdata-interop | gcs/src/main/java/com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystemBase.java | GoogleHadoopFileSystemBase.listStatus | @Override
public FileStatus[] listStatus(Path hadoopPath)
throws IOException {
"""
Lists file status. If the given path points to a directory then the status
of children is returned, otherwise the status of the given file is returned.
@param hadoopPath Given path.
@return File status list or null if path does not exist.
@throws IOException if an error occurs.
"""
long startTime = System.nanoTime();
Preconditions.checkArgument(hadoopPath != null, "hadoopPath must not be null");
checkOpen();
logger.atFine().log("GHFS.listStatus: %s", hadoopPath);
URI gcsPath = getGcsPath(hadoopPath);
List<FileStatus> status;
try {
List<FileInfo> fileInfos = getGcsFs().listFileInfo(gcsPath);
status = new ArrayList<>(fileInfos.size());
String userName = getUgiUserName();
for (FileInfo fileInfo : fileInfos) {
status.add(getFileStatus(fileInfo, userName));
}
} catch (FileNotFoundException fnfe) {
logger.atFine().withCause(fnfe).log("Got fnfe: ");
throw new FileNotFoundException(String.format("Path '%s' does not exist.", gcsPath));
}
long duration = System.nanoTime() - startTime;
increment(Counter.LIST_STATUS);
increment(Counter.LIST_STATUS_TIME, duration);
return status.toArray(new FileStatus[0]);
} | java | @Override
public FileStatus[] listStatus(Path hadoopPath)
throws IOException {
long startTime = System.nanoTime();
Preconditions.checkArgument(hadoopPath != null, "hadoopPath must not be null");
checkOpen();
logger.atFine().log("GHFS.listStatus: %s", hadoopPath);
URI gcsPath = getGcsPath(hadoopPath);
List<FileStatus> status;
try {
List<FileInfo> fileInfos = getGcsFs().listFileInfo(gcsPath);
status = new ArrayList<>(fileInfos.size());
String userName = getUgiUserName();
for (FileInfo fileInfo : fileInfos) {
status.add(getFileStatus(fileInfo, userName));
}
} catch (FileNotFoundException fnfe) {
logger.atFine().withCause(fnfe).log("Got fnfe: ");
throw new FileNotFoundException(String.format("Path '%s' does not exist.", gcsPath));
}
long duration = System.nanoTime() - startTime;
increment(Counter.LIST_STATUS);
increment(Counter.LIST_STATUS_TIME, duration);
return status.toArray(new FileStatus[0]);
} | [
"@",
"Override",
"public",
"FileStatus",
"[",
"]",
"listStatus",
"(",
"Path",
"hadoopPath",
")",
"throws",
"IOException",
"{",
"long",
"startTime",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"hadoopPath",
"!=",
"null",
",",
"\"hadoopPath must not be null\"",
")",
";",
"checkOpen",
"(",
")",
";",
"logger",
".",
"atFine",
"(",
")",
".",
"log",
"(",
"\"GHFS.listStatus: %s\"",
",",
"hadoopPath",
")",
";",
"URI",
"gcsPath",
"=",
"getGcsPath",
"(",
"hadoopPath",
")",
";",
"List",
"<",
"FileStatus",
">",
"status",
";",
"try",
"{",
"List",
"<",
"FileInfo",
">",
"fileInfos",
"=",
"getGcsFs",
"(",
")",
".",
"listFileInfo",
"(",
"gcsPath",
")",
";",
"status",
"=",
"new",
"ArrayList",
"<>",
"(",
"fileInfos",
".",
"size",
"(",
")",
")",
";",
"String",
"userName",
"=",
"getUgiUserName",
"(",
")",
";",
"for",
"(",
"FileInfo",
"fileInfo",
":",
"fileInfos",
")",
"{",
"status",
".",
"add",
"(",
"getFileStatus",
"(",
"fileInfo",
",",
"userName",
")",
")",
";",
"}",
"}",
"catch",
"(",
"FileNotFoundException",
"fnfe",
")",
"{",
"logger",
".",
"atFine",
"(",
")",
".",
"withCause",
"(",
"fnfe",
")",
".",
"log",
"(",
"\"Got fnfe: \"",
")",
";",
"throw",
"new",
"FileNotFoundException",
"(",
"String",
".",
"format",
"(",
"\"Path '%s' does not exist.\"",
",",
"gcsPath",
")",
")",
";",
"}",
"long",
"duration",
"=",
"System",
".",
"nanoTime",
"(",
")",
"-",
"startTime",
";",
"increment",
"(",
"Counter",
".",
"LIST_STATUS",
")",
";",
"increment",
"(",
"Counter",
".",
"LIST_STATUS_TIME",
",",
"duration",
")",
";",
"return",
"status",
".",
"toArray",
"(",
"new",
"FileStatus",
"[",
"0",
"]",
")",
";",
"}"
] | Lists file status. If the given path points to a directory then the status
of children is returned, otherwise the status of the given file is returned.
@param hadoopPath Given path.
@return File status list or null if path does not exist.
@throws IOException if an error occurs. | [
"Lists",
"file",
"status",
".",
"If",
"the",
"given",
"path",
"points",
"to",
"a",
"directory",
"then",
"the",
"status",
"of",
"children",
"is",
"returned",
"otherwise",
"the",
"status",
"of",
"the",
"given",
"file",
"is",
"returned",
"."
] | train | https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcs/src/main/java/com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystemBase.java#L968-L997 |
googleapis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableClusterUtilities.java | BigtableClusterUtilities.getCluster | public Cluster getCluster(String clusterId, String zoneId) {
"""
Gets the current configuration of the cluster as encapsulated by a {@link Cluster} object.
@param clusterId
@param zoneId
@return the {@link Cluster} if it was set. If the cluster is not found, throw a {@link
NullPointerException}.
"""
Cluster response = null;
for (Cluster cluster : getClusters().getClustersList()) {
if (cluster.getName().endsWith("/clusters/" + clusterId)
&& cluster.getLocation().endsWith("/locations/" + zoneId)) {
if (response == null) {
response = cluster;
} else {
throw new IllegalStateException(
String.format("Got multiple clusters named %s in zone %z.", clusterId, zoneId));
}
}
}
return Preconditions.checkNotNull(response,
String.format("Cluster %s in zone %s was not found.", clusterId, zoneId));
} | java | public Cluster getCluster(String clusterId, String zoneId) {
Cluster response = null;
for (Cluster cluster : getClusters().getClustersList()) {
if (cluster.getName().endsWith("/clusters/" + clusterId)
&& cluster.getLocation().endsWith("/locations/" + zoneId)) {
if (response == null) {
response = cluster;
} else {
throw new IllegalStateException(
String.format("Got multiple clusters named %s in zone %z.", clusterId, zoneId));
}
}
}
return Preconditions.checkNotNull(response,
String.format("Cluster %s in zone %s was not found.", clusterId, zoneId));
} | [
"public",
"Cluster",
"getCluster",
"(",
"String",
"clusterId",
",",
"String",
"zoneId",
")",
"{",
"Cluster",
"response",
"=",
"null",
";",
"for",
"(",
"Cluster",
"cluster",
":",
"getClusters",
"(",
")",
".",
"getClustersList",
"(",
")",
")",
"{",
"if",
"(",
"cluster",
".",
"getName",
"(",
")",
".",
"endsWith",
"(",
"\"/clusters/\"",
"+",
"clusterId",
")",
"&&",
"cluster",
".",
"getLocation",
"(",
")",
".",
"endsWith",
"(",
"\"/locations/\"",
"+",
"zoneId",
")",
")",
"{",
"if",
"(",
"response",
"==",
"null",
")",
"{",
"response",
"=",
"cluster",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"Got multiple clusters named %s in zone %z.\"",
",",
"clusterId",
",",
"zoneId",
")",
")",
";",
"}",
"}",
"}",
"return",
"Preconditions",
".",
"checkNotNull",
"(",
"response",
",",
"String",
".",
"format",
"(",
"\"Cluster %s in zone %s was not found.\"",
",",
"clusterId",
",",
"zoneId",
")",
")",
";",
"}"
] | Gets the current configuration of the cluster as encapsulated by a {@link Cluster} object.
@param clusterId
@param zoneId
@return the {@link Cluster} if it was set. If the cluster is not found, throw a {@link
NullPointerException}. | [
"Gets",
"the",
"current",
"configuration",
"of",
"the",
"cluster",
"as",
"encapsulated",
"by",
"a",
"{",
"@link",
"Cluster",
"}",
"object",
"."
] | train | https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableClusterUtilities.java#L293-L308 |
apereo/cas | support/cas-server-support-token-tickets/src/main/java/org/apereo/cas/token/authentication/principal/TokenWebApplicationServiceResponseBuilder.java | TokenWebApplicationServiceResponseBuilder.generateToken | @SneakyThrows
protected String generateToken(final Service service, final Map<String, String> parameters) {
"""
Generate token string.
@param service the service
@param parameters the parameters
@return the jwt
"""
val ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET);
return this.tokenTicketBuilder.build(ticketId, service);
} | java | @SneakyThrows
protected String generateToken(final Service service, final Map<String, String> parameters) {
val ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET);
return this.tokenTicketBuilder.build(ticketId, service);
} | [
"@",
"SneakyThrows",
"protected",
"String",
"generateToken",
"(",
"final",
"Service",
"service",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"val",
"ticketId",
"=",
"parameters",
".",
"get",
"(",
"CasProtocolConstants",
".",
"PARAMETER_TICKET",
")",
";",
"return",
"this",
".",
"tokenTicketBuilder",
".",
"build",
"(",
"ticketId",
",",
"service",
")",
";",
"}"
] | Generate token string.
@param service the service
@param parameters the parameters
@return the jwt | [
"Generate",
"token",
"string",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-token-tickets/src/main/java/org/apereo/cas/token/authentication/principal/TokenWebApplicationServiceResponseBuilder.java#L69-L73 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBHash.java | BoBHash.fromCid | public static BoBHash fromCid(String cid) {
"""
Get BoB hash from cid attribute string.
@param cid
@return the BoB hash
"""
String hashType = cid.substring(0, cid.indexOf("+"));
String hash = cid.substring(cid.indexOf("+") + 1, cid.indexOf("@bob.xmpp.org"));
return new BoBHash(hash, hashType);
} | java | public static BoBHash fromCid(String cid) {
String hashType = cid.substring(0, cid.indexOf("+"));
String hash = cid.substring(cid.indexOf("+") + 1, cid.indexOf("@bob.xmpp.org"));
return new BoBHash(hash, hashType);
} | [
"public",
"static",
"BoBHash",
"fromCid",
"(",
"String",
"cid",
")",
"{",
"String",
"hashType",
"=",
"cid",
".",
"substring",
"(",
"0",
",",
"cid",
".",
"indexOf",
"(",
"\"+\"",
")",
")",
";",
"String",
"hash",
"=",
"cid",
".",
"substring",
"(",
"cid",
".",
"indexOf",
"(",
"\"+\"",
")",
"+",
"1",
",",
"cid",
".",
"indexOf",
"(",
"\"@bob.xmpp.org\"",
")",
")",
";",
"return",
"new",
"BoBHash",
"(",
"hash",
",",
"hashType",
")",
";",
"}"
] | Get BoB hash from cid attribute string.
@param cid
@return the BoB hash | [
"Get",
"BoB",
"hash",
"from",
"cid",
"attribute",
"string",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/bob/BoBHash.java#L115-L119 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/BitSet.java | BitSet.valueOf | public static BitSet valueOf(long[] longs) {
"""
Returns a new bit set containing all the bits in the given long array.
<p>More precisely,
<br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
<br>for all {@code n < 64 * longs.length}.
<p>This method is equivalent to
{@code BitSet.valueOf(LongBuffer.wrap(longs))}.
@param longs a long array containing a little-endian representation
of a sequence of bits to be used as the initial bits of the
new bit set
@return a {@code BitSet} containing all the bits in the long array
@since 1.7
"""
int n;
for (n = longs.length; n > 0 && longs[n - 1] == 0; n--)
;
return new BitSet(Arrays.copyOf(longs, n));
} | java | public static BitSet valueOf(long[] longs) {
int n;
for (n = longs.length; n > 0 && longs[n - 1] == 0; n--)
;
return new BitSet(Arrays.copyOf(longs, n));
} | [
"public",
"static",
"BitSet",
"valueOf",
"(",
"long",
"[",
"]",
"longs",
")",
"{",
"int",
"n",
";",
"for",
"(",
"n",
"=",
"longs",
".",
"length",
";",
"n",
">",
"0",
"&&",
"longs",
"[",
"n",
"-",
"1",
"]",
"==",
"0",
";",
"n",
"--",
")",
";",
"return",
"new",
"BitSet",
"(",
"Arrays",
".",
"copyOf",
"(",
"longs",
",",
"n",
")",
")",
";",
"}"
] | Returns a new bit set containing all the bits in the given long array.
<p>More precisely,
<br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
<br>for all {@code n < 64 * longs.length}.
<p>This method is equivalent to
{@code BitSet.valueOf(LongBuffer.wrap(longs))}.
@param longs a long array containing a little-endian representation
of a sequence of bits to be used as the initial bits of the
new bit set
@return a {@code BitSet} containing all the bits in the long array
@since 1.7 | [
"Returns",
"a",
"new",
"bit",
"set",
"containing",
"all",
"the",
"bits",
"in",
"the",
"given",
"long",
"array",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/BitSet.java#L195-L200 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java | HttpBuilder.optionsAsync | public <T> CompletableFuture<T> optionsAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
"""
Executes an asynchronous OPTIONS request on the configured URI (asynchronous alias to `options(Class,Consumer)`), with additional configuration
provided by the configuration function. The result will be cast to the specified `type`.
This method is generally used for Java-specific configuration.
[source,groovy]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
String result = http.optionsAsync(String.class, config -> {
config.getRequest().getUri().setPath("/foo");
});
----
The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface.
@param type the type of the response content
@param configuration the additional configuration function (delegated to {@link HttpConfig})
@return the resulting content cast to the specified type wrapped in a {@link CompletableFuture}
"""
return CompletableFuture.supplyAsync(() -> options(type, configuration), getExecutor());
} | java | public <T> CompletableFuture<T> optionsAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> options(type, configuration), getExecutor());
} | [
"public",
"<",
"T",
">",
"CompletableFuture",
"<",
"T",
">",
"optionsAsync",
"(",
"final",
"Class",
"<",
"T",
">",
"type",
",",
"final",
"Consumer",
"<",
"HttpConfig",
">",
"configuration",
")",
"{",
"return",
"CompletableFuture",
".",
"supplyAsync",
"(",
"(",
")",
"->",
"options",
"(",
"type",
",",
"configuration",
")",
",",
"getExecutor",
"(",
")",
")",
";",
"}"
] | Executes an asynchronous OPTIONS request on the configured URI (asynchronous alias to `options(Class,Consumer)`), with additional configuration
provided by the configuration function. The result will be cast to the specified `type`.
This method is generally used for Java-specific configuration.
[source,groovy]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
String result = http.optionsAsync(String.class, config -> {
config.getRequest().getUri().setPath("/foo");
});
----
The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface.
@param type the type of the response content
@param configuration the additional configuration function (delegated to {@link HttpConfig})
@return the resulting content cast to the specified type wrapped in a {@link CompletableFuture} | [
"Executes",
"an",
"asynchronous",
"OPTIONS",
"request",
"on",
"the",
"configured",
"URI",
"(",
"asynchronous",
"alias",
"to",
"options",
"(",
"Class",
"Consumer",
")",
")",
"with",
"additional",
"configuration",
"provided",
"by",
"the",
"configuration",
"function",
".",
"The",
"result",
"will",
"be",
"cast",
"to",
"the",
"specified",
"type",
"."
] | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L1982-L1984 |
eclipse/xtext-extras | org.eclipse.xtext.purexbase/src-gen/org/eclipse/xtext/purexbase/pureXbase/util/PureXbaseSwitch.java | PureXbaseSwitch.doSwitch | @Override
protected T doSwitch(int classifierID, EObject theEObject) {
"""
Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
<!-- begin-user-doc -->
<!-- end-user-doc -->
@return the first non-null result returned by a <code>caseXXX</code> call.
@generated
"""
switch (classifierID)
{
case PureXbasePackage.MODEL:
{
Model model = (Model)theEObject;
T result = caseModel(model);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
} | java | @Override
protected T doSwitch(int classifierID, EObject theEObject)
{
switch (classifierID)
{
case PureXbasePackage.MODEL:
{
Model model = (Model)theEObject;
T result = caseModel(model);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
} | [
"@",
"Override",
"protected",
"T",
"doSwitch",
"(",
"int",
"classifierID",
",",
"EObject",
"theEObject",
")",
"{",
"switch",
"(",
"classifierID",
")",
"{",
"case",
"PureXbasePackage",
".",
"MODEL",
":",
"{",
"Model",
"model",
"=",
"(",
"Model",
")",
"theEObject",
";",
"T",
"result",
"=",
"caseModel",
"(",
"model",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"result",
"=",
"defaultCase",
"(",
"theEObject",
")",
";",
"return",
"result",
";",
"}",
"default",
":",
"return",
"defaultCase",
"(",
"theEObject",
")",
";",
"}",
"}"
] | Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
<!-- begin-user-doc -->
<!-- end-user-doc -->
@return the first non-null result returned by a <code>caseXXX</code> call.
@generated | [
"Calls",
"<code",
">",
"caseXXX<",
"/",
"code",
">",
"for",
"each",
"class",
"of",
"the",
"model",
"until",
"one",
"returns",
"a",
"non",
"null",
"result",
";",
"it",
"yields",
"that",
"result",
".",
"<!",
"--",
"begin",
"-",
"user",
"-",
"doc",
"--",
">",
"<!",
"--",
"end",
"-",
"user",
"-",
"doc",
"--",
">"
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.purexbase/src-gen/org/eclipse/xtext/purexbase/pureXbase/util/PureXbaseSwitch.java#L71-L85 |
spring-projects/spring-social | spring-social-web/src/main/java/org/springframework/social/connect/web/ProviderSignInUtils.java | ProviderSignInUtils.doPostSignUp | public void doPostSignUp(String userId, RequestAttributes request) {
"""
Add the connection to the provider user the client attempted to sign-in with to the new local user's set of connections.
Should be called after signing-up a new user in the context of a provider sign-in attempt.
In this context, the user did not yet have a local account but attempted to sign-in using one of his or her existing provider accounts.
Ensures provider sign-in attempt session context is cleaned up.
Does nothing if no provider sign-in was attempted for the current user session (is safe to call in that case).
@param userId the local application's user ID
@param request the current request attributes, used to extract sign-in attempt information from the current user session
"""
ProviderSignInAttempt signInAttempt = (ProviderSignInAttempt) sessionStrategy.getAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE);
if (signInAttempt != null) {
signInAttempt.addConnection(userId,connectionFactoryLocator,connectionRepository);
sessionStrategy.removeAttribute(request,ProviderSignInAttempt.SESSION_ATTRIBUTE);
}
} | java | public void doPostSignUp(String userId, RequestAttributes request) {
ProviderSignInAttempt signInAttempt = (ProviderSignInAttempt) sessionStrategy.getAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE);
if (signInAttempt != null) {
signInAttempt.addConnection(userId,connectionFactoryLocator,connectionRepository);
sessionStrategy.removeAttribute(request,ProviderSignInAttempt.SESSION_ATTRIBUTE);
}
} | [
"public",
"void",
"doPostSignUp",
"(",
"String",
"userId",
",",
"RequestAttributes",
"request",
")",
"{",
"ProviderSignInAttempt",
"signInAttempt",
"=",
"(",
"ProviderSignInAttempt",
")",
"sessionStrategy",
".",
"getAttribute",
"(",
"request",
",",
"ProviderSignInAttempt",
".",
"SESSION_ATTRIBUTE",
")",
";",
"if",
"(",
"signInAttempt",
"!=",
"null",
")",
"{",
"signInAttempt",
".",
"addConnection",
"(",
"userId",
",",
"connectionFactoryLocator",
",",
"connectionRepository",
")",
";",
"sessionStrategy",
".",
"removeAttribute",
"(",
"request",
",",
"ProviderSignInAttempt",
".",
"SESSION_ATTRIBUTE",
")",
";",
"}",
"}"
] | Add the connection to the provider user the client attempted to sign-in with to the new local user's set of connections.
Should be called after signing-up a new user in the context of a provider sign-in attempt.
In this context, the user did not yet have a local account but attempted to sign-in using one of his or her existing provider accounts.
Ensures provider sign-in attempt session context is cleaned up.
Does nothing if no provider sign-in was attempted for the current user session (is safe to call in that case).
@param userId the local application's user ID
@param request the current request attributes, used to extract sign-in attempt information from the current user session | [
"Add",
"the",
"connection",
"to",
"the",
"provider",
"user",
"the",
"client",
"attempted",
"to",
"sign",
"-",
"in",
"with",
"to",
"the",
"new",
"local",
"user",
"s",
"set",
"of",
"connections",
".",
"Should",
"be",
"called",
"after",
"signing",
"-",
"up",
"a",
"new",
"user",
"in",
"the",
"context",
"of",
"a",
"provider",
"sign",
"-",
"in",
"attempt",
".",
"In",
"this",
"context",
"the",
"user",
"did",
"not",
"yet",
"have",
"a",
"local",
"account",
"but",
"attempted",
"to",
"sign",
"-",
"in",
"using",
"one",
"of",
"his",
"or",
"her",
"existing",
"provider",
"accounts",
".",
"Ensures",
"provider",
"sign",
"-",
"in",
"attempt",
"session",
"context",
"is",
"cleaned",
"up",
".",
"Does",
"nothing",
"if",
"no",
"provider",
"sign",
"-",
"in",
"was",
"attempted",
"for",
"the",
"current",
"user",
"session",
"(",
"is",
"safe",
"to",
"call",
"in",
"that",
"case",
")",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-web/src/main/java/org/springframework/social/connect/web/ProviderSignInUtils.java#L67-L73 |
igniterealtime/jbosh | src/main/java/org/igniterealtime/jbosh/ApacheHTTPResponse.java | ApacheHTTPResponse.awaitResponse | private synchronized void awaitResponse() throws BOSHException {
"""
Await the response, storing the result in the instance variables of
this class when they arrive.
@throws InterruptedException if interrupted while awaiting the response
@throws BOSHException on communication failure
"""
HttpEntity entity = null;
try {
HttpResponse httpResp = client.execute(post, context);
entity = httpResp.getEntity();
byte[] data = EntityUtils.toByteArray(entity);
String encoding = entity.getContentEncoding() != null ?
entity.getContentEncoding().getValue() :
null;
if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) {
data = ZLIBCodec.decode(data);
} else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) {
data = GZIPCodec.decode(data);
}
body = StaticBody.fromString(new String(data, CHARSET));
statusCode = httpResp.getStatusLine().getStatusCode();
sent = true;
} catch (IOException iox) {
abort();
toThrow = new BOSHException("Could not obtain response", iox);
throw(toThrow);
} catch (RuntimeException ex) {
abort();
throw(ex);
}
} | java | private synchronized void awaitResponse() throws BOSHException {
HttpEntity entity = null;
try {
HttpResponse httpResp = client.execute(post, context);
entity = httpResp.getEntity();
byte[] data = EntityUtils.toByteArray(entity);
String encoding = entity.getContentEncoding() != null ?
entity.getContentEncoding().getValue() :
null;
if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) {
data = ZLIBCodec.decode(data);
} else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) {
data = GZIPCodec.decode(data);
}
body = StaticBody.fromString(new String(data, CHARSET));
statusCode = httpResp.getStatusLine().getStatusCode();
sent = true;
} catch (IOException iox) {
abort();
toThrow = new BOSHException("Could not obtain response", iox);
throw(toThrow);
} catch (RuntimeException ex) {
abort();
throw(ex);
}
} | [
"private",
"synchronized",
"void",
"awaitResponse",
"(",
")",
"throws",
"BOSHException",
"{",
"HttpEntity",
"entity",
"=",
"null",
";",
"try",
"{",
"HttpResponse",
"httpResp",
"=",
"client",
".",
"execute",
"(",
"post",
",",
"context",
")",
";",
"entity",
"=",
"httpResp",
".",
"getEntity",
"(",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"EntityUtils",
".",
"toByteArray",
"(",
"entity",
")",
";",
"String",
"encoding",
"=",
"entity",
".",
"getContentEncoding",
"(",
")",
"!=",
"null",
"?",
"entity",
".",
"getContentEncoding",
"(",
")",
".",
"getValue",
"(",
")",
":",
"null",
";",
"if",
"(",
"ZLIBCodec",
".",
"getID",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"encoding",
")",
")",
"{",
"data",
"=",
"ZLIBCodec",
".",
"decode",
"(",
"data",
")",
";",
"}",
"else",
"if",
"(",
"GZIPCodec",
".",
"getID",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"encoding",
")",
")",
"{",
"data",
"=",
"GZIPCodec",
".",
"decode",
"(",
"data",
")",
";",
"}",
"body",
"=",
"StaticBody",
".",
"fromString",
"(",
"new",
"String",
"(",
"data",
",",
"CHARSET",
")",
")",
";",
"statusCode",
"=",
"httpResp",
".",
"getStatusLine",
"(",
")",
".",
"getStatusCode",
"(",
")",
";",
"sent",
"=",
"true",
";",
"}",
"catch",
"(",
"IOException",
"iox",
")",
"{",
"abort",
"(",
")",
";",
"toThrow",
"=",
"new",
"BOSHException",
"(",
"\"Could not obtain response\"",
",",
"iox",
")",
";",
"throw",
"(",
"toThrow",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"ex",
")",
"{",
"abort",
"(",
")",
";",
"throw",
"(",
"ex",
")",
";",
"}",
"}"
] | Await the response, storing the result in the instance variables of
this class when they arrive.
@throws InterruptedException if interrupted while awaiting the response
@throws BOSHException on communication failure | [
"Await",
"the",
"response",
"storing",
"the",
"result",
"in",
"the",
"instance",
"variables",
"of",
"this",
"class",
"when",
"they",
"arrive",
"."
] | train | https://github.com/igniterealtime/jbosh/blob/b43378f27e19b753b552b1e9666abc0476cdceff/src/main/java/org/igniterealtime/jbosh/ApacheHTTPResponse.java#L232-L257 |
banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/FormBeanUtil.java | FormBeanUtil.createEvent | public static EventModel createEvent(ModelForm form, Object model) throws Exception {
"""
create a EventModel from a existed ModelForm. it is only for
create/edit/delete of ModelSaveAction
"""
EventModel em = new EventModel();
try {
PropertyUtils.copyProperties(model, form);
em.setModelIF(model);
String action = form.getAction();
em.setActionName(action);
em.setActionType(FormBeanUtil.actionTransfer(action));
} catch (Exception ex) {
Debug.logError("[JdonFramework]create Event error:" + ex, module);
throw new Exception(ex);
}
return em;
} | java | public static EventModel createEvent(ModelForm form, Object model) throws Exception {
EventModel em = new EventModel();
try {
PropertyUtils.copyProperties(model, form);
em.setModelIF(model);
String action = form.getAction();
em.setActionName(action);
em.setActionType(FormBeanUtil.actionTransfer(action));
} catch (Exception ex) {
Debug.logError("[JdonFramework]create Event error:" + ex, module);
throw new Exception(ex);
}
return em;
} | [
"public",
"static",
"EventModel",
"createEvent",
"(",
"ModelForm",
"form",
",",
"Object",
"model",
")",
"throws",
"Exception",
"{",
"EventModel",
"em",
"=",
"new",
"EventModel",
"(",
")",
";",
"try",
"{",
"PropertyUtils",
".",
"copyProperties",
"(",
"model",
",",
"form",
")",
";",
"em",
".",
"setModelIF",
"(",
"model",
")",
";",
"String",
"action",
"=",
"form",
".",
"getAction",
"(",
")",
";",
"em",
".",
"setActionName",
"(",
"action",
")",
";",
"em",
".",
"setActionType",
"(",
"FormBeanUtil",
".",
"actionTransfer",
"(",
"action",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"Debug",
".",
"logError",
"(",
"\"[JdonFramework]create Event error:\"",
"+",
"ex",
",",
"module",
")",
";",
"throw",
"new",
"Exception",
"(",
"ex",
")",
";",
"}",
"return",
"em",
";",
"}"
] | create a EventModel from a existed ModelForm. it is only for
create/edit/delete of ModelSaveAction | [
"create",
"a",
"EventModel",
"from",
"a",
"existed",
"ModelForm",
".",
"it",
"is",
"only",
"for",
"create",
"/",
"edit",
"/",
"delete",
"of",
"ModelSaveAction"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/FormBeanUtil.java#L235-L248 |
meltmedia/cadmium | servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/error/ErrorUtil.java | ErrorUtil.throwInternalError | public static void throwInternalError(String message, UriInfo uriInfo) {
"""
Wraps the error as {@link WebApplicationException} with error mapped as JSON Response
@param message {@link String} representing internal error
@param uriInfo {@link UriInfo} used for forming link
"""
GenericError error = new GenericError(
message,
ErrorCode.INTERNAL.getCode(),
uriInfo.getAbsolutePath().toString());
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(error)
.build());
} | java | public static void throwInternalError(String message, UriInfo uriInfo) {
GenericError error = new GenericError(
message,
ErrorCode.INTERNAL.getCode(),
uriInfo.getAbsolutePath().toString());
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(error)
.build());
} | [
"public",
"static",
"void",
"throwInternalError",
"(",
"String",
"message",
",",
"UriInfo",
"uriInfo",
")",
"{",
"GenericError",
"error",
"=",
"new",
"GenericError",
"(",
"message",
",",
"ErrorCode",
".",
"INTERNAL",
".",
"getCode",
"(",
")",
",",
"uriInfo",
".",
"getAbsolutePath",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"WebApplicationException",
"(",
"Response",
".",
"status",
"(",
"Response",
".",
"Status",
".",
"INTERNAL_SERVER_ERROR",
")",
".",
"type",
"(",
"MediaType",
".",
"APPLICATION_JSON_TYPE",
")",
".",
"entity",
"(",
"error",
")",
".",
"build",
"(",
")",
")",
";",
"}"
] | Wraps the error as {@link WebApplicationException} with error mapped as JSON Response
@param message {@link String} representing internal error
@param uriInfo {@link UriInfo} used for forming link | [
"Wraps",
"the",
"error",
"as",
"{"
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/error/ErrorUtil.java#L72-L82 |
VoltDB/voltdb | src/frontend/org/voltdb/VoltProcedure.java | VoltProcedure.voltQueueSQL | public void voltQueueSQL(final SQLStmt stmt, Object... args) {
"""
Queue the SQL {@link org.voltdb.SQLStmt statement} for execution with the specified argument list.
@param stmt {@link org.voltdb.SQLStmt Statement} to queue for execution.
@param args List of arguments to be bound as parameters for the {@link org.voltdb.SQLStmt statement}
@see <a href="#allowable_params">List of allowable parameter types</a>
"""
m_runner.voltQueueSQL(stmt, (Expectation) null, args);
} | java | public void voltQueueSQL(final SQLStmt stmt, Object... args) {
m_runner.voltQueueSQL(stmt, (Expectation) null, args);
} | [
"public",
"void",
"voltQueueSQL",
"(",
"final",
"SQLStmt",
"stmt",
",",
"Object",
"...",
"args",
")",
"{",
"m_runner",
".",
"voltQueueSQL",
"(",
"stmt",
",",
"(",
"Expectation",
")",
"null",
",",
"args",
")",
";",
"}"
] | Queue the SQL {@link org.voltdb.SQLStmt statement} for execution with the specified argument list.
@param stmt {@link org.voltdb.SQLStmt Statement} to queue for execution.
@param args List of arguments to be bound as parameters for the {@link org.voltdb.SQLStmt statement}
@see <a href="#allowable_params">List of allowable parameter types</a> | [
"Queue",
"the",
"SQL",
"{",
"@link",
"org",
".",
"voltdb",
".",
"SQLStmt",
"statement",
"}",
"for",
"execution",
"with",
"the",
"specified",
"argument",
"list",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/VoltProcedure.java#L243-L245 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/NodeManager.java | NodeManager.deleteAppFromNode | public Set<ClusterNode.GrantId> deleteAppFromNode(
String nodeName, ResourceType type) {
"""
Remove one application type from the node. Happens when the daemon
responsible for handling this application type on the node goes down
@param nodeName the name of the node
@param type the type of the resource
@return the list of grants that belonged to the application on this node
"""
ClusterNode node = nameToNode.get(nodeName);
if (node == null) {
LOG.warn("Trying to delete type " + type +
" from non-existent node: " + nodeName);
return null;
}
return deleteAppFromNode(node, type);
} | java | public Set<ClusterNode.GrantId> deleteAppFromNode(
String nodeName, ResourceType type) {
ClusterNode node = nameToNode.get(nodeName);
if (node == null) {
LOG.warn("Trying to delete type " + type +
" from non-existent node: " + nodeName);
return null;
}
return deleteAppFromNode(node, type);
} | [
"public",
"Set",
"<",
"ClusterNode",
".",
"GrantId",
">",
"deleteAppFromNode",
"(",
"String",
"nodeName",
",",
"ResourceType",
"type",
")",
"{",
"ClusterNode",
"node",
"=",
"nameToNode",
".",
"get",
"(",
"nodeName",
")",
";",
"if",
"(",
"node",
"==",
"null",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Trying to delete type \"",
"+",
"type",
"+",
"\" from non-existent node: \"",
"+",
"nodeName",
")",
";",
"return",
"null",
";",
"}",
"return",
"deleteAppFromNode",
"(",
"node",
",",
"type",
")",
";",
"}"
] | Remove one application type from the node. Happens when the daemon
responsible for handling this application type on the node goes down
@param nodeName the name of the node
@param type the type of the resource
@return the list of grants that belonged to the application on this node | [
"Remove",
"one",
"application",
"type",
"from",
"the",
"node",
".",
"Happens",
"when",
"the",
"daemon",
"responsible",
"for",
"handling",
"this",
"application",
"type",
"on",
"the",
"node",
"goes",
"down"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/NodeManager.java#L787-L796 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java | AccountsInner.listStorageAccountsWithServiceResponseAsync | public Observable<ServiceResponse<Page<StorageAccountInfoInner>>> listStorageAccountsWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String filter, final Integer top, final Integer skip, final String expand, final String select, final String orderby, final Boolean count, final String search, final String format) {
"""
Gets the first page of Azure Storage accounts, if any, linked to the specified Data Lake Analytics account. The response includes a link to the next page, if any.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account for which to list Azure Storage accounts.
@param filter The OData filter. Optional.
@param top The number of items to return. Optional.
@param skip The number of items to skip over before returning elements. Optional.
@param expand OData expansion. Expand related resources in line with the retrieved resources, e.g. Categories/$expand=Products would expand Product data in line with each Category entry. Optional.
@param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional.
@param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional.
@param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional.
@param search A free form search. A free-text search expression to match for whether a particular entry should be included in the feed, e.g. Categories?$search=blue OR green. Optional.
@param format The desired return format. Return the response in particular formatxii without access to request headers for standard content-type negotiation (e.g Orders?$format=json). Optional.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StorageAccountInfoInner> object
"""
return listStorageAccountsSinglePageAsync(resourceGroupName, accountName, filter, top, skip, expand, select, orderby, count, search, format)
.concatMap(new Func1<ServiceResponse<Page<StorageAccountInfoInner>>, Observable<ServiceResponse<Page<StorageAccountInfoInner>>>>() {
@Override
public Observable<ServiceResponse<Page<StorageAccountInfoInner>>> call(ServiceResponse<Page<StorageAccountInfoInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listStorageAccountsNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<StorageAccountInfoInner>>> listStorageAccountsWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String filter, final Integer top, final Integer skip, final String expand, final String select, final String orderby, final Boolean count, final String search, final String format) {
return listStorageAccountsSinglePageAsync(resourceGroupName, accountName, filter, top, skip, expand, select, orderby, count, search, format)
.concatMap(new Func1<ServiceResponse<Page<StorageAccountInfoInner>>, Observable<ServiceResponse<Page<StorageAccountInfoInner>>>>() {
@Override
public Observable<ServiceResponse<Page<StorageAccountInfoInner>>> call(ServiceResponse<Page<StorageAccountInfoInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listStorageAccountsNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"StorageAccountInfoInner",
">",
">",
">",
"listStorageAccountsWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
",",
"final",
"String",
"filter",
",",
"final",
"Integer",
"top",
",",
"final",
"Integer",
"skip",
",",
"final",
"String",
"expand",
",",
"final",
"String",
"select",
",",
"final",
"String",
"orderby",
",",
"final",
"Boolean",
"count",
",",
"final",
"String",
"search",
",",
"final",
"String",
"format",
")",
"{",
"return",
"listStorageAccountsSinglePageAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"filter",
",",
"top",
",",
"skip",
",",
"expand",
",",
"select",
",",
"orderby",
",",
"count",
",",
"search",
",",
"format",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"StorageAccountInfoInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"StorageAccountInfoInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"StorageAccountInfoInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"StorageAccountInfoInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listStorageAccountsNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the first page of Azure Storage accounts, if any, linked to the specified Data Lake Analytics account. The response includes a link to the next page, if any.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account.
@param accountName The name of the Data Lake Analytics account for which to list Azure Storage accounts.
@param filter The OData filter. Optional.
@param top The number of items to return. Optional.
@param skip The number of items to skip over before returning elements. Optional.
@param expand OData expansion. Expand related resources in line with the retrieved resources, e.g. Categories/$expand=Products would expand Product data in line with each Category entry. Optional.
@param select OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional.
@param orderby OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, e.g. Categories?$orderby=CategoryName desc. Optional.
@param count The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. Optional.
@param search A free form search. A free-text search expression to match for whether a particular entry should be included in the feed, e.g. Categories?$search=blue OR green. Optional.
@param format The desired return format. Return the response in particular formatxii without access to request headers for standard content-type negotiation (e.g Orders?$format=json). Optional.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StorageAccountInfoInner> object | [
"Gets",
"the",
"first",
"page",
"of",
"Azure",
"Storage",
"accounts",
"if",
"any",
"linked",
"to",
"the",
"specified",
"Data",
"Lake",
"Analytics",
"account",
".",
"The",
"response",
"includes",
"a",
"link",
"to",
"the",
"next",
"page",
"if",
"any",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L1449-L1461 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java | DateFormatSymbols.setZodiacNames | public void setZodiacNames(String[] zodiacNames, int context, int width) {
"""
Sets calendar zodiac name strings, for example: "Rat", "Ox", "Tiger", etc.
@param zodiacNames The new zodiac name strings.
@param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported).
@param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported).
"""
if (context == FORMAT && width == ABBREVIATED) {
shortZodiacNames = duplicate(zodiacNames);
}
} | java | public void setZodiacNames(String[] zodiacNames, int context, int width) {
if (context == FORMAT && width == ABBREVIATED) {
shortZodiacNames = duplicate(zodiacNames);
}
} | [
"public",
"void",
"setZodiacNames",
"(",
"String",
"[",
"]",
"zodiacNames",
",",
"int",
"context",
",",
"int",
"width",
")",
"{",
"if",
"(",
"context",
"==",
"FORMAT",
"&&",
"width",
"==",
"ABBREVIATED",
")",
"{",
"shortZodiacNames",
"=",
"duplicate",
"(",
"zodiacNames",
")",
";",
"}",
"}"
] | Sets calendar zodiac name strings, for example: "Rat", "Ox", "Tiger", etc.
@param zodiacNames The new zodiac name strings.
@param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported).
@param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported). | [
"Sets",
"calendar",
"zodiac",
"name",
"strings",
"for",
"example",
":",
"Rat",
"Ox",
"Tiger",
"etc",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java#L1148-L1152 |
sarl/sarl | docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java | SarlLinkFactory.getLinkForClass | protected Content getLinkForClass(Content link, LinkInfo linkInfo, Type type) {
"""
Build the link for the class.
@param link the link.
@param linkInfo the information on the link.
@param type the type.
@return the content.
"""
if (linkInfo.isTypeBound && linkInfo.excludeTypeBoundsLinks) {
//Since we are excluding type parameter links, we should not
//be linking to the type bound.
link.addContent(type.typeName());
link.addContent(getTypeParameterLinks(linkInfo));
return null;
}
linkInfo.classDoc = type.asClassDoc();
final Content nlink = newContent();
nlink.addContent(getClassLink(linkInfo));
if (linkInfo.includeTypeAsSepLink) {
nlink.addContent(getTypeParameterLinks(linkInfo, false));
}
return nlink;
} | java | protected Content getLinkForClass(Content link, LinkInfo linkInfo, Type type) {
if (linkInfo.isTypeBound && linkInfo.excludeTypeBoundsLinks) {
//Since we are excluding type parameter links, we should not
//be linking to the type bound.
link.addContent(type.typeName());
link.addContent(getTypeParameterLinks(linkInfo));
return null;
}
linkInfo.classDoc = type.asClassDoc();
final Content nlink = newContent();
nlink.addContent(getClassLink(linkInfo));
if (linkInfo.includeTypeAsSepLink) {
nlink.addContent(getTypeParameterLinks(linkInfo, false));
}
return nlink;
} | [
"protected",
"Content",
"getLinkForClass",
"(",
"Content",
"link",
",",
"LinkInfo",
"linkInfo",
",",
"Type",
"type",
")",
"{",
"if",
"(",
"linkInfo",
".",
"isTypeBound",
"&&",
"linkInfo",
".",
"excludeTypeBoundsLinks",
")",
"{",
"//Since we are excluding type parameter links, we should not",
"//be linking to the type bound.",
"link",
".",
"addContent",
"(",
"type",
".",
"typeName",
"(",
")",
")",
";",
"link",
".",
"addContent",
"(",
"getTypeParameterLinks",
"(",
"linkInfo",
")",
")",
";",
"return",
"null",
";",
"}",
"linkInfo",
".",
"classDoc",
"=",
"type",
".",
"asClassDoc",
"(",
")",
";",
"final",
"Content",
"nlink",
"=",
"newContent",
"(",
")",
";",
"nlink",
".",
"addContent",
"(",
"getClassLink",
"(",
"linkInfo",
")",
")",
";",
"if",
"(",
"linkInfo",
".",
"includeTypeAsSepLink",
")",
"{",
"nlink",
".",
"addContent",
"(",
"getTypeParameterLinks",
"(",
"linkInfo",
",",
"false",
")",
")",
";",
"}",
"return",
"nlink",
";",
"}"
] | Build the link for the class.
@param link the link.
@param linkInfo the information on the link.
@param type the type.
@return the content. | [
"Build",
"the",
"link",
"for",
"the",
"class",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/references/SarlLinkFactory.java#L158-L173 |
looly/hutool | hutool-http/src/main/java/cn/hutool/http/HttpUtil.java | HttpUtil.downloadString | public static String downloadString(String url, Charset customCharset, StreamProgress streamPress) {
"""
下载远程文本
@param url 请求的url
@param customCharset 自定义的字符集,可以使用{@link CharsetUtil#charset} 方法转换
@param streamPress 进度条 {@link StreamProgress}
@return 文本
"""
if (StrUtil.isBlank(url)) {
throw new NullPointerException("[url] is null!");
}
FastByteArrayOutputStream out = new FastByteArrayOutputStream();
download(url, out, true, streamPress);
return null == customCharset ? out.toString() : out.toString(customCharset);
} | java | public static String downloadString(String url, Charset customCharset, StreamProgress streamPress) {
if (StrUtil.isBlank(url)) {
throw new NullPointerException("[url] is null!");
}
FastByteArrayOutputStream out = new FastByteArrayOutputStream();
download(url, out, true, streamPress);
return null == customCharset ? out.toString() : out.toString(customCharset);
} | [
"public",
"static",
"String",
"downloadString",
"(",
"String",
"url",
",",
"Charset",
"customCharset",
",",
"StreamProgress",
"streamPress",
")",
"{",
"if",
"(",
"StrUtil",
".",
"isBlank",
"(",
"url",
")",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"[url] is null!\"",
")",
";",
"}",
"FastByteArrayOutputStream",
"out",
"=",
"new",
"FastByteArrayOutputStream",
"(",
")",
";",
"download",
"(",
"url",
",",
"out",
",",
"true",
",",
"streamPress",
")",
";",
"return",
"null",
"==",
"customCharset",
"?",
"out",
".",
"toString",
"(",
")",
":",
"out",
".",
"toString",
"(",
"customCharset",
")",
";",
"}"
] | 下载远程文本
@param url 请求的url
@param customCharset 自定义的字符集,可以使用{@link CharsetUtil#charset} 方法转换
@param streamPress 进度条 {@link StreamProgress}
@return 文本 | [
"下载远程文本"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/HttpUtil.java#L237-L245 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/notification/ClientNotificationArea.java | ClientNotificationArea.addServerNotificationListener | public void addServerNotificationListener(RESTRequest request, ServerNotificationRegistration serverNotificationRegistration, JSONConverter converter) {
"""
Add the server notification to our internal list so we can cleanup afterwards
"""
NotificationTargetInformation nti = toNotificationTargetInformation(request, serverNotificationRegistration.objectName.getCanonicalName());
//Fetch the filter/handback objects
NotificationFilter filter = (NotificationFilter) getObject(serverNotificationRegistration.filterID, serverNotificationRegistration.filter, converter);
Object handback = getObject(serverNotificationRegistration.handbackID, serverNotificationRegistration.handback, converter);
// Check whether the producer of the notification is local or remote.
if (nti.getRoutingInformation() == null) {
//Add to the MBeanServer
MBeanServerHelper.addServerNotification(serverNotificationRegistration.objectName,
serverNotificationRegistration.listener,
filter,
handback,
converter);
} else {
// Add the notification listener to the Target-Client Manager through EventAdmin
MBeanRoutedNotificationHelper helper = MBeanRoutedNotificationHelper.getMBeanRoutedNotificationHelper();
helper.addRoutedServerNotificationListener(nti,
serverNotificationRegistration.listener,
filter,
handback,
converter);
}
//Make the local ServerNotification
ServerNotification serverNotification = new ServerNotification();
serverNotification.listener = serverNotificationRegistration.listener;
serverNotification.filter = serverNotificationRegistration.filterID;
serverNotification.handback = serverNotificationRegistration.handbackID;
//See if there's a list already
List<ServerNotification> list = serverNotifications.get(nti);
if (list == null) {
list = Collections.synchronizedList(new ArrayList<ServerNotification>());
List<ServerNotification> mapList = serverNotifications.putIfAbsent(nti, list);
if (mapList != null) {
list = mapList;
}
}
//Add the new notification into the list
list.add(serverNotification);
} | java | public void addServerNotificationListener(RESTRequest request, ServerNotificationRegistration serverNotificationRegistration, JSONConverter converter) {
NotificationTargetInformation nti = toNotificationTargetInformation(request, serverNotificationRegistration.objectName.getCanonicalName());
//Fetch the filter/handback objects
NotificationFilter filter = (NotificationFilter) getObject(serverNotificationRegistration.filterID, serverNotificationRegistration.filter, converter);
Object handback = getObject(serverNotificationRegistration.handbackID, serverNotificationRegistration.handback, converter);
// Check whether the producer of the notification is local or remote.
if (nti.getRoutingInformation() == null) {
//Add to the MBeanServer
MBeanServerHelper.addServerNotification(serverNotificationRegistration.objectName,
serverNotificationRegistration.listener,
filter,
handback,
converter);
} else {
// Add the notification listener to the Target-Client Manager through EventAdmin
MBeanRoutedNotificationHelper helper = MBeanRoutedNotificationHelper.getMBeanRoutedNotificationHelper();
helper.addRoutedServerNotificationListener(nti,
serverNotificationRegistration.listener,
filter,
handback,
converter);
}
//Make the local ServerNotification
ServerNotification serverNotification = new ServerNotification();
serverNotification.listener = serverNotificationRegistration.listener;
serverNotification.filter = serverNotificationRegistration.filterID;
serverNotification.handback = serverNotificationRegistration.handbackID;
//See if there's a list already
List<ServerNotification> list = serverNotifications.get(nti);
if (list == null) {
list = Collections.synchronizedList(new ArrayList<ServerNotification>());
List<ServerNotification> mapList = serverNotifications.putIfAbsent(nti, list);
if (mapList != null) {
list = mapList;
}
}
//Add the new notification into the list
list.add(serverNotification);
} | [
"public",
"void",
"addServerNotificationListener",
"(",
"RESTRequest",
"request",
",",
"ServerNotificationRegistration",
"serverNotificationRegistration",
",",
"JSONConverter",
"converter",
")",
"{",
"NotificationTargetInformation",
"nti",
"=",
"toNotificationTargetInformation",
"(",
"request",
",",
"serverNotificationRegistration",
".",
"objectName",
".",
"getCanonicalName",
"(",
")",
")",
";",
"//Fetch the filter/handback objects",
"NotificationFilter",
"filter",
"=",
"(",
"NotificationFilter",
")",
"getObject",
"(",
"serverNotificationRegistration",
".",
"filterID",
",",
"serverNotificationRegistration",
".",
"filter",
",",
"converter",
")",
";",
"Object",
"handback",
"=",
"getObject",
"(",
"serverNotificationRegistration",
".",
"handbackID",
",",
"serverNotificationRegistration",
".",
"handback",
",",
"converter",
")",
";",
"// Check whether the producer of the notification is local or remote.",
"if",
"(",
"nti",
".",
"getRoutingInformation",
"(",
")",
"==",
"null",
")",
"{",
"//Add to the MBeanServer",
"MBeanServerHelper",
".",
"addServerNotification",
"(",
"serverNotificationRegistration",
".",
"objectName",
",",
"serverNotificationRegistration",
".",
"listener",
",",
"filter",
",",
"handback",
",",
"converter",
")",
";",
"}",
"else",
"{",
"// Add the notification listener to the Target-Client Manager through EventAdmin",
"MBeanRoutedNotificationHelper",
"helper",
"=",
"MBeanRoutedNotificationHelper",
".",
"getMBeanRoutedNotificationHelper",
"(",
")",
";",
"helper",
".",
"addRoutedServerNotificationListener",
"(",
"nti",
",",
"serverNotificationRegistration",
".",
"listener",
",",
"filter",
",",
"handback",
",",
"converter",
")",
";",
"}",
"//Make the local ServerNotification",
"ServerNotification",
"serverNotification",
"=",
"new",
"ServerNotification",
"(",
")",
";",
"serverNotification",
".",
"listener",
"=",
"serverNotificationRegistration",
".",
"listener",
";",
"serverNotification",
".",
"filter",
"=",
"serverNotificationRegistration",
".",
"filterID",
";",
"serverNotification",
".",
"handback",
"=",
"serverNotificationRegistration",
".",
"handbackID",
";",
"//See if there's a list already",
"List",
"<",
"ServerNotification",
">",
"list",
"=",
"serverNotifications",
".",
"get",
"(",
"nti",
")",
";",
"if",
"(",
"list",
"==",
"null",
")",
"{",
"list",
"=",
"Collections",
".",
"synchronizedList",
"(",
"new",
"ArrayList",
"<",
"ServerNotification",
">",
"(",
")",
")",
";",
"List",
"<",
"ServerNotification",
">",
"mapList",
"=",
"serverNotifications",
".",
"putIfAbsent",
"(",
"nti",
",",
"list",
")",
";",
"if",
"(",
"mapList",
"!=",
"null",
")",
"{",
"list",
"=",
"mapList",
";",
"}",
"}",
"//Add the new notification into the list",
"list",
".",
"add",
"(",
"serverNotification",
")",
";",
"}"
] | Add the server notification to our internal list so we can cleanup afterwards | [
"Add",
"the",
"server",
"notification",
"to",
"our",
"internal",
"list",
"so",
"we",
"can",
"cleanup",
"afterwards"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/notification/ClientNotificationArea.java#L497-L542 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/flow/FlowPath.java | FlowPath.setRewindPositionOnce | public void setRewindPositionOnce(@NonNull String frameName, int position) {
"""
This method allows to set position for next rewind within graph.
PLEASE NOTE: This methods check, if rewind position wasn't set yet. If it was already set for this frame - it'll be no-op method
@param frameName
@param position
"""
if (getRewindPosition(frameName) >= 0)
return;
frames.get(frameName).setRewindPosition(position);
} | java | public void setRewindPositionOnce(@NonNull String frameName, int position) {
if (getRewindPosition(frameName) >= 0)
return;
frames.get(frameName).setRewindPosition(position);
} | [
"public",
"void",
"setRewindPositionOnce",
"(",
"@",
"NonNull",
"String",
"frameName",
",",
"int",
"position",
")",
"{",
"if",
"(",
"getRewindPosition",
"(",
"frameName",
")",
">=",
"0",
")",
"return",
";",
"frames",
".",
"get",
"(",
"frameName",
")",
".",
"setRewindPosition",
"(",
"position",
")",
";",
"}"
] | This method allows to set position for next rewind within graph.
PLEASE NOTE: This methods check, if rewind position wasn't set yet. If it was already set for this frame - it'll be no-op method
@param frameName
@param position | [
"This",
"method",
"allows",
"to",
"set",
"position",
"for",
"next",
"rewind",
"within",
"graph",
".",
"PLEASE",
"NOTE",
":",
"This",
"methods",
"check",
"if",
"rewind",
"position",
"wasn",
"t",
"set",
"yet",
".",
"If",
"it",
"was",
"already",
"set",
"for",
"this",
"frame",
"-",
"it",
"ll",
"be",
"no",
"-",
"op",
"method"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/flow/FlowPath.java#L208-L213 |
before/uadetector | modules/uadetector-resources/src/main/java/net/sf/uadetector/service/UADetectorServiceFactory.java | UADetectorServiceFactory.getOnlineUpdatingParser | public static UserAgentStringParser getOnlineUpdatingParser(final URL dataUrl, final URL versionUrl) {
"""
Returns an implementation of {@link UserAgentStringParser} which checks at regular intervals for new versions of
<em>UAS data</em> (also known as database). When newer data available, it automatically loads and updates it.
<p>
At initialization time the returned parser will be loaded with the <em>UAS data</em> of this module (the shipped
one within the <em>uadetector-resources</em> JAR) and tries to update it. The initialization is started only when
this method is called the first time.
<p>
The update of the data store runs as background task. With this feature we try to reduce the initialization time
of this <code>UserAgentStringParser</code>, because a network connection is involved and the remote system can be
not available or slow.
<p>
The static class definition {@code OnlineUpdatingParserHolder} within this factory class is <em>not</em>
initialized until the JVM determines that {@code OnlineUpdatingParserHolder} must be executed. The static class
{@code OnlineUpdatingParserHolder} is only executed when the static method {@code getOnlineUserAgentStringParser}
is invoked on the class {@code UADetectorServiceFactory}, and the first time this happens the JVM will load and
initialize the {@code OnlineUpdatingParserHolder} class.
<p>
If during the operation the Internet connection gets lost, then this instance continues to work properly (and
under correct log level settings you will get an corresponding log messages).
@param dataUrl
@param versionUrl
@return an user agent string parser with updating service
"""
return OnlineUpdatingParserHolder.getParser(dataUrl, versionUrl, RESOURCE_MODULE);
} | java | public static UserAgentStringParser getOnlineUpdatingParser(final URL dataUrl, final URL versionUrl) {
return OnlineUpdatingParserHolder.getParser(dataUrl, versionUrl, RESOURCE_MODULE);
} | [
"public",
"static",
"UserAgentStringParser",
"getOnlineUpdatingParser",
"(",
"final",
"URL",
"dataUrl",
",",
"final",
"URL",
"versionUrl",
")",
"{",
"return",
"OnlineUpdatingParserHolder",
".",
"getParser",
"(",
"dataUrl",
",",
"versionUrl",
",",
"RESOURCE_MODULE",
")",
";",
"}"
] | Returns an implementation of {@link UserAgentStringParser} which checks at regular intervals for new versions of
<em>UAS data</em> (also known as database). When newer data available, it automatically loads and updates it.
<p>
At initialization time the returned parser will be loaded with the <em>UAS data</em> of this module (the shipped
one within the <em>uadetector-resources</em> JAR) and tries to update it. The initialization is started only when
this method is called the first time.
<p>
The update of the data store runs as background task. With this feature we try to reduce the initialization time
of this <code>UserAgentStringParser</code>, because a network connection is involved and the remote system can be
not available or slow.
<p>
The static class definition {@code OnlineUpdatingParserHolder} within this factory class is <em>not</em>
initialized until the JVM determines that {@code OnlineUpdatingParserHolder} must be executed. The static class
{@code OnlineUpdatingParserHolder} is only executed when the static method {@code getOnlineUserAgentStringParser}
is invoked on the class {@code UADetectorServiceFactory}, and the first time this happens the JVM will load and
initialize the {@code OnlineUpdatingParserHolder} class.
<p>
If during the operation the Internet connection gets lost, then this instance continues to work properly (and
under correct log level settings you will get an corresponding log messages).
@param dataUrl
@param versionUrl
@return an user agent string parser with updating service | [
"Returns",
"an",
"implementation",
"of",
"{",
"@link",
"UserAgentStringParser",
"}",
"which",
"checks",
"at",
"regular",
"intervals",
"for",
"new",
"versions",
"of",
"<em",
">",
"UAS",
"data<",
"/",
"em",
">",
"(",
"also",
"known",
"as",
"database",
")",
".",
"When",
"newer",
"data",
"available",
"it",
"automatically",
"loads",
"and",
"updates",
"it",
"."
] | train | https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-resources/src/main/java/net/sf/uadetector/service/UADetectorServiceFactory.java#L253-L255 |
mikepenz/Android-Iconics | library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java | IconicsDrawable.roundedCornersRxDp | @NonNull
public IconicsDrawable roundedCornersRxDp(@Dimension(unit = DP) int sizeDp) {
"""
Set rounded corner from dp
@return The current IconicsDrawable for chaining.
"""
return roundedCornersRxPx(Utils.convertDpToPx(mContext, sizeDp));
} | java | @NonNull
public IconicsDrawable roundedCornersRxDp(@Dimension(unit = DP) int sizeDp) {
return roundedCornersRxPx(Utils.convertDpToPx(mContext, sizeDp));
} | [
"@",
"NonNull",
"public",
"IconicsDrawable",
"roundedCornersRxDp",
"(",
"@",
"Dimension",
"(",
"unit",
"=",
"DP",
")",
"int",
"sizeDp",
")",
"{",
"return",
"roundedCornersRxPx",
"(",
"Utils",
".",
"convertDpToPx",
"(",
"mContext",
",",
"sizeDp",
")",
")",
";",
"}"
] | Set rounded corner from dp
@return The current IconicsDrawable for chaining. | [
"Set",
"rounded",
"corner",
"from",
"dp"
] | train | https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L912-L915 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java | ReflectionUtils.hasInterface | public static boolean hasInterface(Class<?> clazz, Class<?> iface) {
"""
Tells if a class (or one of its super-classes) implements an interface;
or an interface is a sub-interface of a super-interface.
Note:
<ul>
<li>Sub-interface against super-interface: this method returns
{@code true}.</li>
<li>Class against interface: this method returns {@code true}.</li>
<li>Class against super-interface: this method returns {@code true}.</li>
</ul>
@param clazz
@param iface
@return
"""
if (clazz == null || iface == null || clazz == iface) {
return false;
}
return iface.isInterface() && iface.isAssignableFrom(clazz);
} | java | public static boolean hasInterface(Class<?> clazz, Class<?> iface) {
if (clazz == null || iface == null || clazz == iface) {
return false;
}
return iface.isInterface() && iface.isAssignableFrom(clazz);
} | [
"public",
"static",
"boolean",
"hasInterface",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Class",
"<",
"?",
">",
"iface",
")",
"{",
"if",
"(",
"clazz",
"==",
"null",
"||",
"iface",
"==",
"null",
"||",
"clazz",
"==",
"iface",
")",
"{",
"return",
"false",
";",
"}",
"return",
"iface",
".",
"isInterface",
"(",
")",
"&&",
"iface",
".",
"isAssignableFrom",
"(",
"clazz",
")",
";",
"}"
] | Tells if a class (or one of its super-classes) implements an interface;
or an interface is a sub-interface of a super-interface.
Note:
<ul>
<li>Sub-interface against super-interface: this method returns
{@code true}.</li>
<li>Class against interface: this method returns {@code true}.</li>
<li>Class against super-interface: this method returns {@code true}.</li>
</ul>
@param clazz
@param iface
@return | [
"Tells",
"if",
"a",
"class",
"(",
"or",
"one",
"of",
"its",
"super",
"-",
"classes",
")",
"implements",
"an",
"interface",
";",
"or",
"an",
"interface",
"is",
"a",
"sub",
"-",
"interface",
"of",
"a",
"super",
"-",
"interface",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ReflectionUtils.java#L146-L151 |
kite-sdk/kite | kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveAbstractMetadataProvider.java | HiveAbstractMetadataProvider.isExternal | protected boolean isExternal(String namespace, String name) {
"""
Returns whether the table is a managed hive table.
@param name a Table name
@return true if the table is managed, false otherwise
@throws DatasetNotFoundException If the table does not exist in Hive
"""
String resolved = resolveNamespace(namespace, name);
if (resolved != null) {
return isExternal(getMetaStoreUtil().getTable(resolved, name));
}
return false;
} | java | protected boolean isExternal(String namespace, String name) {
String resolved = resolveNamespace(namespace, name);
if (resolved != null) {
return isExternal(getMetaStoreUtil().getTable(resolved, name));
}
return false;
} | [
"protected",
"boolean",
"isExternal",
"(",
"String",
"namespace",
",",
"String",
"name",
")",
"{",
"String",
"resolved",
"=",
"resolveNamespace",
"(",
"namespace",
",",
"name",
")",
";",
"if",
"(",
"resolved",
"!=",
"null",
")",
"{",
"return",
"isExternal",
"(",
"getMetaStoreUtil",
"(",
")",
".",
"getTable",
"(",
"resolved",
",",
"name",
")",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Returns whether the table is a managed hive table.
@param name a Table name
@return true if the table is managed, false otherwise
@throws DatasetNotFoundException If the table does not exist in Hive | [
"Returns",
"whether",
"the",
"table",
"is",
"a",
"managed",
"hive",
"table",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveAbstractMetadataProvider.java#L90-L96 |
fcrepo3/fcrepo | fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java | InstallOptions.validateAll | private void validateAll() throws OptionValidationException {
"""
Validate the options, assuming defaults have already been applied.
Validation for a given option might entail more than a syntax check. It
might check whether a given directory exists, for example.
"""
boolean unattended = getBooleanValue(UNATTENDED, false);
for (String optionId : getOptionNames()) {
OptionDefinition opt = OptionDefinition.get(optionId, this);
if (opt == null) {
throw new OptionValidationException("Option is not defined", optionId);
}
opt.validateValue(getValue(optionId), unattended);
}
} | java | private void validateAll() throws OptionValidationException {
boolean unattended = getBooleanValue(UNATTENDED, false);
for (String optionId : getOptionNames()) {
OptionDefinition opt = OptionDefinition.get(optionId, this);
if (opt == null) {
throw new OptionValidationException("Option is not defined", optionId);
}
opt.validateValue(getValue(optionId), unattended);
}
} | [
"private",
"void",
"validateAll",
"(",
")",
"throws",
"OptionValidationException",
"{",
"boolean",
"unattended",
"=",
"getBooleanValue",
"(",
"UNATTENDED",
",",
"false",
")",
";",
"for",
"(",
"String",
"optionId",
":",
"getOptionNames",
"(",
")",
")",
"{",
"OptionDefinition",
"opt",
"=",
"OptionDefinition",
".",
"get",
"(",
"optionId",
",",
"this",
")",
";",
"if",
"(",
"opt",
"==",
"null",
")",
"{",
"throw",
"new",
"OptionValidationException",
"(",
"\"Option is not defined\"",
",",
"optionId",
")",
";",
"}",
"opt",
".",
"validateValue",
"(",
"getValue",
"(",
"optionId",
")",
",",
"unattended",
")",
";",
"}",
"}"
] | Validate the options, assuming defaults have already been applied.
Validation for a given option might entail more than a syntax check. It
might check whether a given directory exists, for example. | [
"Validate",
"the",
"options",
"assuming",
"defaults",
"have",
"already",
"been",
"applied",
".",
"Validation",
"for",
"a",
"given",
"option",
"might",
"entail",
"more",
"than",
"a",
"syntax",
"check",
".",
"It",
"might",
"check",
"whether",
"a",
"given",
"directory",
"exists",
"for",
"example",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-installer/src/main/java/org/fcrepo/utilities/install/InstallOptions.java#L474-L483 |
revelytix/spark | spark-http-client/src/main/java/spark/protocol/parser/XMLResultsParser.java | XMLResultsParser.parseBooleanResult | static private Result parseBooleanResult(Command cmd, XMLStreamReader rdr,
List<String> metadata) throws XMLStreamException, SparqlException {
"""
Parses a boolean result from the reader. The reader is expected to be on the START_ELEMENT
event for the opening <boolean> tag.
@param cmd The command to associate with the result.
@param rdr The XML reader from which to read the result.
@param metadata The metadata to include in the result.
@return The parsed result.
"""
if (rdr.next() != CHARACTERS) {
throw new SparqlException("Unexpected data in Boolean result: " + rdr.getEventType());
}
boolean result = Boolean.parseBoolean(rdr.getText());
testClose(rdr, rdr.nextTag(), BOOLEAN, "Bad close of boolean element");
cleanup(rdr);
return new ProtocolBooleanResult(cmd, result, metadata);
} | java | static private Result parseBooleanResult(Command cmd, XMLStreamReader rdr,
List<String> metadata) throws XMLStreamException, SparqlException {
if (rdr.next() != CHARACTERS) {
throw new SparqlException("Unexpected data in Boolean result: " + rdr.getEventType());
}
boolean result = Boolean.parseBoolean(rdr.getText());
testClose(rdr, rdr.nextTag(), BOOLEAN, "Bad close of boolean element");
cleanup(rdr);
return new ProtocolBooleanResult(cmd, result, metadata);
} | [
"static",
"private",
"Result",
"parseBooleanResult",
"(",
"Command",
"cmd",
",",
"XMLStreamReader",
"rdr",
",",
"List",
"<",
"String",
">",
"metadata",
")",
"throws",
"XMLStreamException",
",",
"SparqlException",
"{",
"if",
"(",
"rdr",
".",
"next",
"(",
")",
"!=",
"CHARACTERS",
")",
"{",
"throw",
"new",
"SparqlException",
"(",
"\"Unexpected data in Boolean result: \"",
"+",
"rdr",
".",
"getEventType",
"(",
")",
")",
";",
"}",
"boolean",
"result",
"=",
"Boolean",
".",
"parseBoolean",
"(",
"rdr",
".",
"getText",
"(",
")",
")",
";",
"testClose",
"(",
"rdr",
",",
"rdr",
".",
"nextTag",
"(",
")",
",",
"BOOLEAN",
",",
"\"Bad close of boolean element\"",
")",
";",
"cleanup",
"(",
"rdr",
")",
";",
"return",
"new",
"ProtocolBooleanResult",
"(",
"cmd",
",",
"result",
",",
"metadata",
")",
";",
"}"
] | Parses a boolean result from the reader. The reader is expected to be on the START_ELEMENT
event for the opening <boolean> tag.
@param cmd The command to associate with the result.
@param rdr The XML reader from which to read the result.
@param metadata The metadata to include in the result.
@return The parsed result. | [
"Parses",
"a",
"boolean",
"result",
"from",
"the",
"reader",
".",
"The",
"reader",
"is",
"expected",
"to",
"be",
"on",
"the",
"START_ELEMENT",
"event",
"for",
"the",
"opening",
"<boolean",
">",
"tag",
"."
] | train | https://github.com/revelytix/spark/blob/d777d40c962bc66fdc04b7c3a66d20b777ff6fb4/spark-http-client/src/main/java/spark/protocol/parser/XMLResultsParser.java#L174-L183 |
facebook/fresco | fbcore/src/main/java/com/facebook/common/util/UriUtil.java | UriUtil.getUriForQualifiedResource | public static Uri getUriForQualifiedResource(String packageName, int resourceId) {
"""
Returns a URI for the given resource ID in the given package. Use this method only if you need
to specify a package name different to your application's main package.
@param packageName a package name (e.g. com.facebook.myapp.plugin)
@param resourceId to resource ID to use
@return the URI
"""
return new Uri.Builder()
.scheme(QUALIFIED_RESOURCE_SCHEME)
.authority(packageName)
.path(String.valueOf(resourceId))
.build();
} | java | public static Uri getUriForQualifiedResource(String packageName, int resourceId) {
return new Uri.Builder()
.scheme(QUALIFIED_RESOURCE_SCHEME)
.authority(packageName)
.path(String.valueOf(resourceId))
.build();
} | [
"public",
"static",
"Uri",
"getUriForQualifiedResource",
"(",
"String",
"packageName",
",",
"int",
"resourceId",
")",
"{",
"return",
"new",
"Uri",
".",
"Builder",
"(",
")",
".",
"scheme",
"(",
"QUALIFIED_RESOURCE_SCHEME",
")",
".",
"authority",
"(",
"packageName",
")",
".",
"path",
"(",
"String",
".",
"valueOf",
"(",
"resourceId",
")",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a URI for the given resource ID in the given package. Use this method only if you need
to specify a package name different to your application's main package.
@param packageName a package name (e.g. com.facebook.myapp.plugin)
@param resourceId to resource ID to use
@return the URI | [
"Returns",
"a",
"URI",
"for",
"the",
"given",
"resource",
"ID",
"in",
"the",
"given",
"package",
".",
"Use",
"this",
"method",
"only",
"if",
"you",
"need",
"to",
"specify",
"a",
"package",
"name",
"different",
"to",
"your",
"application",
"s",
"main",
"package",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/util/UriUtil.java#L262-L268 |
kiswanij/jk-util | src/main/java/com/jk/util/JKNumbersUtil.java | JKNumbersUtil.addAmounts | public static double addAmounts(final double num1, final double num2) {
"""
Adds the amounts.
@param num1 the num 1
@param num2 the num 2
@return the double
"""
final BigDecimal b1 = new BigDecimal(num1);
final BigDecimal b2 = new BigDecimal(num2);
BigDecimal b3 = b1.add(b2);
b3 = b3.setScale(3, BigDecimal.ROUND_HALF_UP);
final double result = b3.doubleValue();
return result;
} | java | public static double addAmounts(final double num1, final double num2) {
final BigDecimal b1 = new BigDecimal(num1);
final BigDecimal b2 = new BigDecimal(num2);
BigDecimal b3 = b1.add(b2);
b3 = b3.setScale(3, BigDecimal.ROUND_HALF_UP);
final double result = b3.doubleValue();
return result;
} | [
"public",
"static",
"double",
"addAmounts",
"(",
"final",
"double",
"num1",
",",
"final",
"double",
"num2",
")",
"{",
"final",
"BigDecimal",
"b1",
"=",
"new",
"BigDecimal",
"(",
"num1",
")",
";",
"final",
"BigDecimal",
"b2",
"=",
"new",
"BigDecimal",
"(",
"num2",
")",
";",
"BigDecimal",
"b3",
"=",
"b1",
".",
"add",
"(",
"b2",
")",
";",
"b3",
"=",
"b3",
".",
"setScale",
"(",
"3",
",",
"BigDecimal",
".",
"ROUND_HALF_UP",
")",
";",
"final",
"double",
"result",
"=",
"b3",
".",
"doubleValue",
"(",
")",
";",
"return",
"result",
";",
"}"
] | Adds the amounts.
@param num1 the num 1
@param num2 the num 2
@return the double | [
"Adds",
"the",
"amounts",
"."
] | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKNumbersUtil.java#L36-L43 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/FullFrameRect.java | FullFrameRect.drawFrame | public void drawFrame(int textureId, float[] texMatrix) {
"""
Draws a viewport-filling rect, texturing it with the specified texture object.
"""
// Use the identity matrix for MVP so our 2x2 FULL_RECTANGLE covers the viewport.
synchronized (mDrawLock) {
if (mCorrectVerticalVideo && !mScaleToFit && (requestedOrientation == SCREEN_ROTATION.VERTICAL || requestedOrientation == SCREEN_ROTATION.UPSIDEDOWN_VERTICAL)) {
Matrix.scaleM(texMatrix, 0, 0.316f, 1.0f, 1f);
}
mProgram.draw(IDENTITY_MATRIX, mRectDrawable.getVertexArray(), 0,
mRectDrawable.getVertexCount(), mRectDrawable.getCoordsPerVertex(),
mRectDrawable.getVertexStride(),
texMatrix, TEX_COORDS_BUF, textureId, TEX_COORDS_STRIDE);
}
} | java | public void drawFrame(int textureId, float[] texMatrix) {
// Use the identity matrix for MVP so our 2x2 FULL_RECTANGLE covers the viewport.
synchronized (mDrawLock) {
if (mCorrectVerticalVideo && !mScaleToFit && (requestedOrientation == SCREEN_ROTATION.VERTICAL || requestedOrientation == SCREEN_ROTATION.UPSIDEDOWN_VERTICAL)) {
Matrix.scaleM(texMatrix, 0, 0.316f, 1.0f, 1f);
}
mProgram.draw(IDENTITY_MATRIX, mRectDrawable.getVertexArray(), 0,
mRectDrawable.getVertexCount(), mRectDrawable.getCoordsPerVertex(),
mRectDrawable.getVertexStride(),
texMatrix, TEX_COORDS_BUF, textureId, TEX_COORDS_STRIDE);
}
} | [
"public",
"void",
"drawFrame",
"(",
"int",
"textureId",
",",
"float",
"[",
"]",
"texMatrix",
")",
"{",
"// Use the identity matrix for MVP so our 2x2 FULL_RECTANGLE covers the viewport.",
"synchronized",
"(",
"mDrawLock",
")",
"{",
"if",
"(",
"mCorrectVerticalVideo",
"&&",
"!",
"mScaleToFit",
"&&",
"(",
"requestedOrientation",
"==",
"SCREEN_ROTATION",
".",
"VERTICAL",
"||",
"requestedOrientation",
"==",
"SCREEN_ROTATION",
".",
"UPSIDEDOWN_VERTICAL",
")",
")",
"{",
"Matrix",
".",
"scaleM",
"(",
"texMatrix",
",",
"0",
",",
"0.316f",
",",
"1.0f",
",",
"1f",
")",
";",
"}",
"mProgram",
".",
"draw",
"(",
"IDENTITY_MATRIX",
",",
"mRectDrawable",
".",
"getVertexArray",
"(",
")",
",",
"0",
",",
"mRectDrawable",
".",
"getVertexCount",
"(",
")",
",",
"mRectDrawable",
".",
"getCoordsPerVertex",
"(",
")",
",",
"mRectDrawable",
".",
"getVertexStride",
"(",
")",
",",
"texMatrix",
",",
"TEX_COORDS_BUF",
",",
"textureId",
",",
"TEX_COORDS_STRIDE",
")",
";",
"}",
"}"
] | Draws a viewport-filling rect, texturing it with the specified texture object. | [
"Draws",
"a",
"viewport",
"-",
"filling",
"rect",
"texturing",
"it",
"with",
"the",
"specified",
"texture",
"object",
"."
] | train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/FullFrameRect.java#L137-L148 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/FocusManager.java | FocusManager.resetFocus | public static void resetFocus (Stage stage, Actor caller) {
"""
Takes focus from current focused widget (if any), and sets current focused widget to null
@param stage if passed stage is not null then stage keyboard focus will be set to null only if current
focus owner is passed actor
"""
if (focusedWidget != null) focusedWidget.focusLost();
if (stage != null && stage.getKeyboardFocus() == caller) stage.setKeyboardFocus(null);
focusedWidget = null;
} | java | public static void resetFocus (Stage stage, Actor caller) {
if (focusedWidget != null) focusedWidget.focusLost();
if (stage != null && stage.getKeyboardFocus() == caller) stage.setKeyboardFocus(null);
focusedWidget = null;
} | [
"public",
"static",
"void",
"resetFocus",
"(",
"Stage",
"stage",
",",
"Actor",
"caller",
")",
"{",
"if",
"(",
"focusedWidget",
"!=",
"null",
")",
"focusedWidget",
".",
"focusLost",
"(",
")",
";",
"if",
"(",
"stage",
"!=",
"null",
"&&",
"stage",
".",
"getKeyboardFocus",
"(",
")",
"==",
"caller",
")",
"stage",
".",
"setKeyboardFocus",
"(",
"null",
")",
";",
"focusedWidget",
"=",
"null",
";",
"}"
] | Takes focus from current focused widget (if any), and sets current focused widget to null
@param stage if passed stage is not null then stage keyboard focus will be set to null only if current
focus owner is passed actor | [
"Takes",
"focus",
"from",
"current",
"focused",
"widget",
"(",
"if",
"any",
")",
"and",
"sets",
"current",
"focused",
"widget",
"to",
"null"
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/FocusManager.java#L61-L65 |
emilsjolander/sprinkles | library/src/main/java/se/emilsjolander/sprinkles/Query.java | Query.one | public static <T extends QueryResult> OneQuery<T> one(Class<T> clazz, int sqlResId,
Object... sqlArgs) {
"""
Start a query for a single instance of type T
@param clazz
The class representing the type of the model you want returned
@param sqlResId
The raw sql resource id that should be executed.
@param sqlArgs
The array of arguments to insert instead of ? in the placeholderQuery statement.
Strings are automatically placeholderQuery escaped.
@param <T>
The type of the model you want returned
@return the query to execute
"""
String sql = Utils.readRawText(sqlResId);
return one(clazz, sql, sqlArgs);
} | java | public static <T extends QueryResult> OneQuery<T> one(Class<T> clazz, int sqlResId,
Object... sqlArgs) {
String sql = Utils.readRawText(sqlResId);
return one(clazz, sql, sqlArgs);
} | [
"public",
"static",
"<",
"T",
"extends",
"QueryResult",
">",
"OneQuery",
"<",
"T",
">",
"one",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"int",
"sqlResId",
",",
"Object",
"...",
"sqlArgs",
")",
"{",
"String",
"sql",
"=",
"Utils",
".",
"readRawText",
"(",
"sqlResId",
")",
";",
"return",
"one",
"(",
"clazz",
",",
"sql",
",",
"sqlArgs",
")",
";",
"}"
] | Start a query for a single instance of type T
@param clazz
The class representing the type of the model you want returned
@param sqlResId
The raw sql resource id that should be executed.
@param sqlArgs
The array of arguments to insert instead of ? in the placeholderQuery statement.
Strings are automatically placeholderQuery escaped.
@param <T>
The type of the model you want returned
@return the query to execute | [
"Start",
"a",
"query",
"for",
"a",
"single",
"instance",
"of",
"type",
"T"
] | train | https://github.com/emilsjolander/sprinkles/blob/3a666f18ee5158db6fe3b4f4346b470481559606/library/src/main/java/se/emilsjolander/sprinkles/Query.java#L56-L60 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/selenium/SeleniumHelper.java | SeleniumHelper.doInCurrentContext | public <R> R doInCurrentContext(Function<SearchContext, ? extends R> function) {
"""
Perform action/supplier in current context.
@param function function to perform.
@param <R> type of result.
@return function result.
@throws StaleContextException if function threw stale element exception (i.e. current context could not be used)
"""
try {
return function.apply(getCurrentContext());
} catch (WebDriverException e) {
if (isStaleElementException(e)) {
// current context was no good to search in
currentContextIsStale = true;
// by getting the context we trigger explicit exception
getCurrentContext();
}
throw e;
}
} | java | public <R> R doInCurrentContext(Function<SearchContext, ? extends R> function) {
try {
return function.apply(getCurrentContext());
} catch (WebDriverException e) {
if (isStaleElementException(e)) {
// current context was no good to search in
currentContextIsStale = true;
// by getting the context we trigger explicit exception
getCurrentContext();
}
throw e;
}
} | [
"public",
"<",
"R",
">",
"R",
"doInCurrentContext",
"(",
"Function",
"<",
"SearchContext",
",",
"?",
"extends",
"R",
">",
"function",
")",
"{",
"try",
"{",
"return",
"function",
".",
"apply",
"(",
"getCurrentContext",
"(",
")",
")",
";",
"}",
"catch",
"(",
"WebDriverException",
"e",
")",
"{",
"if",
"(",
"isStaleElementException",
"(",
"e",
")",
")",
"{",
"// current context was no good to search in",
"currentContextIsStale",
"=",
"true",
";",
"// by getting the context we trigger explicit exception",
"getCurrentContext",
"(",
")",
";",
"}",
"throw",
"e",
";",
"}",
"}"
] | Perform action/supplier in current context.
@param function function to perform.
@param <R> type of result.
@return function result.
@throws StaleContextException if function threw stale element exception (i.e. current context could not be used) | [
"Perform",
"action",
"/",
"supplier",
"in",
"current",
"context",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/selenium/SeleniumHelper.java#L749-L761 |
aws/aws-sdk-java | aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/ComputeResource.java | ComputeResource.withTags | public ComputeResource withTags(java.util.Map<String, String> tags) {
"""
<p>
Key-value pair tags to be applied to resources that are launched in the compute environment. For AWS Batch, these
take the form of "String1": "String2", where String1 is the tag key and String2 is the tag value—for example, {
"Name": "AWS Batch Instance - C4OnDemand" }.
</p>
@param tags
Key-value pair tags to be applied to resources that are launched in the compute environment. For AWS
Batch, these take the form of "String1": "String2", where String1 is the tag key and String2 is the tag
value—for example, { "Name": "AWS Batch Instance - C4OnDemand" }.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public ComputeResource withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"ComputeResource",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Key-value pair tags to be applied to resources that are launched in the compute environment. For AWS Batch, these
take the form of "String1": "String2", where String1 is the tag key and String2 is the tag value—for example, {
"Name": "AWS Batch Instance - C4OnDemand" }.
</p>
@param tags
Key-value pair tags to be applied to resources that are launched in the compute environment. For AWS
Batch, these take the form of "String1": "String2", where String1 is the tag key and String2 is the tag
value—for example, { "Name": "AWS Batch Instance - C4OnDemand" }.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Key",
"-",
"value",
"pair",
"tags",
"to",
"be",
"applied",
"to",
"resources",
"that",
"are",
"launched",
"in",
"the",
"compute",
"environment",
".",
"For",
"AWS",
"Batch",
"these",
"take",
"the",
"form",
"of",
"String1",
":",
"String2",
"where",
"String1",
"is",
"the",
"tag",
"key",
"and",
"String2",
"is",
"the",
"tag",
"value—for",
"example",
"{",
"Name",
":",
"AWS",
"Batch",
"Instance",
"-",
"C4OnDemand",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/ComputeResource.java#L786-L789 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/TopicDistribution.java | TopicDistribution.setProbability | public void setProbability(int i, double v) {
"""
indexed setter for probability - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array
"""
if (TopicDistribution_Type.featOkTst && ((TopicDistribution_Type)jcasType).casFeat_probability == null)
jcasType.jcas.throwFeatMissing("probability", "ch.epfl.bbp.uima.types.TopicDistribution");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((TopicDistribution_Type)jcasType).casFeatCode_probability), i);
jcasType.ll_cas.ll_setDoubleArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((TopicDistribution_Type)jcasType).casFeatCode_probability), i, v);} | java | public void setProbability(int i, double v) {
if (TopicDistribution_Type.featOkTst && ((TopicDistribution_Type)jcasType).casFeat_probability == null)
jcasType.jcas.throwFeatMissing("probability", "ch.epfl.bbp.uima.types.TopicDistribution");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((TopicDistribution_Type)jcasType).casFeatCode_probability), i);
jcasType.ll_cas.ll_setDoubleArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((TopicDistribution_Type)jcasType).casFeatCode_probability), i, v);} | [
"public",
"void",
"setProbability",
"(",
"int",
"i",
",",
"double",
"v",
")",
"{",
"if",
"(",
"TopicDistribution_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"TopicDistribution_Type",
")",
"jcasType",
")",
".",
"casFeat_probability",
"==",
"null",
")",
"jcasType",
".",
"jcas",
".",
"throwFeatMissing",
"(",
"\"probability\"",
",",
"\"ch.epfl.bbp.uima.types.TopicDistribution\"",
")",
";",
"jcasType",
".",
"jcas",
".",
"checkArrayBounds",
"(",
"jcasType",
".",
"ll_cas",
".",
"ll_getRefValue",
"(",
"addr",
",",
"(",
"(",
"TopicDistribution_Type",
")",
"jcasType",
")",
".",
"casFeatCode_probability",
")",
",",
"i",
")",
";",
"jcasType",
".",
"ll_cas",
".",
"ll_setDoubleArrayValue",
"(",
"jcasType",
".",
"ll_cas",
".",
"ll_getRefValue",
"(",
"addr",
",",
"(",
"(",
"TopicDistribution_Type",
")",
"jcasType",
")",
".",
"casFeatCode_probability",
")",
",",
"i",
",",
"v",
")",
";",
"}"
] | indexed setter for probability - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"probability",
"-",
"sets",
"an",
"indexed",
"value",
"-"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/TopicDistribution.java#L117-L121 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.notEmpty | public static <T> T [] notEmpty (final T [] aValue, final String sName) {
"""
Check that the passed Array is neither <code>null</code> nor empty.
@param <T>
Type to be checked and returned
@param aValue
The Array to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is empty
"""
return notEmpty (aValue, () -> sName);
} | java | public static <T> T [] notEmpty (final T [] aValue, final String sName)
{
return notEmpty (aValue, () -> sName);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"[",
"]",
"notEmpty",
"(",
"final",
"T",
"[",
"]",
"aValue",
",",
"final",
"String",
"sName",
")",
"{",
"return",
"notEmpty",
"(",
"aValue",
",",
"(",
")",
"->",
"sName",
")",
";",
"}"
] | Check that the passed Array is neither <code>null</code> nor empty.
@param <T>
Type to be checked and returned
@param aValue
The Array to check.
@param sName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is empty | [
"Check",
"that",
"the",
"passed",
"Array",
"is",
"neither",
"<code",
">",
"null<",
"/",
"code",
">",
"nor",
"empty",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L390-L393 |
windup/windup | rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XmlFileService.java | XmlFileService.loadDocument | public Document loadDocument(GraphRewrite event, EvaluationContext context, XmlFileModel model) throws WindupException {
"""
Loads and parses the provided XML file. This will quietly fail (not throwing an {@link Exception}) and return
null if it is unable to parse the provided {@link XmlFileModel}. A {@link ClassificationModel} will be created to
indicate that this file failed to parse.
@return Returns either the parsed {@link Document} or null if the {@link Document} could not be parsed
"""
if (model.asFile().length() == 0)
{
final String msg = "Failed to parse, XML file is empty: " + model.getFilePath();
LOG.log(Level.WARNING, msg);
model.setParseError(msg);
throw new WindupException(msg);
}
ClassificationService classificationService = new ClassificationService(getGraphContext());
XMLDocumentCache.Result cacheResult = XMLDocumentCache.get(model);
if (cacheResult.isParseFailure())
{
final String msg = "Not loading XML file '" + model.getFilePath() + "' due to previous parse failure: " + model.getParseError();
LOG.log(Level.FINE, msg);
//model.setParseError(msg);
throw new WindupException(msg);
}
Document document = cacheResult.getDocument();
if (document != null)
return document;
// Not yet cached - load, store in cache and return.
try (InputStream is = model.asInputStream())
{
document = LocationAwareXmlReader.readXML(is);
XMLDocumentCache.cache(model, document);
}
catch (SAXException | IOException e)
{
XMLDocumentCache.cacheParseFailure(model);
document = null;
final String message = "Failed to parse XML file: " + model.getFilePath() + ", due to: " + e.getMessage();
LOG.log(Level.WARNING, message);
classificationService.attachClassification(event, context, model, UNPARSEABLE_XML_CLASSIFICATION, UNPARSEABLE_XML_DESCRIPTION);
model.setParseError(message);
throw new WindupException(message, e);
}
return document;
} | java | public Document loadDocument(GraphRewrite event, EvaluationContext context, XmlFileModel model) throws WindupException
{
if (model.asFile().length() == 0)
{
final String msg = "Failed to parse, XML file is empty: " + model.getFilePath();
LOG.log(Level.WARNING, msg);
model.setParseError(msg);
throw new WindupException(msg);
}
ClassificationService classificationService = new ClassificationService(getGraphContext());
XMLDocumentCache.Result cacheResult = XMLDocumentCache.get(model);
if (cacheResult.isParseFailure())
{
final String msg = "Not loading XML file '" + model.getFilePath() + "' due to previous parse failure: " + model.getParseError();
LOG.log(Level.FINE, msg);
//model.setParseError(msg);
throw new WindupException(msg);
}
Document document = cacheResult.getDocument();
if (document != null)
return document;
// Not yet cached - load, store in cache and return.
try (InputStream is = model.asInputStream())
{
document = LocationAwareXmlReader.readXML(is);
XMLDocumentCache.cache(model, document);
}
catch (SAXException | IOException e)
{
XMLDocumentCache.cacheParseFailure(model);
document = null;
final String message = "Failed to parse XML file: " + model.getFilePath() + ", due to: " + e.getMessage();
LOG.log(Level.WARNING, message);
classificationService.attachClassification(event, context, model, UNPARSEABLE_XML_CLASSIFICATION, UNPARSEABLE_XML_DESCRIPTION);
model.setParseError(message);
throw new WindupException(message, e);
}
return document;
} | [
"public",
"Document",
"loadDocument",
"(",
"GraphRewrite",
"event",
",",
"EvaluationContext",
"context",
",",
"XmlFileModel",
"model",
")",
"throws",
"WindupException",
"{",
"if",
"(",
"model",
".",
"asFile",
"(",
")",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"final",
"String",
"msg",
"=",
"\"Failed to parse, XML file is empty: \"",
"+",
"model",
".",
"getFilePath",
"(",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"msg",
")",
";",
"model",
".",
"setParseError",
"(",
"msg",
")",
";",
"throw",
"new",
"WindupException",
"(",
"msg",
")",
";",
"}",
"ClassificationService",
"classificationService",
"=",
"new",
"ClassificationService",
"(",
"getGraphContext",
"(",
")",
")",
";",
"XMLDocumentCache",
".",
"Result",
"cacheResult",
"=",
"XMLDocumentCache",
".",
"get",
"(",
"model",
")",
";",
"if",
"(",
"cacheResult",
".",
"isParseFailure",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"\"Not loading XML file '\"",
"+",
"model",
".",
"getFilePath",
"(",
")",
"+",
"\"' due to previous parse failure: \"",
"+",
"model",
".",
"getParseError",
"(",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"msg",
")",
";",
"//model.setParseError(msg);",
"throw",
"new",
"WindupException",
"(",
"msg",
")",
";",
"}",
"Document",
"document",
"=",
"cacheResult",
".",
"getDocument",
"(",
")",
";",
"if",
"(",
"document",
"!=",
"null",
")",
"return",
"document",
";",
"// Not yet cached - load, store in cache and return.",
"try",
"(",
"InputStream",
"is",
"=",
"model",
".",
"asInputStream",
"(",
")",
")",
"{",
"document",
"=",
"LocationAwareXmlReader",
".",
"readXML",
"(",
"is",
")",
";",
"XMLDocumentCache",
".",
"cache",
"(",
"model",
",",
"document",
")",
";",
"}",
"catch",
"(",
"SAXException",
"|",
"IOException",
"e",
")",
"{",
"XMLDocumentCache",
".",
"cacheParseFailure",
"(",
"model",
")",
";",
"document",
"=",
"null",
";",
"final",
"String",
"message",
"=",
"\"Failed to parse XML file: \"",
"+",
"model",
".",
"getFilePath",
"(",
")",
"+",
"\", due to: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"message",
")",
";",
"classificationService",
".",
"attachClassification",
"(",
"event",
",",
"context",
",",
"model",
",",
"UNPARSEABLE_XML_CLASSIFICATION",
",",
"UNPARSEABLE_XML_DESCRIPTION",
")",
";",
"model",
".",
"setParseError",
"(",
"message",
")",
";",
"throw",
"new",
"WindupException",
"(",
"message",
",",
"e",
")",
";",
"}",
"return",
"document",
";",
"}"
] | Loads and parses the provided XML file. This will quietly fail (not throwing an {@link Exception}) and return
null if it is unable to parse the provided {@link XmlFileModel}. A {@link ClassificationModel} will be created to
indicate that this file failed to parse.
@return Returns either the parsed {@link Document} or null if the {@link Document} could not be parsed | [
"Loads",
"and",
"parses",
"the",
"provided",
"XML",
"file",
".",
"This",
"will",
"quietly",
"fail",
"(",
"not",
"throwing",
"an",
"{",
"@link",
"Exception",
"}",
")",
"and",
"return",
"null",
"if",
"it",
"is",
"unable",
"to",
"parse",
"the",
"provided",
"{",
"@link",
"XmlFileModel",
"}",
".",
"A",
"{",
"@link",
"ClassificationModel",
"}",
"will",
"be",
"created",
"to",
"indicate",
"that",
"this",
"file",
"failed",
"to",
"parse",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-xml/api/src/main/java/org/jboss/windup/rules/apps/xml/service/XmlFileService.java#L66-L109 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/reportservice/RunDeliveryReportForOrder.java | RunDeliveryReportForOrder.runExample | public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long orderId)
throws IOException, InterruptedException {
"""
Runs the example.
@param adManagerServices the services factory.
@param session the session.
@param orderId the ID of the order to run the report for.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
@throws IOException if unable to write the response to a file.
@throws InterruptedException if the thread is interrupted while waiting for the report to
complete.
"""
// Get the ReportService.
ReportServiceInterface reportService =
adManagerServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.DATE, Dimension.ORDER_ID});
reportQuery.setColumns(new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR,
Column.AD_SERVER_CPM_AND_CPC_REVENUE});
reportQuery.setDimensionAttributes(new DimensionAttribute[] {
DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME,
DimensionAttribute.ORDER_END_DATE_TIME});
// Create statement to filter for an order.
StatementBuilder statementBuilder = new StatementBuilder()
.where("ORDER_ID = :orderId")
.withBindVariableValue("orderId", orderId);
// Set the filter statement.
reportQuery.setStatement(statementBuilder.toStatement());
// Set the start and end dates or choose a dynamic date range type.
reportQuery.setDateRangeType(DateRangeType.CUSTOM_DATE);
reportQuery.setStartDate(
DateTimes.toDateTime("2013-05-01T00:00:00", "America/New_York").getDate());
reportQuery.setEndDate(
DateTimes.toDateTime("2013-05-31T00:00:00", "America/New_York").getDate());
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
File file = File.createTempFile("delivery-report-", ".csv.gz");
System.out.printf("Downloading report to %s ...", file.toString());
// Download the report.
ReportDownloadOptions options = new ReportDownloadOptions();
options.setExportFormat(ExportFormat.CSV_DUMP);
options.setUseGzipCompression(true);
URL url = reportDownloader.getDownloadUrl(options);
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
System.out.println("done.");
} | java | public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long orderId)
throws IOException, InterruptedException {
// Get the ReportService.
ReportServiceInterface reportService =
adManagerServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.DATE, Dimension.ORDER_ID});
reportQuery.setColumns(new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR,
Column.AD_SERVER_CPM_AND_CPC_REVENUE});
reportQuery.setDimensionAttributes(new DimensionAttribute[] {
DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME,
DimensionAttribute.ORDER_END_DATE_TIME});
// Create statement to filter for an order.
StatementBuilder statementBuilder = new StatementBuilder()
.where("ORDER_ID = :orderId")
.withBindVariableValue("orderId", orderId);
// Set the filter statement.
reportQuery.setStatement(statementBuilder.toStatement());
// Set the start and end dates or choose a dynamic date range type.
reportQuery.setDateRangeType(DateRangeType.CUSTOM_DATE);
reportQuery.setStartDate(
DateTimes.toDateTime("2013-05-01T00:00:00", "America/New_York").getDate());
reportQuery.setEndDate(
DateTimes.toDateTime("2013-05-31T00:00:00", "America/New_York").getDate());
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
File file = File.createTempFile("delivery-report-", ".csv.gz");
System.out.printf("Downloading report to %s ...", file.toString());
// Download the report.
ReportDownloadOptions options = new ReportDownloadOptions();
options.setExportFormat(ExportFormat.CSV_DUMP);
options.setUseGzipCompression(true);
URL url = reportDownloader.getDownloadUrl(options);
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
System.out.println("done.");
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
",",
"long",
"orderId",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"// Get the ReportService.",
"ReportServiceInterface",
"reportService",
"=",
"adManagerServices",
".",
"get",
"(",
"session",
",",
"ReportServiceInterface",
".",
"class",
")",
";",
"// Create report query.",
"ReportQuery",
"reportQuery",
"=",
"new",
"ReportQuery",
"(",
")",
";",
"reportQuery",
".",
"setDimensions",
"(",
"new",
"Dimension",
"[",
"]",
"{",
"Dimension",
".",
"DATE",
",",
"Dimension",
".",
"ORDER_ID",
"}",
")",
";",
"reportQuery",
".",
"setColumns",
"(",
"new",
"Column",
"[",
"]",
"{",
"Column",
".",
"AD_SERVER_IMPRESSIONS",
",",
"Column",
".",
"AD_SERVER_CLICKS",
",",
"Column",
".",
"AD_SERVER_CTR",
",",
"Column",
".",
"AD_SERVER_CPM_AND_CPC_REVENUE",
"}",
")",
";",
"reportQuery",
".",
"setDimensionAttributes",
"(",
"new",
"DimensionAttribute",
"[",
"]",
"{",
"DimensionAttribute",
".",
"ORDER_TRAFFICKER",
",",
"DimensionAttribute",
".",
"ORDER_START_DATE_TIME",
",",
"DimensionAttribute",
".",
"ORDER_END_DATE_TIME",
"}",
")",
";",
"// Create statement to filter for an order.",
"StatementBuilder",
"statementBuilder",
"=",
"new",
"StatementBuilder",
"(",
")",
".",
"where",
"(",
"\"ORDER_ID = :orderId\"",
")",
".",
"withBindVariableValue",
"(",
"\"orderId\"",
",",
"orderId",
")",
";",
"// Set the filter statement.",
"reportQuery",
".",
"setStatement",
"(",
"statementBuilder",
".",
"toStatement",
"(",
")",
")",
";",
"// Set the start and end dates or choose a dynamic date range type.",
"reportQuery",
".",
"setDateRangeType",
"(",
"DateRangeType",
".",
"CUSTOM_DATE",
")",
";",
"reportQuery",
".",
"setStartDate",
"(",
"DateTimes",
".",
"toDateTime",
"(",
"\"2013-05-01T00:00:00\"",
",",
"\"America/New_York\"",
")",
".",
"getDate",
"(",
")",
")",
";",
"reportQuery",
".",
"setEndDate",
"(",
"DateTimes",
".",
"toDateTime",
"(",
"\"2013-05-31T00:00:00\"",
",",
"\"America/New_York\"",
")",
".",
"getDate",
"(",
")",
")",
";",
"// Create report job.",
"ReportJob",
"reportJob",
"=",
"new",
"ReportJob",
"(",
")",
";",
"reportJob",
".",
"setReportQuery",
"(",
"reportQuery",
")",
";",
"// Run report job.",
"reportJob",
"=",
"reportService",
".",
"runReportJob",
"(",
"reportJob",
")",
";",
"// Create report downloader.",
"ReportDownloader",
"reportDownloader",
"=",
"new",
"ReportDownloader",
"(",
"reportService",
",",
"reportJob",
".",
"getId",
"(",
")",
")",
";",
"// Wait for the report to be ready.",
"reportDownloader",
".",
"waitForReportReady",
"(",
")",
";",
"// Change to your file location.",
"File",
"file",
"=",
"File",
".",
"createTempFile",
"(",
"\"delivery-report-\"",
",",
"\".csv.gz\"",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"Downloading report to %s ...\"",
",",
"file",
".",
"toString",
"(",
")",
")",
";",
"// Download the report.",
"ReportDownloadOptions",
"options",
"=",
"new",
"ReportDownloadOptions",
"(",
")",
";",
"options",
".",
"setExportFormat",
"(",
"ExportFormat",
".",
"CSV_DUMP",
")",
";",
"options",
".",
"setUseGzipCompression",
"(",
"true",
")",
";",
"URL",
"url",
"=",
"reportDownloader",
".",
"getDownloadUrl",
"(",
"options",
")",
";",
"Resources",
".",
"asByteSource",
"(",
"url",
")",
".",
"copyTo",
"(",
"Files",
".",
"asByteSink",
"(",
"file",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"done.\"",
")",
";",
"}"
] | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@param orderId the ID of the order to run the report for.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
@throws IOException if unable to write the response to a file.
@throws InterruptedException if the thread is interrupted while waiting for the report to
complete. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/reportservice/RunDeliveryReportForOrder.java#L77-L135 |
brettonw/Bag | src/main/java/com/brettonw/bag/formats/FormatReaderComposite.java | FormatReaderComposite.basicArrayReader | public static FormatReaderComposite basicArrayReader (String input, String arrayDelimiter) {
"""
/*
public static FormatReaderComposite basicArrayReader (String input, String arrayDelimiter, String ignore) {
return new FormatReaderComposite (input, new HandlerArrayFromDelimited (arrayDelimiter).ignore (ignore));
}
"""
return new FormatReaderComposite (input, new HandlerArrayFromDelimited (arrayDelimiter));
} | java | public static FormatReaderComposite basicArrayReader (String input, String arrayDelimiter) {
return new FormatReaderComposite (input, new HandlerArrayFromDelimited (arrayDelimiter));
} | [
"public",
"static",
"FormatReaderComposite",
"basicArrayReader",
"(",
"String",
"input",
",",
"String",
"arrayDelimiter",
")",
"{",
"return",
"new",
"FormatReaderComposite",
"(",
"input",
",",
"new",
"HandlerArrayFromDelimited",
"(",
"arrayDelimiter",
")",
")",
";",
"}"
] | /*
public static FormatReaderComposite basicArrayReader (String input, String arrayDelimiter, String ignore) {
return new FormatReaderComposite (input, new HandlerArrayFromDelimited (arrayDelimiter).ignore (ignore));
} | [
"/",
"*",
"public",
"static",
"FormatReaderComposite",
"basicArrayReader",
"(",
"String",
"input",
"String",
"arrayDelimiter",
"String",
"ignore",
")",
"{",
"return",
"new",
"FormatReaderComposite",
"(",
"input",
"new",
"HandlerArrayFromDelimited",
"(",
"arrayDelimiter",
")",
".",
"ignore",
"(",
"ignore",
"))",
";",
"}"
] | train | https://github.com/brettonw/Bag/blob/25c0ff74893b6c9a2c61bf0f97189ab82e0b2f56/src/main/java/com/brettonw/bag/formats/FormatReaderComposite.java#L35-L37 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.clickOnScreen | public void clickOnScreen(float x, float y, int numberOfClicks) {
"""
Clicks the specified coordinates rapidly a specified number of times. Requires API level >= 14.
@param x the x coordinate
@param y the y coordinate
@param numberOfClicks the number of clicks to perform
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "clickOnScreen("+x+", "+y+", "+numberOfClicks+")");
}
if (android.os.Build.VERSION.SDK_INT < 14){
throw new RuntimeException("clickOnScreen(float x, float y, int numberOfClicks) requires API level >= 14");
}
tapper.generateTapGesture(numberOfClicks, new PointF(x, y));
} | java | public void clickOnScreen(float x, float y, int numberOfClicks) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "clickOnScreen("+x+", "+y+", "+numberOfClicks+")");
}
if (android.os.Build.VERSION.SDK_INT < 14){
throw new RuntimeException("clickOnScreen(float x, float y, int numberOfClicks) requires API level >= 14");
}
tapper.generateTapGesture(numberOfClicks, new PointF(x, y));
} | [
"public",
"void",
"clickOnScreen",
"(",
"float",
"x",
",",
"float",
"y",
",",
"int",
"numberOfClicks",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"clickOnScreen(\"",
"+",
"x",
"+",
"\", \"",
"+",
"y",
"+",
"\", \"",
"+",
"numberOfClicks",
"+",
"\")\"",
")",
";",
"}",
"if",
"(",
"android",
".",
"os",
".",
"Build",
".",
"VERSION",
".",
"SDK_INT",
"<",
"14",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"clickOnScreen(float x, float y, int numberOfClicks) requires API level >= 14\"",
")",
";",
"}",
"tapper",
".",
"generateTapGesture",
"(",
"numberOfClicks",
",",
"new",
"PointF",
"(",
"x",
",",
"y",
")",
")",
";",
"}"
] | Clicks the specified coordinates rapidly a specified number of times. Requires API level >= 14.
@param x the x coordinate
@param y the y coordinate
@param numberOfClicks the number of clicks to perform | [
"Clicks",
"the",
"specified",
"coordinates",
"rapidly",
"a",
"specified",
"number",
"of",
"times",
".",
"Requires",
"API",
"level",
">",
"=",
"14",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1151-L1161 |
codelibs/minhash | src/main/java/org/codelibs/minhash/MinHash.java | MinHash.newData | public static Data newData(final Analyzer analyzer, final String text,
final int numOfBits) {
"""
Create a target data which has analyzer, text and the number of bits.
@param analyzer
@param text
@param numOfBits
@return
"""
return new Data(analyzer, text, numOfBits);
} | java | public static Data newData(final Analyzer analyzer, final String text,
final int numOfBits) {
return new Data(analyzer, text, numOfBits);
} | [
"public",
"static",
"Data",
"newData",
"(",
"final",
"Analyzer",
"analyzer",
",",
"final",
"String",
"text",
",",
"final",
"int",
"numOfBits",
")",
"{",
"return",
"new",
"Data",
"(",
"analyzer",
",",
"text",
",",
"numOfBits",
")",
";",
"}"
] | Create a target data which has analyzer, text and the number of bits.
@param analyzer
@param text
@param numOfBits
@return | [
"Create",
"a",
"target",
"data",
"which",
"has",
"analyzer",
"text",
"and",
"the",
"number",
"of",
"bits",
"."
] | train | https://github.com/codelibs/minhash/blob/2aaa16e3096461c0f550d0eb462ae9e69d1b7749/src/main/java/org/codelibs/minhash/MinHash.java#L273-L276 |
berkesa/datatree | src/main/java/io/datatree/Tree.java | Tree.getPath | protected StringBuilder getPath(StringBuilder path, int startIndex, boolean addPoint) {
"""
Recursive path-builder method.
@param path
path builder
@param startIndex
first index within array (startIndex = 0 -> zero based
array-indexing)
@param addPoint
a point is insertable into the path
@return path of this node
"""
boolean simple = true;
if (key != null) {
if (addPoint && path.length() > 0) {
path.insert(0, '.');
}
if (key instanceof Integer) {
path.insert(0, ']');
if (startIndex == 0) {
path.insert(0, key);
} else {
path.insert(0, startIndex + (int) key);
}
path.insert(0, '[');
simple = false;
} else {
path.insert(0, key);
}
}
if (parent != null) {
parent.getPath(path, startIndex, simple);
}
return path;
} | java | protected StringBuilder getPath(StringBuilder path, int startIndex, boolean addPoint) {
boolean simple = true;
if (key != null) {
if (addPoint && path.length() > 0) {
path.insert(0, '.');
}
if (key instanceof Integer) {
path.insert(0, ']');
if (startIndex == 0) {
path.insert(0, key);
} else {
path.insert(0, startIndex + (int) key);
}
path.insert(0, '[');
simple = false;
} else {
path.insert(0, key);
}
}
if (parent != null) {
parent.getPath(path, startIndex, simple);
}
return path;
} | [
"protected",
"StringBuilder",
"getPath",
"(",
"StringBuilder",
"path",
",",
"int",
"startIndex",
",",
"boolean",
"addPoint",
")",
"{",
"boolean",
"simple",
"=",
"true",
";",
"if",
"(",
"key",
"!=",
"null",
")",
"{",
"if",
"(",
"addPoint",
"&&",
"path",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"path",
".",
"insert",
"(",
"0",
",",
"'",
"'",
")",
";",
"}",
"if",
"(",
"key",
"instanceof",
"Integer",
")",
"{",
"path",
".",
"insert",
"(",
"0",
",",
"'",
"'",
")",
";",
"if",
"(",
"startIndex",
"==",
"0",
")",
"{",
"path",
".",
"insert",
"(",
"0",
",",
"key",
")",
";",
"}",
"else",
"{",
"path",
".",
"insert",
"(",
"0",
",",
"startIndex",
"+",
"(",
"int",
")",
"key",
")",
";",
"}",
"path",
".",
"insert",
"(",
"0",
",",
"'",
"'",
")",
";",
"simple",
"=",
"false",
";",
"}",
"else",
"{",
"path",
".",
"insert",
"(",
"0",
",",
"key",
")",
";",
"}",
"}",
"if",
"(",
"parent",
"!=",
"null",
")",
"{",
"parent",
".",
"getPath",
"(",
"path",
",",
"startIndex",
",",
"simple",
")",
";",
"}",
"return",
"path",
";",
"}"
] | Recursive path-builder method.
@param path
path builder
@param startIndex
first index within array (startIndex = 0 -> zero based
array-indexing)
@param addPoint
a point is insertable into the path
@return path of this node | [
"Recursive",
"path",
"-",
"builder",
"method",
"."
] | train | https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/Tree.java#L402-L425 |
mgormley/prim | src/main/java/edu/jhu/prim/util/math/FastMath.java | FastMath.logSubtractExact | public static double logSubtractExact(double x, double y) {
"""
Subtracts two probabilities that are stored as log probabilities.
Note that x >= y.
@param x log(p)
@param y log(q)
@return log(p - q) = log(exp(p) - exp(q))
@throws IllegalStateException if x < y
"""
if (x < y) {
throw new IllegalStateException("x must be >= y. x=" + x + " y=" + y);
}
// p = 0 or q = 0, where x = log(p), y = log(q)
if (Double.NEGATIVE_INFINITY == y) {
return x;
} else if (Double.NEGATIVE_INFINITY == x) {
return y;
} else if (x == y) {
return Double.NEGATIVE_INFINITY;
}
// p != 0 && q != 0
//return x + Math.log1p(-FastMath.exp(y - x));
//
// The method below is more numerically stable for small differences in x and y.
// See paper: http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
return x + log1mexp(x - y);
} | java | public static double logSubtractExact(double x, double y) {
if (x < y) {
throw new IllegalStateException("x must be >= y. x=" + x + " y=" + y);
}
// p = 0 or q = 0, where x = log(p), y = log(q)
if (Double.NEGATIVE_INFINITY == y) {
return x;
} else if (Double.NEGATIVE_INFINITY == x) {
return y;
} else if (x == y) {
return Double.NEGATIVE_INFINITY;
}
// p != 0 && q != 0
//return x + Math.log1p(-FastMath.exp(y - x));
//
// The method below is more numerically stable for small differences in x and y.
// See paper: http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
return x + log1mexp(x - y);
} | [
"public",
"static",
"double",
"logSubtractExact",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"if",
"(",
"x",
"<",
"y",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"x must be >= y. x=\"",
"+",
"x",
"+",
"\" y=\"",
"+",
"y",
")",
";",
"}",
"// p = 0 or q = 0, where x = log(p), y = log(q)",
"if",
"(",
"Double",
".",
"NEGATIVE_INFINITY",
"==",
"y",
")",
"{",
"return",
"x",
";",
"}",
"else",
"if",
"(",
"Double",
".",
"NEGATIVE_INFINITY",
"==",
"x",
")",
"{",
"return",
"y",
";",
"}",
"else",
"if",
"(",
"x",
"==",
"y",
")",
"{",
"return",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"}",
"// p != 0 && q != 0",
"//return x + Math.log1p(-FastMath.exp(y - x));",
"// ",
"// The method below is more numerically stable for small differences in x and y.",
"// See paper: http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf",
"return",
"x",
"+",
"log1mexp",
"(",
"x",
"-",
"y",
")",
";",
"}"
] | Subtracts two probabilities that are stored as log probabilities.
Note that x >= y.
@param x log(p)
@param y log(q)
@return log(p - q) = log(exp(p) - exp(q))
@throws IllegalStateException if x < y | [
"Subtracts",
"two",
"probabilities",
"that",
"are",
"stored",
"as",
"log",
"probabilities",
".",
"Note",
"that",
"x",
">",
"=",
"y",
"."
] | train | https://github.com/mgormley/prim/blob/5dce5e1ae94a9ae558a6262fc246e1a24f56686c/src/main/java/edu/jhu/prim/util/math/FastMath.java#L82-L102 |
james-hu/jabb-core | src/main/java/net/sf/jabb/cache/AbstractCachedKeyValueRepositoriesNotifier.java | AbstractCachedKeyValueRepositoriesNotifier.onChange | public void onChange(String valueScope, Object key) {
"""
Notify both local and remote repositories about the value change
@param valueScope value scope
@param key the key
"""
notifyLocalRepositories(valueScope, key);
notifyRemoteRepositories(valueScope, key);
} | java | public void onChange(String valueScope, Object key){
notifyLocalRepositories(valueScope, key);
notifyRemoteRepositories(valueScope, key);
} | [
"public",
"void",
"onChange",
"(",
"String",
"valueScope",
",",
"Object",
"key",
")",
"{",
"notifyLocalRepositories",
"(",
"valueScope",
",",
"key",
")",
";",
"notifyRemoteRepositories",
"(",
"valueScope",
",",
"key",
")",
";",
"}"
] | Notify both local and remote repositories about the value change
@param valueScope value scope
@param key the key | [
"Notify",
"both",
"local",
"and",
"remote",
"repositories",
"about",
"the",
"value",
"change"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/cache/AbstractCachedKeyValueRepositoriesNotifier.java#L31-L34 |
jenkinsci/ssh-slaves-plugin | src/main/java/hudson/plugins/sshslaves/verifiers/HostKeyHelper.java | HostKeyHelper.saveHostKey | public void saveHostKey(Computer host, HostKey hostKey) throws IOException {
"""
Persists an SSH key to disk for the requested host. This effectively marks
the requested key as trusted for all future connections to the host, until
any future save attempt replaces this key.
@param host the host the key is being saved for
@param hostKey the key to be saved as the trusted key for this host
@throws IOException on failure saving the key for the host
"""
XmlFile xmlHostKeyFile = new XmlFile(getSshHostKeyFile(host.getNode()));
xmlHostKeyFile.write(hostKey);
cache.put(host, hostKey);
} | java | public void saveHostKey(Computer host, HostKey hostKey) throws IOException {
XmlFile xmlHostKeyFile = new XmlFile(getSshHostKeyFile(host.getNode()));
xmlHostKeyFile.write(hostKey);
cache.put(host, hostKey);
} | [
"public",
"void",
"saveHostKey",
"(",
"Computer",
"host",
",",
"HostKey",
"hostKey",
")",
"throws",
"IOException",
"{",
"XmlFile",
"xmlHostKeyFile",
"=",
"new",
"XmlFile",
"(",
"getSshHostKeyFile",
"(",
"host",
".",
"getNode",
"(",
")",
")",
")",
";",
"xmlHostKeyFile",
".",
"write",
"(",
"hostKey",
")",
";",
"cache",
".",
"put",
"(",
"host",
",",
"hostKey",
")",
";",
"}"
] | Persists an SSH key to disk for the requested host. This effectively marks
the requested key as trusted for all future connections to the host, until
any future save attempt replaces this key.
@param host the host the key is being saved for
@param hostKey the key to be saved as the trusted key for this host
@throws IOException on failure saving the key for the host | [
"Persists",
"an",
"SSH",
"key",
"to",
"disk",
"for",
"the",
"requested",
"host",
".",
"This",
"effectively",
"marks",
"the",
"requested",
"key",
"as",
"trusted",
"for",
"all",
"future",
"connections",
"to",
"the",
"host",
"until",
"any",
"future",
"save",
"attempt",
"replaces",
"this",
"key",
"."
] | train | https://github.com/jenkinsci/ssh-slaves-plugin/blob/95f528730fc1e01b25983459927b7516ead3ee00/src/main/java/hudson/plugins/sshslaves/verifiers/HostKeyHelper.java#L90-L94 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/CommonG.java | CommonG.removeJSONPathElement | public String removeJSONPathElement(String jsonString, String expr) {
"""
Remove a subelement in a JsonPath
@param jsonString String of the json
@param expr regex to be removed
"""
Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
DocumentContext context = JsonPath.using(conf).parse(jsonString);
context.delete(expr);
return context.jsonString();
} | java | public String removeJSONPathElement(String jsonString, String expr) {
Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).mappingProvider(new GsonMappingProvider()).build();
DocumentContext context = JsonPath.using(conf).parse(jsonString);
context.delete(expr);
return context.jsonString();
} | [
"public",
"String",
"removeJSONPathElement",
"(",
"String",
"jsonString",
",",
"String",
"expr",
")",
"{",
"Configuration",
"conf",
"=",
"Configuration",
".",
"builder",
"(",
")",
".",
"jsonProvider",
"(",
"new",
"GsonJsonProvider",
"(",
")",
")",
".",
"mappingProvider",
"(",
"new",
"GsonMappingProvider",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"DocumentContext",
"context",
"=",
"JsonPath",
".",
"using",
"(",
"conf",
")",
".",
"parse",
"(",
"jsonString",
")",
";",
"context",
".",
"delete",
"(",
"expr",
")",
";",
"return",
"context",
".",
"jsonString",
"(",
")",
";",
"}"
] | Remove a subelement in a JsonPath
@param jsonString String of the json
@param expr regex to be removed | [
"Remove",
"a",
"subelement",
"in",
"a",
"JsonPath"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L1911-L1917 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/topic/TopicManagerImpl.java | TopicManagerImpl.unregisterTopicSession | @Override
public int unregisterTopicSession(String topic, Session session) {
"""
Unregister session for topic. topic 'ALL' remove session for all topics
@param topic
@param session
@return int : number subscribers remaining
"""
if (isInconsistenceContext(topic, session)) {
return 0;
}
logger.debug("'{}' unsubscribe to '{}'", session.getId(), topic);
if (Constants.Topic.ALL.equals(topic)) {
for (Map.Entry<String, Collection<Session>> entry : map.entrySet()) {
Collection<Session> sessions = entry.getValue();
removeSessionToSessions(session, sessions);
if (sessions.isEmpty()) {
map.remove(entry.getKey());
}
}
} else {
Collection<Session> sessions = map.get(topic);
removeSessionToSessions(session, sessions);
if (sessions==null || sessions.isEmpty()) {
map.remove(topic);
}
}
return getNumberSubscribers(topic);
} | java | @Override
public int unregisterTopicSession(String topic, Session session) {
if (isInconsistenceContext(topic, session)) {
return 0;
}
logger.debug("'{}' unsubscribe to '{}'", session.getId(), topic);
if (Constants.Topic.ALL.equals(topic)) {
for (Map.Entry<String, Collection<Session>> entry : map.entrySet()) {
Collection<Session> sessions = entry.getValue();
removeSessionToSessions(session, sessions);
if (sessions.isEmpty()) {
map.remove(entry.getKey());
}
}
} else {
Collection<Session> sessions = map.get(topic);
removeSessionToSessions(session, sessions);
if (sessions==null || sessions.isEmpty()) {
map.remove(topic);
}
}
return getNumberSubscribers(topic);
} | [
"@",
"Override",
"public",
"int",
"unregisterTopicSession",
"(",
"String",
"topic",
",",
"Session",
"session",
")",
"{",
"if",
"(",
"isInconsistenceContext",
"(",
"topic",
",",
"session",
")",
")",
"{",
"return",
"0",
";",
"}",
"logger",
".",
"debug",
"(",
"\"'{}' unsubscribe to '{}'\"",
",",
"session",
".",
"getId",
"(",
")",
",",
"topic",
")",
";",
"if",
"(",
"Constants",
".",
"Topic",
".",
"ALL",
".",
"equals",
"(",
"topic",
")",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Collection",
"<",
"Session",
">",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"Collection",
"<",
"Session",
">",
"sessions",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"removeSessionToSessions",
"(",
"session",
",",
"sessions",
")",
";",
"if",
"(",
"sessions",
".",
"isEmpty",
"(",
")",
")",
"{",
"map",
".",
"remove",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"}",
"}",
"}",
"else",
"{",
"Collection",
"<",
"Session",
">",
"sessions",
"=",
"map",
".",
"get",
"(",
"topic",
")",
";",
"removeSessionToSessions",
"(",
"session",
",",
"sessions",
")",
";",
"if",
"(",
"sessions",
"==",
"null",
"||",
"sessions",
".",
"isEmpty",
"(",
")",
")",
"{",
"map",
".",
"remove",
"(",
"topic",
")",
";",
"}",
"}",
"return",
"getNumberSubscribers",
"(",
"topic",
")",
";",
"}"
] | Unregister session for topic. topic 'ALL' remove session for all topics
@param topic
@param session
@return int : number subscribers remaining | [
"Unregister",
"session",
"for",
"topic",
".",
"topic",
"ALL",
"remove",
"session",
"for",
"all",
"topics"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/topic/TopicManagerImpl.java#L88-L110 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.createPrinterGraphics | public java.awt.Graphics2D createPrinterGraphics(float width, float height, PrinterJob printerJob) {
"""
Gets a <CODE>Graphics2D</CODE> to print on. The graphics
are translated to PDF commands.
@param width the width of the panel
@param height the height of the panel
@param printerJob
@return a <CODE>Graphics2D</CODE>
"""
return new PdfPrinterGraphics2D(this, width, height, null, false, false, 0, printerJob);
} | java | public java.awt.Graphics2D createPrinterGraphics(float width, float height, PrinterJob printerJob) {
return new PdfPrinterGraphics2D(this, width, height, null, false, false, 0, printerJob);
} | [
"public",
"java",
".",
"awt",
".",
"Graphics2D",
"createPrinterGraphics",
"(",
"float",
"width",
",",
"float",
"height",
",",
"PrinterJob",
"printerJob",
")",
"{",
"return",
"new",
"PdfPrinterGraphics2D",
"(",
"this",
",",
"width",
",",
"height",
",",
"null",
",",
"false",
",",
"false",
",",
"0",
",",
"printerJob",
")",
";",
"}"
] | Gets a <CODE>Graphics2D</CODE> to print on. The graphics
are translated to PDF commands.
@param width the width of the panel
@param height the height of the panel
@param printerJob
@return a <CODE>Graphics2D</CODE> | [
"Gets",
"a",
"<CODE",
">",
"Graphics2D<",
"/",
"CODE",
">",
"to",
"print",
"on",
".",
"The",
"graphics",
"are",
"translated",
"to",
"PDF",
"commands",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L2823-L2825 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java | ClassUtility.findAndBuildGenericType | public static Object findAndBuildGenericType(final Class<?> mainClass, final Class<?> assignableClass, final Class<?> excludedClass, final Object... parameters) throws CoreException {
"""
Find and Build the generic type according to assignable and excluded classes.
@param mainClass The main class used (that contains at least one generic type)
@param assignableClasses if the array contains only one class it define the type of the generic to build, otherwise it defines the types to skip to find the obejct to build
@param excludedClass the class that shouldn't be retrieved (ie: NullXX class)
@param parameters used by the constructor of the generic type
@return the first generic type of a class that is compatible with provided assignable class.
@throws CoreException if the class cannot be found and is not an excluded class
"""
Object object = null;
final Class<?> objectClass = ClassUtility.findGenericClass(mainClass, assignableClass);
if (objectClass != null && (excludedClass == null || !excludedClass.equals(objectClass))) {
object = buildGenericType(mainClass, new Class<?>[] { assignableClass }, parameters);
}
return object;
} | java | public static Object findAndBuildGenericType(final Class<?> mainClass, final Class<?> assignableClass, final Class<?> excludedClass, final Object... parameters) throws CoreException {
Object object = null;
final Class<?> objectClass = ClassUtility.findGenericClass(mainClass, assignableClass);
if (objectClass != null && (excludedClass == null || !excludedClass.equals(objectClass))) {
object = buildGenericType(mainClass, new Class<?>[] { assignableClass }, parameters);
}
return object;
} | [
"public",
"static",
"Object",
"findAndBuildGenericType",
"(",
"final",
"Class",
"<",
"?",
">",
"mainClass",
",",
"final",
"Class",
"<",
"?",
">",
"assignableClass",
",",
"final",
"Class",
"<",
"?",
">",
"excludedClass",
",",
"final",
"Object",
"...",
"parameters",
")",
"throws",
"CoreException",
"{",
"Object",
"object",
"=",
"null",
";",
"final",
"Class",
"<",
"?",
">",
"objectClass",
"=",
"ClassUtility",
".",
"findGenericClass",
"(",
"mainClass",
",",
"assignableClass",
")",
";",
"if",
"(",
"objectClass",
"!=",
"null",
"&&",
"(",
"excludedClass",
"==",
"null",
"||",
"!",
"excludedClass",
".",
"equals",
"(",
"objectClass",
")",
")",
")",
"{",
"object",
"=",
"buildGenericType",
"(",
"mainClass",
",",
"new",
"Class",
"<",
"?",
">",
"[",
"]",
"{",
"assignableClass",
"}",
",",
"parameters",
")",
";",
"}",
"return",
"object",
";",
"}"
] | Find and Build the generic type according to assignable and excluded classes.
@param mainClass The main class used (that contains at least one generic type)
@param assignableClasses if the array contains only one class it define the type of the generic to build, otherwise it defines the types to skip to find the obejct to build
@param excludedClass the class that shouldn't be retrieved (ie: NullXX class)
@param parameters used by the constructor of the generic type
@return the first generic type of a class that is compatible with provided assignable class.
@throws CoreException if the class cannot be found and is not an excluded class | [
"Find",
"and",
"Build",
"the",
"generic",
"type",
"according",
"to",
"assignable",
"and",
"excluded",
"classes",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/util/ClassUtility.java#L161-L170 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/AbstractClientOptionsBuilder.java | AbstractClientOptionsBuilder.contentPreview | public B contentPreview(int length, Charset defaultCharset) {
"""
Sets the {@link ContentPreviewerFactory} creating a {@link ContentPreviewer} which produces the preview
with the maxmium {@code length} limit for a request and a response.
The previewer is enabled only if the content type of a request/response meets
any of the following cases.
<ul>
<li>when it matches {@code text/*} or {@code application/x-www-form-urlencoded}</li>
<li>when its charset has been specified</li>
<li>when its subtype is {@code "xml"} or {@code "json"}</li>
<li>when its subtype ends with {@code "+xml"} or {@code "+json"}</li>
</ul>
@param length the maximum length of the preview.
@param defaultCharset the default charset for a request/response with unspecified charset in
{@code "content-type"} header.
"""
return contentPreviewerFactory(ContentPreviewerFactory.ofText(length, defaultCharset));
} | java | public B contentPreview(int length, Charset defaultCharset) {
return contentPreviewerFactory(ContentPreviewerFactory.ofText(length, defaultCharset));
} | [
"public",
"B",
"contentPreview",
"(",
"int",
"length",
",",
"Charset",
"defaultCharset",
")",
"{",
"return",
"contentPreviewerFactory",
"(",
"ContentPreviewerFactory",
".",
"ofText",
"(",
"length",
",",
"defaultCharset",
")",
")",
";",
"}"
] | Sets the {@link ContentPreviewerFactory} creating a {@link ContentPreviewer} which produces the preview
with the maxmium {@code length} limit for a request and a response.
The previewer is enabled only if the content type of a request/response meets
any of the following cases.
<ul>
<li>when it matches {@code text/*} or {@code application/x-www-form-urlencoded}</li>
<li>when its charset has been specified</li>
<li>when its subtype is {@code "xml"} or {@code "json"}</li>
<li>when its subtype ends with {@code "+xml"} or {@code "+json"}</li>
</ul>
@param length the maximum length of the preview.
@param defaultCharset the default charset for a request/response with unspecified charset in
{@code "content-type"} header. | [
"Sets",
"the",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/AbstractClientOptionsBuilder.java#L214-L216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.