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
|
---|---|---|---|---|---|---|---|---|---|---|
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/security/certgen/TLSCertificateKeyPair.java | TLSCertificateKeyPair.fromX509CertKeyPair | static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
"""
*
Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
encoded in PEM and also in DER for the certificate
@param x509Cert the certificate to process
@param keyPair the key pair to process
@return a TLSCertificateKeyPair
@throws IOException upon failure
"""
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
JcaPEMWriter w = new JcaPEMWriter(writer);
w.writeObject(x509Cert);
w.flush();
w.close();
byte[] pemBytes = baos.toByteArray();
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
PemReader pr = new PemReader(isr);
PemObject pem = pr.readPemObject();
byte[] derBytes = pem.getContent();
baos = new ByteArrayOutputStream();
PrintWriter wr = new PrintWriter(baos);
wr.println("-----BEGIN PRIVATE KEY-----");
wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
wr.println("-----END PRIVATE KEY-----");
wr.flush();
wr.close();
byte[] keyBytes = baos.toByteArray();
return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
} | java | static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
JcaPEMWriter w = new JcaPEMWriter(writer);
w.writeObject(x509Cert);
w.flush();
w.close();
byte[] pemBytes = baos.toByteArray();
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
PemReader pr = new PemReader(isr);
PemObject pem = pr.readPemObject();
byte[] derBytes = pem.getContent();
baos = new ByteArrayOutputStream();
PrintWriter wr = new PrintWriter(baos);
wr.println("-----BEGIN PRIVATE KEY-----");
wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
wr.println("-----END PRIVATE KEY-----");
wr.flush();
wr.close();
byte[] keyBytes = baos.toByteArray();
return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
} | [
"static",
"TLSCertificateKeyPair",
"fromX509CertKeyPair",
"(",
"X509Certificate",
"x509Cert",
",",
"KeyPair",
"keyPair",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"PrintWriter",
"writer",
"=",
"new",
"PrintWriter",
"(",
"baos",
")",
";",
"JcaPEMWriter",
"w",
"=",
"new",
"JcaPEMWriter",
"(",
"writer",
")",
";",
"w",
".",
"writeObject",
"(",
"x509Cert",
")",
";",
"w",
".",
"flush",
"(",
")",
";",
"w",
".",
"close",
"(",
")",
";",
"byte",
"[",
"]",
"pemBytes",
"=",
"baos",
".",
"toByteArray",
"(",
")",
";",
"InputStreamReader",
"isr",
"=",
"new",
"InputStreamReader",
"(",
"new",
"ByteArrayInputStream",
"(",
"pemBytes",
")",
")",
";",
"PemReader",
"pr",
"=",
"new",
"PemReader",
"(",
"isr",
")",
";",
"PemObject",
"pem",
"=",
"pr",
".",
"readPemObject",
"(",
")",
";",
"byte",
"[",
"]",
"derBytes",
"=",
"pem",
".",
"getContent",
"(",
")",
";",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"PrintWriter",
"wr",
"=",
"new",
"PrintWriter",
"(",
"baos",
")",
";",
"wr",
".",
"println",
"(",
"\"-----BEGIN PRIVATE KEY-----\"",
")",
";",
"wr",
".",
"println",
"(",
"new",
"String",
"(",
"Base64",
".",
"encodeBase64",
"(",
"keyPair",
".",
"getPrivate",
"(",
")",
".",
"getEncoded",
"(",
")",
")",
")",
")",
";",
"wr",
".",
"println",
"(",
"\"-----END PRIVATE KEY-----\"",
")",
";",
"wr",
".",
"flush",
"(",
")",
";",
"wr",
".",
"close",
"(",
")",
";",
"byte",
"[",
"]",
"keyBytes",
"=",
"baos",
".",
"toByteArray",
"(",
")",
";",
"return",
"new",
"TLSCertificateKeyPair",
"(",
"pemBytes",
",",
"derBytes",
",",
"keyBytes",
")",
";",
"}"
] | *
Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
encoded in PEM and also in DER for the certificate
@param x509Cert the certificate to process
@param keyPair the key pair to process
@return a TLSCertificateKeyPair
@throws IOException upon failure | [
"*",
"Creates",
"a",
"TLSCertificateKeyPair",
"out",
"of",
"the",
"given",
"{"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/security/certgen/TLSCertificateKeyPair.java#L53-L76 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java | Text.getAbsoluteParent | public static String getAbsoluteParent(String path, int level) {
"""
Returns the n<sup>th</sup> absolute parent of the path, where n=level.
<p>
Example:<br>
<code>
Text.getAbsoluteParent("/foo/bar/test", 1) == "/foo/bar"
</code>
@param path
the path of the page
@param level
the level of the parent
@return String absolute parent
"""
int idx = 0;
int len = path.length();
while (level >= 0 && idx < len)
{
idx = path.indexOf('/', idx + 1);
if (idx < 0)
{
idx = len;
}
level--;
}
return level >= 0 ? "" : path.substring(0, idx);
} | java | public static String getAbsoluteParent(String path, int level)
{
int idx = 0;
int len = path.length();
while (level >= 0 && idx < len)
{
idx = path.indexOf('/', idx + 1);
if (idx < 0)
{
idx = len;
}
level--;
}
return level >= 0 ? "" : path.substring(0, idx);
} | [
"public",
"static",
"String",
"getAbsoluteParent",
"(",
"String",
"path",
",",
"int",
"level",
")",
"{",
"int",
"idx",
"=",
"0",
";",
"int",
"len",
"=",
"path",
".",
"length",
"(",
")",
";",
"while",
"(",
"level",
">=",
"0",
"&&",
"idx",
"<",
"len",
")",
"{",
"idx",
"=",
"path",
".",
"indexOf",
"(",
"'",
"'",
",",
"idx",
"+",
"1",
")",
";",
"if",
"(",
"idx",
"<",
"0",
")",
"{",
"idx",
"=",
"len",
";",
"}",
"level",
"--",
";",
"}",
"return",
"level",
">=",
"0",
"?",
"\"\"",
":",
"path",
".",
"substring",
"(",
"0",
",",
"idx",
")",
";",
"}"
] | Returns the n<sup>th</sup> absolute parent of the path, where n=level.
<p>
Example:<br>
<code>
Text.getAbsoluteParent("/foo/bar/test", 1) == "/foo/bar"
</code>
@param path
the path of the page
@param level
the level of the parent
@return String absolute parent | [
"Returns",
"the",
"n<sup",
">",
"th<",
"/",
"sup",
">",
"absolute",
"parent",
"of",
"the",
"path",
"where",
"n",
"=",
"level",
".",
"<p",
">",
"Example",
":",
"<br",
">",
"<code",
">",
"Text",
".",
"getAbsoluteParent",
"(",
"/",
"foo",
"/",
"bar",
"/",
"test",
"1",
")",
"==",
"/",
"foo",
"/",
"bar",
"<",
"/",
"code",
">"
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java#L811-L825 |
mozilla/rhino | src/org/mozilla/javascript/DToA.java | DToA.d2b | private static BigInteger d2b(double d, int[] e, int[] bits) {
"""
/* Convert d into the form b*2^e, where b is an odd integer. b is the returned
Bigint and e is the returned binary exponent. Return the number of significant
bits in b in bits. d must be finite and nonzero.
"""
byte dbl_bits[];
int i, k, y, z, de;
long dBits = Double.doubleToLongBits(d);
int d0 = (int)(dBits >>> 32);
int d1 = (int)(dBits);
z = d0 & Frac_mask;
d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
if ((de = (d0 >>> Exp_shift)) != 0)
z |= Exp_msk1;
if ((y = d1) != 0) {
dbl_bits = new byte[8];
k = lo0bits(y);
y >>>= k;
if (k != 0) {
stuffBits(dbl_bits, 4, y | z << (32 - k));
z >>= k;
}
else
stuffBits(dbl_bits, 4, y);
stuffBits(dbl_bits, 0, z);
i = (z != 0) ? 2 : 1;
}
else {
// JS_ASSERT(z);
dbl_bits = new byte[4];
k = lo0bits(z);
z >>>= k;
stuffBits(dbl_bits, 0, z);
k += 32;
i = 1;
}
if (de != 0) {
e[0] = de - Bias - (P-1) + k;
bits[0] = P - k;
}
else {
e[0] = de - Bias - (P-1) + 1 + k;
bits[0] = 32*i - hi0bits(z);
}
return new BigInteger(dbl_bits);
} | java | private static BigInteger d2b(double d, int[] e, int[] bits)
{
byte dbl_bits[];
int i, k, y, z, de;
long dBits = Double.doubleToLongBits(d);
int d0 = (int)(dBits >>> 32);
int d1 = (int)(dBits);
z = d0 & Frac_mask;
d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
if ((de = (d0 >>> Exp_shift)) != 0)
z |= Exp_msk1;
if ((y = d1) != 0) {
dbl_bits = new byte[8];
k = lo0bits(y);
y >>>= k;
if (k != 0) {
stuffBits(dbl_bits, 4, y | z << (32 - k));
z >>= k;
}
else
stuffBits(dbl_bits, 4, y);
stuffBits(dbl_bits, 0, z);
i = (z != 0) ? 2 : 1;
}
else {
// JS_ASSERT(z);
dbl_bits = new byte[4];
k = lo0bits(z);
z >>>= k;
stuffBits(dbl_bits, 0, z);
k += 32;
i = 1;
}
if (de != 0) {
e[0] = de - Bias - (P-1) + k;
bits[0] = P - k;
}
else {
e[0] = de - Bias - (P-1) + 1 + k;
bits[0] = 32*i - hi0bits(z);
}
return new BigInteger(dbl_bits);
} | [
"private",
"static",
"BigInteger",
"d2b",
"(",
"double",
"d",
",",
"int",
"[",
"]",
"e",
",",
"int",
"[",
"]",
"bits",
")",
"{",
"byte",
"dbl_bits",
"[",
"]",
";",
"int",
"i",
",",
"k",
",",
"y",
",",
"z",
",",
"de",
";",
"long",
"dBits",
"=",
"Double",
".",
"doubleToLongBits",
"(",
"d",
")",
";",
"int",
"d0",
"=",
"(",
"int",
")",
"(",
"dBits",
">>>",
"32",
")",
";",
"int",
"d1",
"=",
"(",
"int",
")",
"(",
"dBits",
")",
";",
"z",
"=",
"d0",
"&",
"Frac_mask",
";",
"d0",
"&=",
"0x7fffffff",
";",
"/* clear sign bit, which we ignore */",
"if",
"(",
"(",
"de",
"=",
"(",
"d0",
">>>",
"Exp_shift",
")",
")",
"!=",
"0",
")",
"z",
"|=",
"Exp_msk1",
";",
"if",
"(",
"(",
"y",
"=",
"d1",
")",
"!=",
"0",
")",
"{",
"dbl_bits",
"=",
"new",
"byte",
"[",
"8",
"]",
";",
"k",
"=",
"lo0bits",
"(",
"y",
")",
";",
"y",
">>>=",
"k",
";",
"if",
"(",
"k",
"!=",
"0",
")",
"{",
"stuffBits",
"(",
"dbl_bits",
",",
"4",
",",
"y",
"|",
"z",
"<<",
"(",
"32",
"-",
"k",
")",
")",
";",
"z",
">>=",
"k",
";",
"}",
"else",
"stuffBits",
"(",
"dbl_bits",
",",
"4",
",",
"y",
")",
";",
"stuffBits",
"(",
"dbl_bits",
",",
"0",
",",
"z",
")",
";",
"i",
"=",
"(",
"z",
"!=",
"0",
")",
"?",
"2",
":",
"1",
";",
"}",
"else",
"{",
"// JS_ASSERT(z);",
"dbl_bits",
"=",
"new",
"byte",
"[",
"4",
"]",
";",
"k",
"=",
"lo0bits",
"(",
"z",
")",
";",
"z",
">>>=",
"k",
";",
"stuffBits",
"(",
"dbl_bits",
",",
"0",
",",
"z",
")",
";",
"k",
"+=",
"32",
";",
"i",
"=",
"1",
";",
"}",
"if",
"(",
"de",
"!=",
"0",
")",
"{",
"e",
"[",
"0",
"]",
"=",
"de",
"-",
"Bias",
"-",
"(",
"P",
"-",
"1",
")",
"+",
"k",
";",
"bits",
"[",
"0",
"]",
"=",
"P",
"-",
"k",
";",
"}",
"else",
"{",
"e",
"[",
"0",
"]",
"=",
"de",
"-",
"Bias",
"-",
"(",
"P",
"-",
"1",
")",
"+",
"1",
"+",
"k",
";",
"bits",
"[",
"0",
"]",
"=",
"32",
"*",
"i",
"-",
"hi0bits",
"(",
"z",
")",
";",
"}",
"return",
"new",
"BigInteger",
"(",
"dbl_bits",
")",
";",
"}"
] | /* Convert d into the form b*2^e, where b is an odd integer. b is the returned
Bigint and e is the returned binary exponent. Return the number of significant
bits in b in bits. d must be finite and nonzero. | [
"/",
"*",
"Convert",
"d",
"into",
"the",
"form",
"b",
"*",
"2^e",
"where",
"b",
"is",
"an",
"odd",
"integer",
".",
"b",
"is",
"the",
"returned",
"Bigint",
"and",
"e",
"is",
"the",
"returned",
"binary",
"exponent",
".",
"Return",
"the",
"number",
"of",
"significant",
"bits",
"in",
"b",
"in",
"bits",
".",
"d",
"must",
"be",
"finite",
"and",
"nonzero",
"."
] | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/DToA.java#L159-L204 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseTableAuditingPoliciesInner.java | DatabaseTableAuditingPoliciesInner.listByDatabaseAsync | public Observable<DatabaseTableAuditingPolicyListResultInner> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) {
"""
Lists a database's table auditing policies. Table auditing is deprecated, use blob auditing instead.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database for which the table audit policy is defined.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseTableAuditingPolicyListResultInner object
"""
return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseTableAuditingPolicyListResultInner>, DatabaseTableAuditingPolicyListResultInner>() {
@Override
public DatabaseTableAuditingPolicyListResultInner call(ServiceResponse<DatabaseTableAuditingPolicyListResultInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseTableAuditingPolicyListResultInner> listByDatabaseAsync(String resourceGroupName, String serverName, String databaseName) {
return listByDatabaseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseTableAuditingPolicyListResultInner>, DatabaseTableAuditingPolicyListResultInner>() {
@Override
public DatabaseTableAuditingPolicyListResultInner call(ServiceResponse<DatabaseTableAuditingPolicyListResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseTableAuditingPolicyListResultInner",
">",
"listByDatabaseAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"listByDatabaseWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"DatabaseTableAuditingPolicyListResultInner",
">",
",",
"DatabaseTableAuditingPolicyListResultInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"DatabaseTableAuditingPolicyListResultInner",
"call",
"(",
"ServiceResponse",
"<",
"DatabaseTableAuditingPolicyListResultInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Lists a database's table auditing policies. Table auditing is deprecated, use blob auditing instead.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database for which the table audit policy is defined.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseTableAuditingPolicyListResultInner object | [
"Lists",
"a",
"database",
"s",
"table",
"auditing",
"policies",
".",
"Table",
"auditing",
"is",
"deprecated",
"use",
"blob",
"auditing",
"instead",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseTableAuditingPoliciesInner.java#L306-L313 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationImpl_CustomFieldSerializer.java | OWLAnnotationImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLAnnotationImpl instance) throws SerializationException {
"""
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
"""
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLAnnotationImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLAnnotationImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{"
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLAnnotationImpl_CustomFieldSerializer.java#L71-L74 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java | PerspectiveOps.createIntrinsic | public static CameraPinhole createIntrinsic(int width, int height, double hfov, double vfov) {
"""
Creates a set of intrinsic parameters, without distortion, for a camera with the specified characteristics
@param width Image width
@param height Image height
@param hfov Horizontal FOV in degrees
@param vfov Vertical FOV in degrees
@return guess camera parameters
"""
CameraPinhole intrinsic = new CameraPinhole();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.cy / Math.tan(UtilAngle.degreeToRadian(vfov/2.0));
return intrinsic;
} | java | public static CameraPinhole createIntrinsic(int width, int height, double hfov, double vfov) {
CameraPinhole intrinsic = new CameraPinhole();
intrinsic.width = width;
intrinsic.height = height;
intrinsic.cx = width / 2;
intrinsic.cy = height / 2;
intrinsic.fx = intrinsic.cx / Math.tan(UtilAngle.degreeToRadian(hfov/2.0));
intrinsic.fy = intrinsic.cy / Math.tan(UtilAngle.degreeToRadian(vfov/2.0));
return intrinsic;
} | [
"public",
"static",
"CameraPinhole",
"createIntrinsic",
"(",
"int",
"width",
",",
"int",
"height",
",",
"double",
"hfov",
",",
"double",
"vfov",
")",
"{",
"CameraPinhole",
"intrinsic",
"=",
"new",
"CameraPinhole",
"(",
")",
";",
"intrinsic",
".",
"width",
"=",
"width",
";",
"intrinsic",
".",
"height",
"=",
"height",
";",
"intrinsic",
".",
"cx",
"=",
"width",
"/",
"2",
";",
"intrinsic",
".",
"cy",
"=",
"height",
"/",
"2",
";",
"intrinsic",
".",
"fx",
"=",
"intrinsic",
".",
"cx",
"/",
"Math",
".",
"tan",
"(",
"UtilAngle",
".",
"degreeToRadian",
"(",
"hfov",
"/",
"2.0",
")",
")",
";",
"intrinsic",
".",
"fy",
"=",
"intrinsic",
".",
"cy",
"/",
"Math",
".",
"tan",
"(",
"UtilAngle",
".",
"degreeToRadian",
"(",
"vfov",
"/",
"2.0",
")",
")",
";",
"return",
"intrinsic",
";",
"}"
] | Creates a set of intrinsic parameters, without distortion, for a camera with the specified characteristics
@param width Image width
@param height Image height
@param hfov Horizontal FOV in degrees
@param vfov Vertical FOV in degrees
@return guess camera parameters | [
"Creates",
"a",
"set",
"of",
"intrinsic",
"parameters",
"without",
"distortion",
"for",
"a",
"camera",
"with",
"the",
"specified",
"characteristics"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L97-L107 |
alibaba/ARouter | arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java | Postcard.withSparseParcelableArray | public Postcard withSparseParcelableArray(@Nullable String key, @Nullable SparseArray<? extends Parcelable> value) {
"""
Inserts a SparceArray of Parcelable values into the mapping of this
Bundle, replacing any existing value for the given key. Either key
or value may be null.
@param key a String, or null
@param value a SparseArray of Parcelable objects, or null
@return current
"""
mBundle.putSparseParcelableArray(key, value);
return this;
} | java | public Postcard withSparseParcelableArray(@Nullable String key, @Nullable SparseArray<? extends Parcelable> value) {
mBundle.putSparseParcelableArray(key, value);
return this;
} | [
"public",
"Postcard",
"withSparseParcelableArray",
"(",
"@",
"Nullable",
"String",
"key",
",",
"@",
"Nullable",
"SparseArray",
"<",
"?",
"extends",
"Parcelable",
">",
"value",
")",
"{",
"mBundle",
".",
"putSparseParcelableArray",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Inserts a SparceArray of Parcelable values into the mapping of this
Bundle, replacing any existing value for the given key. Either key
or value may be null.
@param key a String, or null
@param value a SparseArray of Parcelable objects, or null
@return current | [
"Inserts",
"a",
"SparceArray",
"of",
"Parcelable",
"values",
"into",
"the",
"mapping",
"of",
"this",
"Bundle",
"replacing",
"any",
"existing",
"value",
"for",
"the",
"given",
"key",
".",
"Either",
"key",
"or",
"value",
"may",
"be",
"null",
"."
] | train | https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/facade/Postcard.java#L416-L419 |
alkacon/opencms-core | src/org/opencms/ade/sitemap/CmsVfsSitemapService.java | CmsVfsSitemapService.saveInternal | protected CmsSitemapChange saveInternal(String entryPoint, CmsSitemapChange change) throws CmsException {
"""
Internal method for saving a sitemap.<p>
@param entryPoint the URI of the sitemap to save
@param change the change to save
@return list of changed sitemap entries
@throws CmsException if something goes wrong
"""
ensureSession();
switch (change.getChangeType()) {
case clipboardOnly:
// do nothing
break;
case remove:
change = removeEntryFromNavigation(change);
break;
case undelete:
change = undelete(change);
break;
default:
change = applyChange(entryPoint, change);
}
setClipboardData(change.getClipBoardData());
return change;
} | java | protected CmsSitemapChange saveInternal(String entryPoint, CmsSitemapChange change) throws CmsException {
ensureSession();
switch (change.getChangeType()) {
case clipboardOnly:
// do nothing
break;
case remove:
change = removeEntryFromNavigation(change);
break;
case undelete:
change = undelete(change);
break;
default:
change = applyChange(entryPoint, change);
}
setClipboardData(change.getClipBoardData());
return change;
} | [
"protected",
"CmsSitemapChange",
"saveInternal",
"(",
"String",
"entryPoint",
",",
"CmsSitemapChange",
"change",
")",
"throws",
"CmsException",
"{",
"ensureSession",
"(",
")",
";",
"switch",
"(",
"change",
".",
"getChangeType",
"(",
")",
")",
"{",
"case",
"clipboardOnly",
":",
"// do nothing",
"break",
";",
"case",
"remove",
":",
"change",
"=",
"removeEntryFromNavigation",
"(",
"change",
")",
";",
"break",
";",
"case",
"undelete",
":",
"change",
"=",
"undelete",
"(",
"change",
")",
";",
"break",
";",
"default",
":",
"change",
"=",
"applyChange",
"(",
"entryPoint",
",",
"change",
")",
";",
"}",
"setClipboardData",
"(",
"change",
".",
"getClipBoardData",
"(",
")",
")",
";",
"return",
"change",
";",
"}"
] | Internal method for saving a sitemap.<p>
@param entryPoint the URI of the sitemap to save
@param change the change to save
@return list of changed sitemap entries
@throws CmsException if something goes wrong | [
"Internal",
"method",
"for",
"saving",
"a",
"sitemap",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L1234-L1252 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java | Dater.of | public static Dater of(String date, String pattern) {
"""
Returns a new Dater instance with the given date and pattern
@param date
@return
"""
return new Dater(checkNotNull(date), checkNotNull(pattern));
} | java | public static Dater of(String date, String pattern) {
return new Dater(checkNotNull(date), checkNotNull(pattern));
} | [
"public",
"static",
"Dater",
"of",
"(",
"String",
"date",
",",
"String",
"pattern",
")",
"{",
"return",
"new",
"Dater",
"(",
"checkNotNull",
"(",
"date",
")",
",",
"checkNotNull",
"(",
"pattern",
")",
")",
";",
"}"
] | Returns a new Dater instance with the given date and pattern
@param date
@return | [
"Returns",
"a",
"new",
"Dater",
"instance",
"with",
"the",
"given",
"date",
"and",
"pattern"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Dater.java#L254-L256 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/format/DateTimeFormatter.java | DateTimeFormatter.withChronology | public DateTimeFormatter withChronology(Chronology chrono) {
"""
Returns a copy of this formatter with a new override chronology.
<p>
This returns a formatter with similar state to this formatter but
with the override chronology set.
By default, a formatter has no override chronology, returning null.
<p>
If an override is added, then any date that is printed or parsed will be affected.
<p>
When printing, if the {@code Temporal} object contains a date then it will
be converted to a date in the override chronology.
Any time or zone will be retained unless overridden.
The converted result will behave in a manner equivalent to an implementation
of {@code ChronoLocalDate},{@code ChronoLocalDateTime} or {@code ChronoZonedDateTime}.
<p>
When parsing, the override chronology will be used to interpret the
{@linkplain ChronoField fields} into a date unless the
formatter directly parses a valid chronology.
<p>
This instance is immutable and unaffected by this method call.
@param chrono the new chronology, not null
@return a formatter based on this formatter with the requested override chronology, not null
"""
if (Jdk8Methods.equals(this.chrono, chrono)) {
return this;
}
return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
} | java | public DateTimeFormatter withChronology(Chronology chrono) {
if (Jdk8Methods.equals(this.chrono, chrono)) {
return this;
}
return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone);
} | [
"public",
"DateTimeFormatter",
"withChronology",
"(",
"Chronology",
"chrono",
")",
"{",
"if",
"(",
"Jdk8Methods",
".",
"equals",
"(",
"this",
".",
"chrono",
",",
"chrono",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"DateTimeFormatter",
"(",
"printerParser",
",",
"locale",
",",
"decimalStyle",
",",
"resolverStyle",
",",
"resolverFields",
",",
"chrono",
",",
"zone",
")",
";",
"}"
] | Returns a copy of this formatter with a new override chronology.
<p>
This returns a formatter with similar state to this formatter but
with the override chronology set.
By default, a formatter has no override chronology, returning null.
<p>
If an override is added, then any date that is printed or parsed will be affected.
<p>
When printing, if the {@code Temporal} object contains a date then it will
be converted to a date in the override chronology.
Any time or zone will be retained unless overridden.
The converted result will behave in a manner equivalent to an implementation
of {@code ChronoLocalDate},{@code ChronoLocalDateTime} or {@code ChronoZonedDateTime}.
<p>
When parsing, the override chronology will be used to interpret the
{@linkplain ChronoField fields} into a date unless the
formatter directly parses a valid chronology.
<p>
This instance is immutable and unaffected by this method call.
@param chrono the new chronology, not null
@return a formatter based on this formatter with the requested override chronology, not null | [
"Returns",
"a",
"copy",
"of",
"this",
"formatter",
"with",
"a",
"new",
"override",
"chronology",
".",
"<p",
">",
"This",
"returns",
"a",
"formatter",
"with",
"similar",
"state",
"to",
"this",
"formatter",
"but",
"with",
"the",
"override",
"chronology",
"set",
".",
"By",
"default",
"a",
"formatter",
"has",
"no",
"override",
"chronology",
"returning",
"null",
".",
"<p",
">",
"If",
"an",
"override",
"is",
"added",
"then",
"any",
"date",
"that",
"is",
"printed",
"or",
"parsed",
"will",
"be",
"affected",
".",
"<p",
">",
"When",
"printing",
"if",
"the",
"{",
"@code",
"Temporal",
"}",
"object",
"contains",
"a",
"date",
"then",
"it",
"will",
"be",
"converted",
"to",
"a",
"date",
"in",
"the",
"override",
"chronology",
".",
"Any",
"time",
"or",
"zone",
"will",
"be",
"retained",
"unless",
"overridden",
".",
"The",
"converted",
"result",
"will",
"behave",
"in",
"a",
"manner",
"equivalent",
"to",
"an",
"implementation",
"of",
"{",
"@code",
"ChronoLocalDate",
"}",
"{",
"@code",
"ChronoLocalDateTime",
"}",
"or",
"{",
"@code",
"ChronoZonedDateTime",
"}",
".",
"<p",
">",
"When",
"parsing",
"the",
"override",
"chronology",
"will",
"be",
"used",
"to",
"interpret",
"the",
"{",
"@linkplain",
"ChronoField",
"fields",
"}",
"into",
"a",
"date",
"unless",
"the",
"formatter",
"directly",
"parses",
"a",
"valid",
"chronology",
".",
"<p",
">",
"This",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
"."
] | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/format/DateTimeFormatter.java#L1135-L1140 |
graknlabs/grakn | server/src/server/exception/TransactionException.java | TransactionException.invalidLabelStart | public static TransactionException invalidLabelStart(Label label) {
"""
Thrown when creating a label which starts with a reserved character Schema.ImplicitType#RESERVED
"""
return create(String.format("Cannot create a label {%s} starting with character {%s} as it is a reserved starting character", label, Schema.ImplicitType.RESERVED.getValue()));
} | java | public static TransactionException invalidLabelStart(Label label) {
return create(String.format("Cannot create a label {%s} starting with character {%s} as it is a reserved starting character", label, Schema.ImplicitType.RESERVED.getValue()));
} | [
"public",
"static",
"TransactionException",
"invalidLabelStart",
"(",
"Label",
"label",
")",
"{",
"return",
"create",
"(",
"String",
".",
"format",
"(",
"\"Cannot create a label {%s} starting with character {%s} as it is a reserved starting character\"",
",",
"label",
",",
"Schema",
".",
"ImplicitType",
".",
"RESERVED",
".",
"getValue",
"(",
")",
")",
")",
";",
"}"
] | Thrown when creating a label which starts with a reserved character Schema.ImplicitType#RESERVED | [
"Thrown",
"when",
"creating",
"a",
"label",
"which",
"starts",
"with",
"a",
"reserved",
"character",
"Schema",
".",
"ImplicitType#RESERVED"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L299-L301 |
mirage-sql/mirage | src/main/java/com/miragesql/miragesql/SqlExecutor.java | SqlExecutor.executeUpdateSql | public int executeUpdateSql(String sql, PropertyDesc[] propDescs, Object entity) {
"""
Executes an update SQL.
@param sql the update SQL to execute
@param propDescs the array of parameters
@param entity the entity object in insertion, otherwise null
@return the number of updated rows
@throws SQLRuntimeException if a database access error occurs
"""
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Connection conn = connectionProvider.getConnection();
if (logger.isDebugEnabled()) {
printSql(sql);
printParameters(propDescs);
}
if(entity != null && dialect.supportsGenerationType(GenerationType.IDENTITY)){
stmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
stmt = conn.prepareStatement(sql);
}
setParameters(stmt, propDescs, entity);
int result = stmt.executeUpdate();
// Sets GenerationType.IDENTITY properties value.
if(entity != null && dialect.supportsGenerationType(GenerationType.IDENTITY)){
rs = stmt.getGeneratedKeys();
fillIdentityPrimaryKeys(entity, rs);
}
return result;
} catch(SQLException ex){
throw new SQLRuntimeException(ex);
} finally {
JdbcUtil.close(rs);
JdbcUtil.close(stmt);
}
} | java | public int executeUpdateSql(String sql, PropertyDesc[] propDescs, Object entity){
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Connection conn = connectionProvider.getConnection();
if (logger.isDebugEnabled()) {
printSql(sql);
printParameters(propDescs);
}
if(entity != null && dialect.supportsGenerationType(GenerationType.IDENTITY)){
stmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
stmt = conn.prepareStatement(sql);
}
setParameters(stmt, propDescs, entity);
int result = stmt.executeUpdate();
// Sets GenerationType.IDENTITY properties value.
if(entity != null && dialect.supportsGenerationType(GenerationType.IDENTITY)){
rs = stmt.getGeneratedKeys();
fillIdentityPrimaryKeys(entity, rs);
}
return result;
} catch(SQLException ex){
throw new SQLRuntimeException(ex);
} finally {
JdbcUtil.close(rs);
JdbcUtil.close(stmt);
}
} | [
"public",
"int",
"executeUpdateSql",
"(",
"String",
"sql",
",",
"PropertyDesc",
"[",
"]",
"propDescs",
",",
"Object",
"entity",
")",
"{",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"ResultSet",
"rs",
"=",
"null",
";",
"try",
"{",
"Connection",
"conn",
"=",
"connectionProvider",
".",
"getConnection",
"(",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"printSql",
"(",
"sql",
")",
";",
"printParameters",
"(",
"propDescs",
")",
";",
"}",
"if",
"(",
"entity",
"!=",
"null",
"&&",
"dialect",
".",
"supportsGenerationType",
"(",
"GenerationType",
".",
"IDENTITY",
")",
")",
"{",
"stmt",
"=",
"conn",
".",
"prepareStatement",
"(",
"sql",
",",
"PreparedStatement",
".",
"RETURN_GENERATED_KEYS",
")",
";",
"}",
"else",
"{",
"stmt",
"=",
"conn",
".",
"prepareStatement",
"(",
"sql",
")",
";",
"}",
"setParameters",
"(",
"stmt",
",",
"propDescs",
",",
"entity",
")",
";",
"int",
"result",
"=",
"stmt",
".",
"executeUpdate",
"(",
")",
";",
"// Sets GenerationType.IDENTITY properties value.\r",
"if",
"(",
"entity",
"!=",
"null",
"&&",
"dialect",
".",
"supportsGenerationType",
"(",
"GenerationType",
".",
"IDENTITY",
")",
")",
"{",
"rs",
"=",
"stmt",
".",
"getGeneratedKeys",
"(",
")",
";",
"fillIdentityPrimaryKeys",
"(",
"entity",
",",
"rs",
")",
";",
"}",
"return",
"result",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"SQLRuntimeException",
"(",
"ex",
")",
";",
"}",
"finally",
"{",
"JdbcUtil",
".",
"close",
"(",
"rs",
")",
";",
"JdbcUtil",
".",
"close",
"(",
"stmt",
")",
";",
"}",
"}"
] | Executes an update SQL.
@param sql the update SQL to execute
@param propDescs the array of parameters
@param entity the entity object in insertion, otherwise null
@return the number of updated rows
@throws SQLRuntimeException if a database access error occurs | [
"Executes",
"an",
"update",
"SQL",
"."
] | train | https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/SqlExecutor.java#L274-L309 |
cojen/Cojen | src/main/java/org/cojen/classfile/MethodInfo.java | MethodInfo.addInnerClass | public ClassFile addInnerClass(String innerClassName, Class superClass) {
"""
Add an inner class to this method.
@param innerClassName Optional short inner class name.
@param superClass Super class.
"""
return addInnerClass(innerClassName, superClass.getName());
} | java | public ClassFile addInnerClass(String innerClassName, Class superClass) {
return addInnerClass(innerClassName, superClass.getName());
} | [
"public",
"ClassFile",
"addInnerClass",
"(",
"String",
"innerClassName",
",",
"Class",
"superClass",
")",
"{",
"return",
"addInnerClass",
"(",
"innerClassName",
",",
"superClass",
".",
"getName",
"(",
")",
")",
";",
"}"
] | Add an inner class to this method.
@param innerClassName Optional short inner class name.
@param superClass Super class. | [
"Add",
"an",
"inner",
"class",
"to",
"this",
"method",
"."
] | train | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/MethodInfo.java#L331-L333 |
rometools/rome | rome-propono/src/main/java/com/rometools/propono/atom/client/ClientCollection.java | ClientCollection.createMediaEntry | public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final byte[] bytes) throws ProponoException {
"""
Create new media entry assocaited with collection, but do not save. server. Depending on the
Atom server, you may or may not be able to persist the properties of the entry that is
returned.
@param title Title to used for uploaded file.
@param slug String to be used in file-name of stored file
@param contentType MIME content-type of file.
@param bytes Data to be uploaded as byte array.
@throws ProponoException if collecton is not writable
"""
if (!isWritable()) {
throw new ProponoException("Collection is not writable");
}
return new ClientMediaEntry(service, this, title, slug, contentType, bytes);
} | java | public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final byte[] bytes) throws ProponoException {
if (!isWritable()) {
throw new ProponoException("Collection is not writable");
}
return new ClientMediaEntry(service, this, title, slug, contentType, bytes);
} | [
"public",
"ClientMediaEntry",
"createMediaEntry",
"(",
"final",
"String",
"title",
",",
"final",
"String",
"slug",
",",
"final",
"String",
"contentType",
",",
"final",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"ProponoException",
"{",
"if",
"(",
"!",
"isWritable",
"(",
")",
")",
"{",
"throw",
"new",
"ProponoException",
"(",
"\"Collection is not writable\"",
")",
";",
"}",
"return",
"new",
"ClientMediaEntry",
"(",
"service",
",",
"this",
",",
"title",
",",
"slug",
",",
"contentType",
",",
"bytes",
")",
";",
"}"
] | Create new media entry assocaited with collection, but do not save. server. Depending on the
Atom server, you may or may not be able to persist the properties of the entry that is
returned.
@param title Title to used for uploaded file.
@param slug String to be used in file-name of stored file
@param contentType MIME content-type of file.
@param bytes Data to be uploaded as byte array.
@throws ProponoException if collecton is not writable | [
"Create",
"new",
"media",
"entry",
"assocaited",
"with",
"collection",
"but",
"do",
"not",
"save",
".",
"server",
".",
"Depending",
"on",
"the",
"Atom",
"server",
"you",
"may",
"or",
"may",
"not",
"be",
"able",
"to",
"persist",
"the",
"properties",
"of",
"the",
"entry",
"that",
"is",
"returned",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome-propono/src/main/java/com/rometools/propono/atom/client/ClientCollection.java#L158-L163 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobStreamsInner.java | JobStreamsInner.getAsync | public Observable<JobStreamInner> getAsync(String resourceGroupName, String automationAccountName, String jobId, String jobStreamId) {
"""
Retrieve the job stream identified by job stream id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param jobId The job id.
@param jobStreamId The job stream id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the JobStreamInner object
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, jobStreamId).map(new Func1<ServiceResponse<JobStreamInner>, JobStreamInner>() {
@Override
public JobStreamInner call(ServiceResponse<JobStreamInner> response) {
return response.body();
}
});
} | java | public Observable<JobStreamInner> getAsync(String resourceGroupName, String automationAccountName, String jobId, String jobStreamId) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, jobStreamId).map(new Func1<ServiceResponse<JobStreamInner>, JobStreamInner>() {
@Override
public JobStreamInner call(ServiceResponse<JobStreamInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"JobStreamInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"jobId",
",",
"String",
"jobStreamId",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"jobId",
",",
"jobStreamId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"JobStreamInner",
">",
",",
"JobStreamInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"JobStreamInner",
"call",
"(",
"ServiceResponse",
"<",
"JobStreamInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Retrieve the job stream identified by job stream id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param jobId The job id.
@param jobStreamId The job stream id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the JobStreamInner object | [
"Retrieve",
"the",
"job",
"stream",
"identified",
"by",
"job",
"stream",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobStreamsInner.java#L115-L122 |
pressgang-ccms/PressGangCCMSContentSpec | src/main/java/org/jboss/pressgang/ccms/contentspec/entities/InjectionOptions.java | InjectionOptions.getInjectionSetting | private String getInjectionSetting(final String input, final char startDelim) {
"""
Gets the Injection Setting for these options when using the String Constructor.
@param input The input to be parsed to get the setting.
@param startDelim The delimiter that specifies that start of options (ie '[')
@return The title as a String or null if the title is blank.
"""
return input == null || input.equals("") ? null : StringUtilities.split(input, startDelim)[0].trim();
} | java | private String getInjectionSetting(final String input, final char startDelim) {
return input == null || input.equals("") ? null : StringUtilities.split(input, startDelim)[0].trim();
} | [
"private",
"String",
"getInjectionSetting",
"(",
"final",
"String",
"input",
",",
"final",
"char",
"startDelim",
")",
"{",
"return",
"input",
"==",
"null",
"||",
"input",
".",
"equals",
"(",
"\"\"",
")",
"?",
"null",
":",
"StringUtilities",
".",
"split",
"(",
"input",
",",
"startDelim",
")",
"[",
"0",
"]",
".",
"trim",
"(",
")",
";",
"}"
] | Gets the Injection Setting for these options when using the String Constructor.
@param input The input to be parsed to get the setting.
@param startDelim The delimiter that specifies that start of options (ie '[')
@return The title as a String or null if the title is blank. | [
"Gets",
"the",
"Injection",
"Setting",
"for",
"these",
"options",
"when",
"using",
"the",
"String",
"Constructor",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/entities/InjectionOptions.java#L78-L80 |
stripe/stripe-android | stripe/src/main/java/com/stripe/android/Stripe.java | Stripe.retrieveSourceSynchronous | public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
"""
Retrieve an existing {@link Source} from the Stripe API. Note that this is a
synchronous method, and cannot be called on the main thread. Doing so will cause your app
to crash. This method uses the default publishable key for this {@link Stripe} instance.
@param sourceId the {@link Source#mId} field of the desired Source object
@param clientSecret the {@link Source#mClientSecret} field of the desired Source object
@return a {@link Source} if one could be found based on the input params, or {@code null} if
no such Source could be found.
@throws AuthenticationException failure to properly authenticate yourself (check your key)
@throws InvalidRequestException your request has invalid parameters
@throws APIConnectionException failure to connect to Stripe's API
@throws APIException any other type of problem (for instance, a temporary issue with
Stripe's servers)
"""
return retrieveSourceSynchronous(sourceId, clientSecret, null);
} | java | public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return retrieveSourceSynchronous(sourceId, clientSecret, null);
} | [
"public",
"Source",
"retrieveSourceSynchronous",
"(",
"@",
"NonNull",
"@",
"Size",
"(",
"min",
"=",
"1",
")",
"String",
"sourceId",
",",
"@",
"NonNull",
"@",
"Size",
"(",
"min",
"=",
"1",
")",
"String",
"clientSecret",
")",
"throws",
"AuthenticationException",
",",
"InvalidRequestException",
",",
"APIConnectionException",
",",
"APIException",
"{",
"return",
"retrieveSourceSynchronous",
"(",
"sourceId",
",",
"clientSecret",
",",
"null",
")",
";",
"}"
] | Retrieve an existing {@link Source} from the Stripe API. Note that this is a
synchronous method, and cannot be called on the main thread. Doing so will cause your app
to crash. This method uses the default publishable key for this {@link Stripe} instance.
@param sourceId the {@link Source#mId} field of the desired Source object
@param clientSecret the {@link Source#mClientSecret} field of the desired Source object
@return a {@link Source} if one could be found based on the input params, or {@code null} if
no such Source could be found.
@throws AuthenticationException failure to properly authenticate yourself (check your key)
@throws InvalidRequestException your request has invalid parameters
@throws APIConnectionException failure to connect to Stripe's API
@throws APIException any other type of problem (for instance, a temporary issue with
Stripe's servers) | [
"Retrieve",
"an",
"existing",
"{",
"@link",
"Source",
"}",
"from",
"the",
"Stripe",
"API",
".",
"Note",
"that",
"this",
"is",
"a",
"synchronous",
"method",
"and",
"cannot",
"be",
"called",
"on",
"the",
"main",
"thread",
".",
"Doing",
"so",
"will",
"cause",
"your",
"app",
"to",
"crash",
".",
"This",
"method",
"uses",
"the",
"default",
"publishable",
"key",
"for",
"this",
"{",
"@link",
"Stripe",
"}",
"instance",
"."
] | train | https://github.com/stripe/stripe-android/blob/0f199255f3769a3b84583fe3ace47bfae8c3b1c8/stripe/src/main/java/com/stripe/android/Stripe.java#L784-L792 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java | SecurityServletConfiguratorHelper.createFormLoginConfiguration | private FormLoginConfiguration createFormLoginConfiguration(LoginConfig loginConfig) {
"""
Creates a form login configuration object that represents a form-login-config element in web.xml and/or web-fragment.xml files.
@param loginConfig the login-config element
@return the security code's representation of a login configuration
"""
FormLoginConfiguration formLoginConfiguration = null;
FormLoginConfig formLoginConfig = loginConfig.getFormLoginConfig();
if (formLoginConfig != null) {
String loginPage = formLoginConfig.getFormLoginPage();
String errorPage = formLoginConfig.getFormErrorPage();
formLoginConfiguration = new FormLoginConfigurationImpl(loginPage, errorPage);
}
return formLoginConfiguration;
} | java | private FormLoginConfiguration createFormLoginConfiguration(LoginConfig loginConfig) {
FormLoginConfiguration formLoginConfiguration = null;
FormLoginConfig formLoginConfig = loginConfig.getFormLoginConfig();
if (formLoginConfig != null) {
String loginPage = formLoginConfig.getFormLoginPage();
String errorPage = formLoginConfig.getFormErrorPage();
formLoginConfiguration = new FormLoginConfigurationImpl(loginPage, errorPage);
}
return formLoginConfiguration;
} | [
"private",
"FormLoginConfiguration",
"createFormLoginConfiguration",
"(",
"LoginConfig",
"loginConfig",
")",
"{",
"FormLoginConfiguration",
"formLoginConfiguration",
"=",
"null",
";",
"FormLoginConfig",
"formLoginConfig",
"=",
"loginConfig",
".",
"getFormLoginConfig",
"(",
")",
";",
"if",
"(",
"formLoginConfig",
"!=",
"null",
")",
"{",
"String",
"loginPage",
"=",
"formLoginConfig",
".",
"getFormLoginPage",
"(",
")",
";",
"String",
"errorPage",
"=",
"formLoginConfig",
".",
"getFormErrorPage",
"(",
")",
";",
"formLoginConfiguration",
"=",
"new",
"FormLoginConfigurationImpl",
"(",
"loginPage",
",",
"errorPage",
")",
";",
"}",
"return",
"formLoginConfiguration",
";",
"}"
] | Creates a form login configuration object that represents a form-login-config element in web.xml and/or web-fragment.xml files.
@param loginConfig the login-config element
@return the security code's representation of a login configuration | [
"Creates",
"a",
"form",
"login",
"configuration",
"object",
"that",
"represents",
"a",
"form",
"-",
"login",
"-",
"config",
"element",
"in",
"web",
".",
"xml",
"and",
"/",
"or",
"web",
"-",
"fragment",
".",
"xml",
"files",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java#L646-L655 |
JOML-CI/JOML | src/org/joml/Vector4d.java | Vector4d.set | public Vector4d set(int index, ByteBuffer buffer) {
"""
Read this vector from the supplied {@link ByteBuffer} starting at the specified
absolute buffer position/index.
<p>
This method will not increment the position of the given ByteBuffer.
@param index
the absolute position into the ByteBuffer
@param buffer
values will be read in <code>x, y, z, w</code> order
@return this
"""
MemUtil.INSTANCE.get(this, index, buffer);
return this;
} | java | public Vector4d set(int index, ByteBuffer buffer) {
MemUtil.INSTANCE.get(this, index, buffer);
return this;
} | [
"public",
"Vector4d",
"set",
"(",
"int",
"index",
",",
"ByteBuffer",
"buffer",
")",
"{",
"MemUtil",
".",
"INSTANCE",
".",
"get",
"(",
"this",
",",
"index",
",",
"buffer",
")",
";",
"return",
"this",
";",
"}"
] | Read this vector from the supplied {@link ByteBuffer} starting at the specified
absolute buffer position/index.
<p>
This method will not increment the position of the given ByteBuffer.
@param index
the absolute position into the ByteBuffer
@param buffer
values will be read in <code>x, y, z, w</code> order
@return this | [
"Read",
"this",
"vector",
"from",
"the",
"supplied",
"{",
"@link",
"ByteBuffer",
"}",
"starting",
"at",
"the",
"specified",
"absolute",
"buffer",
"position",
"/",
"index",
".",
"<p",
">",
"This",
"method",
"will",
"not",
"increment",
"the",
"position",
"of",
"the",
"given",
"ByteBuffer",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector4d.java#L502-L505 |
azkaban/azkaban | azkaban-web-server/src/main/java/azkaban/flowtrigger/quartz/FlowTriggerScheduler.java | FlowTriggerScheduler.getScheduledFlowTriggerJobs | public List<ScheduledFlowTrigger> getScheduledFlowTriggerJobs() {
"""
Retrieve the list of scheduled flow triggers from quartz database
"""
try {
final Scheduler quartzScheduler = this.scheduler.getScheduler();
final List<String> groupNames = quartzScheduler.getJobGroupNames();
final List<ScheduledFlowTrigger> flowTriggerJobDetails = new ArrayList<>();
for (final String groupName : groupNames) {
final JobKey jobKey = new JobKey(FlowTriggerQuartzJob.JOB_NAME, groupName);
ScheduledFlowTrigger scheduledFlowTrigger = null;
try {
final JobDetail job = quartzScheduler.getJobDetail(jobKey);
final JobDataMap jobDataMap = job.getJobDataMap();
final String flowId = jobDataMap.getString(FlowTriggerQuartzJob.FLOW_ID);
final int projectId = jobDataMap.getInt(FlowTriggerQuartzJob.PROJECT_ID);
final FlowTrigger flowTrigger = (FlowTrigger) jobDataMap
.get(FlowTriggerQuartzJob.FLOW_TRIGGER);
final String submitUser = jobDataMap.getString(FlowTriggerQuartzJob.SUBMIT_USER);
final List<? extends Trigger> quartzTriggers = quartzScheduler.getTriggersOfJob(jobKey);
final boolean isPaused = this.scheduler
.isJobPaused(FlowTriggerQuartzJob.JOB_NAME, groupName);
final Project project = projectManager.getProject(projectId);
final Flow flow = project.getFlow(flowId);
scheduledFlowTrigger = new ScheduledFlowTrigger(projectId,
this.projectManager.getProject(projectId).getName(),
flowId, flowTrigger, submitUser, quartzTriggers.isEmpty() ? null
: quartzTriggers.get(0), isPaused, flow.isLocked());
} catch (final Exception ex) {
logger.error("Unable to get flow trigger by job key {}", jobKey, ex);
scheduledFlowTrigger = null;
}
flowTriggerJobDetails.add(scheduledFlowTrigger);
}
return flowTriggerJobDetails;
} catch (final Exception ex) {
logger.error("Unable to get scheduled flow triggers", ex);
return new ArrayList<>();
}
} | java | public List<ScheduledFlowTrigger> getScheduledFlowTriggerJobs() {
try {
final Scheduler quartzScheduler = this.scheduler.getScheduler();
final List<String> groupNames = quartzScheduler.getJobGroupNames();
final List<ScheduledFlowTrigger> flowTriggerJobDetails = new ArrayList<>();
for (final String groupName : groupNames) {
final JobKey jobKey = new JobKey(FlowTriggerQuartzJob.JOB_NAME, groupName);
ScheduledFlowTrigger scheduledFlowTrigger = null;
try {
final JobDetail job = quartzScheduler.getJobDetail(jobKey);
final JobDataMap jobDataMap = job.getJobDataMap();
final String flowId = jobDataMap.getString(FlowTriggerQuartzJob.FLOW_ID);
final int projectId = jobDataMap.getInt(FlowTriggerQuartzJob.PROJECT_ID);
final FlowTrigger flowTrigger = (FlowTrigger) jobDataMap
.get(FlowTriggerQuartzJob.FLOW_TRIGGER);
final String submitUser = jobDataMap.getString(FlowTriggerQuartzJob.SUBMIT_USER);
final List<? extends Trigger> quartzTriggers = quartzScheduler.getTriggersOfJob(jobKey);
final boolean isPaused = this.scheduler
.isJobPaused(FlowTriggerQuartzJob.JOB_NAME, groupName);
final Project project = projectManager.getProject(projectId);
final Flow flow = project.getFlow(flowId);
scheduledFlowTrigger = new ScheduledFlowTrigger(projectId,
this.projectManager.getProject(projectId).getName(),
flowId, flowTrigger, submitUser, quartzTriggers.isEmpty() ? null
: quartzTriggers.get(0), isPaused, flow.isLocked());
} catch (final Exception ex) {
logger.error("Unable to get flow trigger by job key {}", jobKey, ex);
scheduledFlowTrigger = null;
}
flowTriggerJobDetails.add(scheduledFlowTrigger);
}
return flowTriggerJobDetails;
} catch (final Exception ex) {
logger.error("Unable to get scheduled flow triggers", ex);
return new ArrayList<>();
}
} | [
"public",
"List",
"<",
"ScheduledFlowTrigger",
">",
"getScheduledFlowTriggerJobs",
"(",
")",
"{",
"try",
"{",
"final",
"Scheduler",
"quartzScheduler",
"=",
"this",
".",
"scheduler",
".",
"getScheduler",
"(",
")",
";",
"final",
"List",
"<",
"String",
">",
"groupNames",
"=",
"quartzScheduler",
".",
"getJobGroupNames",
"(",
")",
";",
"final",
"List",
"<",
"ScheduledFlowTrigger",
">",
"flowTriggerJobDetails",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"final",
"String",
"groupName",
":",
"groupNames",
")",
"{",
"final",
"JobKey",
"jobKey",
"=",
"new",
"JobKey",
"(",
"FlowTriggerQuartzJob",
".",
"JOB_NAME",
",",
"groupName",
")",
";",
"ScheduledFlowTrigger",
"scheduledFlowTrigger",
"=",
"null",
";",
"try",
"{",
"final",
"JobDetail",
"job",
"=",
"quartzScheduler",
".",
"getJobDetail",
"(",
"jobKey",
")",
";",
"final",
"JobDataMap",
"jobDataMap",
"=",
"job",
".",
"getJobDataMap",
"(",
")",
";",
"final",
"String",
"flowId",
"=",
"jobDataMap",
".",
"getString",
"(",
"FlowTriggerQuartzJob",
".",
"FLOW_ID",
")",
";",
"final",
"int",
"projectId",
"=",
"jobDataMap",
".",
"getInt",
"(",
"FlowTriggerQuartzJob",
".",
"PROJECT_ID",
")",
";",
"final",
"FlowTrigger",
"flowTrigger",
"=",
"(",
"FlowTrigger",
")",
"jobDataMap",
".",
"get",
"(",
"FlowTriggerQuartzJob",
".",
"FLOW_TRIGGER",
")",
";",
"final",
"String",
"submitUser",
"=",
"jobDataMap",
".",
"getString",
"(",
"FlowTriggerQuartzJob",
".",
"SUBMIT_USER",
")",
";",
"final",
"List",
"<",
"?",
"extends",
"Trigger",
">",
"quartzTriggers",
"=",
"quartzScheduler",
".",
"getTriggersOfJob",
"(",
"jobKey",
")",
";",
"final",
"boolean",
"isPaused",
"=",
"this",
".",
"scheduler",
".",
"isJobPaused",
"(",
"FlowTriggerQuartzJob",
".",
"JOB_NAME",
",",
"groupName",
")",
";",
"final",
"Project",
"project",
"=",
"projectManager",
".",
"getProject",
"(",
"projectId",
")",
";",
"final",
"Flow",
"flow",
"=",
"project",
".",
"getFlow",
"(",
"flowId",
")",
";",
"scheduledFlowTrigger",
"=",
"new",
"ScheduledFlowTrigger",
"(",
"projectId",
",",
"this",
".",
"projectManager",
".",
"getProject",
"(",
"projectId",
")",
".",
"getName",
"(",
")",
",",
"flowId",
",",
"flowTrigger",
",",
"submitUser",
",",
"quartzTriggers",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"quartzTriggers",
".",
"get",
"(",
"0",
")",
",",
"isPaused",
",",
"flow",
".",
"isLocked",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"\"Unable to get flow trigger by job key {}\"",
",",
"jobKey",
",",
"ex",
")",
";",
"scheduledFlowTrigger",
"=",
"null",
";",
"}",
"flowTriggerJobDetails",
".",
"add",
"(",
"scheduledFlowTrigger",
")",
";",
"}",
"return",
"flowTriggerJobDetails",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"\"Unable to get scheduled flow triggers\"",
",",
"ex",
")",
";",
"return",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"}"
] | Retrieve the list of scheduled flow triggers from quartz database | [
"Retrieve",
"the",
"list",
"of",
"scheduled",
"flow",
"triggers",
"from",
"quartz",
"database"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/flowtrigger/quartz/FlowTriggerScheduler.java#L136-L175 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java | TmdbPeople.getPersonCombinedCredits | public PersonCreditList<CreditBasic> getPersonCombinedCredits(int personId, String language) throws MovieDbException {
"""
Get the combined (movie and TV) credits for a specific person id.
To get the expanded details for each TV record, call the /credit method
with the provided credit_id.
This will provide details about which episode and/or season the credit is
for.
@param personId
@param language
@return
@throws MovieDbException
"""
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, personId);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.COMBINED_CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(PersonCreditList.class, PersonCreditsMixIn.class);
TypeReference tr = new TypeReference<PersonCreditList<CreditBasic>>() {
};
return mapper.readValue(webpage, tr);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person combined credits", url, ex);
}
} | java | public PersonCreditList<CreditBasic> getPersonCombinedCredits(int personId, String language) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, personId);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.PERSON).subMethod(MethodSub.COMBINED_CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(PersonCreditList.class, PersonCreditsMixIn.class);
TypeReference tr = new TypeReference<PersonCreditList<CreditBasic>>() {
};
return mapper.readValue(webpage, tr);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get person combined credits", url, ex);
}
} | [
"public",
"PersonCreditList",
"<",
"CreditBasic",
">",
"getPersonCombinedCredits",
"(",
"int",
"personId",
",",
"String",
"language",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"ID",
",",
"personId",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"LANGUAGE",
",",
"language",
")",
";",
"URL",
"url",
"=",
"new",
"ApiUrl",
"(",
"apiKey",
",",
"MethodBase",
".",
"PERSON",
")",
".",
"subMethod",
"(",
"MethodSub",
".",
"COMBINED_CREDITS",
")",
".",
"buildUrl",
"(",
"parameters",
")",
";",
"String",
"webpage",
"=",
"httpTools",
".",
"getRequest",
"(",
"url",
")",
";",
"try",
"{",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"mapper",
".",
"addMixIn",
"(",
"PersonCreditList",
".",
"class",
",",
"PersonCreditsMixIn",
".",
"class",
")",
";",
"TypeReference",
"tr",
"=",
"new",
"TypeReference",
"<",
"PersonCreditList",
"<",
"CreditBasic",
">",
">",
"(",
")",
"{",
"}",
";",
"return",
"mapper",
".",
"readValue",
"(",
"webpage",
",",
"tr",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"MovieDbException",
"(",
"ApiExceptionType",
".",
"MAPPING_FAILED",
",",
"\"Failed to get person combined credits\"",
",",
"url",
",",
"ex",
")",
";",
"}",
"}"
] | Get the combined (movie and TV) credits for a specific person id.
To get the expanded details for each TV record, call the /credit method
with the provided credit_id.
This will provide details about which episode and/or season the credit is
for.
@param personId
@param language
@return
@throws MovieDbException | [
"Get",
"the",
"combined",
"(",
"movie",
"and",
"TV",
")",
"credits",
"for",
"a",
"specific",
"person",
"id",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbPeople.java#L169-L186 |
TakahikoKawasaki/nv-bluetooth | src/main/java/com/neovisionaries/bluetooth/ble/advertising/ADPayloadParser.java | ADPayloadParser.registerManufacturerSpecificBuilder | public void registerManufacturerSpecificBuilder(int companyId, ADManufacturerSpecificBuilder builder) {
"""
Register a builder for the company ID. The given builder is added
at the beginning of the list of the builders for the company ID.
@param companyId
Company ID. The value must be in the range from 0 to 0xFFFF.
@param builder
A builder.
"""
if (companyId < 0 || 0xFFFF < companyId)
{
String message = String.format("'companyId' is out of the valid range: %d", companyId);
throw new IllegalArgumentException(message);
}
if (builder == null)
{
return;
}
// Use the company ID as the key for the builder.
Integer key = Integer.valueOf(companyId);
// Get the existing list of builders for the company ID.
List<ADManufacturerSpecificBuilder> builders = mMSBuilders.get(key);
// If no builder has been registered for the company ID yet.
if (builders == null)
{
builders = new ArrayList<ADManufacturerSpecificBuilder>();
mMSBuilders.put(key, builders);
}
// Register the builder at the beginning of the builder list.
builders.add(0, builder);
} | java | public void registerManufacturerSpecificBuilder(int companyId, ADManufacturerSpecificBuilder builder)
{
if (companyId < 0 || 0xFFFF < companyId)
{
String message = String.format("'companyId' is out of the valid range: %d", companyId);
throw new IllegalArgumentException(message);
}
if (builder == null)
{
return;
}
// Use the company ID as the key for the builder.
Integer key = Integer.valueOf(companyId);
// Get the existing list of builders for the company ID.
List<ADManufacturerSpecificBuilder> builders = mMSBuilders.get(key);
// If no builder has been registered for the company ID yet.
if (builders == null)
{
builders = new ArrayList<ADManufacturerSpecificBuilder>();
mMSBuilders.put(key, builders);
}
// Register the builder at the beginning of the builder list.
builders.add(0, builder);
} | [
"public",
"void",
"registerManufacturerSpecificBuilder",
"(",
"int",
"companyId",
",",
"ADManufacturerSpecificBuilder",
"builder",
")",
"{",
"if",
"(",
"companyId",
"<",
"0",
"||",
"0xFFFF",
"<",
"companyId",
")",
"{",
"String",
"message",
"=",
"String",
".",
"format",
"(",
"\"'companyId' is out of the valid range: %d\"",
",",
"companyId",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
";",
"}",
"if",
"(",
"builder",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// Use the company ID as the key for the builder.",
"Integer",
"key",
"=",
"Integer",
".",
"valueOf",
"(",
"companyId",
")",
";",
"// Get the existing list of builders for the company ID.",
"List",
"<",
"ADManufacturerSpecificBuilder",
">",
"builders",
"=",
"mMSBuilders",
".",
"get",
"(",
"key",
")",
";",
"// If no builder has been registered for the company ID yet.",
"if",
"(",
"builders",
"==",
"null",
")",
"{",
"builders",
"=",
"new",
"ArrayList",
"<",
"ADManufacturerSpecificBuilder",
">",
"(",
")",
";",
"mMSBuilders",
".",
"put",
"(",
"key",
",",
"builders",
")",
";",
"}",
"// Register the builder at the beginning of the builder list.",
"builders",
".",
"add",
"(",
"0",
",",
"builder",
")",
";",
"}"
] | Register a builder for the company ID. The given builder is added
at the beginning of the list of the builders for the company ID.
@param companyId
Company ID. The value must be in the range from 0 to 0xFFFF.
@param builder
A builder. | [
"Register",
"a",
"builder",
"for",
"the",
"company",
"ID",
".",
"The",
"given",
"builder",
"is",
"added",
"at",
"the",
"beginning",
"of",
"the",
"list",
"of",
"the",
"builders",
"for",
"the",
"company",
"ID",
"."
] | train | https://github.com/TakahikoKawasaki/nv-bluetooth/blob/ef0099e941cd377571398615ea5e18cfc84cadd3/src/main/java/com/neovisionaries/bluetooth/ble/advertising/ADPayloadParser.java#L193-L221 |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/xjc/reader/TypeUtil.java | TypeUtil.getCommonBaseType | public static JType getCommonBaseType( JCodeModel codeModel, Collection<? extends JType> types ) {
"""
Computes the common base type of two types.
@param types
set of {@link JType} objects.
"""
return getCommonBaseType( codeModel, types.toArray(new JType[types.size()]) );
} | java | public static JType getCommonBaseType( JCodeModel codeModel, Collection<? extends JType> types ) {
return getCommonBaseType( codeModel, types.toArray(new JType[types.size()]) );
} | [
"public",
"static",
"JType",
"getCommonBaseType",
"(",
"JCodeModel",
"codeModel",
",",
"Collection",
"<",
"?",
"extends",
"JType",
">",
"types",
")",
"{",
"return",
"getCommonBaseType",
"(",
"codeModel",
",",
"types",
".",
"toArray",
"(",
"new",
"JType",
"[",
"types",
".",
"size",
"(",
")",
"]",
")",
")",
";",
"}"
] | Computes the common base type of two types.
@param types
set of {@link JType} objects. | [
"Computes",
"the",
"common",
"base",
"type",
"of",
"two",
"types",
"."
] | train | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/xjc/reader/TypeUtil.java#L51-L53 |
aalmiray/Json-lib | src/main/java/net/sf/json/JSONArray.java | JSONArray.element | public JSONArray element( Map value, JsonConfig jsonConfig ) {
"""
Put a value in the JSONArray, where the value will be a JSONObject which
is produced from a Map.
@param value A Map value.
@return this.
"""
if( value instanceof JSONObject ){
elements.add( value );
return this;
}else{
return element( JSONObject.fromObject( value, jsonConfig ) );
}
} | java | public JSONArray element( Map value, JsonConfig jsonConfig ) {
if( value instanceof JSONObject ){
elements.add( value );
return this;
}else{
return element( JSONObject.fromObject( value, jsonConfig ) );
}
} | [
"public",
"JSONArray",
"element",
"(",
"Map",
"value",
",",
"JsonConfig",
"jsonConfig",
")",
"{",
"if",
"(",
"value",
"instanceof",
"JSONObject",
")",
"{",
"elements",
".",
"add",
"(",
"value",
")",
";",
"return",
"this",
";",
"}",
"else",
"{",
"return",
"element",
"(",
"JSONObject",
".",
"fromObject",
"(",
"value",
",",
"jsonConfig",
")",
")",
";",
"}",
"}"
] | Put a value in the JSONArray, where the value will be a JSONObject which
is produced from a Map.
@param value A Map value.
@return this. | [
"Put",
"a",
"value",
"in",
"the",
"JSONArray",
"where",
"the",
"value",
"will",
"be",
"a",
"JSONObject",
"which",
"is",
"produced",
"from",
"a",
"Map",
"."
] | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONArray.java#L1534-L1541 |
cloudant/java-cloudant | cloudant-client/src/main/java/com/cloudant/client/internal/DatabaseURIHelper.java | DatabaseURIHelper.changesUri | public URI changesUri(String queryKey, Object queryValue) {
"""
Returns URI for {@code _changes} endpoint using passed
{@code query}.
"""
if(queryKey.equals("since")){
if(!(queryValue instanceof String)){
//json encode the seq number since it isn't a string
Gson gson = new Gson();
queryValue = gson.toJson(queryValue);
}
}
return this.path("_changes").query(queryKey, queryValue).build();
} | java | public URI changesUri(String queryKey, Object queryValue) {
if(queryKey.equals("since")){
if(!(queryValue instanceof String)){
//json encode the seq number since it isn't a string
Gson gson = new Gson();
queryValue = gson.toJson(queryValue);
}
}
return this.path("_changes").query(queryKey, queryValue).build();
} | [
"public",
"URI",
"changesUri",
"(",
"String",
"queryKey",
",",
"Object",
"queryValue",
")",
"{",
"if",
"(",
"queryKey",
".",
"equals",
"(",
"\"since\"",
")",
")",
"{",
"if",
"(",
"!",
"(",
"queryValue",
"instanceof",
"String",
")",
")",
"{",
"//json encode the seq number since it isn't a string",
"Gson",
"gson",
"=",
"new",
"Gson",
"(",
")",
";",
"queryValue",
"=",
"gson",
".",
"toJson",
"(",
"queryValue",
")",
";",
"}",
"}",
"return",
"this",
".",
"path",
"(",
"\"_changes\"",
")",
".",
"query",
"(",
"queryKey",
",",
"queryValue",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns URI for {@code _changes} endpoint using passed
{@code query}. | [
"Returns",
"URI",
"for",
"{"
] | train | https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/internal/DatabaseURIHelper.java#L91-L101 |
playn/playn | core/src/playn/core/json/JsonArray.java | JsonArray.getString | public String getString(int key, String default_) {
"""
Returns the {@link String} at the given index, or the default if it does not exist or is the wrong type.
"""
Object o = get(key);
return (o instanceof String) ? (String)o : default_;
} | java | public String getString(int key, String default_) {
Object o = get(key);
return (o instanceof String) ? (String)o : default_;
} | [
"public",
"String",
"getString",
"(",
"int",
"key",
",",
"String",
"default_",
")",
"{",
"Object",
"o",
"=",
"get",
"(",
"key",
")",
";",
"return",
"(",
"o",
"instanceof",
"String",
")",
"?",
"(",
"String",
")",
"o",
":",
"default_",
";",
"}"
] | Returns the {@link String} at the given index, or the default if it does not exist or is the wrong type. | [
"Returns",
"the",
"{"
] | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonArray.java#L194-L197 |
super-csv/super-csv | super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java | CsvBeanReader.instantiateBean | private static <T> T instantiateBean(final Class<T> clazz) {
"""
Instantiates the bean (or creates a proxy if it's an interface).
@param clazz
the bean class to instantiate (a proxy will be created if an interface is supplied), using the default
(no argument) constructor
@return the instantiated bean
@throws SuperCsvReflectionException
if there was a reflection exception when instantiating the bean
"""
final T bean;
if( clazz.isInterface() ) {
bean = BeanInterfaceProxy.createProxy(clazz);
} else {
try {
Constructor<T> c = clazz.getDeclaredConstructor(new Class[0]);
c.setAccessible(true);
bean = c.newInstance(new Object[0]);
}
catch(InstantiationException e) {
throw new SuperCsvReflectionException(String.format(
"error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e);
}
catch(NoSuchMethodException e) {
throw new SuperCsvReflectionException(String.format(
"error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e);
}
catch(IllegalAccessException e) {
throw new SuperCsvReflectionException("error instantiating bean", e);
}
catch(InvocationTargetException e) {
throw new SuperCsvReflectionException("error instantiating bean", e);
}
}
return bean;
} | java | private static <T> T instantiateBean(final Class<T> clazz) {
final T bean;
if( clazz.isInterface() ) {
bean = BeanInterfaceProxy.createProxy(clazz);
} else {
try {
Constructor<T> c = clazz.getDeclaredConstructor(new Class[0]);
c.setAccessible(true);
bean = c.newInstance(new Object[0]);
}
catch(InstantiationException e) {
throw new SuperCsvReflectionException(String.format(
"error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e);
}
catch(NoSuchMethodException e) {
throw new SuperCsvReflectionException(String.format(
"error instantiating bean, check that %s has a default no-args constructor", clazz.getName()), e);
}
catch(IllegalAccessException e) {
throw new SuperCsvReflectionException("error instantiating bean", e);
}
catch(InvocationTargetException e) {
throw new SuperCsvReflectionException("error instantiating bean", e);
}
}
return bean;
} | [
"private",
"static",
"<",
"T",
">",
"T",
"instantiateBean",
"(",
"final",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"final",
"T",
"bean",
";",
"if",
"(",
"clazz",
".",
"isInterface",
"(",
")",
")",
"{",
"bean",
"=",
"BeanInterfaceProxy",
".",
"createProxy",
"(",
"clazz",
")",
";",
"}",
"else",
"{",
"try",
"{",
"Constructor",
"<",
"T",
">",
"c",
"=",
"clazz",
".",
"getDeclaredConstructor",
"(",
"new",
"Class",
"[",
"0",
"]",
")",
";",
"c",
".",
"setAccessible",
"(",
"true",
")",
";",
"bean",
"=",
"c",
".",
"newInstance",
"(",
"new",
"Object",
"[",
"0",
"]",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"throw",
"new",
"SuperCsvReflectionException",
"(",
"String",
".",
"format",
"(",
"\"error instantiating bean, check that %s has a default no-args constructor\"",
",",
"clazz",
".",
"getName",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"SuperCsvReflectionException",
"(",
"String",
".",
"format",
"(",
"\"error instantiating bean, check that %s has a default no-args constructor\"",
",",
"clazz",
".",
"getName",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"SuperCsvReflectionException",
"(",
"\"error instantiating bean\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"SuperCsvReflectionException",
"(",
"\"error instantiating bean\"",
",",
"e",
")",
";",
"}",
"}",
"return",
"bean",
";",
"}"
] | Instantiates the bean (or creates a proxy if it's an interface).
@param clazz
the bean class to instantiate (a proxy will be created if an interface is supplied), using the default
(no argument) constructor
@return the instantiated bean
@throws SuperCsvReflectionException
if there was a reflection exception when instantiating the bean | [
"Instantiates",
"the",
"bean",
"(",
"or",
"creates",
"a",
"proxy",
"if",
"it",
"s",
"an",
"interface",
")",
"."
] | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/io/CsvBeanReader.java#L92-L119 |
phax/ph-oton | ph-oton-jscode/src/main/java/com/helger/html/jscode/JSRegExLiteral.java | JSRegExLiteral.gim | @Nonnull
public JSRegExLiteral gim (final boolean bGlobal, final boolean bCaseInsensitive, final boolean bMultiLine) {
"""
Set global, case insensitive and multi line at once
@param bGlobal
value for global
@param bCaseInsensitive
value for case insensitive
@param bMultiLine
value for multi line
@return this
"""
return global (bGlobal).caseInsensitive (bCaseInsensitive).multiLine (bMultiLine);
} | java | @Nonnull
public JSRegExLiteral gim (final boolean bGlobal, final boolean bCaseInsensitive, final boolean bMultiLine)
{
return global (bGlobal).caseInsensitive (bCaseInsensitive).multiLine (bMultiLine);
} | [
"@",
"Nonnull",
"public",
"JSRegExLiteral",
"gim",
"(",
"final",
"boolean",
"bGlobal",
",",
"final",
"boolean",
"bCaseInsensitive",
",",
"final",
"boolean",
"bMultiLine",
")",
"{",
"return",
"global",
"(",
"bGlobal",
")",
".",
"caseInsensitive",
"(",
"bCaseInsensitive",
")",
".",
"multiLine",
"(",
"bMultiLine",
")",
";",
"}"
] | Set global, case insensitive and multi line at once
@param bGlobal
value for global
@param bCaseInsensitive
value for case insensitive
@param bMultiLine
value for multi line
@return this | [
"Set",
"global",
"case",
"insensitive",
"and",
"multi",
"line",
"at",
"once"
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-jscode/src/main/java/com/helger/html/jscode/JSRegExLiteral.java#L93-L97 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/jdk8/Jdk8Methods.java | Jdk8Methods.safeMultiply | public static long safeMultiply(long a, int b) {
"""
Safely multiply a long by an int.
@param a the first value
@param b the second value
@return the new total
@throws ArithmeticException if the result overflows a long
"""
switch (b) {
case -1:
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("Multiplication overflows a long: " + a + " * " + b);
}
return -a;
case 0:
return 0L;
case 1:
return a;
}
long total = a * b;
if (total / b != a) {
throw new ArithmeticException("Multiplication overflows a long: " + a + " * " + b);
}
return total;
} | java | public static long safeMultiply(long a, int b) {
switch (b) {
case -1:
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("Multiplication overflows a long: " + a + " * " + b);
}
return -a;
case 0:
return 0L;
case 1:
return a;
}
long total = a * b;
if (total / b != a) {
throw new ArithmeticException("Multiplication overflows a long: " + a + " * " + b);
}
return total;
} | [
"public",
"static",
"long",
"safeMultiply",
"(",
"long",
"a",
",",
"int",
"b",
")",
"{",
"switch",
"(",
"b",
")",
"{",
"case",
"-",
"1",
":",
"if",
"(",
"a",
"==",
"Long",
".",
"MIN_VALUE",
")",
"{",
"throw",
"new",
"ArithmeticException",
"(",
"\"Multiplication overflows a long: \"",
"+",
"a",
"+",
"\" * \"",
"+",
"b",
")",
";",
"}",
"return",
"-",
"a",
";",
"case",
"0",
":",
"return",
"0L",
";",
"case",
"1",
":",
"return",
"a",
";",
"}",
"long",
"total",
"=",
"a",
"*",
"b",
";",
"if",
"(",
"total",
"/",
"b",
"!=",
"a",
")",
"{",
"throw",
"new",
"ArithmeticException",
"(",
"\"Multiplication overflows a long: \"",
"+",
"a",
"+",
"\" * \"",
"+",
"b",
")",
";",
"}",
"return",
"total",
";",
"}"
] | Safely multiply a long by an int.
@param a the first value
@param b the second value
@return the new total
@throws ArithmeticException if the result overflows a long | [
"Safely",
"multiply",
"a",
"long",
"by",
"an",
"int",
"."
] | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/jdk8/Jdk8Methods.java#L231-L248 |
jetty-project/jetty-npn | npn-boot/src/main/java/sun/security/ssl/Handshaker.java | Handshaker.sendChangeCipherSpec | void sendChangeCipherSpec(Finished mesg, boolean lastMessage)
throws IOException {
"""
/*
Sends a change cipher spec message and updates the write side
cipher state so that future messages use the just-negotiated spec.
"""
output.flush(); // i.e. handshake data
/*
* The write cipher state is protected by the connection write lock
* so we must grab it while making the change. We also
* make sure no writes occur between sending the ChangeCipherSpec
* message, installing the new cipher state, and sending the
* Finished message.
*
* We already hold SSLEngine/SSLSocket "this" by virtue
* of this being called from the readRecord code.
*/
OutputRecord r;
if (conn != null) {
r = new OutputRecord(Record.ct_change_cipher_spec);
} else {
r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine);
}
r.setVersion(protocolVersion);
r.write(1); // single byte of data
if (conn != null) {
conn.writeLock.lock();
try {
conn.writeRecord(r);
conn.changeWriteCiphers();
// NPN_CHANGES_BEGIN
sendNextProtocol(NextProtoNego.get(conn));
mesg = updateFinished(mesg);
// NPN_CHANGES_END
if (debug != null && Debug.isOn("handshake")) {
mesg.print(System.out);
}
mesg.write(output);
output.flush();
} finally {
conn.writeLock.unlock();
}
} else {
synchronized (engine.writeLock) {
engine.writeRecord((EngineOutputRecord)r);
engine.changeWriteCiphers();
// NPN_CHANGES_BEGIN
sendNextProtocol(NextProtoNego.get(engine));
mesg = updateFinished(mesg);
// NPN_CHANGES_END
if (debug != null && Debug.isOn("handshake")) {
mesg.print(System.out);
}
mesg.write(output);
if (lastMessage) {
output.setFinishedMsg();
}
output.flush();
}
}
} | java | void sendChangeCipherSpec(Finished mesg, boolean lastMessage)
throws IOException {
output.flush(); // i.e. handshake data
/*
* The write cipher state is protected by the connection write lock
* so we must grab it while making the change. We also
* make sure no writes occur between sending the ChangeCipherSpec
* message, installing the new cipher state, and sending the
* Finished message.
*
* We already hold SSLEngine/SSLSocket "this" by virtue
* of this being called from the readRecord code.
*/
OutputRecord r;
if (conn != null) {
r = new OutputRecord(Record.ct_change_cipher_spec);
} else {
r = new EngineOutputRecord(Record.ct_change_cipher_spec, engine);
}
r.setVersion(protocolVersion);
r.write(1); // single byte of data
if (conn != null) {
conn.writeLock.lock();
try {
conn.writeRecord(r);
conn.changeWriteCiphers();
// NPN_CHANGES_BEGIN
sendNextProtocol(NextProtoNego.get(conn));
mesg = updateFinished(mesg);
// NPN_CHANGES_END
if (debug != null && Debug.isOn("handshake")) {
mesg.print(System.out);
}
mesg.write(output);
output.flush();
} finally {
conn.writeLock.unlock();
}
} else {
synchronized (engine.writeLock) {
engine.writeRecord((EngineOutputRecord)r);
engine.changeWriteCiphers();
// NPN_CHANGES_BEGIN
sendNextProtocol(NextProtoNego.get(engine));
mesg = updateFinished(mesg);
// NPN_CHANGES_END
if (debug != null && Debug.isOn("handshake")) {
mesg.print(System.out);
}
mesg.write(output);
if (lastMessage) {
output.setFinishedMsg();
}
output.flush();
}
}
} | [
"void",
"sendChangeCipherSpec",
"(",
"Finished",
"mesg",
",",
"boolean",
"lastMessage",
")",
"throws",
"IOException",
"{",
"output",
".",
"flush",
"(",
")",
";",
"// i.e. handshake data",
"/*\n * The write cipher state is protected by the connection write lock\n * so we must grab it while making the change. We also\n * make sure no writes occur between sending the ChangeCipherSpec\n * message, installing the new cipher state, and sending the\n * Finished message.\n *\n * We already hold SSLEngine/SSLSocket \"this\" by virtue\n * of this being called from the readRecord code.\n */",
"OutputRecord",
"r",
";",
"if",
"(",
"conn",
"!=",
"null",
")",
"{",
"r",
"=",
"new",
"OutputRecord",
"(",
"Record",
".",
"ct_change_cipher_spec",
")",
";",
"}",
"else",
"{",
"r",
"=",
"new",
"EngineOutputRecord",
"(",
"Record",
".",
"ct_change_cipher_spec",
",",
"engine",
")",
";",
"}",
"r",
".",
"setVersion",
"(",
"protocolVersion",
")",
";",
"r",
".",
"write",
"(",
"1",
")",
";",
"// single byte of data",
"if",
"(",
"conn",
"!=",
"null",
")",
"{",
"conn",
".",
"writeLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"conn",
".",
"writeRecord",
"(",
"r",
")",
";",
"conn",
".",
"changeWriteCiphers",
"(",
")",
";",
"// NPN_CHANGES_BEGIN",
"sendNextProtocol",
"(",
"NextProtoNego",
".",
"get",
"(",
"conn",
")",
")",
";",
"mesg",
"=",
"updateFinished",
"(",
"mesg",
")",
";",
"// NPN_CHANGES_END",
"if",
"(",
"debug",
"!=",
"null",
"&&",
"Debug",
".",
"isOn",
"(",
"\"handshake\"",
")",
")",
"{",
"mesg",
".",
"print",
"(",
"System",
".",
"out",
")",
";",
"}",
"mesg",
".",
"write",
"(",
"output",
")",
";",
"output",
".",
"flush",
"(",
")",
";",
"}",
"finally",
"{",
"conn",
".",
"writeLock",
".",
"unlock",
"(",
")",
";",
"}",
"}",
"else",
"{",
"synchronized",
"(",
"engine",
".",
"writeLock",
")",
"{",
"engine",
".",
"writeRecord",
"(",
"(",
"EngineOutputRecord",
")",
"r",
")",
";",
"engine",
".",
"changeWriteCiphers",
"(",
")",
";",
"// NPN_CHANGES_BEGIN",
"sendNextProtocol",
"(",
"NextProtoNego",
".",
"get",
"(",
"engine",
")",
")",
";",
"mesg",
"=",
"updateFinished",
"(",
"mesg",
")",
";",
"// NPN_CHANGES_END",
"if",
"(",
"debug",
"!=",
"null",
"&&",
"Debug",
".",
"isOn",
"(",
"\"handshake\"",
")",
")",
"{",
"mesg",
".",
"print",
"(",
"System",
".",
"out",
")",
";",
"}",
"mesg",
".",
"write",
"(",
"output",
")",
";",
"if",
"(",
"lastMessage",
")",
"{",
"output",
".",
"setFinishedMsg",
"(",
")",
";",
"}",
"output",
".",
"flush",
"(",
")",
";",
"}",
"}",
"}"
] | /*
Sends a change cipher spec message and updates the write side
cipher state so that future messages use the just-negotiated spec. | [
"/",
"*",
"Sends",
"a",
"change",
"cipher",
"spec",
"message",
"and",
"updates",
"the",
"write",
"side",
"cipher",
"state",
"so",
"that",
"future",
"messages",
"use",
"the",
"just",
"-",
"negotiated",
"spec",
"."
] | train | https://github.com/jetty-project/jetty-npn/blob/a26a7a5eabeeb57a63c6ee08fcf9b8cec1fa6c0d/npn-boot/src/main/java/sun/security/ssl/Handshaker.java#L987-L1048 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java | LocalNetworkGatewaysInner.getByResourceGroupAsync | public Observable<LocalNetworkGatewayInner> getByResourceGroupAsync(String resourceGroupName, String localNetworkGatewayName) {
"""
Gets the specified local network gateway in a resource group.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LocalNetworkGatewayInner object
"""
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() {
@Override
public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) {
return response.body();
}
});
} | java | public Observable<LocalNetworkGatewayInner> getByResourceGroupAsync(String resourceGroupName, String localNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).map(new Func1<ServiceResponse<LocalNetworkGatewayInner>, LocalNetworkGatewayInner>() {
@Override
public LocalNetworkGatewayInner call(ServiceResponse<LocalNetworkGatewayInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"LocalNetworkGatewayInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"localNetworkGatewayName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"localNetworkGatewayName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"LocalNetworkGatewayInner",
">",
",",
"LocalNetworkGatewayInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"LocalNetworkGatewayInner",
"call",
"(",
"ServiceResponse",
"<",
"LocalNetworkGatewayInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the specified local network gateway in a resource group.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LocalNetworkGatewayInner object | [
"Gets",
"the",
"specified",
"local",
"network",
"gateway",
"in",
"a",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java#L310-L317 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.getInternalState | @SuppressWarnings("unchecked")
public static <T> T getInternalState(Object object, String fieldName, Class<?> where) {
"""
Get the value of a field using reflection. Use this method when you need
to specify in which class the field is declared. This might be useful
when you have mocked the instance you are trying to access. Use this
method to avoid casting.
@param <T> the expected type of the field
@param object the object to modify
@param fieldName the name of the field
@param where which class the field is defined
@return the internal state
"""
if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) {
throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null.");
}
Field field = null;
try {
field = where.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(object);
} catch (NoSuchFieldException e) {
throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName()
+ ".");
} catch (Exception e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
}
} | java | @SuppressWarnings("unchecked")
public static <T> T getInternalState(Object object, String fieldName, Class<?> where) {
if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) {
throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null.");
}
Field field = null;
try {
field = where.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(object);
} catch (NoSuchFieldException e) {
throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName()
+ ".");
} catch (Exception e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"getInternalState",
"(",
"Object",
"object",
",",
"String",
"fieldName",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"if",
"(",
"object",
"==",
"null",
"||",
"fieldName",
"==",
"null",
"||",
"fieldName",
".",
"equals",
"(",
"\"\"",
")",
"||",
"fieldName",
".",
"startsWith",
"(",
"\" \"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"object, field name, and \\\"where\\\" must not be empty or null.\"",
")",
";",
"}",
"Field",
"field",
"=",
"null",
";",
"try",
"{",
"field",
"=",
"where",
".",
"getDeclaredField",
"(",
"fieldName",
")",
";",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"(",
"T",
")",
"field",
".",
"get",
"(",
"object",
")",
";",
"}",
"catch",
"(",
"NoSuchFieldException",
"e",
")",
"{",
"throw",
"new",
"FieldNotFoundException",
"(",
"\"Field '\"",
"+",
"fieldName",
"+",
"\"' was not found in class \"",
"+",
"where",
".",
"getName",
"(",
")",
"+",
"\".\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Internal error: Failed to get field in method getInternalState.\"",
",",
"e",
")",
";",
"}",
"}"
] | Get the value of a field using reflection. Use this method when you need
to specify in which class the field is declared. This might be useful
when you have mocked the instance you are trying to access. Use this
method to avoid casting.
@param <T> the expected type of the field
@param object the object to modify
@param fieldName the name of the field
@param where which class the field is defined
@return the internal state | [
"Get",
"the",
"value",
"of",
"a",
"field",
"using",
"reflection",
".",
"Use",
"this",
"method",
"when",
"you",
"need",
"to",
"specify",
"in",
"which",
"class",
"the",
"field",
"is",
"declared",
".",
"This",
"might",
"be",
"useful",
"when",
"you",
"have",
"mocked",
"the",
"instance",
"you",
"are",
"trying",
"to",
"access",
".",
"Use",
"this",
"method",
"to",
"avoid",
"casting",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L612-L629 |
janus-project/guava.janusproject.io | guava/src/com/google/common/collect/Iterables.java | Iterables.concat | public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
"""
Combines four iterables into a single iterable. The returned iterable has
an iterator that traverses the elements in {@code a}, followed by the
elements in {@code b}, followed by the elements in {@code c}, followed by
the elements in {@code d}. The source iterators are not polled until
necessary.
<p>The returned iterable's iterator supports {@code remove()} when the
corresponding input iterator supports it.
"""
return concat(ImmutableList.of(a, b, c, d));
} | java | public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
return concat(ImmutableList.of(a, b, c, d));
} | [
"public",
"static",
"<",
"T",
">",
"Iterable",
"<",
"T",
">",
"concat",
"(",
"Iterable",
"<",
"?",
"extends",
"T",
">",
"a",
",",
"Iterable",
"<",
"?",
"extends",
"T",
">",
"b",
",",
"Iterable",
"<",
"?",
"extends",
"T",
">",
"c",
",",
"Iterable",
"<",
"?",
"extends",
"T",
">",
"d",
")",
"{",
"return",
"concat",
"(",
"ImmutableList",
".",
"of",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
")",
";",
"}"
] | Combines four iterables into a single iterable. The returned iterable has
an iterator that traverses the elements in {@code a}, followed by the
elements in {@code b}, followed by the elements in {@code c}, followed by
the elements in {@code d}. The source iterators are not polled until
necessary.
<p>The returned iterable's iterator supports {@code remove()} when the
corresponding input iterator supports it. | [
"Combines",
"four",
"iterables",
"into",
"a",
"single",
"iterable",
".",
"The",
"returned",
"iterable",
"has",
"an",
"iterator",
"that",
"traverses",
"the",
"elements",
"in",
"{",
"@code",
"a",
"}",
"followed",
"by",
"the",
"elements",
"in",
"{",
"@code",
"b",
"}",
"followed",
"by",
"the",
"elements",
"in",
"{",
"@code",
"c",
"}",
"followed",
"by",
"the",
"elements",
"in",
"{",
"@code",
"d",
"}",
".",
"The",
"source",
"iterators",
"are",
"not",
"polled",
"until",
"necessary",
"."
] | train | https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/collect/Iterables.java#L467-L471 |
hawkular/hawkular-agent | hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java | OshiPlatformCache.getFileStoreMetric | public Double getFileStoreMetric(String fileStoreNameName, ID metricToCollect) {
"""
Returns the given metric's value, or null if there is no file store with the given name.
@param fileStoreNameName name of file store
@param metricToCollect the metric to collect
@return the value of the metric, or null if there is no file store with the given name
"""
Map<String, OSFileStore> cache = getFileStores();
OSFileStore fileStore = cache.get(fileStoreNameName);
if (fileStore == null) {
return null;
}
if (PlatformMetricType.FILE_STORE_TOTAL_SPACE.getMetricTypeId().equals(metricToCollect)) {
return Double.valueOf(fileStore.getTotalSpace());
} else if (PlatformMetricType.FILE_STORE_USABLE_SPACE.getMetricTypeId().equals(metricToCollect)) {
return Double.valueOf(fileStore.getUsableSpace());
} else {
throw new UnsupportedOperationException("Invalid file store metric to collect: " + metricToCollect);
}
} | java | public Double getFileStoreMetric(String fileStoreNameName, ID metricToCollect) {
Map<String, OSFileStore> cache = getFileStores();
OSFileStore fileStore = cache.get(fileStoreNameName);
if (fileStore == null) {
return null;
}
if (PlatformMetricType.FILE_STORE_TOTAL_SPACE.getMetricTypeId().equals(metricToCollect)) {
return Double.valueOf(fileStore.getTotalSpace());
} else if (PlatformMetricType.FILE_STORE_USABLE_SPACE.getMetricTypeId().equals(metricToCollect)) {
return Double.valueOf(fileStore.getUsableSpace());
} else {
throw new UnsupportedOperationException("Invalid file store metric to collect: " + metricToCollect);
}
} | [
"public",
"Double",
"getFileStoreMetric",
"(",
"String",
"fileStoreNameName",
",",
"ID",
"metricToCollect",
")",
"{",
"Map",
"<",
"String",
",",
"OSFileStore",
">",
"cache",
"=",
"getFileStores",
"(",
")",
";",
"OSFileStore",
"fileStore",
"=",
"cache",
".",
"get",
"(",
"fileStoreNameName",
")",
";",
"if",
"(",
"fileStore",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"PlatformMetricType",
".",
"FILE_STORE_TOTAL_SPACE",
".",
"getMetricTypeId",
"(",
")",
".",
"equals",
"(",
"metricToCollect",
")",
")",
"{",
"return",
"Double",
".",
"valueOf",
"(",
"fileStore",
".",
"getTotalSpace",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"PlatformMetricType",
".",
"FILE_STORE_USABLE_SPACE",
".",
"getMetricTypeId",
"(",
")",
".",
"equals",
"(",
"metricToCollect",
")",
")",
"{",
"return",
"Double",
".",
"valueOf",
"(",
"fileStore",
".",
"getUsableSpace",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Invalid file store metric to collect: \"",
"+",
"metricToCollect",
")",
";",
"}",
"}"
] | Returns the given metric's value, or null if there is no file store with the given name.
@param fileStoreNameName name of file store
@param metricToCollect the metric to collect
@return the value of the metric, or null if there is no file store with the given name | [
"Returns",
"the",
"given",
"metric",
"s",
"value",
"or",
"null",
"if",
"there",
"is",
"no",
"file",
"store",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/protocol/platform/OshiPlatformCache.java#L309-L324 |
autermann/yaml | src/main/java/com/github/autermann/yaml/YamlNodeRepresenter.java | YamlNodeRepresenter.delegate | private MappingNode delegate(Tag tag,
Iterable<Entry<YamlNode, YamlNode>> mapping) {
"""
Create a {@link MappingNode} from the specified entries and tag.
@param tag the tag
@param mapping the entries
@return the mapping node
"""
List<NodeTuple> value = new LinkedList<>();
MappingNode node = new MappingNode(tag, value, null);
representedObjects.put(objectToRepresent, node);
boolean bestStyle = true;
for (Map.Entry<?, ?> entry : mapping) {
Node nodeKey = representData(entry.getKey());
Node nodeValue = representData(entry.getValue());
bestStyle = bestStyle(nodeKey, bestStyle);
bestStyle = bestStyle(nodeValue, bestStyle);
value.add(new NodeTuple(nodeKey, nodeValue));
}
if (getDefaultFlowStyle() != FlowStyle.AUTO) {
node.setFlowStyle(getDefaultFlowStyle().getStyleBoolean());
} else {
node.setFlowStyle(bestStyle);
}
return node;
} | java | private MappingNode delegate(Tag tag,
Iterable<Entry<YamlNode, YamlNode>> mapping) {
List<NodeTuple> value = new LinkedList<>();
MappingNode node = new MappingNode(tag, value, null);
representedObjects.put(objectToRepresent, node);
boolean bestStyle = true;
for (Map.Entry<?, ?> entry : mapping) {
Node nodeKey = representData(entry.getKey());
Node nodeValue = representData(entry.getValue());
bestStyle = bestStyle(nodeKey, bestStyle);
bestStyle = bestStyle(nodeValue, bestStyle);
value.add(new NodeTuple(nodeKey, nodeValue));
}
if (getDefaultFlowStyle() != FlowStyle.AUTO) {
node.setFlowStyle(getDefaultFlowStyle().getStyleBoolean());
} else {
node.setFlowStyle(bestStyle);
}
return node;
} | [
"private",
"MappingNode",
"delegate",
"(",
"Tag",
"tag",
",",
"Iterable",
"<",
"Entry",
"<",
"YamlNode",
",",
"YamlNode",
">",
">",
"mapping",
")",
"{",
"List",
"<",
"NodeTuple",
">",
"value",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"MappingNode",
"node",
"=",
"new",
"MappingNode",
"(",
"tag",
",",
"value",
",",
"null",
")",
";",
"representedObjects",
".",
"put",
"(",
"objectToRepresent",
",",
"node",
")",
";",
"boolean",
"bestStyle",
"=",
"true",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"?",
",",
"?",
">",
"entry",
":",
"mapping",
")",
"{",
"Node",
"nodeKey",
"=",
"representData",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"Node",
"nodeValue",
"=",
"representData",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"bestStyle",
"=",
"bestStyle",
"(",
"nodeKey",
",",
"bestStyle",
")",
";",
"bestStyle",
"=",
"bestStyle",
"(",
"nodeValue",
",",
"bestStyle",
")",
";",
"value",
".",
"add",
"(",
"new",
"NodeTuple",
"(",
"nodeKey",
",",
"nodeValue",
")",
")",
";",
"}",
"if",
"(",
"getDefaultFlowStyle",
"(",
")",
"!=",
"FlowStyle",
".",
"AUTO",
")",
"{",
"node",
".",
"setFlowStyle",
"(",
"getDefaultFlowStyle",
"(",
")",
".",
"getStyleBoolean",
"(",
")",
")",
";",
"}",
"else",
"{",
"node",
".",
"setFlowStyle",
"(",
"bestStyle",
")",
";",
"}",
"return",
"node",
";",
"}"
] | Create a {@link MappingNode} from the specified entries and tag.
@param tag the tag
@param mapping the entries
@return the mapping node | [
"Create",
"a",
"{",
"@link",
"MappingNode",
"}",
"from",
"the",
"specified",
"entries",
"and",
"tag",
"."
] | train | https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/YamlNodeRepresenter.java#L162-L182 |
henkexbg/gallery-api | src/main/java/com/github/henkexbg/gallery/service/impl/GalleryServiceImpl.java | GalleryServiceImpl.getPublicPathFromRealFile | @Override
public String getPublicPathFromRealFile(String publicRoot, File file) throws IOException, NotAllowedException {
"""
A kind of inverse lookup - finding the public path given the actual file.
<strong>NOTE! This method does NOT verify that the current user actually
has the right to access the given publicRoot! It is the responsibility of
calling methods to make sure only allowed root paths are used.</strong>
@param publicRoot
@param file
@return The public path of the given file for the given publicRoot.
@throws IOException
@throws NotAllowedException
"""
String actualFilePath = file.getCanonicalPath();
File rootFile = galleryAuthorizationService.getRootPathsForCurrentUser().get(publicRoot);
String relativePath = actualFilePath.substring(rootFile.getCanonicalPath().length(), actualFilePath.length());
StringBuilder builder = new StringBuilder();
builder.append(publicRoot);
builder.append(relativePath);
String publicPath = separatorsToUnix(builder.toString());
LOG.debug("Actual file: {}, generated public path: {}", file, publicPath);
return publicPath;
} | java | @Override
public String getPublicPathFromRealFile(String publicRoot, File file) throws IOException, NotAllowedException {
String actualFilePath = file.getCanonicalPath();
File rootFile = galleryAuthorizationService.getRootPathsForCurrentUser().get(publicRoot);
String relativePath = actualFilePath.substring(rootFile.getCanonicalPath().length(), actualFilePath.length());
StringBuilder builder = new StringBuilder();
builder.append(publicRoot);
builder.append(relativePath);
String publicPath = separatorsToUnix(builder.toString());
LOG.debug("Actual file: {}, generated public path: {}", file, publicPath);
return publicPath;
} | [
"@",
"Override",
"public",
"String",
"getPublicPathFromRealFile",
"(",
"String",
"publicRoot",
",",
"File",
"file",
")",
"throws",
"IOException",
",",
"NotAllowedException",
"{",
"String",
"actualFilePath",
"=",
"file",
".",
"getCanonicalPath",
"(",
")",
";",
"File",
"rootFile",
"=",
"galleryAuthorizationService",
".",
"getRootPathsForCurrentUser",
"(",
")",
".",
"get",
"(",
"publicRoot",
")",
";",
"String",
"relativePath",
"=",
"actualFilePath",
".",
"substring",
"(",
"rootFile",
".",
"getCanonicalPath",
"(",
")",
".",
"length",
"(",
")",
",",
"actualFilePath",
".",
"length",
"(",
")",
")",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"publicRoot",
")",
";",
"builder",
".",
"append",
"(",
"relativePath",
")",
";",
"String",
"publicPath",
"=",
"separatorsToUnix",
"(",
"builder",
".",
"toString",
"(",
")",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Actual file: {}, generated public path: {}\"",
",",
"file",
",",
"publicPath",
")",
";",
"return",
"publicPath",
";",
"}"
] | A kind of inverse lookup - finding the public path given the actual file.
<strong>NOTE! This method does NOT verify that the current user actually
has the right to access the given publicRoot! It is the responsibility of
calling methods to make sure only allowed root paths are used.</strong>
@param publicRoot
@param file
@return The public path of the given file for the given publicRoot.
@throws IOException
@throws NotAllowedException | [
"A",
"kind",
"of",
"inverse",
"lookup",
"-",
"finding",
"the",
"public",
"path",
"given",
"the",
"actual",
"file",
".",
"<strong",
">",
"NOTE!",
"This",
"method",
"does",
"NOT",
"verify",
"that",
"the",
"current",
"user",
"actually",
"has",
"the",
"right",
"to",
"access",
"the",
"given",
"publicRoot!",
"It",
"is",
"the",
"responsibility",
"of",
"calling",
"methods",
"to",
"make",
"sure",
"only",
"allowed",
"root",
"paths",
"are",
"used",
".",
"<",
"/",
"strong",
">"
] | train | https://github.com/henkexbg/gallery-api/blob/530e68c225b5e8fc3b608d670b34bd539a5b0a71/src/main/java/com/github/henkexbg/gallery/service/impl/GalleryServiceImpl.java#L321-L332 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.createMessageReceiverFromEntityPath | public static IMessageReceiver createMessageReceiverFromEntityPath(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) throws InterruptedException, ServiceBusException {
"""
Creates a message receiver to the entity using the client settings in PeekLock mode
@param namespaceEndpointURI endpoint uri of entity namespace
@param entityPath path of the entity
@param clientSettings client settings
@return IMessageReceiver instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the receiver cannot be created
"""
return Utils.completeFuture(createMessageReceiverFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings));
} | java | public static IMessageReceiver createMessageReceiverFromEntityPath(URI namespaceEndpointURI, String entityPath, ClientSettings clientSettings) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(createMessageReceiverFromEntityPathAsync(namespaceEndpointURI, entityPath, clientSettings));
} | [
"public",
"static",
"IMessageReceiver",
"createMessageReceiverFromEntityPath",
"(",
"URI",
"namespaceEndpointURI",
",",
"String",
"entityPath",
",",
"ClientSettings",
"clientSettings",
")",
"throws",
"InterruptedException",
",",
"ServiceBusException",
"{",
"return",
"Utils",
".",
"completeFuture",
"(",
"createMessageReceiverFromEntityPathAsync",
"(",
"namespaceEndpointURI",
",",
"entityPath",
",",
"clientSettings",
")",
")",
";",
"}"
] | Creates a message receiver to the entity using the client settings in PeekLock mode
@param namespaceEndpointURI endpoint uri of entity namespace
@param entityPath path of the entity
@param clientSettings client settings
@return IMessageReceiver instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the receiver cannot be created | [
"Creates",
"a",
"message",
"receiver",
"to",
"the",
"entity",
"using",
"the",
"client",
"settings",
"in",
"PeekLock",
"mode"
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L308-L310 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java | CommercePriceEntryPersistenceImpl.findByGroupId | @Override
public List<CommercePriceEntry> findByGroupId(long groupId, int start,
int end) {
"""
Returns a range of all the commerce price entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommercePriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce price entries
@param end the upper bound of the range of commerce price entries (not inclusive)
@return the range of matching commerce price entries
"""
return findByGroupId(groupId, start, end, null);
} | java | @Override
public List<CommercePriceEntry> findByGroupId(long groupId, int start,
int end) {
return findByGroupId(groupId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommercePriceEntry",
">",
"findByGroupId",
"(",
"long",
"groupId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByGroupId",
"(",
"groupId",
",",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce price entries where groupId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommercePriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param groupId the group ID
@param start the lower bound of the range of commerce price entries
@param end the upper bound of the range of commerce price entries (not inclusive)
@return the range of matching commerce price entries | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"price",
"entries",
"where",
"groupId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommercePriceEntryPersistenceImpl.java#L1535-L1539 |
aws/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetDeploymentResult.java | GetDeploymentResult.setApiSummary | public void setApiSummary(java.util.Map<String, java.util.Map<String, MethodSnapshot>> apiSummary) {
"""
<p>
A summary of the <a>RestApi</a> at the date and time that the deployment resource was created.
</p>
@param apiSummary
A summary of the <a>RestApi</a> at the date and time that the deployment resource was created.
"""
this.apiSummary = apiSummary;
} | java | public void setApiSummary(java.util.Map<String, java.util.Map<String, MethodSnapshot>> apiSummary) {
this.apiSummary = apiSummary;
} | [
"public",
"void",
"setApiSummary",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"MethodSnapshot",
">",
">",
"apiSummary",
")",
"{",
"this",
".",
"apiSummary",
"=",
"apiSummary",
";",
"}"
] | <p>
A summary of the <a>RestApi</a> at the date and time that the deployment resource was created.
</p>
@param apiSummary
A summary of the <a>RestApi</a> at the date and time that the deployment resource was created. | [
"<p",
">",
"A",
"summary",
"of",
"the",
"<a",
">",
"RestApi<",
"/",
"a",
">",
"at",
"the",
"date",
"and",
"time",
"that",
"the",
"deployment",
"resource",
"was",
"created",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetDeploymentResult.java#L200-L202 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java | NetworkWatchersInner.beginGetNextHop | public NextHopResultInner beginGetNextHop(String resourceGroupName, String networkWatcherName, NextHopParameters parameters) {
"""
Gets the next hop from the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param parameters Parameters that define the source and destination endpoint.
@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 NextHopResultInner object if successful.
"""
return beginGetNextHopWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().single().body();
} | java | public NextHopResultInner beginGetNextHop(String resourceGroupName, String networkWatcherName, NextHopParameters parameters) {
return beginGetNextHopWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().single().body();
} | [
"public",
"NextHopResultInner",
"beginGetNextHop",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkWatcherName",
",",
"NextHopParameters",
"parameters",
")",
"{",
"return",
"beginGetNextHopWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkWatcherName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Gets the next hop from the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param parameters Parameters that define the source and destination endpoint.
@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 NextHopResultInner object if successful. | [
"Gets",
"the",
"next",
"hop",
"from",
"the",
"specified",
"VM",
"."
] | 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/NetworkWatchersInner.java#L1201-L1203 |
belaban/JGroups | src/org/jgroups/auth/Krb5TokenUtils.java | Krb5TokenUtils.validateSecurityContext | public static String validateSecurityContext(Subject subject, final byte[] serviceTicket) throws GSSException {
"""
Validate the service ticket by extracting the client principal name
"""
// Accept the context and return the client principal name.
return Subject.doAs(subject, (PrivilegedAction<String>)() -> {
try {
// Identify the server that communications are being made
// to.
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
return context.getSrcName().toString();
} catch (Exception e) {
log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
return null;
}
});
} | java | public static String validateSecurityContext(Subject subject, final byte[] serviceTicket) throws GSSException {
// Accept the context and return the client principal name.
return Subject.doAs(subject, (PrivilegedAction<String>)() -> {
try {
// Identify the server that communications are being made
// to.
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
return context.getSrcName().toString();
} catch (Exception e) {
log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
return null;
}
});
} | [
"public",
"static",
"String",
"validateSecurityContext",
"(",
"Subject",
"subject",
",",
"final",
"byte",
"[",
"]",
"serviceTicket",
")",
"throws",
"GSSException",
"{",
"// Accept the context and return the client principal name.",
"return",
"Subject",
".",
"doAs",
"(",
"subject",
",",
"(",
"PrivilegedAction",
"<",
"String",
">",
")",
"(",
")",
"->",
"{",
"try",
"{",
"// Identify the server that communications are being made",
"// to.",
"GSSManager",
"manager",
"=",
"GSSManager",
".",
"getInstance",
"(",
")",
";",
"GSSContext",
"context",
"=",
"manager",
".",
"createContext",
"(",
"(",
"GSSCredential",
")",
"null",
")",
";",
"context",
".",
"acceptSecContext",
"(",
"serviceTicket",
",",
"0",
",",
"serviceTicket",
".",
"length",
")",
";",
"return",
"context",
".",
"getSrcName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"Util",
".",
"getMessage",
"(",
"\"Krb5TokenKerberosContextProcessingException\"",
")",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"}"
] | Validate the service ticket by extracting the client principal name | [
"Validate",
"the",
"service",
"ticket",
"by",
"extracting",
"the",
"client",
"principal",
"name"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/auth/Krb5TokenUtils.java#L87-L103 |
io7m/jaffirm | com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Postconditions.java | Postconditions.checkPostconditionsL | public static long checkPostconditionsL(
final long value,
final ContractLongConditionType... conditions)
throws PostconditionViolationException {
"""
A {@code long} specialized version of {@link #checkPostconditions(Object,
ContractConditionType[])}
@param value The value
@param conditions The conditions the value must obey
@return value
@throws PostconditionViolationException If any of the conditions are false
"""
final Violations violations = innerCheckAllLong(value, conditions);
if (violations != null) {
throw failed(null, Long.valueOf(value), violations);
}
return value;
} | java | public static long checkPostconditionsL(
final long value,
final ContractLongConditionType... conditions)
throws PostconditionViolationException
{
final Violations violations = innerCheckAllLong(value, conditions);
if (violations != null) {
throw failed(null, Long.valueOf(value), violations);
}
return value;
} | [
"public",
"static",
"long",
"checkPostconditionsL",
"(",
"final",
"long",
"value",
",",
"final",
"ContractLongConditionType",
"...",
"conditions",
")",
"throws",
"PostconditionViolationException",
"{",
"final",
"Violations",
"violations",
"=",
"innerCheckAllLong",
"(",
"value",
",",
"conditions",
")",
";",
"if",
"(",
"violations",
"!=",
"null",
")",
"{",
"throw",
"failed",
"(",
"null",
",",
"Long",
".",
"valueOf",
"(",
"value",
")",
",",
"violations",
")",
";",
"}",
"return",
"value",
";",
"}"
] | A {@code long} specialized version of {@link #checkPostconditions(Object,
ContractConditionType[])}
@param value The value
@param conditions The conditions the value must obey
@return value
@throws PostconditionViolationException If any of the conditions are false | [
"A",
"{",
"@code",
"long",
"}",
"specialized",
"version",
"of",
"{",
"@link",
"#checkPostconditions",
"(",
"Object",
"ContractConditionType",
"[]",
")",
"}"
] | train | https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Postconditions.java#L122-L132 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.groupingBy | public <K, D> Map<K, D> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, ?, D> downstream) {
"""
Returns a {@code Map} whose keys are the values resulting from applying
the classification function to the input elements, and whose
corresponding values are the result of reduction of the input elements
which map to the associated key under the classification function.
<p>
There are no guarantees on the type, mutability or serializability of the
{@code Map} objects returned.
<p>
This is a <a href="package-summary.html#StreamOps">terminal</a>
operation.
@param <K> the type of the keys
@param <D> the result type of the downstream reduction
@param classifier the classifier function mapping input elements to keys
@param downstream a {@code Collector} implementing the downstream
reduction
@return a {@code Map} containing the results of the group-by operation
@see #groupingBy(Function)
@see Collectors#groupingBy(Function, Collector)
@see Collectors#groupingByConcurrent(Function, Collector)
"""
if (isParallel() && downstream.characteristics().contains(Characteristics.UNORDERED))
return rawCollect(Collectors.groupingByConcurrent(classifier, downstream));
return rawCollect(Collectors.groupingBy(classifier, downstream));
} | java | public <K, D> Map<K, D> groupingBy(Function<? super T, ? extends K> classifier,
Collector<? super T, ?, D> downstream) {
if (isParallel() && downstream.characteristics().contains(Characteristics.UNORDERED))
return rawCollect(Collectors.groupingByConcurrent(classifier, downstream));
return rawCollect(Collectors.groupingBy(classifier, downstream));
} | [
"public",
"<",
"K",
",",
"D",
">",
"Map",
"<",
"K",
",",
"D",
">",
"groupingBy",
"(",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"K",
">",
"classifier",
",",
"Collector",
"<",
"?",
"super",
"T",
",",
"?",
",",
"D",
">",
"downstream",
")",
"{",
"if",
"(",
"isParallel",
"(",
")",
"&&",
"downstream",
".",
"characteristics",
"(",
")",
".",
"contains",
"(",
"Characteristics",
".",
"UNORDERED",
")",
")",
"return",
"rawCollect",
"(",
"Collectors",
".",
"groupingByConcurrent",
"(",
"classifier",
",",
"downstream",
")",
")",
";",
"return",
"rawCollect",
"(",
"Collectors",
".",
"groupingBy",
"(",
"classifier",
",",
"downstream",
")",
")",
";",
"}"
] | Returns a {@code Map} whose keys are the values resulting from applying
the classification function to the input elements, and whose
corresponding values are the result of reduction of the input elements
which map to the associated key under the classification function.
<p>
There are no guarantees on the type, mutability or serializability of the
{@code Map} objects returned.
<p>
This is a <a href="package-summary.html#StreamOps">terminal</a>
operation.
@param <K> the type of the keys
@param <D> the result type of the downstream reduction
@param classifier the classifier function mapping input elements to keys
@param downstream a {@code Collector} implementing the downstream
reduction
@return a {@code Map} containing the results of the group-by operation
@see #groupingBy(Function)
@see Collectors#groupingBy(Function, Collector)
@see Collectors#groupingByConcurrent(Function, Collector) | [
"Returns",
"a",
"{",
"@code",
"Map",
"}",
"whose",
"keys",
"are",
"the",
"values",
"resulting",
"from",
"applying",
"the",
"classification",
"function",
"to",
"the",
"input",
"elements",
"and",
"whose",
"corresponding",
"values",
"are",
"the",
"result",
"of",
"reduction",
"of",
"the",
"input",
"elements",
"which",
"map",
"to",
"the",
"associated",
"key",
"under",
"the",
"classification",
"function",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L532-L537 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java | PackageSummaryBuilder.buildPackageTags | public void buildPackageTags(XMLNode node, Content packageContentTree) {
"""
Build the tags of the summary.
@param node the XML element that specifies which components to document
@param packageContentTree the tree to which the package tags will be added
"""
if (configuration.nocomment) {
return;
}
packageWriter.addPackageTags(packageContentTree);
} | java | public void buildPackageTags(XMLNode node, Content packageContentTree) {
if (configuration.nocomment) {
return;
}
packageWriter.addPackageTags(packageContentTree);
} | [
"public",
"void",
"buildPackageTags",
"(",
"XMLNode",
"node",
",",
"Content",
"packageContentTree",
")",
"{",
"if",
"(",
"configuration",
".",
"nocomment",
")",
"{",
"return",
";",
"}",
"packageWriter",
".",
"addPackageTags",
"(",
"packageContentTree",
")",
";",
"}"
] | Build the tags of the summary.
@param node the XML element that specifies which components to document
@param packageContentTree the tree to which the package tags will be added | [
"Build",
"the",
"tags",
"of",
"the",
"summary",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java#L347-L352 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/preview/ui/A_CmsPreviewDialog.java | A_CmsPreviewDialog.confirmSaveChanges | public void confirmSaveChanges(String message, final Command onConfirm, final Command onCancel) {
"""
Displays a confirm save changes dialog with the given message.
May insert individual message before the given one for further information.<p>
Will call the appropriate command after saving/cancel.<p>
@param message the message to display
@param onConfirm the command executed after saving
@param onCancel the command executed on cancel
"""
CmsConfirmDialog confirmDialog = new CmsConfirmDialog("Confirm", message);
confirmDialog.setHandler(new I_CmsConfirmDialogHandler() {
/**
* @see org.opencms.gwt.client.ui.I_CmsCloseDialogHandler#onClose()
*/
public void onClose() {
if (onCancel != null) {
onCancel.execute();
}
}
/**
* @see org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler#onOk()
*/
public void onOk() {
if (onConfirm != null) {
onConfirm.execute();
}
}
});
confirmDialog.center();
} | java | public void confirmSaveChanges(String message, final Command onConfirm, final Command onCancel) {
CmsConfirmDialog confirmDialog = new CmsConfirmDialog("Confirm", message);
confirmDialog.setHandler(new I_CmsConfirmDialogHandler() {
/**
* @see org.opencms.gwt.client.ui.I_CmsCloseDialogHandler#onClose()
*/
public void onClose() {
if (onCancel != null) {
onCancel.execute();
}
}
/**
* @see org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler#onOk()
*/
public void onOk() {
if (onConfirm != null) {
onConfirm.execute();
}
}
});
confirmDialog.center();
} | [
"public",
"void",
"confirmSaveChanges",
"(",
"String",
"message",
",",
"final",
"Command",
"onConfirm",
",",
"final",
"Command",
"onCancel",
")",
"{",
"CmsConfirmDialog",
"confirmDialog",
"=",
"new",
"CmsConfirmDialog",
"(",
"\"Confirm\"",
",",
"message",
")",
";",
"confirmDialog",
".",
"setHandler",
"(",
"new",
"I_CmsConfirmDialogHandler",
"(",
")",
"{",
"/**\n * @see org.opencms.gwt.client.ui.I_CmsCloseDialogHandler#onClose()\n */",
"public",
"void",
"onClose",
"(",
")",
"{",
"if",
"(",
"onCancel",
"!=",
"null",
")",
"{",
"onCancel",
".",
"execute",
"(",
")",
";",
"}",
"}",
"/**\n * @see org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler#onOk()\n */",
"public",
"void",
"onOk",
"(",
")",
"{",
"if",
"(",
"onConfirm",
"!=",
"null",
")",
"{",
"onConfirm",
".",
"execute",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"confirmDialog",
".",
"center",
"(",
")",
";",
"}"
] | Displays a confirm save changes dialog with the given message.
May insert individual message before the given one for further information.<p>
Will call the appropriate command after saving/cancel.<p>
@param message the message to display
@param onConfirm the command executed after saving
@param onCancel the command executed on cancel | [
"Displays",
"a",
"confirm",
"save",
"changes",
"dialog",
"with",
"the",
"given",
"message",
".",
"May",
"insert",
"individual",
"message",
"before",
"the",
"given",
"one",
"for",
"further",
"information",
".",
"<p",
">",
"Will",
"call",
"the",
"appropriate",
"command",
"after",
"saving",
"/",
"cancel",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/preview/ui/A_CmsPreviewDialog.java#L181-L207 |
square/spoon | spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java | HtmlUtils.processStackTrace | static ExceptionInfo processStackTrace(StackTrace exception) {
"""
Parse the string representation of an exception to a {@link ExceptionInfo} instance.
"""
if (exception == null) {
return null;
}
// Escape any special HTML characters in the exception that would otherwise break the HTML
// rendering (e.g. the angle brackets around the default toString() for enums).
String message = StringEscapeUtils.escapeHtml4(exception.toString());
// Newline characters are usually stripped out by the parsing code in
// {@link StackTrace#from(String)}, but they can sometimes remain (e.g. when the stack trace
// is not in an expected format). This replacement needs to be done after any HTML escaping.
message = message.replace("\n", "<br/>");
List<String> lines = exception.getElements()
.stream()
.map(element -> " at " + element.toString())
.collect(toList());
while (exception.getCause() != null) {
exception = exception.getCause();
String causeMessage = StringEscapeUtils.escapeHtml4(exception.toString());
lines.add("Caused by: " + causeMessage.replace("\n", "<br/>"));
}
return new ExceptionInfo(message, lines);
} | java | static ExceptionInfo processStackTrace(StackTrace exception) {
if (exception == null) {
return null;
}
// Escape any special HTML characters in the exception that would otherwise break the HTML
// rendering (e.g. the angle brackets around the default toString() for enums).
String message = StringEscapeUtils.escapeHtml4(exception.toString());
// Newline characters are usually stripped out by the parsing code in
// {@link StackTrace#from(String)}, but they can sometimes remain (e.g. when the stack trace
// is not in an expected format). This replacement needs to be done after any HTML escaping.
message = message.replace("\n", "<br/>");
List<String> lines = exception.getElements()
.stream()
.map(element -> " at " + element.toString())
.collect(toList());
while (exception.getCause() != null) {
exception = exception.getCause();
String causeMessage = StringEscapeUtils.escapeHtml4(exception.toString());
lines.add("Caused by: " + causeMessage.replace("\n", "<br/>"));
}
return new ExceptionInfo(message, lines);
} | [
"static",
"ExceptionInfo",
"processStackTrace",
"(",
"StackTrace",
"exception",
")",
"{",
"if",
"(",
"exception",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// Escape any special HTML characters in the exception that would otherwise break the HTML",
"// rendering (e.g. the angle brackets around the default toString() for enums).",
"String",
"message",
"=",
"StringEscapeUtils",
".",
"escapeHtml4",
"(",
"exception",
".",
"toString",
"(",
")",
")",
";",
"// Newline characters are usually stripped out by the parsing code in",
"// {@link StackTrace#from(String)}, but they can sometimes remain (e.g. when the stack trace",
"// is not in an expected format). This replacement needs to be done after any HTML escaping.",
"message",
"=",
"message",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"<br/>\"",
")",
";",
"List",
"<",
"String",
">",
"lines",
"=",
"exception",
".",
"getElements",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"element",
"->",
"\" at \"",
"+",
"element",
".",
"toString",
"(",
")",
")",
".",
"collect",
"(",
"toList",
"(",
")",
")",
";",
"while",
"(",
"exception",
".",
"getCause",
"(",
")",
"!=",
"null",
")",
"{",
"exception",
"=",
"exception",
".",
"getCause",
"(",
")",
";",
"String",
"causeMessage",
"=",
"StringEscapeUtils",
".",
"escapeHtml4",
"(",
"exception",
".",
"toString",
"(",
")",
")",
";",
"lines",
".",
"add",
"(",
"\"Caused by: \"",
"+",
"causeMessage",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"<br/>\"",
")",
")",
";",
"}",
"return",
"new",
"ExceptionInfo",
"(",
"message",
",",
"lines",
")",
";",
"}"
] | Parse the string representation of an exception to a {@link ExceptionInfo} instance. | [
"Parse",
"the",
"string",
"representation",
"of",
"an",
"exception",
"to",
"a",
"{"
] | train | https://github.com/square/spoon/blob/ebd51fbc1498f6bdcb61aa1281bbac2af99117b3/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java#L135-L158 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java | SignatureUtils.similarPackages | public static boolean similarPackages(String packName1, String packName2, int depth) {
"""
returns whether or not the two packages have the same first 'depth' parts, if they exist
@param packName1
the first package to check
@param packName2
the second package to check
@param depth
the number of package parts to check
@return if they are similar
"""
if (depth == 0) {
return true;
}
String dottedPackName1 = packName1.replace('/', '.');
String dottedPackName2 = packName2.replace('/', '.');
int dot1 = dottedPackName1.indexOf('.');
int dot2 = dottedPackName2.indexOf('.');
if (dot1 < 0) {
return (dot2 < 0);
} else if (dot2 < 0) {
return false;
}
String s1 = dottedPackName1.substring(0, dot1);
String s2 = dottedPackName2.substring(0, dot2);
if (!s1.equals(s2)) {
return false;
}
return similarPackages(dottedPackName1.substring(dot1 + 1), dottedPackName2.substring(dot2 + 1), depth - 1);
} | java | public static boolean similarPackages(String packName1, String packName2, int depth) {
if (depth == 0) {
return true;
}
String dottedPackName1 = packName1.replace('/', '.');
String dottedPackName2 = packName2.replace('/', '.');
int dot1 = dottedPackName1.indexOf('.');
int dot2 = dottedPackName2.indexOf('.');
if (dot1 < 0) {
return (dot2 < 0);
} else if (dot2 < 0) {
return false;
}
String s1 = dottedPackName1.substring(0, dot1);
String s2 = dottedPackName2.substring(0, dot2);
if (!s1.equals(s2)) {
return false;
}
return similarPackages(dottedPackName1.substring(dot1 + 1), dottedPackName2.substring(dot2 + 1), depth - 1);
} | [
"public",
"static",
"boolean",
"similarPackages",
"(",
"String",
"packName1",
",",
"String",
"packName2",
",",
"int",
"depth",
")",
"{",
"if",
"(",
"depth",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"String",
"dottedPackName1",
"=",
"packName1",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"String",
"dottedPackName2",
"=",
"packName2",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"int",
"dot1",
"=",
"dottedPackName1",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"int",
"dot2",
"=",
"dottedPackName2",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"dot1",
"<",
"0",
")",
"{",
"return",
"(",
"dot2",
"<",
"0",
")",
";",
"}",
"else",
"if",
"(",
"dot2",
"<",
"0",
")",
"{",
"return",
"false",
";",
"}",
"String",
"s1",
"=",
"dottedPackName1",
".",
"substring",
"(",
"0",
",",
"dot1",
")",
";",
"String",
"s2",
"=",
"dottedPackName2",
".",
"substring",
"(",
"0",
",",
"dot2",
")",
";",
"if",
"(",
"!",
"s1",
".",
"equals",
"(",
"s2",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"similarPackages",
"(",
"dottedPackName1",
".",
"substring",
"(",
"dot1",
"+",
"1",
")",
",",
"dottedPackName2",
".",
"substring",
"(",
"dot2",
"+",
"1",
")",
",",
"depth",
"-",
"1",
")",
";",
"}"
] | returns whether or not the two packages have the same first 'depth' parts, if they exist
@param packName1
the first package to check
@param packName2
the second package to check
@param depth
the number of package parts to check
@return if they are similar | [
"returns",
"whether",
"or",
"not",
"the",
"two",
"packages",
"have",
"the",
"same",
"first",
"depth",
"parts",
"if",
"they",
"exist"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/utils/SignatureUtils.java#L117-L141 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.opentracing.1.3/src/com/ibm/ws/microprofile/opentracing/OpenTracingService.java | OpenTracingService.isNotTraced | public static boolean isNotTraced(String classOperationName, String methodOperationName) {
"""
Return true if {@code methodOperationName} is not null (i.e. it represents
something that has the {@code Traced} annotation) and if the
{@code Traced} annotation was explicitly set to {@code false}, or return
true if {@code classOperationName} is not null (i.e. it represents
something that has the {@code Traced} annotation) and the
{@code Traced} annotation was explicitly set to {@code false},
and the {@code methodOperationName} is not explicitly set to {@code true}.
@param classOperationName The class operation name
@param methodOperationName The method operation name
@return See above
"""
return OPERATION_NAME_UNTRACED.equals(methodOperationName) || (OPERATION_NAME_UNTRACED.equals(classOperationName) && !isTraced(methodOperationName));
} | java | public static boolean isNotTraced(String classOperationName, String methodOperationName) {
return OPERATION_NAME_UNTRACED.equals(methodOperationName) || (OPERATION_NAME_UNTRACED.equals(classOperationName) && !isTraced(methodOperationName));
} | [
"public",
"static",
"boolean",
"isNotTraced",
"(",
"String",
"classOperationName",
",",
"String",
"methodOperationName",
")",
"{",
"return",
"OPERATION_NAME_UNTRACED",
".",
"equals",
"(",
"methodOperationName",
")",
"||",
"(",
"OPERATION_NAME_UNTRACED",
".",
"equals",
"(",
"classOperationName",
")",
"&&",
"!",
"isTraced",
"(",
"methodOperationName",
")",
")",
";",
"}"
] | Return true if {@code methodOperationName} is not null (i.e. it represents
something that has the {@code Traced} annotation) and if the
{@code Traced} annotation was explicitly set to {@code false}, or return
true if {@code classOperationName} is not null (i.e. it represents
something that has the {@code Traced} annotation) and the
{@code Traced} annotation was explicitly set to {@code false},
and the {@code methodOperationName} is not explicitly set to {@code true}.
@param classOperationName The class operation name
@param methodOperationName The method operation name
@return See above | [
"Return",
"true",
"if",
"{",
"@code",
"methodOperationName",
"}",
"is",
"not",
"null",
"(",
"i",
".",
"e",
".",
"it",
"represents",
"something",
"that",
"has",
"the",
"{",
"@code",
"Traced",
"}",
"annotation",
")",
"and",
"if",
"the",
"{",
"@code",
"Traced",
"}",
"annotation",
"was",
"explicitly",
"set",
"to",
"{",
"@code",
"false",
"}",
"or",
"return",
"true",
"if",
"{",
"@code",
"classOperationName",
"}",
"is",
"not",
"null",
"(",
"i",
".",
"e",
".",
"it",
"represents",
"something",
"that",
"has",
"the",
"{",
"@code",
"Traced",
"}",
"annotation",
")",
"and",
"the",
"{",
"@code",
"Traced",
"}",
"annotation",
"was",
"explicitly",
"set",
"to",
"{",
"@code",
"false",
"}",
"and",
"the",
"{",
"@code",
"methodOperationName",
"}",
"is",
"not",
"explicitly",
"set",
"to",
"{",
"@code",
"true",
"}",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.opentracing.1.3/src/com/ibm/ws/microprofile/opentracing/OpenTracingService.java#L104-L106 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/MutableArray.java | MutableArray.setString | @NonNull
@Override
public MutableArray setString(int index, String value) {
"""
Sets an String object at the given index.
@param index the index. This value must not exceed the bounds of the array.
@param value the String object
@return The self object
"""
return setValue(index, value);
} | java | @NonNull
@Override
public MutableArray setString(int index, String value) {
return setValue(index, value);
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"MutableArray",
"setString",
"(",
"int",
"index",
",",
"String",
"value",
")",
"{",
"return",
"setValue",
"(",
"index",
",",
"value",
")",
";",
"}"
] | Sets an String object at the given index.
@param index the index. This value must not exceed the bounds of the array.
@param value the String object
@return The self object | [
"Sets",
"an",
"String",
"object",
"at",
"the",
"given",
"index",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableArray.java#L117-L121 |
apache/flink | flink-core/src/main/java/org/apache/flink/api/common/Plan.java | Plan.registerCachedFile | public void registerCachedFile(String name, DistributedCacheEntry entry) throws IOException {
"""
register cache files in program level
@param entry contains all relevant information
@param name user defined name of that file
@throws java.io.IOException
"""
if (!this.cacheFile.containsKey(name)) {
this.cacheFile.put(name, entry);
} else {
throw new IOException("cache file " + name + "already exists!");
}
} | java | public void registerCachedFile(String name, DistributedCacheEntry entry) throws IOException {
if (!this.cacheFile.containsKey(name)) {
this.cacheFile.put(name, entry);
} else {
throw new IOException("cache file " + name + "already exists!");
}
} | [
"public",
"void",
"registerCachedFile",
"(",
"String",
"name",
",",
"DistributedCacheEntry",
"entry",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"this",
".",
"cacheFile",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"this",
".",
"cacheFile",
".",
"put",
"(",
"name",
",",
"entry",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IOException",
"(",
"\"cache file \"",
"+",
"name",
"+",
"\"already exists!\"",
")",
";",
"}",
"}"
] | register cache files in program level
@param entry contains all relevant information
@param name user defined name of that file
@throws java.io.IOException | [
"register",
"cache",
"files",
"in",
"program",
"level"
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/Plan.java#L339-L345 |
graknlabs/grakn | server/src/server/session/TransactionOLTP.java | TransactionOLTP.addVertexElementWithEdgeIdProperty | public VertexElement addVertexElementWithEdgeIdProperty(Schema.BaseType baseType, ConceptId conceptId) {
"""
This is only used when reifying a Relation
@param baseType Concept BaseType which will become the VertexLabel
@param conceptId ConceptId to be set on the vertex
@return just created Vertex
"""
return executeLockingMethod(() -> factory().addVertexElementWithEdgeIdProperty(baseType, conceptId));
} | java | public VertexElement addVertexElementWithEdgeIdProperty(Schema.BaseType baseType, ConceptId conceptId) {
return executeLockingMethod(() -> factory().addVertexElementWithEdgeIdProperty(baseType, conceptId));
} | [
"public",
"VertexElement",
"addVertexElementWithEdgeIdProperty",
"(",
"Schema",
".",
"BaseType",
"baseType",
",",
"ConceptId",
"conceptId",
")",
"{",
"return",
"executeLockingMethod",
"(",
"(",
")",
"->",
"factory",
"(",
")",
".",
"addVertexElementWithEdgeIdProperty",
"(",
"baseType",
",",
"conceptId",
")",
")",
";",
"}"
] | This is only used when reifying a Relation
@param baseType Concept BaseType which will become the VertexLabel
@param conceptId ConceptId to be set on the vertex
@return just created Vertex | [
"This",
"is",
"only",
"used",
"when",
"reifying",
"a",
"Relation"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/TransactionOLTP.java#L212-L214 |
mlhartme/sushi | src/main/java/net/oneandone/sushi/fs/file/FileNode.java | FileNode.deleteTree | @Override
public FileNode deleteTree() throws DeleteException, NodeNotFoundException {
"""
Deletes a file or directory. Directories are deleted recursively. Handles Links.
"""
if (!exists()) {
throw new NodeNotFoundException(this);
}
try {
doDeleteTree(path);
} catch (IOException e) {
throw new DeleteException(this, e);
}
return this;
} | java | @Override
public FileNode deleteTree() throws DeleteException, NodeNotFoundException {
if (!exists()) {
throw new NodeNotFoundException(this);
}
try {
doDeleteTree(path);
} catch (IOException e) {
throw new DeleteException(this, e);
}
return this;
} | [
"@",
"Override",
"public",
"FileNode",
"deleteTree",
"(",
")",
"throws",
"DeleteException",
",",
"NodeNotFoundException",
"{",
"if",
"(",
"!",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"NodeNotFoundException",
"(",
"this",
")",
";",
"}",
"try",
"{",
"doDeleteTree",
"(",
"path",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"DeleteException",
"(",
"this",
",",
"e",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Deletes a file or directory. Directories are deleted recursively. Handles Links. | [
"Deletes",
"a",
"file",
"or",
"directory",
".",
"Directories",
"are",
"deleted",
"recursively",
".",
"Handles",
"Links",
"."
] | train | https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/fs/file/FileNode.java#L411-L422 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jwt/src/com/ibm/ws/security/jwt/internal/ConsumerUtil.java | ConsumerUtil.validateSignatureAlgorithmWithKey | void validateSignatureAlgorithmWithKey(JwtConsumerConfig config, Key key) throws InvalidClaimException {
"""
Throws an exception if the provided key is null but the config specifies a
signature algorithm other than "none".
"""
String signatureAlgorithm = config.getSignatureAlgorithm();
if (key == null && signatureAlgorithm != null && !signatureAlgorithm.equalsIgnoreCase("none")) {
String msg = Tr.formatMessage(tc, "JWT_MISSING_KEY", new Object[] { signatureAlgorithm });
throw new InvalidClaimException(msg);
}
} | java | void validateSignatureAlgorithmWithKey(JwtConsumerConfig config, Key key) throws InvalidClaimException {
String signatureAlgorithm = config.getSignatureAlgorithm();
if (key == null && signatureAlgorithm != null && !signatureAlgorithm.equalsIgnoreCase("none")) {
String msg = Tr.formatMessage(tc, "JWT_MISSING_KEY", new Object[] { signatureAlgorithm });
throw new InvalidClaimException(msg);
}
} | [
"void",
"validateSignatureAlgorithmWithKey",
"(",
"JwtConsumerConfig",
"config",
",",
"Key",
"key",
")",
"throws",
"InvalidClaimException",
"{",
"String",
"signatureAlgorithm",
"=",
"config",
".",
"getSignatureAlgorithm",
"(",
")",
";",
"if",
"(",
"key",
"==",
"null",
"&&",
"signatureAlgorithm",
"!=",
"null",
"&&",
"!",
"signatureAlgorithm",
".",
"equalsIgnoreCase",
"(",
"\"none\"",
")",
")",
"{",
"String",
"msg",
"=",
"Tr",
".",
"formatMessage",
"(",
"tc",
",",
"\"JWT_MISSING_KEY\"",
",",
"new",
"Object",
"[",
"]",
"{",
"signatureAlgorithm",
"}",
")",
";",
"throw",
"new",
"InvalidClaimException",
"(",
"msg",
")",
";",
"}",
"}"
] | Throws an exception if the provided key is null but the config specifies a
signature algorithm other than "none". | [
"Throws",
"an",
"exception",
"if",
"the",
"provided",
"key",
"is",
"null",
"but",
"the",
"config",
"specifies",
"a",
"signature",
"algorithm",
"other",
"than",
"none",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jwt/src/com/ibm/ws/security/jwt/internal/ConsumerUtil.java#L394-L400 |
mqlight/java-mqlight | mqlight/src/main/java/com/ibm/mqlight/api/security/KeyStoreUtils.java | KeyStoreUtils.addPrivateKey | public static void addPrivateKey(KeyStore keyStore, File pemKeyFile, char[] passwordChars, List<Certificate> certChain) throws IOException, GeneralSecurityException {
"""
Adds a private key to the specified key store from the passed private key file and certificate chain.
@param keyStore
The key store to receive the private key.
@param pemKeyFile
A PEM format file containing the private key.
@param passwordChars
The password that protects the private key.
@param certChain The certificate chain to associate with the private key.
@throws IOException if the key store file cannot be read
@throws GeneralSecurityException if a cryptography problem is encountered.
"""
final String methodName = "addPrivateKey";
logger.entry(methodName, pemKeyFile, certChain);
PrivateKey privateKey = createPrivateKey(pemKeyFile, passwordChars);
keyStore.setKeyEntry("key", privateKey, passwordChars, certChain.toArray(new Certificate[certChain.size()]));
logger.exit(methodName);
} | java | public static void addPrivateKey(KeyStore keyStore, File pemKeyFile, char[] passwordChars, List<Certificate> certChain) throws IOException, GeneralSecurityException {
final String methodName = "addPrivateKey";
logger.entry(methodName, pemKeyFile, certChain);
PrivateKey privateKey = createPrivateKey(pemKeyFile, passwordChars);
keyStore.setKeyEntry("key", privateKey, passwordChars, certChain.toArray(new Certificate[certChain.size()]));
logger.exit(methodName);
} | [
"public",
"static",
"void",
"addPrivateKey",
"(",
"KeyStore",
"keyStore",
",",
"File",
"pemKeyFile",
",",
"char",
"[",
"]",
"passwordChars",
",",
"List",
"<",
"Certificate",
">",
"certChain",
")",
"throws",
"IOException",
",",
"GeneralSecurityException",
"{",
"final",
"String",
"methodName",
"=",
"\"addPrivateKey\"",
";",
"logger",
".",
"entry",
"(",
"methodName",
",",
"pemKeyFile",
",",
"certChain",
")",
";",
"PrivateKey",
"privateKey",
"=",
"createPrivateKey",
"(",
"pemKeyFile",
",",
"passwordChars",
")",
";",
"keyStore",
".",
"setKeyEntry",
"(",
"\"key\"",
",",
"privateKey",
",",
"passwordChars",
",",
"certChain",
".",
"toArray",
"(",
"new",
"Certificate",
"[",
"certChain",
".",
"size",
"(",
")",
"]",
")",
")",
";",
"logger",
".",
"exit",
"(",
"methodName",
")",
";",
"}"
] | Adds a private key to the specified key store from the passed private key file and certificate chain.
@param keyStore
The key store to receive the private key.
@param pemKeyFile
A PEM format file containing the private key.
@param passwordChars
The password that protects the private key.
@param certChain The certificate chain to associate with the private key.
@throws IOException if the key store file cannot be read
@throws GeneralSecurityException if a cryptography problem is encountered. | [
"Adds",
"a",
"private",
"key",
"to",
"the",
"specified",
"key",
"store",
"from",
"the",
"passed",
"private",
"key",
"file",
"and",
"certificate",
"chain",
"."
] | train | https://github.com/mqlight/java-mqlight/blob/a565dfa6044050826d1221697da9e3268b557aeb/mqlight/src/main/java/com/ibm/mqlight/api/security/KeyStoreUtils.java#L125-L134 |
micronaut-projects/micronaut-core | http/src/main/java/io/micronaut/http/context/ServerRequestContext.java | ServerRequestContext.with | public static <T> T with(HttpRequest request, Supplier<T> callable) {
"""
Wrap the execution of the given callable in request context processing.
@param request The request
@param callable The callable
@param <T> The return type of the callable
@return The return value of the callable
"""
HttpRequest existing = REQUEST.get();
boolean isSet = false;
try {
if (request != existing) {
isSet = true;
REQUEST.set(request);
}
return callable.get();
} finally {
if (isSet) {
REQUEST.remove();
}
}
} | java | public static <T> T with(HttpRequest request, Supplier<T> callable) {
HttpRequest existing = REQUEST.get();
boolean isSet = false;
try {
if (request != existing) {
isSet = true;
REQUEST.set(request);
}
return callable.get();
} finally {
if (isSet) {
REQUEST.remove();
}
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"with",
"(",
"HttpRequest",
"request",
",",
"Supplier",
"<",
"T",
">",
"callable",
")",
"{",
"HttpRequest",
"existing",
"=",
"REQUEST",
".",
"get",
"(",
")",
";",
"boolean",
"isSet",
"=",
"false",
";",
"try",
"{",
"if",
"(",
"request",
"!=",
"existing",
")",
"{",
"isSet",
"=",
"true",
";",
"REQUEST",
".",
"set",
"(",
"request",
")",
";",
"}",
"return",
"callable",
".",
"get",
"(",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"isSet",
")",
"{",
"REQUEST",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}"
] | Wrap the execution of the given callable in request context processing.
@param request The request
@param callable The callable
@param <T> The return type of the callable
@return The return value of the callable | [
"Wrap",
"the",
"execution",
"of",
"the",
"given",
"callable",
"in",
"request",
"context",
"processing",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http/src/main/java/io/micronaut/http/context/ServerRequestContext.java#L79-L93 |
drapostolos/rdp4j | src/main/java/com/github/drapostolos/rdp4j/DirectoryPoller.java | DirectoryPoller.awaitTermination | public void awaitTermination() {
"""
Blocks until the last poll-cycle has finished and all {@link AfterStopEvent} has been
processed.
"""
try {
latch.await();
} catch (InterruptedException e) {
String message = "awaitTermination() method was interrupted!";
throw new UnsupportedOperationException(message, e);
}
} | java | public void awaitTermination() {
try {
latch.await();
} catch (InterruptedException e) {
String message = "awaitTermination() method was interrupted!";
throw new UnsupportedOperationException(message, e);
}
} | [
"public",
"void",
"awaitTermination",
"(",
")",
"{",
"try",
"{",
"latch",
".",
"await",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"String",
"message",
"=",
"\"awaitTermination() method was interrupted!\"",
";",
"throw",
"new",
"UnsupportedOperationException",
"(",
"message",
",",
"e",
")",
";",
"}",
"}"
] | Blocks until the last poll-cycle has finished and all {@link AfterStopEvent} has been
processed. | [
"Blocks",
"until",
"the",
"last",
"poll",
"-",
"cycle",
"has",
"finished",
"and",
"all",
"{"
] | train | https://github.com/drapostolos/rdp4j/blob/ec1db2444d245b7ccd6607182bb56a027fa66d6b/src/main/java/com/github/drapostolos/rdp4j/DirectoryPoller.java#L194-L201 |
jboss/jboss-jstl-api_spec | src/main/java/javax/servlet/jsp/jstl/core/Config.java | Config.get | public static Object get(HttpSession session, String name) {
"""
Looks up a configuration variable in the "session" scope.
<p> The lookup of configuration variables is performed as if each scope
had its own name space, that is, the same configuration variable name
in one scope does not replace one stored in a different scope.</p>
@param session Session object in which the configuration variable is to
be looked up
@param name Configuration variable name
@return The <tt>java.lang.Object</tt> associated with the configuration
variable, or null if it is not defined, if session is null, or if the session
is invalidated.
"""
Object ret = null;
if (session != null) {
try {
ret = session.getAttribute(name + SESSION_SCOPE_SUFFIX);
} catch (IllegalStateException ex) {
} // when session is invalidated
}
return ret;
} | java | public static Object get(HttpSession session, String name) {
Object ret = null;
if (session != null) {
try {
ret = session.getAttribute(name + SESSION_SCOPE_SUFFIX);
} catch (IllegalStateException ex) {
} // when session is invalidated
}
return ret;
} | [
"public",
"static",
"Object",
"get",
"(",
"HttpSession",
"session",
",",
"String",
"name",
")",
"{",
"Object",
"ret",
"=",
"null",
";",
"if",
"(",
"session",
"!=",
"null",
")",
"{",
"try",
"{",
"ret",
"=",
"session",
".",
"getAttribute",
"(",
"name",
"+",
"SESSION_SCOPE_SUFFIX",
")",
";",
"}",
"catch",
"(",
"IllegalStateException",
"ex",
")",
"{",
"}",
"// when session is invalidated",
"}",
"return",
"ret",
";",
"}"
] | Looks up a configuration variable in the "session" scope.
<p> The lookup of configuration variables is performed as if each scope
had its own name space, that is, the same configuration variable name
in one scope does not replace one stored in a different scope.</p>
@param session Session object in which the configuration variable is to
be looked up
@param name Configuration variable name
@return The <tt>java.lang.Object</tt> associated with the configuration
variable, or null if it is not defined, if session is null, or if the session
is invalidated. | [
"Looks",
"up",
"a",
"configuration",
"variable",
"in",
"the",
"session",
"scope",
".",
"<p",
">",
"The",
"lookup",
"of",
"configuration",
"variables",
"is",
"performed",
"as",
"if",
"each",
"scope",
"had",
"its",
"own",
"name",
"space",
"that",
"is",
"the",
"same",
"configuration",
"variable",
"name",
"in",
"one",
"scope",
"does",
"not",
"replace",
"one",
"stored",
"in",
"a",
"different",
"scope",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/javax/servlet/jsp/jstl/core/Config.java#L142-L151 |
google/closure-compiler | src/com/google/javascript/jscomp/AbstractCommandLineRunner.java | AbstractCommandLineRunner.createInputs | @GwtIncompatible("Unnecessary")
private List<SourceFile> createInputs(
List<FlagEntry<JsSourceType>> files,
List<JsonFileSpec> jsonFiles,
List<JsModuleSpec> jsModuleSpecs)
throws IOException {
"""
Creates inputs from a list of source files and json files.
@param files A list of flag entries indicates js and zip file names.
@param jsonFiles A list of json encoded files.
@param jsModuleSpecs A list js module specs.
@return An array of inputs
"""
return createInputs(files, jsonFiles, /* allowStdIn= */ false, jsModuleSpecs);
} | java | @GwtIncompatible("Unnecessary")
private List<SourceFile> createInputs(
List<FlagEntry<JsSourceType>> files,
List<JsonFileSpec> jsonFiles,
List<JsModuleSpec> jsModuleSpecs)
throws IOException {
return createInputs(files, jsonFiles, /* allowStdIn= */ false, jsModuleSpecs);
} | [
"@",
"GwtIncompatible",
"(",
"\"Unnecessary\"",
")",
"private",
"List",
"<",
"SourceFile",
">",
"createInputs",
"(",
"List",
"<",
"FlagEntry",
"<",
"JsSourceType",
">",
">",
"files",
",",
"List",
"<",
"JsonFileSpec",
">",
"jsonFiles",
",",
"List",
"<",
"JsModuleSpec",
">",
"jsModuleSpecs",
")",
"throws",
"IOException",
"{",
"return",
"createInputs",
"(",
"files",
",",
"jsonFiles",
",",
"/* allowStdIn= */",
"false",
",",
"jsModuleSpecs",
")",
";",
"}"
] | Creates inputs from a list of source files and json files.
@param files A list of flag entries indicates js and zip file names.
@param jsonFiles A list of json encoded files.
@param jsModuleSpecs A list js module specs.
@return An array of inputs | [
"Creates",
"inputs",
"from",
"a",
"list",
"of",
"source",
"files",
"and",
"json",
"files",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java#L574-L581 |
casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java | ManagementEnforcer.removeNamedPolicy | public boolean removeNamedPolicy(String ptype, String... params) {
"""
removeNamedPolicy removes an authorization rule from the current named policy.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param params the "p" policy rule.
@return succeeds or not.
"""
return removeNamedPolicy(ptype, Arrays.asList(params));
} | java | public boolean removeNamedPolicy(String ptype, String... params) {
return removeNamedPolicy(ptype, Arrays.asList(params));
} | [
"public",
"boolean",
"removeNamedPolicy",
"(",
"String",
"ptype",
",",
"String",
"...",
"params",
")",
"{",
"return",
"removeNamedPolicy",
"(",
"ptype",
",",
"Arrays",
".",
"asList",
"(",
"params",
")",
")",
";",
"}"
] | removeNamedPolicy removes an authorization rule from the current named policy.
@param ptype the policy type, can be "p", "p2", "p3", ..
@param params the "p" policy rule.
@return succeeds or not. | [
"removeNamedPolicy",
"removes",
"an",
"authorization",
"rule",
"from",
"the",
"current",
"named",
"policy",
"."
] | train | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L356-L358 |
apereo/cas | support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java | LdapUtils.newLdaptiveSearchRequest | public static SearchRequest newLdaptiveSearchRequest(final String baseDn,
final SearchFilter filter,
final String[] binaryAttributes,
final String[] returnAttributes) {
"""
Builds a new request.
@param baseDn the base dn
@param filter the filter
@param binaryAttributes the binary attributes
@param returnAttributes the return attributes
@return the search request
"""
val sr = new SearchRequest(baseDn, filter);
sr.setBinaryAttributes(binaryAttributes);
sr.setReturnAttributes(returnAttributes);
sr.setSearchScope(SearchScope.SUBTREE);
return sr;
} | java | public static SearchRequest newLdaptiveSearchRequest(final String baseDn,
final SearchFilter filter,
final String[] binaryAttributes,
final String[] returnAttributes) {
val sr = new SearchRequest(baseDn, filter);
sr.setBinaryAttributes(binaryAttributes);
sr.setReturnAttributes(returnAttributes);
sr.setSearchScope(SearchScope.SUBTREE);
return sr;
} | [
"public",
"static",
"SearchRequest",
"newLdaptiveSearchRequest",
"(",
"final",
"String",
"baseDn",
",",
"final",
"SearchFilter",
"filter",
",",
"final",
"String",
"[",
"]",
"binaryAttributes",
",",
"final",
"String",
"[",
"]",
"returnAttributes",
")",
"{",
"val",
"sr",
"=",
"new",
"SearchRequest",
"(",
"baseDn",
",",
"filter",
")",
";",
"sr",
".",
"setBinaryAttributes",
"(",
"binaryAttributes",
")",
";",
"sr",
".",
"setReturnAttributes",
"(",
"returnAttributes",
")",
";",
"sr",
".",
"setSearchScope",
"(",
"SearchScope",
".",
"SUBTREE",
")",
";",
"return",
"sr",
";",
"}"
] | Builds a new request.
@param baseDn the base dn
@param filter the filter
@param binaryAttributes the binary attributes
@param returnAttributes the return attributes
@return the search request | [
"Builds",
"a",
"new",
"request",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L469-L478 |
kikinteractive/ice | ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java | ConfigDescriptorFactory.buildDescriptor | public ConfigDescriptor buildDescriptor(Method method, Optional<String> scopeOpt, Optional<String> overrideValue) {
"""
Build a {@link ConfigDescriptor} for a specific Method, given optional scope, and given override value.
@param method method to include in config descriptor
@param scopeOpt optional scope for the config descriptor
@param overrideValue optional override value used to override the static value in the config descriptor
@return a {@link ConfigDescriptor} for the given method, to be used internally in the config system.
"""
checkNotNull(method);
checkNotNull(scopeOpt);
checkNotNull(overrideValue);
StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method);
if (validationState != StaticConfigHelper.MethodValidationState.OK) {
log.debug("Configuration class {} was found to be invalid: {}",
method.getDeclaringClass().getName(), validationState.name());
throw new ConfigException("Invalid Configuration class: {}", validationState.name());
}
Optional<String> value = getMethodDefaultValue(method);
if (overrideValue.isPresent()) {
value = overrideValue;
}
return internalBuildDescriptor(method, scopeOpt, value);
} | java | public ConfigDescriptor buildDescriptor(Method method, Optional<String> scopeOpt, Optional<String> overrideValue)
{
checkNotNull(method);
checkNotNull(scopeOpt);
checkNotNull(overrideValue);
StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method);
if (validationState != StaticConfigHelper.MethodValidationState.OK) {
log.debug("Configuration class {} was found to be invalid: {}",
method.getDeclaringClass().getName(), validationState.name());
throw new ConfigException("Invalid Configuration class: {}", validationState.name());
}
Optional<String> value = getMethodDefaultValue(method);
if (overrideValue.isPresent()) {
value = overrideValue;
}
return internalBuildDescriptor(method, scopeOpt, value);
} | [
"public",
"ConfigDescriptor",
"buildDescriptor",
"(",
"Method",
"method",
",",
"Optional",
"<",
"String",
">",
"scopeOpt",
",",
"Optional",
"<",
"String",
">",
"overrideValue",
")",
"{",
"checkNotNull",
"(",
"method",
")",
";",
"checkNotNull",
"(",
"scopeOpt",
")",
";",
"checkNotNull",
"(",
"overrideValue",
")",
";",
"StaticConfigHelper",
".",
"MethodValidationState",
"validationState",
"=",
"StaticConfigHelper",
".",
"isValidConfigInterfaceMethod",
"(",
"method",
")",
";",
"if",
"(",
"validationState",
"!=",
"StaticConfigHelper",
".",
"MethodValidationState",
".",
"OK",
")",
"{",
"log",
".",
"debug",
"(",
"\"Configuration class {} was found to be invalid: {}\"",
",",
"method",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"validationState",
".",
"name",
"(",
")",
")",
";",
"throw",
"new",
"ConfigException",
"(",
"\"Invalid Configuration class: {}\"",
",",
"validationState",
".",
"name",
"(",
")",
")",
";",
"}",
"Optional",
"<",
"String",
">",
"value",
"=",
"getMethodDefaultValue",
"(",
"method",
")",
";",
"if",
"(",
"overrideValue",
".",
"isPresent",
"(",
")",
")",
"{",
"value",
"=",
"overrideValue",
";",
"}",
"return",
"internalBuildDescriptor",
"(",
"method",
",",
"scopeOpt",
",",
"value",
")",
";",
"}"
] | Build a {@link ConfigDescriptor} for a specific Method, given optional scope, and given override value.
@param method method to include in config descriptor
@param scopeOpt optional scope for the config descriptor
@param overrideValue optional override value used to override the static value in the config descriptor
@return a {@link ConfigDescriptor} for the given method, to be used internally in the config system. | [
"Build",
"a",
"{",
"@link",
"ConfigDescriptor",
"}",
"for",
"a",
"specific",
"Method",
"given",
"optional",
"scope",
"and",
"given",
"override",
"value",
"."
] | train | https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java#L123-L141 |
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java | MultiLineString.fromLineStrings | public static MultiLineString fromLineStrings(@NonNull List<LineString> lineStrings,
@Nullable BoundingBox bbox) {
"""
Create a new instance of this class by defining a list of {@link LineString} objects and
passing that list in as a parameter in this method. The LineStrings should comply with the
GeoJson specifications described in the documentation. Optionally, pass in an instance of a
{@link BoundingBox} which better describes this MultiLineString.
@param lineStrings a list of LineStrings which make up this MultiLineString
@param bbox optionally include a bbox definition
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0
"""
List<List<Point>> coordinates = new ArrayList<>(lineStrings.size());
for (LineString lineString : lineStrings) {
coordinates.add(lineString.coordinates());
}
return new MultiLineString(TYPE, bbox, coordinates);
} | java | public static MultiLineString fromLineStrings(@NonNull List<LineString> lineStrings,
@Nullable BoundingBox bbox) {
List<List<Point>> coordinates = new ArrayList<>(lineStrings.size());
for (LineString lineString : lineStrings) {
coordinates.add(lineString.coordinates());
}
return new MultiLineString(TYPE, bbox, coordinates);
} | [
"public",
"static",
"MultiLineString",
"fromLineStrings",
"(",
"@",
"NonNull",
"List",
"<",
"LineString",
">",
"lineStrings",
",",
"@",
"Nullable",
"BoundingBox",
"bbox",
")",
"{",
"List",
"<",
"List",
"<",
"Point",
">>",
"coordinates",
"=",
"new",
"ArrayList",
"<>",
"(",
"lineStrings",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"LineString",
"lineString",
":",
"lineStrings",
")",
"{",
"coordinates",
".",
"add",
"(",
"lineString",
".",
"coordinates",
"(",
")",
")",
";",
"}",
"return",
"new",
"MultiLineString",
"(",
"TYPE",
",",
"bbox",
",",
"coordinates",
")",
";",
"}"
] | Create a new instance of this class by defining a list of {@link LineString} objects and
passing that list in as a parameter in this method. The LineStrings should comply with the
GeoJson specifications described in the documentation. Optionally, pass in an instance of a
{@link BoundingBox} which better describes this MultiLineString.
@param lineStrings a list of LineStrings which make up this MultiLineString
@param bbox optionally include a bbox definition
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0 | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"defining",
"a",
"list",
"of",
"{",
"@link",
"LineString",
"}",
"objects",
"and",
"passing",
"that",
"list",
"in",
"as",
"a",
"parameter",
"in",
"this",
"method",
".",
"The",
"LineStrings",
"should",
"comply",
"with",
"the",
"GeoJson",
"specifications",
"described",
"in",
"the",
"documentation",
".",
"Optionally",
"pass",
"in",
"an",
"instance",
"of",
"a",
"{",
"@link",
"BoundingBox",
"}",
"which",
"better",
"describes",
"this",
"MultiLineString",
"."
] | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java#L111-L118 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java | DeviceManagerClient.createDeviceRegistry | public final DeviceRegistry createDeviceRegistry(String parent, DeviceRegistry deviceRegistry) {
"""
Creates a device registry that contains devices.
<p>Sample code:
<pre><code>
try (DeviceManagerClient deviceManagerClient = DeviceManagerClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
DeviceRegistry deviceRegistry = DeviceRegistry.newBuilder().build();
DeviceRegistry response = deviceManagerClient.createDeviceRegistry(parent.toString(), deviceRegistry);
}
</code></pre>
@param parent The project and cloud region where this device registry must be created. For
example, `projects/example-project/locations/us-central1`.
@param deviceRegistry The device registry. The field `name` must be empty. The server will
generate that field from the device registry `id` provided and the `parent` field.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
CreateDeviceRegistryRequest request =
CreateDeviceRegistryRequest.newBuilder()
.setParent(parent)
.setDeviceRegistry(deviceRegistry)
.build();
return createDeviceRegistry(request);
} | java | public final DeviceRegistry createDeviceRegistry(String parent, DeviceRegistry deviceRegistry) {
CreateDeviceRegistryRequest request =
CreateDeviceRegistryRequest.newBuilder()
.setParent(parent)
.setDeviceRegistry(deviceRegistry)
.build();
return createDeviceRegistry(request);
} | [
"public",
"final",
"DeviceRegistry",
"createDeviceRegistry",
"(",
"String",
"parent",
",",
"DeviceRegistry",
"deviceRegistry",
")",
"{",
"CreateDeviceRegistryRequest",
"request",
"=",
"CreateDeviceRegistryRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
")",
".",
"setDeviceRegistry",
"(",
"deviceRegistry",
")",
".",
"build",
"(",
")",
";",
"return",
"createDeviceRegistry",
"(",
"request",
")",
";",
"}"
] | Creates a device registry that contains devices.
<p>Sample code:
<pre><code>
try (DeviceManagerClient deviceManagerClient = DeviceManagerClient.create()) {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
DeviceRegistry deviceRegistry = DeviceRegistry.newBuilder().build();
DeviceRegistry response = deviceManagerClient.createDeviceRegistry(parent.toString(), deviceRegistry);
}
</code></pre>
@param parent The project and cloud region where this device registry must be created. For
example, `projects/example-project/locations/us-central1`.
@param deviceRegistry The device registry. The field `name` must be empty. The server will
generate that field from the device registry `id` provided and the `parent` field.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"device",
"registry",
"that",
"contains",
"devices",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java#L216-L224 |
duracloud/duracloud | security/src/main/java/org/duracloud/security/vote/SpaceAccessVoter.java | SpaceAccessVoter.getSpaceACLs | protected Map<String, AclType> getSpaceACLs(HttpServletRequest request) {
"""
This method returns the ACLs of the requested space, or an empty-map if
there is an error or for certain 'keyword' spaces, or null if the space
does not exist.
@param request containing spaceId and storeId
@return ACLs, empty-map, or null
"""
String storeId = getStoreId(request);
String spaceId = getSpaceId(request);
return getSpaceACLs(storeId, spaceId);
} | java | protected Map<String, AclType> getSpaceACLs(HttpServletRequest request) {
String storeId = getStoreId(request);
String spaceId = getSpaceId(request);
return getSpaceACLs(storeId, spaceId);
} | [
"protected",
"Map",
"<",
"String",
",",
"AclType",
">",
"getSpaceACLs",
"(",
"HttpServletRequest",
"request",
")",
"{",
"String",
"storeId",
"=",
"getStoreId",
"(",
"request",
")",
";",
"String",
"spaceId",
"=",
"getSpaceId",
"(",
"request",
")",
";",
"return",
"getSpaceACLs",
"(",
"storeId",
",",
"spaceId",
")",
";",
"}"
] | This method returns the ACLs of the requested space, or an empty-map if
there is an error or for certain 'keyword' spaces, or null if the space
does not exist.
@param request containing spaceId and storeId
@return ACLs, empty-map, or null | [
"This",
"method",
"returns",
"the",
"ACLs",
"of",
"the",
"requested",
"space",
"or",
"an",
"empty",
"-",
"map",
"if",
"there",
"is",
"an",
"error",
"or",
"for",
"certain",
"keyword",
"spaces",
"or",
"null",
"if",
"the",
"space",
"does",
"not",
"exist",
"."
] | train | https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/security/src/main/java/org/duracloud/security/vote/SpaceAccessVoter.java#L140-L144 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/PassthroughResourcesImpl.java | PassthroughResourcesImpl.deleteRequest | public String deleteRequest(String endpoint) throws SmartsheetException {
"""
Issue an HTTP DELETE request.
@param endpoint the API endpoint
@return a JSON response string
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation
"""
return passthroughRequest(HttpMethod.DELETE, endpoint, null, null);
} | java | public String deleteRequest(String endpoint) throws SmartsheetException {
return passthroughRequest(HttpMethod.DELETE, endpoint, null, null);
} | [
"public",
"String",
"deleteRequest",
"(",
"String",
"endpoint",
")",
"throws",
"SmartsheetException",
"{",
"return",
"passthroughRequest",
"(",
"HttpMethod",
".",
"DELETE",
",",
"endpoint",
",",
"null",
",",
"null",
")",
";",
"}"
] | Issue an HTTP DELETE request.
@param endpoint the API endpoint
@return a JSON response string
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | [
"Issue",
"an",
"HTTP",
"DELETE",
"request",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/PassthroughResourcesImpl.java#L114-L116 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/routing/QueryGraph.java | QueryGraph.unfavorVirtualEdgePair | public void unfavorVirtualEdgePair(int virtualNodeId, int virtualEdgeId) {
"""
Sets the virtual edge with virtualEdgeId and its reverse edge to 'unfavored', which
effectively penalizes both virtual edges towards an adjacent node of virtualNodeId.
This makes it more likely (but does not guarantee) that the router chooses a route towards
the other adjacent node of virtualNodeId.
<p>
@param virtualNodeId virtual node at which edges get unfavored
@param virtualEdgeId this edge and the reverse virtual edge become unfavored
"""
if (!isVirtualNode(virtualNodeId)) {
throw new IllegalArgumentException("Node id " + virtualNodeId
+ " must be a virtual node.");
}
VirtualEdgeIteratorState incomingEdge =
(VirtualEdgeIteratorState) getEdgeIteratorState(virtualEdgeId, virtualNodeId);
VirtualEdgeIteratorState reverseEdge = (VirtualEdgeIteratorState) getEdgeIteratorState(
virtualEdgeId, incomingEdge.getBaseNode());
incomingEdge.setUnfavored(true);
unfavoredEdges.add(incomingEdge);
reverseEdge.setUnfavored(true);
unfavoredEdges.add(reverseEdge);
} | java | public void unfavorVirtualEdgePair(int virtualNodeId, int virtualEdgeId) {
if (!isVirtualNode(virtualNodeId)) {
throw new IllegalArgumentException("Node id " + virtualNodeId
+ " must be a virtual node.");
}
VirtualEdgeIteratorState incomingEdge =
(VirtualEdgeIteratorState) getEdgeIteratorState(virtualEdgeId, virtualNodeId);
VirtualEdgeIteratorState reverseEdge = (VirtualEdgeIteratorState) getEdgeIteratorState(
virtualEdgeId, incomingEdge.getBaseNode());
incomingEdge.setUnfavored(true);
unfavoredEdges.add(incomingEdge);
reverseEdge.setUnfavored(true);
unfavoredEdges.add(reverseEdge);
} | [
"public",
"void",
"unfavorVirtualEdgePair",
"(",
"int",
"virtualNodeId",
",",
"int",
"virtualEdgeId",
")",
"{",
"if",
"(",
"!",
"isVirtualNode",
"(",
"virtualNodeId",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Node id \"",
"+",
"virtualNodeId",
"+",
"\" must be a virtual node.\"",
")",
";",
"}",
"VirtualEdgeIteratorState",
"incomingEdge",
"=",
"(",
"VirtualEdgeIteratorState",
")",
"getEdgeIteratorState",
"(",
"virtualEdgeId",
",",
"virtualNodeId",
")",
";",
"VirtualEdgeIteratorState",
"reverseEdge",
"=",
"(",
"VirtualEdgeIteratorState",
")",
"getEdgeIteratorState",
"(",
"virtualEdgeId",
",",
"incomingEdge",
".",
"getBaseNode",
"(",
")",
")",
";",
"incomingEdge",
".",
"setUnfavored",
"(",
"true",
")",
";",
"unfavoredEdges",
".",
"add",
"(",
"incomingEdge",
")",
";",
"reverseEdge",
".",
"setUnfavored",
"(",
"true",
")",
";",
"unfavoredEdges",
".",
"add",
"(",
"reverseEdge",
")",
";",
"}"
] | Sets the virtual edge with virtualEdgeId and its reverse edge to 'unfavored', which
effectively penalizes both virtual edges towards an adjacent node of virtualNodeId.
This makes it more likely (but does not guarantee) that the router chooses a route towards
the other adjacent node of virtualNodeId.
<p>
@param virtualNodeId virtual node at which edges get unfavored
@param virtualEdgeId this edge and the reverse virtual edge become unfavored | [
"Sets",
"the",
"virtual",
"edge",
"with",
"virtualEdgeId",
"and",
"its",
"reverse",
"edge",
"to",
"unfavored",
"which",
"effectively",
"penalizes",
"both",
"virtual",
"edges",
"towards",
"an",
"adjacent",
"node",
"of",
"virtualNodeId",
".",
"This",
"makes",
"it",
"more",
"likely",
"(",
"but",
"does",
"not",
"guarantee",
")",
"that",
"the",
"router",
"chooses",
"a",
"route",
"towards",
"the",
"other",
"adjacent",
"node",
"of",
"virtualNodeId",
".",
"<p",
">"
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/QueryGraph.java#L488-L502 |
aws/aws-sdk-java | aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/AwsSecurityFinding.java | AwsSecurityFinding.withProductFields | public AwsSecurityFinding withProductFields(java.util.Map<String, String> productFields) {
"""
<p>
A data type where security findings providers can include additional solution-specific details that are not part
of the defined AwsSecurityFinding format.
</p>
@param productFields
A data type where security findings providers can include additional solution-specific details that are
not part of the defined AwsSecurityFinding format.
@return Returns a reference to this object so that method calls can be chained together.
"""
setProductFields(productFields);
return this;
} | java | public AwsSecurityFinding withProductFields(java.util.Map<String, String> productFields) {
setProductFields(productFields);
return this;
} | [
"public",
"AwsSecurityFinding",
"withProductFields",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"productFields",
")",
"{",
"setProductFields",
"(",
"productFields",
")",
";",
"return",
"this",
";",
"}"
] | <p>
A data type where security findings providers can include additional solution-specific details that are not part
of the defined AwsSecurityFinding format.
</p>
@param productFields
A data type where security findings providers can include additional solution-specific details that are
not part of the defined AwsSecurityFinding format.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"A",
"data",
"type",
"where",
"security",
"findings",
"providers",
"can",
"include",
"additional",
"solution",
"-",
"specific",
"details",
"that",
"are",
"not",
"part",
"of",
"the",
"defined",
"AwsSecurityFinding",
"format",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/AwsSecurityFinding.java#L1134-L1137 |
rwl/CSparseJ | src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_entry.java | DZcs_entry.cs_entry | public static boolean cs_entry(DZcs T, int i, int j, double [] x) {
"""
Adds an entry to a triplet matrix. Memory-space and dimension of T are
increased if necessary.
@param T
triplet matrix; new entry added on output
@param i
row index of new entry
@param j
column index of new entry
@param x
numerical value of new entry
@return true if successful, false otherwise
"""
return cs_entry(T, i, j, x [0], x [1]);
} | java | public static boolean cs_entry(DZcs T, int i, int j, double [] x)
{
return cs_entry(T, i, j, x [0], x [1]);
} | [
"public",
"static",
"boolean",
"cs_entry",
"(",
"DZcs",
"T",
",",
"int",
"i",
",",
"int",
"j",
",",
"double",
"[",
"]",
"x",
")",
"{",
"return",
"cs_entry",
"(",
"T",
",",
"i",
",",
"j",
",",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
")",
";",
"}"
] | Adds an entry to a triplet matrix. Memory-space and dimension of T are
increased if necessary.
@param T
triplet matrix; new entry added on output
@param i
row index of new entry
@param j
column index of new entry
@param x
numerical value of new entry
@return true if successful, false otherwise | [
"Adds",
"an",
"entry",
"to",
"a",
"triplet",
"matrix",
".",
"Memory",
"-",
"space",
"and",
"dimension",
"of",
"T",
"are",
"increased",
"if",
"necessary",
"."
] | train | https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_entry.java#L55-L58 |
google/closure-compiler | src/com/google/javascript/jscomp/TypedCodeGenerator.java | TypedCodeGenerator.getParameterJSDocType | private String getParameterJSDocType(List<JSType> types, int index, int minArgs, int maxArgs) {
"""
Creates a JSDoc-suitable String representation of the type of a parameter.
"""
JSType type = types.get(index);
if (index < minArgs) {
return type.toAnnotationString(Nullability.EXPLICIT);
}
boolean isRestArgument = maxArgs == Integer.MAX_VALUE && index == types.size() - 1;
if (isRestArgument) {
return "..." + restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT);
}
return restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT) + "=";
} | java | private String getParameterJSDocType(List<JSType> types, int index, int minArgs, int maxArgs) {
JSType type = types.get(index);
if (index < minArgs) {
return type.toAnnotationString(Nullability.EXPLICIT);
}
boolean isRestArgument = maxArgs == Integer.MAX_VALUE && index == types.size() - 1;
if (isRestArgument) {
return "..." + restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT);
}
return restrictByUndefined(type).toAnnotationString(Nullability.EXPLICIT) + "=";
} | [
"private",
"String",
"getParameterJSDocType",
"(",
"List",
"<",
"JSType",
">",
"types",
",",
"int",
"index",
",",
"int",
"minArgs",
",",
"int",
"maxArgs",
")",
"{",
"JSType",
"type",
"=",
"types",
".",
"get",
"(",
"index",
")",
";",
"if",
"(",
"index",
"<",
"minArgs",
")",
"{",
"return",
"type",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
";",
"}",
"boolean",
"isRestArgument",
"=",
"maxArgs",
"==",
"Integer",
".",
"MAX_VALUE",
"&&",
"index",
"==",
"types",
".",
"size",
"(",
")",
"-",
"1",
";",
"if",
"(",
"isRestArgument",
")",
"{",
"return",
"\"...\"",
"+",
"restrictByUndefined",
"(",
"type",
")",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
";",
"}",
"return",
"restrictByUndefined",
"(",
"type",
")",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"EXPLICIT",
")",
"+",
"\"=\"",
";",
"}"
] | Creates a JSDoc-suitable String representation of the type of a parameter. | [
"Creates",
"a",
"JSDoc",
"-",
"suitable",
"String",
"representation",
"of",
"the",
"type",
"of",
"a",
"parameter",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L412-L422 |
google/error-prone-javac | src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java | MemoryFileManager.handleOption | @Override
public boolean handleOption(String current, Iterator<String> remaining) {
"""
Handles one option. If {@code current} is an option to this
file manager it will consume any arguments to that option from
{@code remaining} and return true, otherwise return false.
@param current current option
@param remaining remaining options
@return true if this option was handled by this file manager,
false otherwise
@throws IllegalArgumentException if this option to this file
manager is used incorrectly
@throws IllegalStateException if {@link #close} has been called
and this file manager cannot be reopened
"""
proc.debug(DBG_FMGR, "handleOption: current: %s\n", current +
", remaining: " + remaining);
return stdFileManager.handleOption(current, remaining);
} | java | @Override
public boolean handleOption(String current, Iterator<String> remaining) {
proc.debug(DBG_FMGR, "handleOption: current: %s\n", current +
", remaining: " + remaining);
return stdFileManager.handleOption(current, remaining);
} | [
"@",
"Override",
"public",
"boolean",
"handleOption",
"(",
"String",
"current",
",",
"Iterator",
"<",
"String",
">",
"remaining",
")",
"{",
"proc",
".",
"debug",
"(",
"DBG_FMGR",
",",
"\"handleOption: current: %s\\n\"",
",",
"current",
"+",
"\", remaining: \"",
"+",
"remaining",
")",
";",
"return",
"stdFileManager",
".",
"handleOption",
"(",
"current",
",",
"remaining",
")",
";",
"}"
] | Handles one option. If {@code current} is an option to this
file manager it will consume any arguments to that option from
{@code remaining} and return true, otherwise return false.
@param current current option
@param remaining remaining options
@return true if this option was handled by this file manager,
false otherwise
@throws IllegalArgumentException if this option to this file
manager is used incorrectly
@throws IllegalStateException if {@link #close} has been called
and this file manager cannot be reopened | [
"Handles",
"one",
"option",
".",
"If",
"{",
"@code",
"current",
"}",
"is",
"an",
"option",
"to",
"this",
"file",
"manager",
"it",
"will",
"consume",
"any",
"arguments",
"to",
"that",
"option",
"from",
"{",
"@code",
"remaining",
"}",
"and",
"return",
"true",
"otherwise",
"return",
"false",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java#L339-L344 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java | DrawerBuilder.withAccountHeader | public DrawerBuilder withAccountHeader(@NonNull AccountHeader accountHeader, boolean accountHeaderSticky) {
"""
Add a AccountSwitcherHeader which will be used in this drawer instance. Pass true if it should be sticky
NOTE: This will overwrite any set headerView or stickyHeaderView (depends on the boolean).
@param accountHeader
@param accountHeaderSticky
@return
"""
this.mAccountHeader = accountHeader;
this.mAccountHeaderSticky = accountHeaderSticky;
return this;
} | java | public DrawerBuilder withAccountHeader(@NonNull AccountHeader accountHeader, boolean accountHeaderSticky) {
this.mAccountHeader = accountHeader;
this.mAccountHeaderSticky = accountHeaderSticky;
return this;
} | [
"public",
"DrawerBuilder",
"withAccountHeader",
"(",
"@",
"NonNull",
"AccountHeader",
"accountHeader",
",",
"boolean",
"accountHeaderSticky",
")",
"{",
"this",
".",
"mAccountHeader",
"=",
"accountHeader",
";",
"this",
".",
"mAccountHeaderSticky",
"=",
"accountHeaderSticky",
";",
"return",
"this",
";",
"}"
] | Add a AccountSwitcherHeader which will be used in this drawer instance. Pass true if it should be sticky
NOTE: This will overwrite any set headerView or stickyHeaderView (depends on the boolean).
@param accountHeader
@param accountHeaderSticky
@return | [
"Add",
"a",
"AccountSwitcherHeader",
"which",
"will",
"be",
"used",
"in",
"this",
"drawer",
"instance",
".",
"Pass",
"true",
"if",
"it",
"should",
"be",
"sticky",
"NOTE",
":",
"This",
"will",
"overwrite",
"any",
"set",
"headerView",
"or",
"stickyHeaderView",
"(",
"depends",
"on",
"the",
"boolean",
")",
"."
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L480-L484 |
wisdom-framework/wisdom | core/content-manager/src/main/java/org/wisdom/content/jackson/JacksonSingleton.java | JacksonSingleton.stringify | public String stringify(JsonNode json) {
"""
Converts a JsonNode to its string representation.
This implementation use a `pretty printer`.
@param json the json node
@return the String representation of the given Json Object
@throws java.lang.RuntimeException if the String form cannot be created
"""
try {
return mapper().writerWithDefaultPrettyPrinter().writeValueAsString(json);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot stringify the input json node", e);
}
} | java | public String stringify(JsonNode json) {
try {
return mapper().writerWithDefaultPrettyPrinter().writeValueAsString(json);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot stringify the input json node", e);
}
} | [
"public",
"String",
"stringify",
"(",
"JsonNode",
"json",
")",
"{",
"try",
"{",
"return",
"mapper",
"(",
")",
".",
"writerWithDefaultPrettyPrinter",
"(",
")",
".",
"writeValueAsString",
"(",
"json",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot stringify the input json node\"",
",",
"e",
")",
";",
"}",
"}"
] | Converts a JsonNode to its string representation.
This implementation use a `pretty printer`.
@param json the json node
@return the String representation of the given Json Object
@throws java.lang.RuntimeException if the String form cannot be created | [
"Converts",
"a",
"JsonNode",
"to",
"its",
"string",
"representation",
".",
"This",
"implementation",
"use",
"a",
"pretty",
"printer",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/content-manager/src/main/java/org/wisdom/content/jackson/JacksonSingleton.java#L209-L215 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcSession.java | CmsUgcSession.createUploadResource | public CmsResource createUploadResource(String fieldName, String rawFileName, byte[] content)
throws CmsUgcException {
"""
Creates a new resource from upload data.<p>
@param fieldName the name of the form field for the upload
@param rawFileName the file name
@param content the file content
@return the newly created resource
@throws CmsUgcException if creating the resource fails
"""
CmsResource result = null;
CmsUgcSessionSecurityUtil.checkCreateUpload(m_cms, m_configuration, rawFileName, content.length);
String baseName = rawFileName;
// if the given name is a path, make sure we only get the last segment
int lastSlashPos = Math.max(baseName.lastIndexOf('/'), baseName.lastIndexOf('\\'));
if (lastSlashPos != -1) {
baseName = baseName.substring(1 + lastSlashPos);
}
// translate it so it doesn't contain illegal characters
baseName = OpenCms.getResourceManager().getFileTranslator().translateResource(baseName);
// add a macro before the file extension (if there is a file extension, otherwise just append it)
int dotPos = baseName.lastIndexOf('.');
if (dotPos == -1) {
baseName = baseName + "_%(random)";
} else {
baseName = baseName.substring(0, dotPos) + "_%(random)" + baseName.substring(dotPos);
}
// now prepend the upload folder's path
String uploadRootPath = m_configuration.getUploadParentFolder().get().getRootPath();
String sitePath = CmsStringUtil.joinPaths(m_cms.getRequestContext().removeSiteRoot(uploadRootPath), baseName);
// ... and replace the macro with random strings until we find a path that isn't already used
String realSitePath;
do {
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.addMacro("random", RandomStringUtils.random(8, "0123456789abcdefghijklmnopqrstuvwxyz"));
realSitePath = resolver.resolveMacros(sitePath);
} while (m_cms.existsResource(realSitePath));
try {
I_CmsResourceType resType = OpenCms.getResourceManager().getDefaultTypeForName(realSitePath);
result = m_cms.createResource(realSitePath, resType, content, null);
updateUploadResource(fieldName, result);
return result;
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
}
} | java | public CmsResource createUploadResource(String fieldName, String rawFileName, byte[] content)
throws CmsUgcException {
CmsResource result = null;
CmsUgcSessionSecurityUtil.checkCreateUpload(m_cms, m_configuration, rawFileName, content.length);
String baseName = rawFileName;
// if the given name is a path, make sure we only get the last segment
int lastSlashPos = Math.max(baseName.lastIndexOf('/'), baseName.lastIndexOf('\\'));
if (lastSlashPos != -1) {
baseName = baseName.substring(1 + lastSlashPos);
}
// translate it so it doesn't contain illegal characters
baseName = OpenCms.getResourceManager().getFileTranslator().translateResource(baseName);
// add a macro before the file extension (if there is a file extension, otherwise just append it)
int dotPos = baseName.lastIndexOf('.');
if (dotPos == -1) {
baseName = baseName + "_%(random)";
} else {
baseName = baseName.substring(0, dotPos) + "_%(random)" + baseName.substring(dotPos);
}
// now prepend the upload folder's path
String uploadRootPath = m_configuration.getUploadParentFolder().get().getRootPath();
String sitePath = CmsStringUtil.joinPaths(m_cms.getRequestContext().removeSiteRoot(uploadRootPath), baseName);
// ... and replace the macro with random strings until we find a path that isn't already used
String realSitePath;
do {
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.addMacro("random", RandomStringUtils.random(8, "0123456789abcdefghijklmnopqrstuvwxyz"));
realSitePath = resolver.resolveMacros(sitePath);
} while (m_cms.existsResource(realSitePath));
try {
I_CmsResourceType resType = OpenCms.getResourceManager().getDefaultTypeForName(realSitePath);
result = m_cms.createResource(realSitePath, resType, content, null);
updateUploadResource(fieldName, result);
return result;
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
}
} | [
"public",
"CmsResource",
"createUploadResource",
"(",
"String",
"fieldName",
",",
"String",
"rawFileName",
",",
"byte",
"[",
"]",
"content",
")",
"throws",
"CmsUgcException",
"{",
"CmsResource",
"result",
"=",
"null",
";",
"CmsUgcSessionSecurityUtil",
".",
"checkCreateUpload",
"(",
"m_cms",
",",
"m_configuration",
",",
"rawFileName",
",",
"content",
".",
"length",
")",
";",
"String",
"baseName",
"=",
"rawFileName",
";",
"// if the given name is a path, make sure we only get the last segment",
"int",
"lastSlashPos",
"=",
"Math",
".",
"max",
"(",
"baseName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
",",
"baseName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
";",
"if",
"(",
"lastSlashPos",
"!=",
"-",
"1",
")",
"{",
"baseName",
"=",
"baseName",
".",
"substring",
"(",
"1",
"+",
"lastSlashPos",
")",
";",
"}",
"// translate it so it doesn't contain illegal characters",
"baseName",
"=",
"OpenCms",
".",
"getResourceManager",
"(",
")",
".",
"getFileTranslator",
"(",
")",
".",
"translateResource",
"(",
"baseName",
")",
";",
"// add a macro before the file extension (if there is a file extension, otherwise just append it)",
"int",
"dotPos",
"=",
"baseName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"dotPos",
"==",
"-",
"1",
")",
"{",
"baseName",
"=",
"baseName",
"+",
"\"_%(random)\"",
";",
"}",
"else",
"{",
"baseName",
"=",
"baseName",
".",
"substring",
"(",
"0",
",",
"dotPos",
")",
"+",
"\"_%(random)\"",
"+",
"baseName",
".",
"substring",
"(",
"dotPos",
")",
";",
"}",
"// now prepend the upload folder's path",
"String",
"uploadRootPath",
"=",
"m_configuration",
".",
"getUploadParentFolder",
"(",
")",
".",
"get",
"(",
")",
".",
"getRootPath",
"(",
")",
";",
"String",
"sitePath",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"m_cms",
".",
"getRequestContext",
"(",
")",
".",
"removeSiteRoot",
"(",
"uploadRootPath",
")",
",",
"baseName",
")",
";",
"// ... and replace the macro with random strings until we find a path that isn't already used",
"String",
"realSitePath",
";",
"do",
"{",
"CmsMacroResolver",
"resolver",
"=",
"new",
"CmsMacroResolver",
"(",
")",
";",
"resolver",
".",
"addMacro",
"(",
"\"random\"",
",",
"RandomStringUtils",
".",
"random",
"(",
"8",
",",
"\"0123456789abcdefghijklmnopqrstuvwxyz\"",
")",
")",
";",
"realSitePath",
"=",
"resolver",
".",
"resolveMacros",
"(",
"sitePath",
")",
";",
"}",
"while",
"(",
"m_cms",
".",
"existsResource",
"(",
"realSitePath",
")",
")",
";",
"try",
"{",
"I_CmsResourceType",
"resType",
"=",
"OpenCms",
".",
"getResourceManager",
"(",
")",
".",
"getDefaultTypeForName",
"(",
"realSitePath",
")",
";",
"result",
"=",
"m_cms",
".",
"createResource",
"(",
"realSitePath",
",",
"resType",
",",
"content",
",",
"null",
")",
";",
"updateUploadResource",
"(",
"fieldName",
",",
"result",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"CmsException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getLocalizedMessage",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"CmsUgcException",
"(",
"e",
",",
"CmsUgcConstants",
".",
"ErrorCode",
".",
"errMisc",
",",
"e",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"}",
"}"
] | Creates a new resource from upload data.<p>
@param fieldName the name of the form field for the upload
@param rawFileName the file name
@param content the file content
@return the newly created resource
@throws CmsUgcException if creating the resource fails | [
"Creates",
"a",
"new",
"resource",
"from",
"upload",
"data",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSession.java#L243-L292 |
alkacon/opencms-core | src/org/opencms/xml/containerpage/CmsADECache.java | CmsADECache.getCacheGroupContainer | public CmsXmlGroupContainer getCacheGroupContainer(String key, boolean online) {
"""
Returns the cached group container under the given key and for the given project.<p>
@param key the cache key
@param online if cached in online or offline project
@return the cached group container or <code>null</code> if not found
"""
try {
m_lock.readLock().lock();
CmsXmlGroupContainer retValue;
if (online) {
retValue = m_groupContainersOnline.get(key);
if (LOG.isDebugEnabled()) {
if (retValue == null) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MISSED_ONLINE_1,
new Object[] {key}));
} else {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MATCHED_ONLINE_2,
new Object[] {key, retValue}));
}
}
} else {
retValue = m_groupContainersOffline.get(key);
if (LOG.isDebugEnabled()) {
if (retValue == null) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MISSED_OFFLINE_1,
new Object[] {key}));
} else {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MATCHED_OFFLINE_2,
new Object[] {key, retValue}));
}
}
}
return retValue;
} finally {
m_lock.readLock().unlock();
}
} | java | public CmsXmlGroupContainer getCacheGroupContainer(String key, boolean online) {
try {
m_lock.readLock().lock();
CmsXmlGroupContainer retValue;
if (online) {
retValue = m_groupContainersOnline.get(key);
if (LOG.isDebugEnabled()) {
if (retValue == null) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MISSED_ONLINE_1,
new Object[] {key}));
} else {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MATCHED_ONLINE_2,
new Object[] {key, retValue}));
}
}
} else {
retValue = m_groupContainersOffline.get(key);
if (LOG.isDebugEnabled()) {
if (retValue == null) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MISSED_OFFLINE_1,
new Object[] {key}));
} else {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_DEBUG_CACHE_MATCHED_OFFLINE_2,
new Object[] {key, retValue}));
}
}
}
return retValue;
} finally {
m_lock.readLock().unlock();
}
} | [
"public",
"CmsXmlGroupContainer",
"getCacheGroupContainer",
"(",
"String",
"key",
",",
"boolean",
"online",
")",
"{",
"try",
"{",
"m_lock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"CmsXmlGroupContainer",
"retValue",
";",
"if",
"(",
"online",
")",
"{",
"retValue",
"=",
"m_groupContainersOnline",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"if",
"(",
"retValue",
"==",
"null",
")",
"{",
"LOG",
".",
"debug",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"LOG_DEBUG_CACHE_MISSED_ONLINE_1",
",",
"new",
"Object",
"[",
"]",
"{",
"key",
"}",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"debug",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"LOG_DEBUG_CACHE_MATCHED_ONLINE_2",
",",
"new",
"Object",
"[",
"]",
"{",
"key",
",",
"retValue",
"}",
")",
")",
";",
"}",
"}",
"}",
"else",
"{",
"retValue",
"=",
"m_groupContainersOffline",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"if",
"(",
"retValue",
"==",
"null",
")",
"{",
"LOG",
".",
"debug",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"LOG_DEBUG_CACHE_MISSED_OFFLINE_1",
",",
"new",
"Object",
"[",
"]",
"{",
"key",
"}",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"debug",
"(",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
")",
".",
"key",
"(",
"Messages",
".",
"LOG_DEBUG_CACHE_MATCHED_OFFLINE_2",
",",
"new",
"Object",
"[",
"]",
"{",
"key",
",",
"retValue",
"}",
")",
")",
";",
"}",
"}",
"}",
"return",
"retValue",
";",
"}",
"finally",
"{",
"m_lock",
".",
"readLock",
"(",
")",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns the cached group container under the given key and for the given project.<p>
@param key the cache key
@param online if cached in online or offline project
@return the cached group container or <code>null</code> if not found | [
"Returns",
"the",
"cached",
"group",
"container",
"under",
"the",
"given",
"key",
"and",
"for",
"the",
"given",
"project",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsADECache.java#L185-L227 |
facebookarchive/hadoop-20 | src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/PoolManager.java | PoolManager.getMaxSlots | int getMaxSlots(String poolName, TaskType taskType) {
"""
Get the maximum map or reduce slots for the given pool.
@return the cap set on this pool, or Integer.MAX_VALUE if not set.
"""
Map<String, Integer> maxMap = (taskType == TaskType.MAP ?
poolMaxMaps : poolMaxReduces);
if (maxMap.containsKey(poolName)) {
return maxMap.get(poolName);
} else {
return Integer.MAX_VALUE;
}
} | java | int getMaxSlots(String poolName, TaskType taskType) {
Map<String, Integer> maxMap = (taskType == TaskType.MAP ?
poolMaxMaps : poolMaxReduces);
if (maxMap.containsKey(poolName)) {
return maxMap.get(poolName);
} else {
return Integer.MAX_VALUE;
}
} | [
"int",
"getMaxSlots",
"(",
"String",
"poolName",
",",
"TaskType",
"taskType",
")",
"{",
"Map",
"<",
"String",
",",
"Integer",
">",
"maxMap",
"=",
"(",
"taskType",
"==",
"TaskType",
".",
"MAP",
"?",
"poolMaxMaps",
":",
"poolMaxReduces",
")",
";",
"if",
"(",
"maxMap",
".",
"containsKey",
"(",
"poolName",
")",
")",
"{",
"return",
"maxMap",
".",
"get",
"(",
"poolName",
")",
";",
"}",
"else",
"{",
"return",
"Integer",
".",
"MAX_VALUE",
";",
"}",
"}"
] | Get the maximum map or reduce slots for the given pool.
@return the cap set on this pool, or Integer.MAX_VALUE if not set. | [
"Get",
"the",
"maximum",
"map",
"or",
"reduce",
"slots",
"for",
"the",
"given",
"pool",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/PoolManager.java#L693-L701 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java | JmesPathEvaluationVisitor.visit | @Override
public JsonNode visit(JmesPathMultiSelectList multiSelectList, JsonNode input) throws InvalidTypeException {
"""
Each expression in the multiselect list will be evaluated
against the JSON document. Each returned element will be the
result of evaluating the expression. A multi-select-list with
N expressions will result in a list of length N. Given a
multiselect expression [expr-1,expr-2,...,expr-n], the evaluated
expression will return [evaluate(expr-1), evaluate(expr-2), ...,evaluate(expr-n)].
@param multiSelectList JmesPath multiselect list type
@param input Input json node against which evaluation is done
@return Result of the multiselect list evaluation
@throws InvalidTypeException
"""
List<JmesPathExpression> expressionsList = multiSelectList.getExpressions();
ArrayNode evaluatedExprList = ObjectMapperSingleton.getObjectMapper().createArrayNode();
for (JmesPathExpression expression : expressionsList) {
evaluatedExprList.add(expression.accept(this, input));
}
return evaluatedExprList;
} | java | @Override
public JsonNode visit(JmesPathMultiSelectList multiSelectList, JsonNode input) throws InvalidTypeException {
List<JmesPathExpression> expressionsList = multiSelectList.getExpressions();
ArrayNode evaluatedExprList = ObjectMapperSingleton.getObjectMapper().createArrayNode();
for (JmesPathExpression expression : expressionsList) {
evaluatedExprList.add(expression.accept(this, input));
}
return evaluatedExprList;
} | [
"@",
"Override",
"public",
"JsonNode",
"visit",
"(",
"JmesPathMultiSelectList",
"multiSelectList",
",",
"JsonNode",
"input",
")",
"throws",
"InvalidTypeException",
"{",
"List",
"<",
"JmesPathExpression",
">",
"expressionsList",
"=",
"multiSelectList",
".",
"getExpressions",
"(",
")",
";",
"ArrayNode",
"evaluatedExprList",
"=",
"ObjectMapperSingleton",
".",
"getObjectMapper",
"(",
")",
".",
"createArrayNode",
"(",
")",
";",
"for",
"(",
"JmesPathExpression",
"expression",
":",
"expressionsList",
")",
"{",
"evaluatedExprList",
".",
"add",
"(",
"expression",
".",
"accept",
"(",
"this",
",",
"input",
")",
")",
";",
"}",
"return",
"evaluatedExprList",
";",
"}"
] | Each expression in the multiselect list will be evaluated
against the JSON document. Each returned element will be the
result of evaluating the expression. A multi-select-list with
N expressions will result in a list of length N. Given a
multiselect expression [expr-1,expr-2,...,expr-n], the evaluated
expression will return [evaluate(expr-1), evaluate(expr-2), ...,evaluate(expr-n)].
@param multiSelectList JmesPath multiselect list type
@param input Input json node against which evaluation is done
@return Result of the multiselect list evaluation
@throws InvalidTypeException | [
"Each",
"expression",
"in",
"the",
"multiselect",
"list",
"will",
"be",
"evaluated",
"against",
"the",
"JSON",
"document",
".",
"Each",
"returned",
"element",
"will",
"be",
"the",
"result",
"of",
"evaluating",
"the",
"expression",
".",
"A",
"multi",
"-",
"select",
"-",
"list",
"with",
"N",
"expressions",
"will",
"result",
"in",
"a",
"list",
"of",
"length",
"N",
".",
"Given",
"a",
"multiselect",
"expression",
"[",
"expr",
"-",
"1",
"expr",
"-",
"2",
"...",
"expr",
"-",
"n",
"]",
"the",
"evaluated",
"expression",
"will",
"return",
"[",
"evaluate",
"(",
"expr",
"-",
"1",
")",
"evaluate",
"(",
"expr",
"-",
"2",
")",
"...",
"evaluate",
"(",
"expr",
"-",
"n",
")",
"]",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java#L324-L332 |
landawn/AbacusUtil | src/com/landawn/abacus/util/N.java | N.removeAll | @SafeVarargs
public static double[] removeAll(final double[] a, final double... elements) {
"""
Returns a new array with removes all the occurrences of specified elements from <code>a</code>
@param a
@param elements
@return
@see Collection#removeAll(Collection)
"""
if (N.isNullOrEmpty(a)) {
return N.EMPTY_DOUBLE_ARRAY;
} else if (N.isNullOrEmpty(elements)) {
return a.clone();
} else if (elements.length == 1) {
return removeAllOccurrences(a, elements[0]);
}
final DoubleList list = DoubleList.of(a.clone());
list.removeAll(DoubleList.of(elements));
return list.trimToSize().array();
} | java | @SafeVarargs
public static double[] removeAll(final double[] a, final double... elements) {
if (N.isNullOrEmpty(a)) {
return N.EMPTY_DOUBLE_ARRAY;
} else if (N.isNullOrEmpty(elements)) {
return a.clone();
} else if (elements.length == 1) {
return removeAllOccurrences(a, elements[0]);
}
final DoubleList list = DoubleList.of(a.clone());
list.removeAll(DoubleList.of(elements));
return list.trimToSize().array();
} | [
"@",
"SafeVarargs",
"public",
"static",
"double",
"[",
"]",
"removeAll",
"(",
"final",
"double",
"[",
"]",
"a",
",",
"final",
"double",
"...",
"elements",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"a",
")",
")",
"{",
"return",
"N",
".",
"EMPTY_DOUBLE_ARRAY",
";",
"}",
"else",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"elements",
")",
")",
"{",
"return",
"a",
".",
"clone",
"(",
")",
";",
"}",
"else",
"if",
"(",
"elements",
".",
"length",
"==",
"1",
")",
"{",
"return",
"removeAllOccurrences",
"(",
"a",
",",
"elements",
"[",
"0",
"]",
")",
";",
"}",
"final",
"DoubleList",
"list",
"=",
"DoubleList",
".",
"of",
"(",
"a",
".",
"clone",
"(",
")",
")",
";",
"list",
".",
"removeAll",
"(",
"DoubleList",
".",
"of",
"(",
"elements",
")",
")",
";",
"return",
"list",
".",
"trimToSize",
"(",
")",
".",
"array",
"(",
")",
";",
"}"
] | Returns a new array with removes all the occurrences of specified elements from <code>a</code>
@param a
@param elements
@return
@see Collection#removeAll(Collection) | [
"Returns",
"a",
"new",
"array",
"with",
"removes",
"all",
"the",
"occurrences",
"of",
"specified",
"elements",
"from",
"<code",
">",
"a<",
"/",
"code",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L23512-L23525 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/UserApi.java | UserApi.addSshKey | public SshKey addSshKey(String title, String key) throws GitLabApiException {
"""
Creates a new key owned by the currently authenticated user.
<pre><code>GitLab Endpoint: POST /user/keys</code></pre>
@param title the new SSH Key's title
@param key the new SSH key
@return an SshKey instance with info on the added SSH key
@throws GitLabApiException if any exception occurs
"""
GitLabApiForm formData = new GitLabApiForm().withParam("title", title).withParam("key", key);
Response response = post(Response.Status.CREATED, formData, "user", "keys");
return (response.readEntity(SshKey.class));
} | java | public SshKey addSshKey(String title, String key) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("title", title).withParam("key", key);
Response response = post(Response.Status.CREATED, formData, "user", "keys");
return (response.readEntity(SshKey.class));
} | [
"public",
"SshKey",
"addSshKey",
"(",
"String",
"title",
",",
"String",
"key",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"title\"",
",",
"title",
")",
".",
"withParam",
"(",
"\"key\"",
",",
"key",
")",
";",
"Response",
"response",
"=",
"post",
"(",
"Response",
".",
"Status",
".",
"CREATED",
",",
"formData",
",",
"\"user\"",
",",
"\"keys\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"SshKey",
".",
"class",
")",
")",
";",
"}"
] | Creates a new key owned by the currently authenticated user.
<pre><code>GitLab Endpoint: POST /user/keys</code></pre>
@param title the new SSH Key's title
@param key the new SSH key
@return an SshKey instance with info on the added SSH key
@throws GitLabApiException if any exception occurs | [
"Creates",
"a",
"new",
"key",
"owned",
"by",
"the",
"currently",
"authenticated",
"user",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/UserApi.java#L656-L660 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/format/FastDatePrinter.java | FastDatePrinter.getTimeZoneDisplay | static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) {
"""
<p>
Gets the time zone display name, using a cache for performance.
</p>
@param tz the zone to query
@param daylight true if daylight savings
@param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
@param locale the locale to use
@return the textual name of the time zone
"""
final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
String value = cTimeZoneDisplayCache.get(key);
if (value == null) {
// This is a very slow call, so cache the results.
value = tz.getDisplayName(daylight, style, locale);
final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
if (prior != null) {
value = prior;
}
}
return value;
} | java | static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) {
final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
String value = cTimeZoneDisplayCache.get(key);
if (value == null) {
// This is a very slow call, so cache the results.
value = tz.getDisplayName(daylight, style, locale);
final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
if (prior != null) {
value = prior;
}
}
return value;
} | [
"static",
"String",
"getTimeZoneDisplay",
"(",
"final",
"TimeZone",
"tz",
",",
"final",
"boolean",
"daylight",
",",
"final",
"int",
"style",
",",
"final",
"Locale",
"locale",
")",
"{",
"final",
"TimeZoneDisplayKey",
"key",
"=",
"new",
"TimeZoneDisplayKey",
"(",
"tz",
",",
"daylight",
",",
"style",
",",
"locale",
")",
";",
"String",
"value",
"=",
"cTimeZoneDisplayCache",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"// This is a very slow call, so cache the results.",
"value",
"=",
"tz",
".",
"getDisplayName",
"(",
"daylight",
",",
"style",
",",
"locale",
")",
";",
"final",
"String",
"prior",
"=",
"cTimeZoneDisplayCache",
".",
"putIfAbsent",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"prior",
"!=",
"null",
")",
"{",
"value",
"=",
"prior",
";",
"}",
"}",
"return",
"value",
";",
"}"
] | <p>
Gets the time zone display name, using a cache for performance.
</p>
@param tz the zone to query
@param daylight true if daylight savings
@param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
@param locale the locale to use
@return the textual name of the time zone | [
"<p",
">",
"Gets",
"the",
"time",
"zone",
"display",
"name",
"using",
"a",
"cache",
"for",
"performance",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/format/FastDatePrinter.java#L1069-L1081 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/PrimaveraXERFileReader.java | PrimaveraXERFileReader.readRecord | private void readRecord(Tokenizer tk, List<String> record) throws IOException {
"""
Reads each token from a single record and adds it to a list.
@param tk tokenizer
@param record list of tokens
@throws IOException
"""
record.clear();
while (tk.nextToken() == Tokenizer.TT_WORD)
{
record.add(tk.getToken());
}
} | java | private void readRecord(Tokenizer tk, List<String> record) throws IOException
{
record.clear();
while (tk.nextToken() == Tokenizer.TT_WORD)
{
record.add(tk.getToken());
}
} | [
"private",
"void",
"readRecord",
"(",
"Tokenizer",
"tk",
",",
"List",
"<",
"String",
">",
"record",
")",
"throws",
"IOException",
"{",
"record",
".",
"clear",
"(",
")",
";",
"while",
"(",
"tk",
".",
"nextToken",
"(",
")",
"==",
"Tokenizer",
".",
"TT_WORD",
")",
"{",
"record",
".",
"add",
"(",
"tk",
".",
"getToken",
"(",
")",
")",
";",
"}",
"}"
] | Reads each token from a single record and adds it to a list.
@param tk tokenizer
@param record list of tokens
@throws IOException | [
"Reads",
"each",
"token",
"from",
"a",
"single",
"record",
"and",
"adds",
"it",
"to",
"a",
"list",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/PrimaveraXERFileReader.java#L529-L536 |
code4everything/util | src/main/java/com/zhazhapan/util/BeanUtils.java | BeanUtils.toJsonString | public static String toJsonString(Object object, FieldModifier modifier) throws IllegalAccessException {
"""
将Bean类指定修饰符的属性转换成JSON字符串
@param object Bean对象
@param modifier 属性的权限修饰符
@return 没有格式化的JSON字符串
@throws IllegalAccessException 异常
"""
return toJsonString(object, modifier, JsonMethod.AUTO);
} | java | public static String toJsonString(Object object, FieldModifier modifier) throws IllegalAccessException {
return toJsonString(object, modifier, JsonMethod.AUTO);
} | [
"public",
"static",
"String",
"toJsonString",
"(",
"Object",
"object",
",",
"FieldModifier",
"modifier",
")",
"throws",
"IllegalAccessException",
"{",
"return",
"toJsonString",
"(",
"object",
",",
"modifier",
",",
"JsonMethod",
".",
"AUTO",
")",
";",
"}"
] | 将Bean类指定修饰符的属性转换成JSON字符串
@param object Bean对象
@param modifier 属性的权限修饰符
@return 没有格式化的JSON字符串
@throws IllegalAccessException 异常 | [
"将Bean类指定修饰符的属性转换成JSON字符串"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/BeanUtils.java#L286-L288 |
ZuInnoTe/hadoopcryptoledger | inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java | BitcoinBlockReader.parseTransactionOutputs | public List<BitcoinTransactionOutput> parseTransactionOutputs(ByteBuffer rawByteBuffer, long noOfTransactionOutputs) {
"""
/*
Parses the Bitcoin transaction outputs in a byte buffer.
@param rawByteBuffer ByteBuffer from which the transaction outputs have to be parsed
@param noOfTransactionInputs Number of expected transaction outputs
@return Array of transactions
"""
ArrayList<BitcoinTransactionOutput> currentTransactionOutput = new ArrayList<>((int)(noOfTransactionOutputs));
for (int i=0;i<noOfTransactionOutputs;i++) {
// read value
byte[] currentTransactionOutputValueArray = new byte[8];
rawByteBuffer.get(currentTransactionOutputValueArray);
BigInteger currentTransactionOutputValue = new BigInteger(1,EthereumUtil.reverseByteArray(currentTransactionOutputValueArray));
// read outScript length (Potential Internal Exceed Java Type)
byte[] currentTransactionTxOutScriptLengthVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer);
long currentTransactionTxOutScriptSize=BitcoinUtil.getVarInt(currentTransactionTxOutScriptLengthVarInt);
int currentTransactionTxOutScriptSizeInt=(int)(currentTransactionTxOutScriptSize);
// read outScript
byte[] currentTransactionOutScript=new byte[currentTransactionTxOutScriptSizeInt];
rawByteBuffer.get(currentTransactionOutScript,0,currentTransactionTxOutScriptSizeInt);
currentTransactionOutput.add(new BitcoinTransactionOutput(currentTransactionOutputValue,currentTransactionTxOutScriptLengthVarInt,currentTransactionOutScript));
}
return currentTransactionOutput;
} | java | public List<BitcoinTransactionOutput> parseTransactionOutputs(ByteBuffer rawByteBuffer, long noOfTransactionOutputs) {
ArrayList<BitcoinTransactionOutput> currentTransactionOutput = new ArrayList<>((int)(noOfTransactionOutputs));
for (int i=0;i<noOfTransactionOutputs;i++) {
// read value
byte[] currentTransactionOutputValueArray = new byte[8];
rawByteBuffer.get(currentTransactionOutputValueArray);
BigInteger currentTransactionOutputValue = new BigInteger(1,EthereumUtil.reverseByteArray(currentTransactionOutputValueArray));
// read outScript length (Potential Internal Exceed Java Type)
byte[] currentTransactionTxOutScriptLengthVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer);
long currentTransactionTxOutScriptSize=BitcoinUtil.getVarInt(currentTransactionTxOutScriptLengthVarInt);
int currentTransactionTxOutScriptSizeInt=(int)(currentTransactionTxOutScriptSize);
// read outScript
byte[] currentTransactionOutScript=new byte[currentTransactionTxOutScriptSizeInt];
rawByteBuffer.get(currentTransactionOutScript,0,currentTransactionTxOutScriptSizeInt);
currentTransactionOutput.add(new BitcoinTransactionOutput(currentTransactionOutputValue,currentTransactionTxOutScriptLengthVarInt,currentTransactionOutScript));
}
return currentTransactionOutput;
} | [
"public",
"List",
"<",
"BitcoinTransactionOutput",
">",
"parseTransactionOutputs",
"(",
"ByteBuffer",
"rawByteBuffer",
",",
"long",
"noOfTransactionOutputs",
")",
"{",
"ArrayList",
"<",
"BitcoinTransactionOutput",
">",
"currentTransactionOutput",
"=",
"new",
"ArrayList",
"<>",
"(",
"(",
"int",
")",
"(",
"noOfTransactionOutputs",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"noOfTransactionOutputs",
";",
"i",
"++",
")",
"{",
"// read value",
"byte",
"[",
"]",
"currentTransactionOutputValueArray",
"=",
"new",
"byte",
"[",
"8",
"]",
";",
"rawByteBuffer",
".",
"get",
"(",
"currentTransactionOutputValueArray",
")",
";",
"BigInteger",
"currentTransactionOutputValue",
"=",
"new",
"BigInteger",
"(",
"1",
",",
"EthereumUtil",
".",
"reverseByteArray",
"(",
"currentTransactionOutputValueArray",
")",
")",
";",
"// read outScript length (Potential Internal Exceed Java Type)",
"byte",
"[",
"]",
"currentTransactionTxOutScriptLengthVarInt",
"=",
"BitcoinUtil",
".",
"convertVarIntByteBufferToByteArray",
"(",
"rawByteBuffer",
")",
";",
"long",
"currentTransactionTxOutScriptSize",
"=",
"BitcoinUtil",
".",
"getVarInt",
"(",
"currentTransactionTxOutScriptLengthVarInt",
")",
";",
"int",
"currentTransactionTxOutScriptSizeInt",
"=",
"(",
"int",
")",
"(",
"currentTransactionTxOutScriptSize",
")",
";",
"// read outScript",
"byte",
"[",
"]",
"currentTransactionOutScript",
"=",
"new",
"byte",
"[",
"currentTransactionTxOutScriptSizeInt",
"]",
";",
"rawByteBuffer",
".",
"get",
"(",
"currentTransactionOutScript",
",",
"0",
",",
"currentTransactionTxOutScriptSizeInt",
")",
";",
"currentTransactionOutput",
".",
"add",
"(",
"new",
"BitcoinTransactionOutput",
"(",
"currentTransactionOutputValue",
",",
"currentTransactionTxOutScriptLengthVarInt",
",",
"currentTransactionOutScript",
")",
")",
";",
"}",
"return",
"currentTransactionOutput",
";",
"}"
] | /*
Parses the Bitcoin transaction outputs in a byte buffer.
@param rawByteBuffer ByteBuffer from which the transaction outputs have to be parsed
@param noOfTransactionInputs Number of expected transaction outputs
@return Array of transactions | [
"/",
"*",
"Parses",
"the",
"Bitcoin",
"transaction",
"outputs",
"in",
"a",
"byte",
"buffer",
"."
] | train | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java#L406-L424 |
belaban/JGroups | src/org/jgroups/View.java | View.sameMembersOrdered | public static boolean sameMembersOrdered(View v1, View v2) {
"""
Checks if two views have the same members observing order. E.g. {A,B,C} and {B,A,C} returns false,
{A,C,B} and {A,C,B} returns true
"""
return Arrays.equals(v1.getMembersRaw(), v2.getMembersRaw());
} | java | public static boolean sameMembersOrdered(View v1, View v2) {
return Arrays.equals(v1.getMembersRaw(), v2.getMembersRaw());
} | [
"public",
"static",
"boolean",
"sameMembersOrdered",
"(",
"View",
"v1",
",",
"View",
"v2",
")",
"{",
"return",
"Arrays",
".",
"equals",
"(",
"v1",
".",
"getMembersRaw",
"(",
")",
",",
"v2",
".",
"getMembersRaw",
"(",
")",
")",
";",
"}"
] | Checks if two views have the same members observing order. E.g. {A,B,C} and {B,A,C} returns false,
{A,C,B} and {A,C,B} returns true | [
"Checks",
"if",
"two",
"views",
"have",
"the",
"same",
"members",
"observing",
"order",
".",
"E",
".",
"g",
".",
"{",
"A",
"B",
"C",
"}",
"and",
"{",
"B",
"A",
"C",
"}",
"returns",
"false",
"{",
"A",
"C",
"B",
"}",
"and",
"{",
"A",
"C",
"B",
"}",
"returns",
"true"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/View.java#L311-L313 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addSuccessUpdateDesignJspFile | public FessMessages addSuccessUpdateDesignJspFile(String property, String arg0) {
"""
Add the created action message for the key 'success.update_design_jsp_file' with parameters.
<pre>
message: Updated {0}.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull)
"""
assertPropertyNotNull(property);
add(property, new UserMessage(SUCCESS_update_design_jsp_file, arg0));
return this;
} | java | public FessMessages addSuccessUpdateDesignJspFile(String property, String arg0) {
assertPropertyNotNull(property);
add(property, new UserMessage(SUCCESS_update_design_jsp_file, arg0));
return this;
} | [
"public",
"FessMessages",
"addSuccessUpdateDesignJspFile",
"(",
"String",
"property",
",",
"String",
"arg0",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"SUCCESS_update_design_jsp_file",
",",
"arg0",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add the created action message for the key 'success.update_design_jsp_file' with parameters.
<pre>
message: Updated {0}.
</pre>
@param property The property name for the message. (NotNull)
@param arg0 The parameter arg0 for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"success",
".",
"update_design_jsp_file",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"Updated",
"{",
"0",
"}",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2346-L2350 |
alkacon/opencms-core | src/org/opencms/ui/apps/resourcetypes/CmsResourceTypesTable.java | CmsResourceTypesTable.onItemClick | @SuppressWarnings("unchecked")
void onItemClick(MouseEvents.ClickEvent event, Object itemId, Object propertyId) {
"""
Handles the table item clicks, including clicks on images inside of a table item.<p>
@param event the click event
@param itemId of the clicked row
@param propertyId column id
"""
if (!event.isCtrlKey() && !event.isShiftKey()) {
changeValueIfNotMultiSelect(itemId);
// don't interfere with multi-selection using control key
if (event.getButton().equals(MouseButton.RIGHT) || (propertyId == null)) {
m_menu.setEntries(getMenuEntries(), (Set<String>)getValue());
m_menu.openForTable(event, itemId, propertyId, this);
} else if (event.getButton().equals(MouseButton.LEFT) && TableProperty.Name.equals(propertyId)) {
String typeName = (String)itemId;
openEditDialog(typeName);
}
}
} | java | @SuppressWarnings("unchecked")
void onItemClick(MouseEvents.ClickEvent event, Object itemId, Object propertyId) {
if (!event.isCtrlKey() && !event.isShiftKey()) {
changeValueIfNotMultiSelect(itemId);
// don't interfere with multi-selection using control key
if (event.getButton().equals(MouseButton.RIGHT) || (propertyId == null)) {
m_menu.setEntries(getMenuEntries(), (Set<String>)getValue());
m_menu.openForTable(event, itemId, propertyId, this);
} else if (event.getButton().equals(MouseButton.LEFT) && TableProperty.Name.equals(propertyId)) {
String typeName = (String)itemId;
openEditDialog(typeName);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"void",
"onItemClick",
"(",
"MouseEvents",
".",
"ClickEvent",
"event",
",",
"Object",
"itemId",
",",
"Object",
"propertyId",
")",
"{",
"if",
"(",
"!",
"event",
".",
"isCtrlKey",
"(",
")",
"&&",
"!",
"event",
".",
"isShiftKey",
"(",
")",
")",
"{",
"changeValueIfNotMultiSelect",
"(",
"itemId",
")",
";",
"// don't interfere with multi-selection using control key",
"if",
"(",
"event",
".",
"getButton",
"(",
")",
".",
"equals",
"(",
"MouseButton",
".",
"RIGHT",
")",
"||",
"(",
"propertyId",
"==",
"null",
")",
")",
"{",
"m_menu",
".",
"setEntries",
"(",
"getMenuEntries",
"(",
")",
",",
"(",
"Set",
"<",
"String",
">",
")",
"getValue",
"(",
")",
")",
";",
"m_menu",
".",
"openForTable",
"(",
"event",
",",
"itemId",
",",
"propertyId",
",",
"this",
")",
";",
"}",
"else",
"if",
"(",
"event",
".",
"getButton",
"(",
")",
".",
"equals",
"(",
"MouseButton",
".",
"LEFT",
")",
"&&",
"TableProperty",
".",
"Name",
".",
"equals",
"(",
"propertyId",
")",
")",
"{",
"String",
"typeName",
"=",
"(",
"String",
")",
"itemId",
";",
"openEditDialog",
"(",
"typeName",
")",
";",
"}",
"}",
"}"
] | Handles the table item clicks, including clicks on images inside of a table item.<p>
@param event the click event
@param itemId of the clicked row
@param propertyId column id | [
"Handles",
"the",
"table",
"item",
"clicks",
"including",
"clicks",
"on",
"images",
"inside",
"of",
"a",
"table",
"item",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/resourcetypes/CmsResourceTypesTable.java#L701-L715 |
morimekta/utils | io-util/src/main/java/net/morimekta/util/Strings.java | Strings.asString | public static String asString(Map<?, ?> map) {
"""
Make a minimal printable string value from a typed map.
@param map The map to stringify.
@return The resulting string.
"""
if (map == null) {
return NULL;
}
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(',');
}
builder.append(asString(entry.getKey()))
.append(':')
.append(asString(entry.getValue()));
}
builder.append('}');
return builder.toString();
} | java | public static String asString(Map<?, ?> map) {
if (map == null) {
return NULL;
}
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(',');
}
builder.append(asString(entry.getKey()))
.append(':')
.append(asString(entry.getValue()));
}
builder.append('}');
return builder.toString();
} | [
"public",
"static",
"String",
"asString",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"map",
")",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"return",
"NULL",
";",
"}",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"boolean",
"first",
"=",
"true",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"?",
",",
"?",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"first",
")",
"{",
"first",
"=",
"false",
";",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"}",
"builder",
".",
"append",
"(",
"asString",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"asString",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | Make a minimal printable string value from a typed map.
@param map The map to stringify.
@return The resulting string. | [
"Make",
"a",
"minimal",
"printable",
"string",
"value",
"from",
"a",
"typed",
"map",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Strings.java#L608-L627 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/msgstore/gbs/GBSTree.java | GBSTree.getNode | GBSNode getNode(Object newKey) {
"""
Allocate a new node for the tree.
@param newKey The initial key for the new node.
@return The new node.
"""
GBSNode p;
if (_nodePool == null)
p = new GBSNode(this, newKey);
else
{
p = _nodePool;
_nodePool = p.rightChild();
p.reset(newKey);
}
return p;
} | java | GBSNode getNode(Object newKey)
{
GBSNode p;
if (_nodePool == null)
p = new GBSNode(this, newKey);
else
{
p = _nodePool;
_nodePool = p.rightChild();
p.reset(newKey);
}
return p;
} | [
"GBSNode",
"getNode",
"(",
"Object",
"newKey",
")",
"{",
"GBSNode",
"p",
";",
"if",
"(",
"_nodePool",
"==",
"null",
")",
"p",
"=",
"new",
"GBSNode",
"(",
"this",
",",
"newKey",
")",
";",
"else",
"{",
"p",
"=",
"_nodePool",
";",
"_nodePool",
"=",
"p",
".",
"rightChild",
"(",
")",
";",
"p",
".",
"reset",
"(",
"newKey",
")",
";",
"}",
"return",
"p",
";",
"}"
] | Allocate a new node for the tree.
@param newKey The initial key for the new node.
@return The new node. | [
"Allocate",
"a",
"new",
"node",
"for",
"the",
"tree",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/msgstore/gbs/GBSTree.java#L344-L356 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/util/ColorUtils.java | ColorUtils.HSVtoRGB | public static Color HSVtoRGB (float h, float s, float v, float alpha) {
"""
Converts HSV to RGB
@param h hue 0-360
@param s saturation 0-100
@param v value 0-100
@param alpha 0-1
@return RGB values in LibGDX {@link Color} class
"""
Color c = HSVtoRGB(h, s, v);
c.a = alpha;
return c;
} | java | public static Color HSVtoRGB (float h, float s, float v, float alpha) {
Color c = HSVtoRGB(h, s, v);
c.a = alpha;
return c;
} | [
"public",
"static",
"Color",
"HSVtoRGB",
"(",
"float",
"h",
",",
"float",
"s",
",",
"float",
"v",
",",
"float",
"alpha",
")",
"{",
"Color",
"c",
"=",
"HSVtoRGB",
"(",
"h",
",",
"s",
",",
"v",
")",
";",
"c",
".",
"a",
"=",
"alpha",
";",
"return",
"c",
";",
"}"
] | Converts HSV to RGB
@param h hue 0-360
@param s saturation 0-100
@param v value 0-100
@param alpha 0-1
@return RGB values in LibGDX {@link Color} class | [
"Converts",
"HSV",
"to",
"RGB"
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/util/ColorUtils.java#L36-L40 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFSubstitution.java | NFSubstitution.doSubstitution | public void doSubstitution(double number, StringBuilder toInsertInto, int position, int recursionCount) {
"""
Performs a mathematical operation on the number, formats it using
either ruleSet or decimalFormat, and inserts the result into
toInsertInto.
@param number The number being formatted.
@param toInsertInto The string we insert the result into
@param position The position in toInsertInto where the owning rule's
rule text begins (this value is added to this substitution's
position to determine exactly where to insert the new text)
"""
// perform a transformation on the number being formatted that
// is dependent on the type of substitution this is
double numberToFormat = transformNumber(number);
if (Double.isInfinite(numberToFormat)) {
// This is probably a minus rule. Combine it with an infinite rule.
NFRule infiniteRule = ruleSet.findRule(Double.POSITIVE_INFINITY);
infiniteRule.doFormat(numberToFormat, toInsertInto, position + pos, recursionCount);
return;
}
// if the result is an integer, from here on out we work in integer
// space (saving time and memory and preserving accuracy)
if (numberToFormat == Math.floor(numberToFormat) && ruleSet != null) {
ruleSet.format((long)numberToFormat, toInsertInto, position + pos, recursionCount);
// if the result isn't an integer, then call either our rule set's
// format() method or our DecimalFormat's format() method to
// format the result
} else {
if (ruleSet != null) {
ruleSet.format(numberToFormat, toInsertInto, position + pos, recursionCount);
} else {
toInsertInto.insert(position + this.pos, numberFormat.format(numberToFormat));
}
}
} | java | public void doSubstitution(double number, StringBuilder toInsertInto, int position, int recursionCount) {
// perform a transformation on the number being formatted that
// is dependent on the type of substitution this is
double numberToFormat = transformNumber(number);
if (Double.isInfinite(numberToFormat)) {
// This is probably a minus rule. Combine it with an infinite rule.
NFRule infiniteRule = ruleSet.findRule(Double.POSITIVE_INFINITY);
infiniteRule.doFormat(numberToFormat, toInsertInto, position + pos, recursionCount);
return;
}
// if the result is an integer, from here on out we work in integer
// space (saving time and memory and preserving accuracy)
if (numberToFormat == Math.floor(numberToFormat) && ruleSet != null) {
ruleSet.format((long)numberToFormat, toInsertInto, position + pos, recursionCount);
// if the result isn't an integer, then call either our rule set's
// format() method or our DecimalFormat's format() method to
// format the result
} else {
if (ruleSet != null) {
ruleSet.format(numberToFormat, toInsertInto, position + pos, recursionCount);
} else {
toInsertInto.insert(position + this.pos, numberFormat.format(numberToFormat));
}
}
} | [
"public",
"void",
"doSubstitution",
"(",
"double",
"number",
",",
"StringBuilder",
"toInsertInto",
",",
"int",
"position",
",",
"int",
"recursionCount",
")",
"{",
"// perform a transformation on the number being formatted that",
"// is dependent on the type of substitution this is",
"double",
"numberToFormat",
"=",
"transformNumber",
"(",
"number",
")",
";",
"if",
"(",
"Double",
".",
"isInfinite",
"(",
"numberToFormat",
")",
")",
"{",
"// This is probably a minus rule. Combine it with an infinite rule.",
"NFRule",
"infiniteRule",
"=",
"ruleSet",
".",
"findRule",
"(",
"Double",
".",
"POSITIVE_INFINITY",
")",
";",
"infiniteRule",
".",
"doFormat",
"(",
"numberToFormat",
",",
"toInsertInto",
",",
"position",
"+",
"pos",
",",
"recursionCount",
")",
";",
"return",
";",
"}",
"// if the result is an integer, from here on out we work in integer",
"// space (saving time and memory and preserving accuracy)",
"if",
"(",
"numberToFormat",
"==",
"Math",
".",
"floor",
"(",
"numberToFormat",
")",
"&&",
"ruleSet",
"!=",
"null",
")",
"{",
"ruleSet",
".",
"format",
"(",
"(",
"long",
")",
"numberToFormat",
",",
"toInsertInto",
",",
"position",
"+",
"pos",
",",
"recursionCount",
")",
";",
"// if the result isn't an integer, then call either our rule set's",
"// format() method or our DecimalFormat's format() method to",
"// format the result",
"}",
"else",
"{",
"if",
"(",
"ruleSet",
"!=",
"null",
")",
"{",
"ruleSet",
".",
"format",
"(",
"numberToFormat",
",",
"toInsertInto",
",",
"position",
"+",
"pos",
",",
"recursionCount",
")",
";",
"}",
"else",
"{",
"toInsertInto",
".",
"insert",
"(",
"position",
"+",
"this",
".",
"pos",
",",
"numberFormat",
".",
"format",
"(",
"numberToFormat",
")",
")",
";",
"}",
"}",
"}"
] | Performs a mathematical operation on the number, formats it using
either ruleSet or decimalFormat, and inserts the result into
toInsertInto.
@param number The number being formatted.
@param toInsertInto The string we insert the result into
@param position The position in toInsertInto where the owning rule's
rule text begins (this value is added to this substitution's
position to determine exactly where to insert the new text) | [
"Performs",
"a",
"mathematical",
"operation",
"on",
"the",
"number",
"formats",
"it",
"using",
"either",
"ruleSet",
"or",
"decimalFormat",
"and",
"inserts",
"the",
"result",
"into",
"toInsertInto",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFSubstitution.java#L316-L343 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMParser.java | OSMParser.checkOSMTables | private void checkOSMTables(Connection connection, boolean isH2, TableLocation requestedTable, String osmTableName) throws SQLException {
"""
Check if one table already exists
@param connection
@param isH2
@param requestedTable
@param osmTableName
@throws SQLException
"""
String[] omsTables = new String[]{OSMTablesFactory.TAG, OSMTablesFactory.NODE, OSMTablesFactory.NODE_TAG, OSMTablesFactory.WAY, OSMTablesFactory.WAY_NODE,
OSMTablesFactory.WAY_TAG, OSMTablesFactory.RELATION, OSMTablesFactory.RELATION_TAG, OSMTablesFactory.NODE_MEMBER, OSMTablesFactory.WAY_MEMBER, OSMTablesFactory.RELATION_MEMBER};
for (String omsTableSuffix : omsTables) {
String osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
if (JDBCUtilities.tableExists(connection, osmTable)) {
throw new SQLException("The table " + osmTable + " already exists.");
}
}
} | java | private void checkOSMTables(Connection connection, boolean isH2, TableLocation requestedTable, String osmTableName) throws SQLException {
String[] omsTables = new String[]{OSMTablesFactory.TAG, OSMTablesFactory.NODE, OSMTablesFactory.NODE_TAG, OSMTablesFactory.WAY, OSMTablesFactory.WAY_NODE,
OSMTablesFactory.WAY_TAG, OSMTablesFactory.RELATION, OSMTablesFactory.RELATION_TAG, OSMTablesFactory.NODE_MEMBER, OSMTablesFactory.WAY_MEMBER, OSMTablesFactory.RELATION_MEMBER};
for (String omsTableSuffix : omsTables) {
String osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
if (JDBCUtilities.tableExists(connection, osmTable)) {
throw new SQLException("The table " + osmTable + " already exists.");
}
}
} | [
"private",
"void",
"checkOSMTables",
"(",
"Connection",
"connection",
",",
"boolean",
"isH2",
",",
"TableLocation",
"requestedTable",
",",
"String",
"osmTableName",
")",
"throws",
"SQLException",
"{",
"String",
"[",
"]",
"omsTables",
"=",
"new",
"String",
"[",
"]",
"{",
"OSMTablesFactory",
".",
"TAG",
",",
"OSMTablesFactory",
".",
"NODE",
",",
"OSMTablesFactory",
".",
"NODE_TAG",
",",
"OSMTablesFactory",
".",
"WAY",
",",
"OSMTablesFactory",
".",
"WAY_NODE",
",",
"OSMTablesFactory",
".",
"WAY_TAG",
",",
"OSMTablesFactory",
".",
"RELATION",
",",
"OSMTablesFactory",
".",
"RELATION_TAG",
",",
"OSMTablesFactory",
".",
"NODE_MEMBER",
",",
"OSMTablesFactory",
".",
"WAY_MEMBER",
",",
"OSMTablesFactory",
".",
"RELATION_MEMBER",
"}",
";",
"for",
"(",
"String",
"omsTableSuffix",
":",
"omsTables",
")",
"{",
"String",
"osmTable",
"=",
"TableUtilities",
".",
"caseIdentifier",
"(",
"requestedTable",
",",
"osmTableName",
"+",
"omsTableSuffix",
",",
"isH2",
")",
";",
"if",
"(",
"JDBCUtilities",
".",
"tableExists",
"(",
"connection",
",",
"osmTable",
")",
")",
"{",
"throw",
"new",
"SQLException",
"(",
"\"The table \"",
"+",
"osmTable",
"+",
"\" already exists.\"",
")",
";",
"}",
"}",
"}"
] | Check if one table already exists
@param connection
@param isH2
@param requestedTable
@param osmTableName
@throws SQLException | [
"Check",
"if",
"one",
"table",
"already",
"exists"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMParser.java#L212-L221 |
mangstadt/biweekly | src/main/java/biweekly/io/json/JCalRawWriter.java | JCalRawWriter.writeProperty | public void writeProperty(String propertyName, ICalDataType dataType, JCalValue value) throws IOException {
"""
Writes a property to the current component.
@param propertyName the property name (e.g. "version")
@param dataType the property's data type (e.g. "text")
@param value the property value
@throws IllegalStateException if there are no open components (
{@link #writeStartComponent(String)} must be called first) or if the last
method called was {@link #writeEndComponent()}.
@throws IOException if there's an I/O problem
"""
writeProperty(propertyName, new ICalParameters(), dataType, value);
} | java | public void writeProperty(String propertyName, ICalDataType dataType, JCalValue value) throws IOException {
writeProperty(propertyName, new ICalParameters(), dataType, value);
} | [
"public",
"void",
"writeProperty",
"(",
"String",
"propertyName",
",",
"ICalDataType",
"dataType",
",",
"JCalValue",
"value",
")",
"throws",
"IOException",
"{",
"writeProperty",
"(",
"propertyName",
",",
"new",
"ICalParameters",
"(",
")",
",",
"dataType",
",",
"value",
")",
";",
"}"
] | Writes a property to the current component.
@param propertyName the property name (e.g. "version")
@param dataType the property's data type (e.g. "text")
@param value the property value
@throws IllegalStateException if there are no open components (
{@link #writeStartComponent(String)} must be called first) or if the last
method called was {@link #writeEndComponent()}.
@throws IOException if there's an I/O problem | [
"Writes",
"a",
"property",
"to",
"the",
"current",
"component",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/io/json/JCalRawWriter.java#L177-L179 |
galenframework/galen | galen-core/src/main/java/com/galenframework/specs/page/PageSpec.java | PageSpec.setObjects | public void setObjects(Map<String, Locator> objects) {
"""
Clears current objects list and sets new object list
@param objects
"""
this.objects.clear();
if (objects != null) {
this.objects.putAll(objects);
}
} | java | public void setObjects(Map<String, Locator> objects) {
this.objects.clear();
if (objects != null) {
this.objects.putAll(objects);
}
} | [
"public",
"void",
"setObjects",
"(",
"Map",
"<",
"String",
",",
"Locator",
">",
"objects",
")",
"{",
"this",
".",
"objects",
".",
"clear",
"(",
")",
";",
"if",
"(",
"objects",
"!=",
"null",
")",
"{",
"this",
".",
"objects",
".",
"putAll",
"(",
"objects",
")",
";",
"}",
"}"
] | Clears current objects list and sets new object list
@param objects | [
"Clears",
"current",
"objects",
"list",
"and",
"sets",
"new",
"object",
"list"
] | train | https://github.com/galenframework/galen/blob/6c7dc1f11d097e6aa49c45d6a77ee688741657a4/galen-core/src/main/java/com/galenframework/specs/page/PageSpec.java#L52-L57 |
threerings/narya | core/src/main/java/com/threerings/crowd/server/BodyManager.java | BodyManager.updateOccupantStatus | public void updateOccupantStatus (BodyObject body, final byte status) {
"""
Updates the connection status for the given body object's occupant info in the specified
location.
"""
// no need to NOOP
if (body.status != status) {
// update the status in their body object
body.setStatus(status);
body.getLocal(BodyLocal.class).statusTime = System.currentTimeMillis();
}
updateOccupantInfo(body, new OccupantInfo.Updater<OccupantInfo>() {
public boolean update (OccupantInfo info) {
if (info.status == status) {
return false;
}
info.status = status;
return true;
}
});
} | java | public void updateOccupantStatus (BodyObject body, final byte status)
{
// no need to NOOP
if (body.status != status) {
// update the status in their body object
body.setStatus(status);
body.getLocal(BodyLocal.class).statusTime = System.currentTimeMillis();
}
updateOccupantInfo(body, new OccupantInfo.Updater<OccupantInfo>() {
public boolean update (OccupantInfo info) {
if (info.status == status) {
return false;
}
info.status = status;
return true;
}
});
} | [
"public",
"void",
"updateOccupantStatus",
"(",
"BodyObject",
"body",
",",
"final",
"byte",
"status",
")",
"{",
"// no need to NOOP",
"if",
"(",
"body",
".",
"status",
"!=",
"status",
")",
"{",
"// update the status in their body object",
"body",
".",
"setStatus",
"(",
"status",
")",
";",
"body",
".",
"getLocal",
"(",
"BodyLocal",
".",
"class",
")",
".",
"statusTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"}",
"updateOccupantInfo",
"(",
"body",
",",
"new",
"OccupantInfo",
".",
"Updater",
"<",
"OccupantInfo",
">",
"(",
")",
"{",
"public",
"boolean",
"update",
"(",
"OccupantInfo",
"info",
")",
"{",
"if",
"(",
"info",
".",
"status",
"==",
"status",
")",
"{",
"return",
"false",
";",
"}",
"info",
".",
"status",
"=",
"status",
";",
"return",
"true",
";",
"}",
"}",
")",
";",
"}"
] | Updates the connection status for the given body object's occupant info in the specified
location. | [
"Updates",
"the",
"connection",
"status",
"for",
"the",
"given",
"body",
"object",
"s",
"occupant",
"info",
"in",
"the",
"specified",
"location",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/BodyManager.java#L68-L86 |
JCTools/JCTools | jctools-experimental/src/main/java/org/jctools/sets/SingleWriterHashSet.java | SingleWriterHashSet.compactAndRemove | private void compactAndRemove(final E[] buffer, final long mask, int removeHashIndex) {
"""
/*
implemented as per wiki suggested algo with minor adjustments.
"""
// remove(9a): [9a,9b,10a,9c,10b,11a,null] -> [9b,10a,9c,10b,11a,null,null]
removeHashIndex = (int) (removeHashIndex & mask);
int j = removeHashIndex;
// every compaction is guarded by two mod count increments: one before and one after actual compaction
UNSAFE.putOrderedLong(this, MC_OFFSET, modCount + 1);
while (true) {
int k;
E slotJ;
// skip elements which belong where they are
do {
// j := (j+1) modulo num_slots
j = (int) ((j + 1) & mask);
slotJ = lpElement(buffer, calcElementOffset(j, mask));
// if slot[j] is unoccupied exit
if (slotJ == null) {
// delete last duplicate slot
soElement(buffer, calcElementOffset(removeHashIndex, mask), null);
UNSAFE.putOrderedLong(this, MC_OFFSET, modCount + 1);
return;
}
// k := hash(slot[j].key) modulo num_slots
k = (int) (rehash(slotJ.hashCode()) & mask);
// determine if k lies cyclically in [i,j]
// | i.k.j |
// |....j i.k.| or |.k..j i...|
}
while ( (removeHashIndex <= j) ?
((removeHashIndex < k) && (k <= j)) :
((removeHashIndex < k) || (k <= j)) );
// slot[removeHashIndex] := slot[j]
soElement(buffer, calcElementOffset(removeHashIndex, mask), slotJ);
// removeHashIndex := j
removeHashIndex = j;
}
} | java | private void compactAndRemove(final E[] buffer, final long mask, int removeHashIndex) {
// remove(9a): [9a,9b,10a,9c,10b,11a,null] -> [9b,10a,9c,10b,11a,null,null]
removeHashIndex = (int) (removeHashIndex & mask);
int j = removeHashIndex;
// every compaction is guarded by two mod count increments: one before and one after actual compaction
UNSAFE.putOrderedLong(this, MC_OFFSET, modCount + 1);
while (true) {
int k;
E slotJ;
// skip elements which belong where they are
do {
// j := (j+1) modulo num_slots
j = (int) ((j + 1) & mask);
slotJ = lpElement(buffer, calcElementOffset(j, mask));
// if slot[j] is unoccupied exit
if (slotJ == null) {
// delete last duplicate slot
soElement(buffer, calcElementOffset(removeHashIndex, mask), null);
UNSAFE.putOrderedLong(this, MC_OFFSET, modCount + 1);
return;
}
// k := hash(slot[j].key) modulo num_slots
k = (int) (rehash(slotJ.hashCode()) & mask);
// determine if k lies cyclically in [i,j]
// | i.k.j |
// |....j i.k.| or |.k..j i...|
}
while ( (removeHashIndex <= j) ?
((removeHashIndex < k) && (k <= j)) :
((removeHashIndex < k) || (k <= j)) );
// slot[removeHashIndex] := slot[j]
soElement(buffer, calcElementOffset(removeHashIndex, mask), slotJ);
// removeHashIndex := j
removeHashIndex = j;
}
} | [
"private",
"void",
"compactAndRemove",
"(",
"final",
"E",
"[",
"]",
"buffer",
",",
"final",
"long",
"mask",
",",
"int",
"removeHashIndex",
")",
"{",
"// remove(9a): [9a,9b,10a,9c,10b,11a,null] -> [9b,10a,9c,10b,11a,null,null]",
"removeHashIndex",
"=",
"(",
"int",
")",
"(",
"removeHashIndex",
"&",
"mask",
")",
";",
"int",
"j",
"=",
"removeHashIndex",
";",
"// every compaction is guarded by two mod count increments: one before and one after actual compaction",
"UNSAFE",
".",
"putOrderedLong",
"(",
"this",
",",
"MC_OFFSET",
",",
"modCount",
"+",
"1",
")",
";",
"while",
"(",
"true",
")",
"{",
"int",
"k",
";",
"E",
"slotJ",
";",
"// skip elements which belong where they are",
"do",
"{",
"// j := (j+1) modulo num_slots",
"j",
"=",
"(",
"int",
")",
"(",
"(",
"j",
"+",
"1",
")",
"&",
"mask",
")",
";",
"slotJ",
"=",
"lpElement",
"(",
"buffer",
",",
"calcElementOffset",
"(",
"j",
",",
"mask",
")",
")",
";",
"// if slot[j] is unoccupied exit",
"if",
"(",
"slotJ",
"==",
"null",
")",
"{",
"// delete last duplicate slot",
"soElement",
"(",
"buffer",
",",
"calcElementOffset",
"(",
"removeHashIndex",
",",
"mask",
")",
",",
"null",
")",
";",
"UNSAFE",
".",
"putOrderedLong",
"(",
"this",
",",
"MC_OFFSET",
",",
"modCount",
"+",
"1",
")",
";",
"return",
";",
"}",
"// k := hash(slot[j].key) modulo num_slots",
"k",
"=",
"(",
"int",
")",
"(",
"rehash",
"(",
"slotJ",
".",
"hashCode",
"(",
")",
")",
"&",
"mask",
")",
";",
"// determine if k lies cyclically in [i,j]",
"// | i.k.j |",
"// |....j i.k.| or |.k..j i...|",
"}",
"while",
"(",
"(",
"removeHashIndex",
"<=",
"j",
")",
"?",
"(",
"(",
"removeHashIndex",
"<",
"k",
")",
"&&",
"(",
"k",
"<=",
"j",
")",
")",
":",
"(",
"(",
"removeHashIndex",
"<",
"k",
")",
"||",
"(",
"k",
"<=",
"j",
")",
")",
")",
";",
"// slot[removeHashIndex] := slot[j]",
"soElement",
"(",
"buffer",
",",
"calcElementOffset",
"(",
"removeHashIndex",
",",
"mask",
")",
",",
"slotJ",
")",
";",
"// removeHashIndex := j",
"removeHashIndex",
"=",
"j",
";",
"}",
"}"
] | /*
implemented as per wiki suggested algo with minor adjustments. | [
"/",
"*",
"implemented",
"as",
"per",
"wiki",
"suggested",
"algo",
"with",
"minor",
"adjustments",
"."
] | train | https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-experimental/src/main/java/org/jctools/sets/SingleWriterHashSet.java#L158-L194 |
mongodb/stitch-android-sdk | core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/BsonUtils.java | BsonUtils.parseValue | public static <T> T parseValue(final String json, final Class<T> valueClass) {
"""
Parses the provided extended JSON string and decodes it into a T value as specified by the
provided class type. The type will decoded using the codec found for the type in the default
codec registry. If the provided type is not supported by the default codec registry, the method
will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}.
@param json the JSON string to parse.
@param valueClass the class that the JSON string should be decoded into.
@param <T> the type into which the JSON string is decoded.
@return the decoded value.
"""
final JsonReader bsonReader = new JsonReader(json);
bsonReader.readBsonType();
return DEFAULT_CODEC_REGISTRY
.get(valueClass)
.decode(bsonReader, DecoderContext.builder().build());
} | java | public static <T> T parseValue(final String json, final Class<T> valueClass) {
final JsonReader bsonReader = new JsonReader(json);
bsonReader.readBsonType();
return DEFAULT_CODEC_REGISTRY
.get(valueClass)
.decode(bsonReader, DecoderContext.builder().build());
} | [
"public",
"static",
"<",
"T",
">",
"T",
"parseValue",
"(",
"final",
"String",
"json",
",",
"final",
"Class",
"<",
"T",
">",
"valueClass",
")",
"{",
"final",
"JsonReader",
"bsonReader",
"=",
"new",
"JsonReader",
"(",
"json",
")",
";",
"bsonReader",
".",
"readBsonType",
"(",
")",
";",
"return",
"DEFAULT_CODEC_REGISTRY",
".",
"get",
"(",
"valueClass",
")",
".",
"decode",
"(",
"bsonReader",
",",
"DecoderContext",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"}"
] | Parses the provided extended JSON string and decodes it into a T value as specified by the
provided class type. The type will decoded using the codec found for the type in the default
codec registry. If the provided type is not supported by the default codec registry, the method
will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}.
@param json the JSON string to parse.
@param valueClass the class that the JSON string should be decoded into.
@param <T> the type into which the JSON string is decoded.
@return the decoded value. | [
"Parses",
"the",
"provided",
"extended",
"JSON",
"string",
"and",
"decodes",
"it",
"into",
"a",
"T",
"value",
"as",
"specified",
"by",
"the",
"provided",
"class",
"type",
".",
"The",
"type",
"will",
"decoded",
"using",
"the",
"codec",
"found",
"for",
"the",
"type",
"in",
"the",
"default",
"codec",
"registry",
".",
"If",
"the",
"provided",
"type",
"is",
"not",
"supported",
"by",
"the",
"default",
"codec",
"registry",
"the",
"method",
"will",
"throw",
"a",
"{",
"@link",
"org",
".",
"bson",
".",
"codecs",
".",
"configuration",
".",
"CodecConfigurationException",
"}",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/sdk/src/main/java/com/mongodb/stitch/core/internal/common/BsonUtils.java#L80-L86 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWrite.java | KMLWrite.writeKML | public static void writeKML(Connection connection, String fileName, String tableReference) throws SQLException, IOException {
"""
This method is used to write a spatial table into a KML file
@param connection
@param fileName
@param tableReference
@throws SQLException
@throws IOException
"""
KMLDriverFunction kMLDriverFunction = new KMLDriverFunction();
kMLDriverFunction.exportTable(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | java | public static void writeKML(Connection connection, String fileName, String tableReference) throws SQLException, IOException {
KMLDriverFunction kMLDriverFunction = new KMLDriverFunction();
kMLDriverFunction.exportTable(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | [
"public",
"static",
"void",
"writeKML",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
")",
"throws",
"SQLException",
",",
"IOException",
"{",
"KMLDriverFunction",
"kMLDriverFunction",
"=",
"new",
"KMLDriverFunction",
"(",
")",
";",
"kMLDriverFunction",
".",
"exportTable",
"(",
"connection",
",",
"tableReference",
",",
"URIUtilities",
".",
"fileFromString",
"(",
"fileName",
")",
",",
"new",
"EmptyProgressVisitor",
"(",
")",
")",
";",
"}"
] | This method is used to write a spatial table into a KML file
@param connection
@param fileName
@param tableReference
@throws SQLException
@throws IOException | [
"This",
"method",
"is",
"used",
"to",
"write",
"a",
"spatial",
"table",
"into",
"a",
"KML",
"file"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWrite.java#L56-L59 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Collectors.java | Collectors.averagingLong | @NotNull
public static <T> Collector<T, ?, Double> averagingLong(@NotNull final ToLongFunction<? super T> mapper) {
"""
Returns a {@code Collector} that calculates average of long-valued input elements.
@param <T> the type of the input elements
@param mapper the mapping function which extracts value from element to calculate result
@return a {@code Collector}
@since 1.1.3
"""
return averagingHelper(new BiConsumer<long[], T>() {
@Override
public void accept(long[] t, T u) {
t[0]++; // count
t[1] += mapper.applyAsLong(u); // sum
}
});
} | java | @NotNull
public static <T> Collector<T, ?, Double> averagingLong(@NotNull final ToLongFunction<? super T> mapper) {
return averagingHelper(new BiConsumer<long[], T>() {
@Override
public void accept(long[] t, T u) {
t[0]++; // count
t[1] += mapper.applyAsLong(u); // sum
}
});
} | [
"@",
"NotNull",
"public",
"static",
"<",
"T",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"Double",
">",
"averagingLong",
"(",
"@",
"NotNull",
"final",
"ToLongFunction",
"<",
"?",
"super",
"T",
">",
"mapper",
")",
"{",
"return",
"averagingHelper",
"(",
"new",
"BiConsumer",
"<",
"long",
"[",
"]",
",",
"T",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"accept",
"(",
"long",
"[",
"]",
"t",
",",
"T",
"u",
")",
"{",
"t",
"[",
"0",
"]",
"++",
";",
"// count",
"t",
"[",
"1",
"]",
"+=",
"mapper",
".",
"applyAsLong",
"(",
"u",
")",
";",
"// sum",
"}",
"}",
")",
";",
"}"
] | Returns a {@code Collector} that calculates average of long-valued input elements.
@param <T> the type of the input elements
@param mapper the mapping function which extracts value from element to calculate result
@return a {@code Collector}
@since 1.1.3 | [
"Returns",
"a",
"{",
"@code",
"Collector",
"}",
"that",
"calculates",
"average",
"of",
"long",
"-",
"valued",
"input",
"elements",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L506-L515 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBQuery.java | DBQuery.elemMatch | public static Query elemMatch(String field, Query query) {
"""
An element in the given array field matches the given query
@param field the array field
@param query The query to attempt to match against the elements of the array field
@return the query
"""
return new Query().elemMatch(field, query);
} | java | public static Query elemMatch(String field, Query query) {
return new Query().elemMatch(field, query);
} | [
"public",
"static",
"Query",
"elemMatch",
"(",
"String",
"field",
",",
"Query",
"query",
")",
"{",
"return",
"new",
"Query",
"(",
")",
".",
"elemMatch",
"(",
"field",
",",
"query",
")",
";",
"}"
] | An element in the given array field matches the given query
@param field the array field
@param query The query to attempt to match against the elements of the array field
@return the query | [
"An",
"element",
"in",
"the",
"given",
"array",
"field",
"matches",
"the",
"given",
"query"
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBQuery.java#L267-L269 |
lightblueseas/vintage-time | src/main/java/de/alpharogroup/date/IntervalExtensions.java | IntervalExtensions.isBetween | public static boolean isBetween(final Interval timeRange, final Interval timeRangeToCheck) {
"""
Checks if the given time range is between the given time range to check
@param timeRange
the time range
@param timeRangeToCheck
the time range to check
@return true, if the given time range is between the given time range to check otherwise
false
"""
return ((timeRange.getStart() != null
&& timeRange.getStart().isBefore(timeRangeToCheck.getStart()))
&& (timeRange.getEnd() != null
&& timeRange.getEnd().isAfter(timeRangeToCheck.getEnd())));
} | java | public static boolean isBetween(final Interval timeRange, final Interval timeRangeToCheck)
{
return ((timeRange.getStart() != null
&& timeRange.getStart().isBefore(timeRangeToCheck.getStart()))
&& (timeRange.getEnd() != null
&& timeRange.getEnd().isAfter(timeRangeToCheck.getEnd())));
} | [
"public",
"static",
"boolean",
"isBetween",
"(",
"final",
"Interval",
"timeRange",
",",
"final",
"Interval",
"timeRangeToCheck",
")",
"{",
"return",
"(",
"(",
"timeRange",
".",
"getStart",
"(",
")",
"!=",
"null",
"&&",
"timeRange",
".",
"getStart",
"(",
")",
".",
"isBefore",
"(",
"timeRangeToCheck",
".",
"getStart",
"(",
")",
")",
")",
"&&",
"(",
"timeRange",
".",
"getEnd",
"(",
")",
"!=",
"null",
"&&",
"timeRange",
".",
"getEnd",
"(",
")",
".",
"isAfter",
"(",
"timeRangeToCheck",
".",
"getEnd",
"(",
")",
")",
")",
")",
";",
"}"
] | Checks if the given time range is between the given time range to check
@param timeRange
the time range
@param timeRangeToCheck
the time range to check
@return true, if the given time range is between the given time range to check otherwise
false | [
"Checks",
"if",
"the",
"given",
"time",
"range",
"is",
"between",
"the",
"given",
"time",
"range",
"to",
"check"
] | train | https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/IntervalExtensions.java#L54-L60 |
pip-services3-java/pip-services3-components-java | src/org/pipservices3/components/config/JsonConfigReader.java | JsonConfigReader.readConfig | public static ConfigParams readConfig(String correlationId, String path, ConfigParams parameters)
throws ApplicationException {
"""
Reads configuration from a file, parameterize it with given values and
returns a new ConfigParams object.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param path a path to configuration file.
@param parameters values to parameters the configuration.
@return ConfigParams configuration.
@throws ApplicationException when error occured.
"""
return new JsonConfigReader(path).readConfig(correlationId, parameters);
} | java | public static ConfigParams readConfig(String correlationId, String path, ConfigParams parameters)
throws ApplicationException {
return new JsonConfigReader(path).readConfig(correlationId, parameters);
} | [
"public",
"static",
"ConfigParams",
"readConfig",
"(",
"String",
"correlationId",
",",
"String",
"path",
",",
"ConfigParams",
"parameters",
")",
"throws",
"ApplicationException",
"{",
"return",
"new",
"JsonConfigReader",
"(",
"path",
")",
".",
"readConfig",
"(",
"correlationId",
",",
"parameters",
")",
";",
"}"
] | Reads configuration from a file, parameterize it with given values and
returns a new ConfigParams object.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param path a path to configuration file.
@param parameters values to parameters the configuration.
@return ConfigParams configuration.
@throws ApplicationException when error occured. | [
"Reads",
"configuration",
"from",
"a",
"file",
"parameterize",
"it",
"with",
"given",
"values",
"and",
"returns",
"a",
"new",
"ConfigParams",
"object",
"."
] | train | https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/config/JsonConfigReader.java#L131-L134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.