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
|
---|---|---|---|---|---|---|---|---|---|---|
pac4j/pac4j | pac4j-core/src/main/java/org/pac4j/core/profile/definition/ProfileDefinition.java | ProfileDefinition.setProfileFactory | protected void setProfileFactory(final Function<Object[], P> profileFactory) {
"""
Define the way to build the profile.
@param profileFactory the way to build the profile
"""
CommonHelper.assertNotNull("profileFactory", profileFactory);
this.newProfile = profileFactory;
} | java | protected void setProfileFactory(final Function<Object[], P> profileFactory) {
CommonHelper.assertNotNull("profileFactory", profileFactory);
this.newProfile = profileFactory;
} | [
"protected",
"void",
"setProfileFactory",
"(",
"final",
"Function",
"<",
"Object",
"[",
"]",
",",
"P",
">",
"profileFactory",
")",
"{",
"CommonHelper",
".",
"assertNotNull",
"(",
"\"profileFactory\"",
",",
"profileFactory",
")",
";",
"this",
".",
"newProfile",
"=",
"profileFactory",
";",
"}"
] | Define the way to build the profile.
@param profileFactory the way to build the profile | [
"Define",
"the",
"way",
"to",
"build",
"the",
"profile",
"."
] | train | https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/definition/ProfileDefinition.java#L105-L108 |
libgdx/box2dlights | src/box2dLight/Light.java | Light.setColor | public void setColor(float r, float g, float b, float a) {
"""
Sets light color
<p>NOTE: you can also use colorless light with shadows, e.g. (0,0,0,1)
@param r
lights color red component
@param g
lights color green component
@param b
lights color blue component
@param a
lights shadow intensity
@see #setColor(Color)
"""
color.set(r, g, b, a);
colorF = color.toFloatBits();
if (staticLight) dirty = true;
} | java | public void setColor(float r, float g, float b, float a) {
color.set(r, g, b, a);
colorF = color.toFloatBits();
if (staticLight) dirty = true;
} | [
"public",
"void",
"setColor",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"color",
".",
"set",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
";",
"colorF",
"=",
"color",
".",
"toFloatBits",
"(",
")",
";",
"if",
"(",
"staticLight",
")",
"dirty",
"=",
"true",
";",
"}"
] | Sets light color
<p>NOTE: you can also use colorless light with shadows, e.g. (0,0,0,1)
@param r
lights color red component
@param g
lights color green component
@param b
lights color blue component
@param a
lights shadow intensity
@see #setColor(Color) | [
"Sets",
"light",
"color"
] | train | https://github.com/libgdx/box2dlights/blob/08cf93a41464f71d32475aaa2fe280dc6af78ff3/src/box2dLight/Light.java#L191-L195 |
liferay/com-liferay-commerce | commerce-api/src/main/java/com/liferay/commerce/service/persistence/CPDefinitionInventoryUtil.java | CPDefinitionInventoryUtil.removeByUUID_G | public static CPDefinitionInventory removeByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.exception.NoSuchCPDefinitionInventoryException {
"""
Removes the cp definition inventory where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp definition inventory that was removed
"""
return getPersistence().removeByUUID_G(uuid, groupId);
} | java | public static CPDefinitionInventory removeByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.exception.NoSuchCPDefinitionInventoryException {
return getPersistence().removeByUUID_G(uuid, groupId);
} | [
"public",
"static",
"CPDefinitionInventory",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"com",
".",
"liferay",
".",
"commerce",
".",
"exception",
".",
"NoSuchCPDefinitionInventoryException",
"{",
"return",
"getPersistence",
"(",
")",
".",
"removeByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"}"
] | Removes the cp definition inventory where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp definition inventory that was removed | [
"Removes",
"the",
"cp",
"definition",
"inventory",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-api/src/main/java/com/liferay/commerce/service/persistence/CPDefinitionInventoryUtil.java#L319-L322 |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.createBucket | public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException {
"""
Create a new bucket, and start it.
@param config The bucket configuration to use
@throws BucketAlreadyExistsException If the bucket already exists
@throws IOException If an I/O error occurs
"""
if (!config.validate()) {
throw new IllegalArgumentException("Invalid bucket configuration");
}
synchronized (buckets) {
if (buckets.containsKey(config.name)) {
throw new BucketAlreadyExistsException(config.name);
}
Bucket bucket = Bucket.create(this, config);
BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this);
adminServer.register();
bucket.setAdminServer(adminServer);
HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator);
if (config.type == BucketType.COUCHBASE) {
CAPIServer capi = new CAPIServer(bucket, verifier);
capi.register(httpServer);
bucket.setCAPIServer(capi);
}
buckets.put(config.name, bucket);
bucket.start();
}
} | java | public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException {
if (!config.validate()) {
throw new IllegalArgumentException("Invalid bucket configuration");
}
synchronized (buckets) {
if (buckets.containsKey(config.name)) {
throw new BucketAlreadyExistsException(config.name);
}
Bucket bucket = Bucket.create(this, config);
BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this);
adminServer.register();
bucket.setAdminServer(adminServer);
HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator);
if (config.type == BucketType.COUCHBASE) {
CAPIServer capi = new CAPIServer(bucket, verifier);
capi.register(httpServer);
bucket.setCAPIServer(capi);
}
buckets.put(config.name, bucket);
bucket.start();
}
} | [
"public",
"void",
"createBucket",
"(",
"BucketConfiguration",
"config",
")",
"throws",
"BucketAlreadyExistsException",
",",
"IOException",
"{",
"if",
"(",
"!",
"config",
".",
"validate",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid bucket configuration\"",
")",
";",
"}",
"synchronized",
"(",
"buckets",
")",
"{",
"if",
"(",
"buckets",
".",
"containsKey",
"(",
"config",
".",
"name",
")",
")",
"{",
"throw",
"new",
"BucketAlreadyExistsException",
"(",
"config",
".",
"name",
")",
";",
"}",
"Bucket",
"bucket",
"=",
"Bucket",
".",
"create",
"(",
"this",
",",
"config",
")",
";",
"BucketAdminServer",
"adminServer",
"=",
"new",
"BucketAdminServer",
"(",
"bucket",
",",
"httpServer",
",",
"this",
")",
";",
"adminServer",
".",
"register",
"(",
")",
";",
"bucket",
".",
"setAdminServer",
"(",
"adminServer",
")",
";",
"HttpAuthVerifier",
"verifier",
"=",
"new",
"HttpAuthVerifier",
"(",
"bucket",
",",
"authenticator",
")",
";",
"if",
"(",
"config",
".",
"type",
"==",
"BucketType",
".",
"COUCHBASE",
")",
"{",
"CAPIServer",
"capi",
"=",
"new",
"CAPIServer",
"(",
"bucket",
",",
"verifier",
")",
";",
"capi",
".",
"register",
"(",
"httpServer",
")",
";",
"bucket",
".",
"setCAPIServer",
"(",
"capi",
")",
";",
"}",
"buckets",
".",
"put",
"(",
"config",
".",
"name",
",",
"bucket",
")",
";",
"bucket",
".",
"start",
"(",
")",
";",
"}",
"}"
] | Create a new bucket, and start it.
@param config The bucket configuration to use
@throws BucketAlreadyExistsException If the bucket already exists
@throws IOException If an I/O error occurs | [
"Create",
"a",
"new",
"bucket",
"and",
"start",
"it",
"."
] | train | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L326-L352 |
iipc/openwayback-access-control | oracle/src/main/java/org/archive/accesscontrol/webui/SurtNode.java | SurtNode.nodesFromSurt | public static List<SurtNode> nodesFromSurt(String surt) {
"""
Return a list of the elements in a given SURT.
For example for "(org,archive," we return:
[new SurtNode("(", "("),
new SurtNode("org,", "(org"),
new SurtNode("archive,", "archive,")]
@param surt
@return
"""
List<SurtNode> list = new ArrayList<SurtNode>();
String running = "";
for (String token: new NewSurtTokenizer(surt)) {
running += token;
list.add(new SurtNode(token, running));
}
return list;
} | java | public static List<SurtNode> nodesFromSurt(String surt) {
List<SurtNode> list = new ArrayList<SurtNode>();
String running = "";
for (String token: new NewSurtTokenizer(surt)) {
running += token;
list.add(new SurtNode(token, running));
}
return list;
} | [
"public",
"static",
"List",
"<",
"SurtNode",
">",
"nodesFromSurt",
"(",
"String",
"surt",
")",
"{",
"List",
"<",
"SurtNode",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"SurtNode",
">",
"(",
")",
";",
"String",
"running",
"=",
"\"\"",
";",
"for",
"(",
"String",
"token",
":",
"new",
"NewSurtTokenizer",
"(",
"surt",
")",
")",
"{",
"running",
"+=",
"token",
";",
"list",
".",
"add",
"(",
"new",
"SurtNode",
"(",
"token",
",",
"running",
")",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Return a list of the elements in a given SURT.
For example for "(org,archive," we return:
[new SurtNode("(", "("),
new SurtNode("org,", "(org"),
new SurtNode("archive,", "archive,")]
@param surt
@return | [
"Return",
"a",
"list",
"of",
"the",
"elements",
"in",
"a",
"given",
"SURT",
"."
] | train | https://github.com/iipc/openwayback-access-control/blob/4a0f70f200fd8d7b6e313624b7628656d834bf31/oracle/src/main/java/org/archive/accesscontrol/webui/SurtNode.java#L42-L50 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseDouble | public static double parseDouble (@Nullable final String sStr, final double dDefault) {
"""
Parse the given {@link String} as double.
@param sStr
The string to parse. May be <code>null</code>.
@param dDefault
The default value to be returned if the passed object could not be
converted to a valid value.
@return The default value if the string does not represent a valid value.
"""
// parseDouble throws a NPE if parameter is null
if (sStr != null && sStr.length () > 0)
try
{
// Single point where we replace "," with "." for parsing!
return Double.parseDouble (_getUnifiedDecimal (sStr));
}
catch (final NumberFormatException ex)
{
// Fall through
}
return dDefault;
} | java | public static double parseDouble (@Nullable final String sStr, final double dDefault)
{
// parseDouble throws a NPE if parameter is null
if (sStr != null && sStr.length () > 0)
try
{
// Single point where we replace "," with "." for parsing!
return Double.parseDouble (_getUnifiedDecimal (sStr));
}
catch (final NumberFormatException ex)
{
// Fall through
}
return dDefault;
} | [
"public",
"static",
"double",
"parseDouble",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"final",
"double",
"dDefault",
")",
"{",
"// parseDouble throws a NPE if parameter is null",
"if",
"(",
"sStr",
"!=",
"null",
"&&",
"sStr",
".",
"length",
"(",
")",
">",
"0",
")",
"try",
"{",
"// Single point where we replace \",\" with \".\" for parsing!",
"return",
"Double",
".",
"parseDouble",
"(",
"_getUnifiedDecimal",
"(",
"sStr",
")",
")",
";",
"}",
"catch",
"(",
"final",
"NumberFormatException",
"ex",
")",
"{",
"// Fall through",
"}",
"return",
"dDefault",
";",
"}"
] | Parse the given {@link String} as double.
@param sStr
The string to parse. May be <code>null</code>.
@param dDefault
The default value to be returned if the passed object could not be
converted to a valid value.
@return The default value if the string does not represent a valid value. | [
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"double",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L484-L498 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/RegExUtils.java | RegExUtils.removeFirst | public static String removeFirst(final String text, final Pattern regex) {
"""
<p>Removes the first substring of the text string that matches the given regular expression pattern.</p>
This method is a {@code null} safe equivalent to:
<ul>
<li>{@code pattern.matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.removeFirst(null, *) = null
StringUtils.removeFirst("any", (Pattern) null) = "any"
StringUtils.removeFirst("any", Pattern.compile("")) = "any"
StringUtils.removeFirst("any", Pattern.compile(".*")) = ""
StringUtils.removeFirst("any", Pattern.compile(".+")) = ""
StringUtils.removeFirst("abc", Pattern.compile(".?")) = "bc"
StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\n<__>B"
StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB"
StringUtils.removeFirst("ABCabc123", Pattern.compile("[a-z]")) = "ABCbc123"
StringUtils.removeFirst("ABCabc123abc", Pattern.compile("[a-z]+")) = "ABC123abc"
</pre>
@param text text to remove from, may be null
@param regex the regular expression pattern to which this string is to be matched
@return the text with the first replacement processed,
{@code null} if null String input
@see #replaceFirst(String, Pattern, String)
@see java.util.regex.Matcher#replaceFirst(String)
@see java.util.regex.Pattern
"""
return replaceFirst(text, regex, StringUtils.EMPTY);
} | java | public static String removeFirst(final String text, final Pattern regex) {
return replaceFirst(text, regex, StringUtils.EMPTY);
} | [
"public",
"static",
"String",
"removeFirst",
"(",
"final",
"String",
"text",
",",
"final",
"Pattern",
"regex",
")",
"{",
"return",
"replaceFirst",
"(",
"text",
",",
"regex",
",",
"StringUtils",
".",
"EMPTY",
")",
";",
"}"
] | <p>Removes the first substring of the text string that matches the given regular expression pattern.</p>
This method is a {@code null} safe equivalent to:
<ul>
<li>{@code pattern.matcher(text).replaceFirst(StringUtils.EMPTY)}</li>
</ul>
<p>A {@code null} reference passed to this method is a no-op.</p>
<pre>
StringUtils.removeFirst(null, *) = null
StringUtils.removeFirst("any", (Pattern) null) = "any"
StringUtils.removeFirst("any", Pattern.compile("")) = "any"
StringUtils.removeFirst("any", Pattern.compile(".*")) = ""
StringUtils.removeFirst("any", Pattern.compile(".+")) = ""
StringUtils.removeFirst("abc", Pattern.compile(".?")) = "bc"
StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\n<__>B"
StringUtils.removeFirst("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB"
StringUtils.removeFirst("ABCabc123", Pattern.compile("[a-z]")) = "ABCbc123"
StringUtils.removeFirst("ABCabc123abc", Pattern.compile("[a-z]+")) = "ABC123abc"
</pre>
@param text text to remove from, may be null
@param regex the regular expression pattern to which this string is to be matched
@return the text with the first replacement processed,
{@code null} if null String input
@see #replaceFirst(String, Pattern, String)
@see java.util.regex.Matcher#replaceFirst(String)
@see java.util.regex.Pattern | [
"<p",
">",
"Removes",
"the",
"first",
"substring",
"of",
"the",
"text",
"string",
"that",
"matches",
"the",
"given",
"regular",
"expression",
"pattern",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/RegExUtils.java#L142-L144 |
xetorthio/jedis | src/main/java/redis/clients/jedis/BinaryJedis.java | BinaryJedis.zrank | @Override
public Long zrank(final byte[] key, final byte[] member) {
"""
Return the rank (or index) or member in the sorted set at key, with scores being ordered from
low to high.
<p>
When the given member does not exist in the sorted set, the special value 'nil' is returned.
The returned rank (or index) of the member is 0-based for both commands.
<p>
<b>Time complexity:</b>
<p>
O(log(N))
@see #zrevrank(byte[], byte[])
@param key
@param member
@return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer
reply if the element exists. A nil bulk reply if there is no such element.
"""
checkIsInMultiOrPipeline();
client.zrank(key, member);
return client.getIntegerReply();
} | java | @Override
public Long zrank(final byte[] key, final byte[] member) {
checkIsInMultiOrPipeline();
client.zrank(key, member);
return client.getIntegerReply();
} | [
"@",
"Override",
"public",
"Long",
"zrank",
"(",
"final",
"byte",
"[",
"]",
"key",
",",
"final",
"byte",
"[",
"]",
"member",
")",
"{",
"checkIsInMultiOrPipeline",
"(",
")",
";",
"client",
".",
"zrank",
"(",
"key",
",",
"member",
")",
";",
"return",
"client",
".",
"getIntegerReply",
"(",
")",
";",
"}"
] | Return the rank (or index) or member in the sorted set at key, with scores being ordered from
low to high.
<p>
When the given member does not exist in the sorted set, the special value 'nil' is returned.
The returned rank (or index) of the member is 0-based for both commands.
<p>
<b>Time complexity:</b>
<p>
O(log(N))
@see #zrevrank(byte[], byte[])
@param key
@param member
@return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer
reply if the element exists. A nil bulk reply if there is no such element. | [
"Return",
"the",
"rank",
"(",
"or",
"index",
")",
"or",
"member",
"in",
"the",
"sorted",
"set",
"at",
"key",
"with",
"scores",
"being",
"ordered",
"from",
"low",
"to",
"high",
".",
"<p",
">",
"When",
"the",
"given",
"member",
"does",
"not",
"exist",
"in",
"the",
"sorted",
"set",
"the",
"special",
"value",
"nil",
"is",
"returned",
".",
"The",
"returned",
"rank",
"(",
"or",
"index",
")",
"of",
"the",
"member",
"is",
"0",
"-",
"based",
"for",
"both",
"commands",
".",
"<p",
">",
"<b",
">",
"Time",
"complexity",
":",
"<",
"/",
"b",
">",
"<p",
">",
"O",
"(",
"log",
"(",
"N",
"))"
] | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L1760-L1765 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.createClosedListEntityRole | public UUID createClosedListEntityRole(UUID appId, String versionId, UUID entityId, CreateClosedListEntityRoleOptionalParameter createClosedListEntityRoleOptionalParameter) {
"""
Create an entity role for an entity in the application.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity model ID.
@param createClosedListEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the UUID object if successful.
"""
return createClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createClosedListEntityRoleOptionalParameter).toBlocking().single().body();
} | java | public UUID createClosedListEntityRole(UUID appId, String versionId, UUID entityId, CreateClosedListEntityRoleOptionalParameter createClosedListEntityRoleOptionalParameter) {
return createClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createClosedListEntityRoleOptionalParameter).toBlocking().single().body();
} | [
"public",
"UUID",
"createClosedListEntityRole",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"CreateClosedListEntityRoleOptionalParameter",
"createClosedListEntityRoleOptionalParameter",
")",
"{",
"return",
"createClosedListEntityRoleWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
",",
"createClosedListEntityRoleOptionalParameter",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Create an entity role for an entity in the application.
@param appId The application ID.
@param versionId The version ID.
@param entityId The entity model ID.
@param createClosedListEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the UUID object if successful. | [
"Create",
"an",
"entity",
"role",
"for",
"an",
"entity",
"in",
"the",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8312-L8314 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java | JmesPathEvaluationVisitor.visit | @Override
public JsonNode visit(JmesPathValueProjection valueProjection, JsonNode input) throws InvalidTypeException {
"""
Evaluates the object projection expression.
This will create a list of the values of the JSON
object(lhs), and project the right hand side of the
projection onto the list of values.
@param valueProjection JmesPath value projection type
@param input Input json node against which evaluation is done
@return Result of the value projection evaluation
@throws InvalidTypeException
"""
JsonNode projectedResult = valueProjection.getLhsExpr().accept(this, input);
if (projectedResult.isObject()) {
ArrayNode projectedArrayNode = ObjectMapperSingleton.getObjectMapper().createArrayNode();
Iterator<JsonNode> elements = projectedResult.elements();
while (elements.hasNext()) {
JsonNode projectedElement = valueProjection.getRhsExpr().accept(this, elements.next());
if (projectedElement != null) {
projectedArrayNode.add(projectedElement);
}
}
return projectedArrayNode;
}
return NullNode.getInstance();
} | java | @Override
public JsonNode visit(JmesPathValueProjection valueProjection, JsonNode input) throws InvalidTypeException {
JsonNode projectedResult = valueProjection.getLhsExpr().accept(this, input);
if (projectedResult.isObject()) {
ArrayNode projectedArrayNode = ObjectMapperSingleton.getObjectMapper().createArrayNode();
Iterator<JsonNode> elements = projectedResult.elements();
while (elements.hasNext()) {
JsonNode projectedElement = valueProjection.getRhsExpr().accept(this, elements.next());
if (projectedElement != null) {
projectedArrayNode.add(projectedElement);
}
}
return projectedArrayNode;
}
return NullNode.getInstance();
} | [
"@",
"Override",
"public",
"JsonNode",
"visit",
"(",
"JmesPathValueProjection",
"valueProjection",
",",
"JsonNode",
"input",
")",
"throws",
"InvalidTypeException",
"{",
"JsonNode",
"projectedResult",
"=",
"valueProjection",
".",
"getLhsExpr",
"(",
")",
".",
"accept",
"(",
"this",
",",
"input",
")",
";",
"if",
"(",
"projectedResult",
".",
"isObject",
"(",
")",
")",
"{",
"ArrayNode",
"projectedArrayNode",
"=",
"ObjectMapperSingleton",
".",
"getObjectMapper",
"(",
")",
".",
"createArrayNode",
"(",
")",
";",
"Iterator",
"<",
"JsonNode",
">",
"elements",
"=",
"projectedResult",
".",
"elements",
"(",
")",
";",
"while",
"(",
"elements",
".",
"hasNext",
"(",
")",
")",
"{",
"JsonNode",
"projectedElement",
"=",
"valueProjection",
".",
"getRhsExpr",
"(",
")",
".",
"accept",
"(",
"this",
",",
"elements",
".",
"next",
"(",
")",
")",
";",
"if",
"(",
"projectedElement",
"!=",
"null",
")",
"{",
"projectedArrayNode",
".",
"add",
"(",
"projectedElement",
")",
";",
"}",
"}",
"return",
"projectedArrayNode",
";",
"}",
"return",
"NullNode",
".",
"getInstance",
"(",
")",
";",
"}"
] | Evaluates the object projection expression.
This will create a list of the values of the JSON
object(lhs), and project the right hand side of the
projection onto the list of values.
@param valueProjection JmesPath value projection type
@param input Input json node against which evaluation is done
@return Result of the value projection evaluation
@throws InvalidTypeException | [
"Evaluates",
"the",
"object",
"projection",
"expression",
".",
"This",
"will",
"create",
"a",
"list",
"of",
"the",
"values",
"of",
"the",
"JSON",
"object",
"(",
"lhs",
")",
"and",
"project",
"the",
"right",
"hand",
"side",
"of",
"the",
"projection",
"onto",
"the",
"list",
"of",
"values",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java#L162-L177 |
glyptodon/guacamole-client | guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java | StandardTokens.addStandardTokens | public static void addStandardTokens(TokenFilter filter, Credentials credentials) {
"""
Adds tokens which are standardized by guacamole-ext to the given
TokenFilter using the values from the given Credentials object. These
standardized tokens include the current username (GUAC_USERNAME),
password (GUAC_PASSWORD), and the server date and time (GUAC_DATE and
GUAC_TIME respectively). If either the username or password are not set
within the given credentials, the corresponding token(s) will remain
unset.
@param filter
The TokenFilter to add standard tokens to.
@param credentials
The Credentials to use when populating the GUAC_USERNAME and
GUAC_PASSWORD tokens.
"""
// Add username token
String username = credentials.getUsername();
if (username != null)
filter.setToken(USERNAME_TOKEN, username);
// Add password token
String password = credentials.getPassword();
if (password != null)
filter.setToken(PASSWORD_TOKEN, password);
// Add client hostname token
String hostname = credentials.getRemoteHostname();
if (hostname != null)
filter.setToken(CLIENT_HOSTNAME_TOKEN, hostname);
// Add client address token
String address = credentials.getRemoteAddress();
if (address != null)
filter.setToken(CLIENT_ADDRESS_TOKEN, address);
// Add any tokens which do not require credentials
addStandardTokens(filter);
} | java | public static void addStandardTokens(TokenFilter filter, Credentials credentials) {
// Add username token
String username = credentials.getUsername();
if (username != null)
filter.setToken(USERNAME_TOKEN, username);
// Add password token
String password = credentials.getPassword();
if (password != null)
filter.setToken(PASSWORD_TOKEN, password);
// Add client hostname token
String hostname = credentials.getRemoteHostname();
if (hostname != null)
filter.setToken(CLIENT_HOSTNAME_TOKEN, hostname);
// Add client address token
String address = credentials.getRemoteAddress();
if (address != null)
filter.setToken(CLIENT_ADDRESS_TOKEN, address);
// Add any tokens which do not require credentials
addStandardTokens(filter);
} | [
"public",
"static",
"void",
"addStandardTokens",
"(",
"TokenFilter",
"filter",
",",
"Credentials",
"credentials",
")",
"{",
"// Add username token",
"String",
"username",
"=",
"credentials",
".",
"getUsername",
"(",
")",
";",
"if",
"(",
"username",
"!=",
"null",
")",
"filter",
".",
"setToken",
"(",
"USERNAME_TOKEN",
",",
"username",
")",
";",
"// Add password token",
"String",
"password",
"=",
"credentials",
".",
"getPassword",
"(",
")",
";",
"if",
"(",
"password",
"!=",
"null",
")",
"filter",
".",
"setToken",
"(",
"PASSWORD_TOKEN",
",",
"password",
")",
";",
"// Add client hostname token",
"String",
"hostname",
"=",
"credentials",
".",
"getRemoteHostname",
"(",
")",
";",
"if",
"(",
"hostname",
"!=",
"null",
")",
"filter",
".",
"setToken",
"(",
"CLIENT_HOSTNAME_TOKEN",
",",
"hostname",
")",
";",
"// Add client address token",
"String",
"address",
"=",
"credentials",
".",
"getRemoteAddress",
"(",
")",
";",
"if",
"(",
"address",
"!=",
"null",
")",
"filter",
".",
"setToken",
"(",
"CLIENT_ADDRESS_TOKEN",
",",
"address",
")",
";",
"// Add any tokens which do not require credentials",
"addStandardTokens",
"(",
"filter",
")",
";",
"}"
] | Adds tokens which are standardized by guacamole-ext to the given
TokenFilter using the values from the given Credentials object. These
standardized tokens include the current username (GUAC_USERNAME),
password (GUAC_PASSWORD), and the server date and time (GUAC_DATE and
GUAC_TIME respectively). If either the username or password are not set
within the given credentials, the corresponding token(s) will remain
unset.
@param filter
The TokenFilter to add standard tokens to.
@param credentials
The Credentials to use when populating the GUAC_USERNAME and
GUAC_PASSWORD tokens. | [
"Adds",
"tokens",
"which",
"are",
"standardized",
"by",
"guacamole",
"-",
"ext",
"to",
"the",
"given",
"TokenFilter",
"using",
"the",
"values",
"from",
"the",
"given",
"Credentials",
"object",
".",
"These",
"standardized",
"tokens",
"include",
"the",
"current",
"username",
"(",
"GUAC_USERNAME",
")",
"password",
"(",
"GUAC_PASSWORD",
")",
"and",
"the",
"server",
"date",
"and",
"time",
"(",
"GUAC_DATE",
"and",
"GUAC_TIME",
"respectively",
")",
".",
"If",
"either",
"the",
"username",
"or",
"password",
"are",
"not",
"set",
"within",
"the",
"given",
"credentials",
"the",
"corresponding",
"token",
"(",
"s",
")",
"will",
"remain",
"unset",
"."
] | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java#L120-L145 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/IntentUtils.java | IntentUtils.shareText | public static Intent shareText(String subject, String text) {
"""
Share text via thirdparty app like twitter, facebook, email, sms etc.
@param subject Optional subject of the message
@param text Text to share
"""
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setType("text/plain");
return intent;
} | java | public static Intent shareText(String subject, String text) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setType("text/plain");
return intent;
} | [
"public",
"static",
"Intent",
"shareText",
"(",
"String",
"subject",
",",
"String",
"text",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
")",
";",
"intent",
".",
"setAction",
"(",
"Intent",
".",
"ACTION_SEND",
")",
";",
"if",
"(",
"!",
"TextUtils",
".",
"isEmpty",
"(",
"subject",
")",
")",
"{",
"intent",
".",
"putExtra",
"(",
"Intent",
".",
"EXTRA_SUBJECT",
",",
"subject",
")",
";",
"}",
"intent",
".",
"putExtra",
"(",
"Intent",
".",
"EXTRA_TEXT",
",",
"text",
")",
";",
"intent",
".",
"setType",
"(",
"\"text/plain\"",
")",
";",
"return",
"intent",
";",
"}"
] | Share text via thirdparty app like twitter, facebook, email, sms etc.
@param subject Optional subject of the message
@param text Text to share | [
"Share",
"text",
"via",
"thirdparty",
"app",
"like",
"twitter",
"facebook",
"email",
"sms",
"etc",
"."
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/IntentUtils.java#L100-L109 |
nobuoka/android-lib-ZXingCaptureActivity | src/main/java/info/vividcode/android/zxing/CaptureActivity.java | CaptureActivity.handleDecode | public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
"""
A valid barcode has been found, so give an indication of success and show the results.
@param rawResult The contents of the barcode.
@param scaleFactor amount by which thumbnail was scaled
@param barcode A greyscale bitmap of the camera data which was decoded.
"""
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
// Then not from history, so we have an image to draw on
drawResultPoints(barcode, scaleFactor, rawResult);
}
handleDecodeExternally(rawResult, barcode);
} | java | public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
// Then not from history, so we have an image to draw on
drawResultPoints(barcode, scaleFactor, rawResult);
}
handleDecodeExternally(rawResult, barcode);
} | [
"public",
"void",
"handleDecode",
"(",
"Result",
"rawResult",
",",
"Bitmap",
"barcode",
",",
"float",
"scaleFactor",
")",
"{",
"boolean",
"fromLiveScan",
"=",
"barcode",
"!=",
"null",
";",
"if",
"(",
"fromLiveScan",
")",
"{",
"// Then not from history, so we have an image to draw on",
"drawResultPoints",
"(",
"barcode",
",",
"scaleFactor",
",",
"rawResult",
")",
";",
"}",
"handleDecodeExternally",
"(",
"rawResult",
",",
"barcode",
")",
";",
"}"
] | A valid barcode has been found, so give an indication of success and show the results.
@param rawResult The contents of the barcode.
@param scaleFactor amount by which thumbnail was scaled
@param barcode A greyscale bitmap of the camera data which was decoded. | [
"A",
"valid",
"barcode",
"has",
"been",
"found",
"so",
"give",
"an",
"indication",
"of",
"success",
"and",
"show",
"the",
"results",
"."
] | train | https://github.com/nobuoka/android-lib-ZXingCaptureActivity/blob/17aaa7cf75520d3f2e03db9796b7e8c1d1f1b1e6/src/main/java/info/vividcode/android/zxing/CaptureActivity.java#L228-L236 |
apache/flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/TableFormatFactoryBase.java | TableFormatFactoryBase.deriveSchema | public static TableSchema deriveSchema(Map<String, String> properties) {
"""
Finds the table schema that can be used for a format schema (without time attributes).
"""
final DescriptorProperties descriptorProperties = new DescriptorProperties();
descriptorProperties.putProperties(properties);
final TableSchema.Builder builder = TableSchema.builder();
final TableSchema baseSchema = descriptorProperties.getTableSchema(SCHEMA);
for (int i = 0; i < baseSchema.getFieldCount(); i++) {
final String fieldName = baseSchema.getFieldNames()[i];
final TypeInformation<?> fieldType = baseSchema.getFieldTypes()[i];
final boolean isProctime = descriptorProperties
.getOptionalBoolean(SCHEMA + '.' + i + '.' + SCHEMA_PROCTIME)
.orElse(false);
final String timestampKey = SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_TYPE;
final boolean isRowtime = descriptorProperties.containsKey(timestampKey);
if (!isProctime && !isRowtime) {
// check for aliasing
final String aliasName = descriptorProperties
.getOptionalString(SCHEMA + '.' + i + '.' + SCHEMA_FROM)
.orElse(fieldName);
builder.field(aliasName, fieldType);
}
// only use the rowtime attribute if it references a field
else if (isRowtime &&
descriptorProperties.isValue(timestampKey, ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD)) {
final String aliasName = descriptorProperties
.getString(SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_FROM);
builder.field(aliasName, fieldType);
}
}
return builder.build();
} | java | public static TableSchema deriveSchema(Map<String, String> properties) {
final DescriptorProperties descriptorProperties = new DescriptorProperties();
descriptorProperties.putProperties(properties);
final TableSchema.Builder builder = TableSchema.builder();
final TableSchema baseSchema = descriptorProperties.getTableSchema(SCHEMA);
for (int i = 0; i < baseSchema.getFieldCount(); i++) {
final String fieldName = baseSchema.getFieldNames()[i];
final TypeInformation<?> fieldType = baseSchema.getFieldTypes()[i];
final boolean isProctime = descriptorProperties
.getOptionalBoolean(SCHEMA + '.' + i + '.' + SCHEMA_PROCTIME)
.orElse(false);
final String timestampKey = SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_TYPE;
final boolean isRowtime = descriptorProperties.containsKey(timestampKey);
if (!isProctime && !isRowtime) {
// check for aliasing
final String aliasName = descriptorProperties
.getOptionalString(SCHEMA + '.' + i + '.' + SCHEMA_FROM)
.orElse(fieldName);
builder.field(aliasName, fieldType);
}
// only use the rowtime attribute if it references a field
else if (isRowtime &&
descriptorProperties.isValue(timestampKey, ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD)) {
final String aliasName = descriptorProperties
.getString(SCHEMA + '.' + i + '.' + ROWTIME_TIMESTAMPS_FROM);
builder.field(aliasName, fieldType);
}
}
return builder.build();
} | [
"public",
"static",
"TableSchema",
"deriveSchema",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
")",
"{",
"final",
"DescriptorProperties",
"descriptorProperties",
"=",
"new",
"DescriptorProperties",
"(",
")",
";",
"descriptorProperties",
".",
"putProperties",
"(",
"properties",
")",
";",
"final",
"TableSchema",
".",
"Builder",
"builder",
"=",
"TableSchema",
".",
"builder",
"(",
")",
";",
"final",
"TableSchema",
"baseSchema",
"=",
"descriptorProperties",
".",
"getTableSchema",
"(",
"SCHEMA",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"baseSchema",
".",
"getFieldCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"String",
"fieldName",
"=",
"baseSchema",
".",
"getFieldNames",
"(",
")",
"[",
"i",
"]",
";",
"final",
"TypeInformation",
"<",
"?",
">",
"fieldType",
"=",
"baseSchema",
".",
"getFieldTypes",
"(",
")",
"[",
"i",
"]",
";",
"final",
"boolean",
"isProctime",
"=",
"descriptorProperties",
".",
"getOptionalBoolean",
"(",
"SCHEMA",
"+",
"'",
"'",
"+",
"i",
"+",
"'",
"'",
"+",
"SCHEMA_PROCTIME",
")",
".",
"orElse",
"(",
"false",
")",
";",
"final",
"String",
"timestampKey",
"=",
"SCHEMA",
"+",
"'",
"'",
"+",
"i",
"+",
"'",
"'",
"+",
"ROWTIME_TIMESTAMPS_TYPE",
";",
"final",
"boolean",
"isRowtime",
"=",
"descriptorProperties",
".",
"containsKey",
"(",
"timestampKey",
")",
";",
"if",
"(",
"!",
"isProctime",
"&&",
"!",
"isRowtime",
")",
"{",
"// check for aliasing",
"final",
"String",
"aliasName",
"=",
"descriptorProperties",
".",
"getOptionalString",
"(",
"SCHEMA",
"+",
"'",
"'",
"+",
"i",
"+",
"'",
"'",
"+",
"SCHEMA_FROM",
")",
".",
"orElse",
"(",
"fieldName",
")",
";",
"builder",
".",
"field",
"(",
"aliasName",
",",
"fieldType",
")",
";",
"}",
"// only use the rowtime attribute if it references a field",
"else",
"if",
"(",
"isRowtime",
"&&",
"descriptorProperties",
".",
"isValue",
"(",
"timestampKey",
",",
"ROWTIME_TIMESTAMPS_TYPE_VALUE_FROM_FIELD",
")",
")",
"{",
"final",
"String",
"aliasName",
"=",
"descriptorProperties",
".",
"getString",
"(",
"SCHEMA",
"+",
"'",
"'",
"+",
"i",
"+",
"'",
"'",
"+",
"ROWTIME_TIMESTAMPS_FROM",
")",
";",
"builder",
".",
"field",
"(",
"aliasName",
",",
"fieldType",
")",
";",
"}",
"}",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] | Finds the table schema that can be used for a format schema (without time attributes). | [
"Finds",
"the",
"table",
"schema",
"that",
"can",
"be",
"used",
"for",
"a",
"format",
"schema",
"(",
"without",
"time",
"attributes",
")",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/TableFormatFactoryBase.java#L131-L164 |
Appendium/objectlabkit | datecalc-common/src/main/java/net/objectlab/kit/datecalc/common/ccy/DefaultCurrencyCalculatorConfig.java | DefaultCurrencyCalculatorConfig.setCurrenciesSubjectToCrossCcyForT1 | public void setCurrenciesSubjectToCrossCcyForT1(final Map<String, Set<String>> currenciesSubjectToCrossCcyForT1) {
"""
Will take a copy of a non null set but doing so by replacing the internal one in one go for consistency.
"""
final Map<String, Set<String>> copy = new HashMap<>();
if (currenciesSubjectToCrossCcyForT1 != null) {
copy.putAll(currenciesSubjectToCrossCcyForT1);
}
this.currenciesSubjectToCrossCcyForT1 = copy;
} | java | public void setCurrenciesSubjectToCrossCcyForT1(final Map<String, Set<String>> currenciesSubjectToCrossCcyForT1) {
final Map<String, Set<String>> copy = new HashMap<>();
if (currenciesSubjectToCrossCcyForT1 != null) {
copy.putAll(currenciesSubjectToCrossCcyForT1);
}
this.currenciesSubjectToCrossCcyForT1 = copy;
} | [
"public",
"void",
"setCurrenciesSubjectToCrossCcyForT1",
"(",
"final",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"currenciesSubjectToCrossCcyForT1",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"copy",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"if",
"(",
"currenciesSubjectToCrossCcyForT1",
"!=",
"null",
")",
"{",
"copy",
".",
"putAll",
"(",
"currenciesSubjectToCrossCcyForT1",
")",
";",
"}",
"this",
".",
"currenciesSubjectToCrossCcyForT1",
"=",
"copy",
";",
"}"
] | Will take a copy of a non null set but doing so by replacing the internal one in one go for consistency. | [
"Will",
"take",
"a",
"copy",
"of",
"a",
"non",
"null",
"set",
"but",
"doing",
"so",
"by",
"replacing",
"the",
"internal",
"one",
"in",
"one",
"go",
"for",
"consistency",
"."
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/datecalc-common/src/main/java/net/objectlab/kit/datecalc/common/ccy/DefaultCurrencyCalculatorConfig.java#L46-L52 |
jaxio/javaee-lab | javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java | GenericRepository.findPropertyCount | @Transactional
public int findPropertyCount(E entity, SearchParameters sp, Attribute<?, ?>... attributes) {
"""
Count the number of E instances.
@param entity a sample entity whose non-null properties may be used as search hint
@param sp carries additional search information
@param attributes the list of attributes to the property
@return the number of entities matching the search.
"""
return findPropertyCount(entity, sp, newArrayList(attributes));
} | java | @Transactional
public int findPropertyCount(E entity, SearchParameters sp, Attribute<?, ?>... attributes) {
return findPropertyCount(entity, sp, newArrayList(attributes));
} | [
"@",
"Transactional",
"public",
"int",
"findPropertyCount",
"(",
"E",
"entity",
",",
"SearchParameters",
"sp",
",",
"Attribute",
"<",
"?",
",",
"?",
">",
"...",
"attributes",
")",
"{",
"return",
"findPropertyCount",
"(",
"entity",
",",
"sp",
",",
"newArrayList",
"(",
"attributes",
")",
")",
";",
"}"
] | Count the number of E instances.
@param entity a sample entity whose non-null properties may be used as search hint
@param sp carries additional search information
@param attributes the list of attributes to the property
@return the number of entities matching the search. | [
"Count",
"the",
"number",
"of",
"E",
"instances",
"."
] | train | https://github.com/jaxio/javaee-lab/blob/61238b967952446d81cc68424a4e809093a77fcf/javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java#L392-L395 |
vvakame/JsonPullParser | jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java | JsonUtil.put | public static void put(Writer writer, byte value) throws IOException {
"""
Writes the given value with the given writer.
@param writer
@param value
@throws IOException
@author vvakame
"""
writer.write(String.valueOf(value));
} | java | public static void put(Writer writer, byte value) throws IOException {
writer.write(String.valueOf(value));
} | [
"public",
"static",
"void",
"put",
"(",
"Writer",
"writer",
",",
"byte",
"value",
")",
"throws",
"IOException",
"{",
"writer",
".",
"write",
"(",
"String",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Writes the given value with the given writer.
@param writer
@param value
@throws IOException
@author vvakame | [
"Writes",
"the",
"given",
"value",
"with",
"the",
"given",
"writer",
"."
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L234-L236 |
OpenLiberty/open-liberty | dev/com.ibm.ws.tx.jta.extensions/src/com/ibm/ws/jtaextensions/ExtendedJTATransactionImpl.java | ExtendedJTATransactionImpl.beforeCompletion | public static void beforeCompletion(TransactionImpl tran, int syncLevel) {
"""
Notify all the registered syncs of the begin
of the completion phase of the given transaction
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "beforeCompletion", new Object[] { tran, syncLevel });
if (syncLevel >= 0) {
final ArrayList syncs = _syncLevels.get(syncLevel);
if (syncs != null) {
final int localID = (int) tran.getLocalTID();
final byte[] globalID = tran.getTID();
final int numSyncs = syncs.size();
for (int s = 0; s < numSyncs; s++) {
((SynchronizationCallback) syncs.get(s)).beforeCompletion(localID, globalID);
// exception here means rollback
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "beforeCompletion");
} | java | public static void beforeCompletion(TransactionImpl tran, int syncLevel) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "beforeCompletion", new Object[] { tran, syncLevel });
if (syncLevel >= 0) {
final ArrayList syncs = _syncLevels.get(syncLevel);
if (syncs != null) {
final int localID = (int) tran.getLocalTID();
final byte[] globalID = tran.getTID();
final int numSyncs = syncs.size();
for (int s = 0; s < numSyncs; s++) {
((SynchronizationCallback) syncs.get(s)).beforeCompletion(localID, globalID);
// exception here means rollback
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "beforeCompletion");
} | [
"public",
"static",
"void",
"beforeCompletion",
"(",
"TransactionImpl",
"tran",
",",
"int",
"syncLevel",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"beforeCompletion\"",
",",
"new",
"Object",
"[",
"]",
"{",
"tran",
",",
"syncLevel",
"}",
")",
";",
"if",
"(",
"syncLevel",
">=",
"0",
")",
"{",
"final",
"ArrayList",
"syncs",
"=",
"_syncLevels",
".",
"get",
"(",
"syncLevel",
")",
";",
"if",
"(",
"syncs",
"!=",
"null",
")",
"{",
"final",
"int",
"localID",
"=",
"(",
"int",
")",
"tran",
".",
"getLocalTID",
"(",
")",
";",
"final",
"byte",
"[",
"]",
"globalID",
"=",
"tran",
".",
"getTID",
"(",
")",
";",
"final",
"int",
"numSyncs",
"=",
"syncs",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"s",
"=",
"0",
";",
"s",
"<",
"numSyncs",
";",
"s",
"++",
")",
"{",
"(",
"(",
"SynchronizationCallback",
")",
"syncs",
".",
"get",
"(",
"s",
")",
")",
".",
"beforeCompletion",
"(",
"localID",
",",
"globalID",
")",
";",
"// exception here means rollback",
"}",
"}",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"beforeCompletion\"",
")",
";",
"}"
] | Notify all the registered syncs of the begin
of the completion phase of the given transaction | [
"Notify",
"all",
"the",
"registered",
"syncs",
"of",
"the",
"begin",
"of",
"the",
"completion",
"phase",
"of",
"the",
"given",
"transaction"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.tx.jta.extensions/src/com/ibm/ws/jtaextensions/ExtendedJTATransactionImpl.java#L283-L304 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java | Camera.setLocation | public void setLocation(double x, double y) {
"""
Set the camera location.
@param x The horizontal location.
@param y The vertical location.
"""
final double dx = x - (mover.getX() + offset.getX());
final double dy = y - (mover.getY() + offset.getY());
moveLocation(1, dx, dy);
} | java | public void setLocation(double x, double y)
{
final double dx = x - (mover.getX() + offset.getX());
final double dy = y - (mover.getY() + offset.getY());
moveLocation(1, dx, dy);
} | [
"public",
"void",
"setLocation",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"final",
"double",
"dx",
"=",
"x",
"-",
"(",
"mover",
".",
"getX",
"(",
")",
"+",
"offset",
".",
"getX",
"(",
")",
")",
";",
"final",
"double",
"dy",
"=",
"y",
"-",
"(",
"mover",
".",
"getY",
"(",
")",
"+",
"offset",
".",
"getY",
"(",
")",
")",
";",
"moveLocation",
"(",
"1",
",",
"dx",
",",
"dy",
")",
";",
"}"
] | Set the camera location.
@param x The horizontal location.
@param y The vertical location. | [
"Set",
"the",
"camera",
"location",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Camera.java#L129-L134 |
kaazing/gateway | util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java | Asn1Utils.decodeInteger | public static int decodeInteger(ByteBuffer buf) {
"""
Decode an ASN.1 INTEGER.
@param buf
the buffer containing the DER-encoded INTEGER
@return the value of the INTEGER
"""
DerId id = DerId.decode(buf);
if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM)) {
throw new IllegalArgumentException("Expected INTEGER identifier, received " + id);
}
int len = DerUtils.decodeLength(buf);
if (buf.remaining() < len) {
throw new IllegalArgumentException("Insufficient content for INTEGER");
}
int value = 0;
for (int i = 0; i < len; i++) {
value = (value << 8) + (0xff & buf.get());
}
return value;
} | java | public static int decodeInteger(ByteBuffer buf) {
DerId id = DerId.decode(buf);
if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM)) {
throw new IllegalArgumentException("Expected INTEGER identifier, received " + id);
}
int len = DerUtils.decodeLength(buf);
if (buf.remaining() < len) {
throw new IllegalArgumentException("Insufficient content for INTEGER");
}
int value = 0;
for (int i = 0; i < len; i++) {
value = (value << 8) + (0xff & buf.get());
}
return value;
} | [
"public",
"static",
"int",
"decodeInteger",
"(",
"ByteBuffer",
"buf",
")",
"{",
"DerId",
"id",
"=",
"DerId",
".",
"decode",
"(",
"buf",
")",
";",
"if",
"(",
"!",
"id",
".",
"matches",
"(",
"DerId",
".",
"TagClass",
".",
"UNIVERSAL",
",",
"DerId",
".",
"EncodingType",
".",
"PRIMITIVE",
",",
"ASN1_INTEGER_TAG_NUM",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expected INTEGER identifier, received \"",
"+",
"id",
")",
";",
"}",
"int",
"len",
"=",
"DerUtils",
".",
"decodeLength",
"(",
"buf",
")",
";",
"if",
"(",
"buf",
".",
"remaining",
"(",
")",
"<",
"len",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Insufficient content for INTEGER\"",
")",
";",
"}",
"int",
"value",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"value",
"=",
"(",
"value",
"<<",
"8",
")",
"+",
"(",
"0xff",
"&",
"buf",
".",
"get",
"(",
")",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Decode an ASN.1 INTEGER.
@param buf
the buffer containing the DER-encoded INTEGER
@return the value of the INTEGER | [
"Decode",
"an",
"ASN",
".",
"1",
"INTEGER",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java#L172-L186 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/CollectionNamingConfusion.java | CollectionNamingConfusion.visitMethod | @Override
public void visitMethod(Method obj) {
"""
overrides the visitor to look for local variables where the name has 'Map', 'Set', 'List' in it but the type of that field isn't that. note that this
only is useful if compiled with debug labels.
@param obj
the currently parsed method
"""
LocalVariableTable lvt = obj.getLocalVariableTable();
if (lvt != null) {
LocalVariable[] lvs = lvt.getLocalVariableTable();
for (LocalVariable lv : lvs) {
if (checkConfusedName(lv.getName(), lv.getSignature())) {
bugReporter.reportBug(new BugInstance(this, BugType.CNC_COLLECTION_NAMING_CONFUSION.name(), NORMAL_PRIORITY).addClass(this)
.addString(lv.getName()).addSourceLine(this.clsContext, this, lv.getStartPC()));
}
}
}
} | java | @Override
public void visitMethod(Method obj) {
LocalVariableTable lvt = obj.getLocalVariableTable();
if (lvt != null) {
LocalVariable[] lvs = lvt.getLocalVariableTable();
for (LocalVariable lv : lvs) {
if (checkConfusedName(lv.getName(), lv.getSignature())) {
bugReporter.reportBug(new BugInstance(this, BugType.CNC_COLLECTION_NAMING_CONFUSION.name(), NORMAL_PRIORITY).addClass(this)
.addString(lv.getName()).addSourceLine(this.clsContext, this, lv.getStartPC()));
}
}
}
} | [
"@",
"Override",
"public",
"void",
"visitMethod",
"(",
"Method",
"obj",
")",
"{",
"LocalVariableTable",
"lvt",
"=",
"obj",
".",
"getLocalVariableTable",
"(",
")",
";",
"if",
"(",
"lvt",
"!=",
"null",
")",
"{",
"LocalVariable",
"[",
"]",
"lvs",
"=",
"lvt",
".",
"getLocalVariableTable",
"(",
")",
";",
"for",
"(",
"LocalVariable",
"lv",
":",
"lvs",
")",
"{",
"if",
"(",
"checkConfusedName",
"(",
"lv",
".",
"getName",
"(",
")",
",",
"lv",
".",
"getSignature",
"(",
")",
")",
")",
"{",
"bugReporter",
".",
"reportBug",
"(",
"new",
"BugInstance",
"(",
"this",
",",
"BugType",
".",
"CNC_COLLECTION_NAMING_CONFUSION",
".",
"name",
"(",
")",
",",
"NORMAL_PRIORITY",
")",
".",
"addClass",
"(",
"this",
")",
".",
"addString",
"(",
"lv",
".",
"getName",
"(",
")",
")",
".",
"addSourceLine",
"(",
"this",
".",
"clsContext",
",",
"this",
",",
"lv",
".",
"getStartPC",
"(",
")",
")",
")",
";",
"}",
"}",
"}",
"}"
] | overrides the visitor to look for local variables where the name has 'Map', 'Set', 'List' in it but the type of that field isn't that. note that this
only is useful if compiled with debug labels.
@param obj
the currently parsed method | [
"overrides",
"the",
"visitor",
"to",
"look",
"for",
"local",
"variables",
"where",
"the",
"name",
"has",
"Map",
"Set",
"List",
"in",
"it",
"but",
"the",
"type",
"of",
"that",
"field",
"isn",
"t",
"that",
".",
"note",
"that",
"this",
"only",
"is",
"useful",
"if",
"compiled",
"with",
"debug",
"labels",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/CollectionNamingConfusion.java#L112-L124 |
grails/gorm-hibernate5 | grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsHibernateUtil.java | GrailsHibernateUtil.getGrailsDomainClassProperty | private static PersistentProperty getGrailsDomainClassProperty(AbstractHibernateDatastore datastore, Class<?> targetClass, String propertyName) {
"""
Get hold of the GrailsDomainClassProperty represented by the targetClass' propertyName,
assuming targetClass corresponds to a GrailsDomainClass.
"""
PersistentEntity grailsClass = datastore != null ? datastore.getMappingContext().getPersistentEntity( targetClass.getName()) : null;
if (grailsClass == null) {
throw new IllegalArgumentException("Unexpected: class is not a domain class:"+targetClass.getName());
}
return grailsClass.getPropertyByName(propertyName);
} | java | private static PersistentProperty getGrailsDomainClassProperty(AbstractHibernateDatastore datastore, Class<?> targetClass, String propertyName) {
PersistentEntity grailsClass = datastore != null ? datastore.getMappingContext().getPersistentEntity( targetClass.getName()) : null;
if (grailsClass == null) {
throw new IllegalArgumentException("Unexpected: class is not a domain class:"+targetClass.getName());
}
return grailsClass.getPropertyByName(propertyName);
} | [
"private",
"static",
"PersistentProperty",
"getGrailsDomainClassProperty",
"(",
"AbstractHibernateDatastore",
"datastore",
",",
"Class",
"<",
"?",
">",
"targetClass",
",",
"String",
"propertyName",
")",
"{",
"PersistentEntity",
"grailsClass",
"=",
"datastore",
"!=",
"null",
"?",
"datastore",
".",
"getMappingContext",
"(",
")",
".",
"getPersistentEntity",
"(",
"targetClass",
".",
"getName",
"(",
")",
")",
":",
"null",
";",
"if",
"(",
"grailsClass",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unexpected: class is not a domain class:\"",
"+",
"targetClass",
".",
"getName",
"(",
")",
")",
";",
"}",
"return",
"grailsClass",
".",
"getPropertyByName",
"(",
"propertyName",
")",
";",
"}"
] | Get hold of the GrailsDomainClassProperty represented by the targetClass' propertyName,
assuming targetClass corresponds to a GrailsDomainClass. | [
"Get",
"hold",
"of",
"the",
"GrailsDomainClassProperty",
"represented",
"by",
"the",
"targetClass",
"propertyName",
"assuming",
"targetClass",
"corresponds",
"to",
"a",
"GrailsDomainClass",
"."
] | train | https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsHibernateUtil.java#L242-L248 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/AVTPartXPath.java | AVTPartXPath.fixupVariables | public void fixupVariables(java.util.Vector vars, int globalsSize) {
"""
This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame).
"""
m_xpath.fixupVariables(vars, globalsSize);
} | java | public void fixupVariables(java.util.Vector vars, int globalsSize)
{
m_xpath.fixupVariables(vars, globalsSize);
} | [
"public",
"void",
"fixupVariables",
"(",
"java",
".",
"util",
".",
"Vector",
"vars",
",",
"int",
"globalsSize",
")",
"{",
"m_xpath",
".",
"fixupVariables",
"(",
"vars",
",",
"globalsSize",
")",
";",
"}"
] | This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame). | [
"This",
"function",
"is",
"used",
"to",
"fixup",
"variables",
"from",
"QNames",
"to",
"stack",
"frame",
"indexes",
"at",
"stylesheet",
"build",
"time",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/AVTPartXPath.java#L54-L57 |
telly/groundy | library/src/main/java/com/telly/groundy/Groundy.java | Groundy.arg | public Groundy arg(String key, String[] value) {
"""
Inserts a String array value 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 String array object, or null
"""
mArgs.putStringArray(key, value);
return this;
} | java | public Groundy arg(String key, String[] value) {
mArgs.putStringArray(key, value);
return this;
} | [
"public",
"Groundy",
"arg",
"(",
"String",
"key",
",",
"String",
"[",
"]",
"value",
")",
"{",
"mArgs",
".",
"putStringArray",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Inserts a String array value 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 String array object, or null | [
"Inserts",
"a",
"String",
"array",
"value",
"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/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/Groundy.java#L705-L708 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/WorkbooksInner.java | WorkbooksInner.listByResourceGroup | public List<WorkbookInner> listByResourceGroup(String resourceGroupName, CategoryType category, List<String> tags, Boolean canFetchContent) {
"""
Get all Workbooks defined within a specified resource group and category.
@param resourceGroupName The name of the resource group.
@param category Category of workbook to return. Possible values include: 'workbook', 'TSG', 'performance', 'retention'
@param tags Tags presents on each workbook returned.
@param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If false, only return summary content for workbooks.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws WorkbookErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<WorkbookInner> object if successful.
"""
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, category, tags, canFetchContent).toBlocking().single().body();
} | java | public List<WorkbookInner> listByResourceGroup(String resourceGroupName, CategoryType category, List<String> tags, Boolean canFetchContent) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, category, tags, canFetchContent).toBlocking().single().body();
} | [
"public",
"List",
"<",
"WorkbookInner",
">",
"listByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"CategoryType",
"category",
",",
"List",
"<",
"String",
">",
"tags",
",",
"Boolean",
"canFetchContent",
")",
"{",
"return",
"listByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"category",
",",
"tags",
",",
"canFetchContent",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Get all Workbooks defined within a specified resource group and category.
@param resourceGroupName The name of the resource group.
@param category Category of workbook to return. Possible values include: 'workbook', 'TSG', 'performance', 'retention'
@param tags Tags presents on each workbook returned.
@param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If false, only return summary content for workbooks.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws WorkbookErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<WorkbookInner> object if successful. | [
"Get",
"all",
"Workbooks",
"defined",
"within",
"a",
"specified",
"resource",
"group",
"and",
"category",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/WorkbooksInner.java#L184-L186 |
buyi/RecyclerViewPagerIndicator | recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java | RecyclerTitlePageIndicator.calcBounds | private Rect calcBounds(int index, Paint paint) {
"""
Calculate the bounds for a view's title
@param index
@param paint
@return
"""
//Calculate the text bounds
Rect bounds = new Rect();
CharSequence title = getTitle(index);
bounds.right = (int) paint.measureText(title, 0, title.length());
bounds.bottom = (int) (paint.descent() - paint.ascent());
return bounds;
} | java | private Rect calcBounds(int index, Paint paint) {
//Calculate the text bounds
Rect bounds = new Rect();
CharSequence title = getTitle(index);
bounds.right = (int) paint.measureText(title, 0, title.length());
bounds.bottom = (int) (paint.descent() - paint.ascent());
return bounds;
} | [
"private",
"Rect",
"calcBounds",
"(",
"int",
"index",
",",
"Paint",
"paint",
")",
"{",
"//Calculate the text bounds",
"Rect",
"bounds",
"=",
"new",
"Rect",
"(",
")",
";",
"CharSequence",
"title",
"=",
"getTitle",
"(",
"index",
")",
";",
"bounds",
".",
"right",
"=",
"(",
"int",
")",
"paint",
".",
"measureText",
"(",
"title",
",",
"0",
",",
"title",
".",
"length",
"(",
")",
")",
";",
"bounds",
".",
"bottom",
"=",
"(",
"int",
")",
"(",
"paint",
".",
"descent",
"(",
")",
"-",
"paint",
".",
"ascent",
"(",
")",
")",
";",
"return",
"bounds",
";",
"}"
] | Calculate the bounds for a view's title
@param index
@param paint
@return | [
"Calculate",
"the",
"bounds",
"for",
"a",
"view",
"s",
"title"
] | train | https://github.com/buyi/RecyclerViewPagerIndicator/blob/b3b5283801b60d40f7325c7f590c945262194fad/recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java#L698-L705 |
pdef/pdef-java | pdef/src/main/java/io/pdef/rpc/HttpUrlConnectionRpcSession.java | HttpUrlConnectionRpcSession.sendPostData | protected void sendPostData(final HttpURLConnection connection, final RpcRequest request)
throws IOException {
"""
Sets the connection content-type and content-length and sends the post data.
"""
String post = buildParamsQuery(request.getPost());
byte[] data = post.getBytes(UTF8);
connection.setRequestProperty(CONTENT_TYPE_HEADER, APPLICATION_X_WWW_FORM_URLENCODED);
connection.setRequestProperty(CONTENT_LENGTH_HEADER, String.valueOf(data.length));
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
try {
out.write(data);
} finally {
closeLogExc(out);
}
} | java | protected void sendPostData(final HttpURLConnection connection, final RpcRequest request)
throws IOException {
String post = buildParamsQuery(request.getPost());
byte[] data = post.getBytes(UTF8);
connection.setRequestProperty(CONTENT_TYPE_HEADER, APPLICATION_X_WWW_FORM_URLENCODED);
connection.setRequestProperty(CONTENT_LENGTH_HEADER, String.valueOf(data.length));
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
try {
out.write(data);
} finally {
closeLogExc(out);
}
} | [
"protected",
"void",
"sendPostData",
"(",
"final",
"HttpURLConnection",
"connection",
",",
"final",
"RpcRequest",
"request",
")",
"throws",
"IOException",
"{",
"String",
"post",
"=",
"buildParamsQuery",
"(",
"request",
".",
"getPost",
"(",
")",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"post",
".",
"getBytes",
"(",
"UTF8",
")",
";",
"connection",
".",
"setRequestProperty",
"(",
"CONTENT_TYPE_HEADER",
",",
"APPLICATION_X_WWW_FORM_URLENCODED",
")",
";",
"connection",
".",
"setRequestProperty",
"(",
"CONTENT_LENGTH_HEADER",
",",
"String",
".",
"valueOf",
"(",
"data",
".",
"length",
")",
")",
";",
"OutputStream",
"out",
"=",
"new",
"BufferedOutputStream",
"(",
"connection",
".",
"getOutputStream",
"(",
")",
")",
";",
"try",
"{",
"out",
".",
"write",
"(",
"data",
")",
";",
"}",
"finally",
"{",
"closeLogExc",
"(",
"out",
")",
";",
"}",
"}"
] | Sets the connection content-type and content-length and sends the post data. | [
"Sets",
"the",
"connection",
"content",
"-",
"type",
"and",
"content",
"-",
"length",
"and",
"sends",
"the",
"post",
"data",
"."
] | train | https://github.com/pdef/pdef-java/blob/7776c44d1aab0f3dbf7267b0c32b8f9282fe6167/pdef/src/main/java/io/pdef/rpc/HttpUrlConnectionRpcSession.java#L120-L133 |
nextreports/nextreports-server | src/ro/nextreports/server/web/pivot/PivotTable.java | PivotTable.createTitleLabel | protected Label createTitleLabel(String id, PivotField pivotField) {
"""
Retrieves a label that display the pivot table title (for fields on ROW and DATA areas)
"""
String title = pivotField.getTitle();
if (pivotField.getArea().equals(PivotField.Area.DATA)) {
title += " (" + pivotField.getAggregator().getFunction().toUpperCase() + ")";
}
return new Label(id, title);
} | java | protected Label createTitleLabel(String id, PivotField pivotField) {
String title = pivotField.getTitle();
if (pivotField.getArea().equals(PivotField.Area.DATA)) {
title += " (" + pivotField.getAggregator().getFunction().toUpperCase() + ")";
}
return new Label(id, title);
} | [
"protected",
"Label",
"createTitleLabel",
"(",
"String",
"id",
",",
"PivotField",
"pivotField",
")",
"{",
"String",
"title",
"=",
"pivotField",
".",
"getTitle",
"(",
")",
";",
"if",
"(",
"pivotField",
".",
"getArea",
"(",
")",
".",
"equals",
"(",
"PivotField",
".",
"Area",
".",
"DATA",
")",
")",
"{",
"title",
"+=",
"\" (\"",
"+",
"pivotField",
".",
"getAggregator",
"(",
")",
".",
"getFunction",
"(",
")",
".",
"toUpperCase",
"(",
")",
"+",
"\")\"",
";",
"}",
"return",
"new",
"Label",
"(",
"id",
",",
"title",
")",
";",
"}"
] | Retrieves a label that display the pivot table title (for fields on ROW and DATA areas) | [
"Retrieves",
"a",
"label",
"that",
"display",
"the",
"pivot",
"table",
"title",
"(",
"for",
"fields",
"on",
"ROW",
"and",
"DATA",
"areas",
")"
] | train | https://github.com/nextreports/nextreports-server/blob/cfce12f5c6d52cb6a739388d50142c6e2e07c55e/src/ro/nextreports/server/web/pivot/PivotTable.java#L225-L232 |
alkacon/opencms-core | src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java | CmsXmlConfigUpdater.transformConfig | public void transformConfig() throws Exception {
"""
Transforms the configuration.
@throws Exception if something goes wrong
"""
List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, "transforms.xml"));
for (TransformEntry entry : entries) {
transform(entry.getConfigFile(), entry.getXslt());
}
m_isDone = true;
} | java | public void transformConfig() throws Exception {
List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, "transforms.xml"));
for (TransformEntry entry : entries) {
transform(entry.getConfigFile(), entry.getXslt());
}
m_isDone = true;
} | [
"public",
"void",
"transformConfig",
"(",
")",
"throws",
"Exception",
"{",
"List",
"<",
"TransformEntry",
">",
"entries",
"=",
"readTransformEntries",
"(",
"new",
"File",
"(",
"m_xsltDir",
",",
"\"transforms.xml\"",
")",
")",
";",
"for",
"(",
"TransformEntry",
"entry",
":",
"entries",
")",
"{",
"transform",
"(",
"entry",
".",
"getConfigFile",
"(",
")",
",",
"entry",
".",
"getXslt",
"(",
")",
")",
";",
"}",
"m_isDone",
"=",
"true",
";",
"}"
] | Transforms the configuration.
@throws Exception if something goes wrong | [
"Transforms",
"the",
"configuration",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/xml/CmsXmlConfigUpdater.java#L229-L236 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CqlNativeStorage.java | CqlNativeStorage.setMapTupleValues | private void setMapTupleValues(Tuple tuple, int position, Object value, AbstractType<?> validator) throws ExecException {
"""
set the values of set/list at and after the position of the tuple
"""
AbstractType<?> keyValidator = ((MapType<?, ?>) validator).getKeysType();
AbstractType<?> valueValidator = ((MapType<?, ?>) validator).getValuesType();
int i = 0;
Tuple innerTuple = TupleFactory.getInstance().newTuple(((Map<?,?>) value).size());
for(Map.Entry<?,?> entry : ((Map<Object, Object>)value).entrySet())
{
Tuple mapEntryTuple = TupleFactory.getInstance().newTuple(2);
setTupleValue(mapEntryTuple, 0, cassandraToPigData(entry.getKey(), keyValidator), keyValidator);
setTupleValue(mapEntryTuple, 1, cassandraToPigData(entry.getValue(), valueValidator), valueValidator);
innerTuple.set(i, mapEntryTuple);
i++;
}
tuple.set(position, innerTuple);
} | java | private void setMapTupleValues(Tuple tuple, int position, Object value, AbstractType<?> validator) throws ExecException
{
AbstractType<?> keyValidator = ((MapType<?, ?>) validator).getKeysType();
AbstractType<?> valueValidator = ((MapType<?, ?>) validator).getValuesType();
int i = 0;
Tuple innerTuple = TupleFactory.getInstance().newTuple(((Map<?,?>) value).size());
for(Map.Entry<?,?> entry : ((Map<Object, Object>)value).entrySet())
{
Tuple mapEntryTuple = TupleFactory.getInstance().newTuple(2);
setTupleValue(mapEntryTuple, 0, cassandraToPigData(entry.getKey(), keyValidator), keyValidator);
setTupleValue(mapEntryTuple, 1, cassandraToPigData(entry.getValue(), valueValidator), valueValidator);
innerTuple.set(i, mapEntryTuple);
i++;
}
tuple.set(position, innerTuple);
} | [
"private",
"void",
"setMapTupleValues",
"(",
"Tuple",
"tuple",
",",
"int",
"position",
",",
"Object",
"value",
",",
"AbstractType",
"<",
"?",
">",
"validator",
")",
"throws",
"ExecException",
"{",
"AbstractType",
"<",
"?",
">",
"keyValidator",
"=",
"(",
"(",
"MapType",
"<",
"?",
",",
"?",
">",
")",
"validator",
")",
".",
"getKeysType",
"(",
")",
";",
"AbstractType",
"<",
"?",
">",
"valueValidator",
"=",
"(",
"(",
"MapType",
"<",
"?",
",",
"?",
">",
")",
"validator",
")",
".",
"getValuesType",
"(",
")",
";",
"int",
"i",
"=",
"0",
";",
"Tuple",
"innerTuple",
"=",
"TupleFactory",
".",
"getInstance",
"(",
")",
".",
"newTuple",
"(",
"(",
"(",
"Map",
"<",
"?",
",",
"?",
">",
")",
"value",
")",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"?",
",",
"?",
">",
"entry",
":",
"(",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
")",
"value",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"Tuple",
"mapEntryTuple",
"=",
"TupleFactory",
".",
"getInstance",
"(",
")",
".",
"newTuple",
"(",
"2",
")",
";",
"setTupleValue",
"(",
"mapEntryTuple",
",",
"0",
",",
"cassandraToPigData",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"keyValidator",
")",
",",
"keyValidator",
")",
";",
"setTupleValue",
"(",
"mapEntryTuple",
",",
"1",
",",
"cassandraToPigData",
"(",
"entry",
".",
"getValue",
"(",
")",
",",
"valueValidator",
")",
",",
"valueValidator",
")",
";",
"innerTuple",
".",
"set",
"(",
"i",
",",
"mapEntryTuple",
")",
";",
"i",
"++",
";",
"}",
"tuple",
".",
"set",
"(",
"position",
",",
"innerTuple",
")",
";",
"}"
] | set the values of set/list at and after the position of the tuple | [
"set",
"the",
"values",
"of",
"set",
"/",
"list",
"at",
"and",
"after",
"the",
"position",
"of",
"the",
"tuple"
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CqlNativeStorage.java#L198-L214 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.shareProjectWithGroup | public void shareProjectWithGroup(GitlabAccessLevel accessLevel, String expiration, GitlabGroup group, GitlabProject project) throws IOException {
"""
Share a project with a group.
@param accessLevel The permissions level to grant the group.
@param group The group to share with.
@param project The project to be shared.
@param expiration Share expiration date in ISO 8601 format: 2016-09-26 or {@code null}.
@throws IOException on gitlab api call error
"""
Query query = new Query()
.append("group_id", group.getId().toString())
.append("group_access", String.valueOf(accessLevel.accessValue))
.appendIf("expires_at", expiration);
String tailUrl = GitlabProject.URL + "/" + project.getId() + "/share" + query.toString();
dispatch().to(tailUrl, Void.class);
} | java | public void shareProjectWithGroup(GitlabAccessLevel accessLevel, String expiration, GitlabGroup group, GitlabProject project) throws IOException {
Query query = new Query()
.append("group_id", group.getId().toString())
.append("group_access", String.valueOf(accessLevel.accessValue))
.appendIf("expires_at", expiration);
String tailUrl = GitlabProject.URL + "/" + project.getId() + "/share" + query.toString();
dispatch().to(tailUrl, Void.class);
} | [
"public",
"void",
"shareProjectWithGroup",
"(",
"GitlabAccessLevel",
"accessLevel",
",",
"String",
"expiration",
",",
"GitlabGroup",
"group",
",",
"GitlabProject",
"project",
")",
"throws",
"IOException",
"{",
"Query",
"query",
"=",
"new",
"Query",
"(",
")",
".",
"append",
"(",
"\"group_id\"",
",",
"group",
".",
"getId",
"(",
")",
".",
"toString",
"(",
")",
")",
".",
"append",
"(",
"\"group_access\"",
",",
"String",
".",
"valueOf",
"(",
"accessLevel",
".",
"accessValue",
")",
")",
".",
"appendIf",
"(",
"\"expires_at\"",
",",
"expiration",
")",
";",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"project",
".",
"getId",
"(",
")",
"+",
"\"/share\"",
"+",
"query",
".",
"toString",
"(",
")",
";",
"dispatch",
"(",
")",
".",
"to",
"(",
"tailUrl",
",",
"Void",
".",
"class",
")",
";",
"}"
] | Share a project with a group.
@param accessLevel The permissions level to grant the group.
@param group The group to share with.
@param project The project to be shared.
@param expiration Share expiration date in ISO 8601 format: 2016-09-26 or {@code null}.
@throws IOException on gitlab api call error | [
"Share",
"a",
"project",
"with",
"a",
"group",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3887-L3895 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java | Collectors.joining | public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
"""
Returns a {@code Collector} that concatenates the input elements,
separated by the specified delimiter, with the specified prefix and
suffix, in encounter order.
@param delimiter the delimiter to be used between each element
@param prefix the sequence of characters to be used at the beginning
of the joined result
@param suffix the sequence of characters to be used at the end
of the joined result
@return A {@code Collector} which concatenates CharSequence elements,
separated by the specified delimiter, in encounter order
"""
return new CollectorImpl<>(
() -> new StringJoiner(delimiter, prefix, suffix),
StringJoiner::add, StringJoiner::merge,
StringJoiner::toString, CH_NOID);
} | java | public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
return new CollectorImpl<>(
() -> new StringJoiner(delimiter, prefix, suffix),
StringJoiner::add, StringJoiner::merge,
StringJoiner::toString, CH_NOID);
} | [
"public",
"static",
"Collector",
"<",
"CharSequence",
",",
"?",
",",
"String",
">",
"joining",
"(",
"CharSequence",
"delimiter",
",",
"CharSequence",
"prefix",
",",
"CharSequence",
"suffix",
")",
"{",
"return",
"new",
"CollectorImpl",
"<>",
"(",
"(",
")",
"->",
"new",
"StringJoiner",
"(",
"delimiter",
",",
"prefix",
",",
"suffix",
")",
",",
"StringJoiner",
"::",
"add",
",",
"StringJoiner",
"::",
"merge",
",",
"StringJoiner",
"::",
"toString",
",",
"CH_NOID",
")",
";",
"}"
] | Returns a {@code Collector} that concatenates the input elements,
separated by the specified delimiter, with the specified prefix and
suffix, in encounter order.
@param delimiter the delimiter to be used between each element
@param prefix the sequence of characters to be used at the beginning
of the joined result
@param suffix the sequence of characters to be used at the end
of the joined result
@return A {@code Collector} which concatenates CharSequence elements,
separated by the specified delimiter, in encounter order | [
"Returns",
"a",
"{",
"@code",
"Collector",
"}",
"that",
"concatenates",
"the",
"input",
"elements",
"separated",
"by",
"the",
"specified",
"delimiter",
"with",
"the",
"specified",
"prefix",
"and",
"suffix",
"in",
"encounter",
"order",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java#L295-L302 |
elki-project/elki | elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/clique/CLIQUEUnit.java | CLIQUEUnit.addFeatureVector | public boolean addFeatureVector(DBIDRef id, NumberVector vector) {
"""
Adds the id of the specified feature vector to this unit, if this unit
contains the feature vector.
@param id Vector id
@param vector the feature vector to be added
@return true, if this unit contains the specified feature vector, false
otherwise
"""
if(contains(vector)) {
ids.add(id);
return true;
}
return false;
} | java | public boolean addFeatureVector(DBIDRef id, NumberVector vector) {
if(contains(vector)) {
ids.add(id);
return true;
}
return false;
} | [
"public",
"boolean",
"addFeatureVector",
"(",
"DBIDRef",
"id",
",",
"NumberVector",
"vector",
")",
"{",
"if",
"(",
"contains",
"(",
"vector",
")",
")",
"{",
"ids",
".",
"add",
"(",
"id",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Adds the id of the specified feature vector to this unit, if this unit
contains the feature vector.
@param id Vector id
@param vector the feature vector to be added
@return true, if this unit contains the specified feature vector, false
otherwise | [
"Adds",
"the",
"id",
"of",
"the",
"specified",
"feature",
"vector",
"to",
"this",
"unit",
"if",
"this",
"unit",
"contains",
"the",
"feature",
"vector",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/clique/CLIQUEUnit.java#L139-L145 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/faces/internal/PageFlowViewHandler.java | PageFlowViewHandler.restoreView | public UIViewRoot restoreView(FacesContext context, String viewId) {
"""
If we are in a request forwarded by {@link PageFlowNavigationHandler}, returns <code>null</code>; otherwise,
delegates to the base ViewHandler.
"""
ExternalContext externalContext = context.getExternalContext();
Object request = externalContext.getRequest();
HttpServletRequest httpRequest = null;
if ( request instanceof HttpServletRequest )
{
httpRequest = ( HttpServletRequest ) request;
//
// If we did a forward in PageFlowNavigationHandler, don't try to restore the view.
//
if ( httpRequest.getAttribute( PageFlowNavigationHandler.ALREADY_FORWARDED_ATTR ) != null )
{
return null;
}
//
// Create/restore the backing bean that corresponds to this request.
//
HttpServletResponse response = ( HttpServletResponse ) externalContext.getResponse();
ServletContext servletContext = ( ServletContext ) externalContext.getContext();
setBackingBean( httpRequest, response, servletContext );
}
UIViewRoot viewRoot = _delegate.restoreView( context, viewId );
savePreviousPageInfo( httpRequest, externalContext, viewId, viewRoot );
return viewRoot;
} | java | public UIViewRoot restoreView(FacesContext context, String viewId)
{
ExternalContext externalContext = context.getExternalContext();
Object request = externalContext.getRequest();
HttpServletRequest httpRequest = null;
if ( request instanceof HttpServletRequest )
{
httpRequest = ( HttpServletRequest ) request;
//
// If we did a forward in PageFlowNavigationHandler, don't try to restore the view.
//
if ( httpRequest.getAttribute( PageFlowNavigationHandler.ALREADY_FORWARDED_ATTR ) != null )
{
return null;
}
//
// Create/restore the backing bean that corresponds to this request.
//
HttpServletResponse response = ( HttpServletResponse ) externalContext.getResponse();
ServletContext servletContext = ( ServletContext ) externalContext.getContext();
setBackingBean( httpRequest, response, servletContext );
}
UIViewRoot viewRoot = _delegate.restoreView( context, viewId );
savePreviousPageInfo( httpRequest, externalContext, viewId, viewRoot );
return viewRoot;
} | [
"public",
"UIViewRoot",
"restoreView",
"(",
"FacesContext",
"context",
",",
"String",
"viewId",
")",
"{",
"ExternalContext",
"externalContext",
"=",
"context",
".",
"getExternalContext",
"(",
")",
";",
"Object",
"request",
"=",
"externalContext",
".",
"getRequest",
"(",
")",
";",
"HttpServletRequest",
"httpRequest",
"=",
"null",
";",
"if",
"(",
"request",
"instanceof",
"HttpServletRequest",
")",
"{",
"httpRequest",
"=",
"(",
"HttpServletRequest",
")",
"request",
";",
"//",
"// If we did a forward in PageFlowNavigationHandler, don't try to restore the view.",
"//",
"if",
"(",
"httpRequest",
".",
"getAttribute",
"(",
"PageFlowNavigationHandler",
".",
"ALREADY_FORWARDED_ATTR",
")",
"!=",
"null",
")",
"{",
"return",
"null",
";",
"}",
"//",
"// Create/restore the backing bean that corresponds to this request.",
"//",
"HttpServletResponse",
"response",
"=",
"(",
"HttpServletResponse",
")",
"externalContext",
".",
"getResponse",
"(",
")",
";",
"ServletContext",
"servletContext",
"=",
"(",
"ServletContext",
")",
"externalContext",
".",
"getContext",
"(",
")",
";",
"setBackingBean",
"(",
"httpRequest",
",",
"response",
",",
"servletContext",
")",
";",
"}",
"UIViewRoot",
"viewRoot",
"=",
"_delegate",
".",
"restoreView",
"(",
"context",
",",
"viewId",
")",
";",
"savePreviousPageInfo",
"(",
"httpRequest",
",",
"externalContext",
",",
"viewId",
",",
"viewRoot",
")",
";",
"return",
"viewRoot",
";",
"}"
] | If we are in a request forwarded by {@link PageFlowNavigationHandler}, returns <code>null</code>; otherwise,
delegates to the base ViewHandler. | [
"If",
"we",
"are",
"in",
"a",
"request",
"forwarded",
"by",
"{"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/faces/internal/PageFlowViewHandler.java#L210-L240 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/android/support/v7/widget/ChatLinearLayoutManager.java | ChatLinearLayoutManager.recycleByLayoutState | private void recycleByLayoutState(RecyclerView.Recycler recycler, LayoutState layoutState) {
"""
Helper method to call appropriate recycle method depending on current layout direction
@param recycler Current recycler that is attached to RecyclerView
@param layoutState Current layout state. Right now, this object does not change but
we may consider moving it out of this view so passing around as a
parameter for now, rather than accessing {@link #mLayoutState}
@see #recycleViewsFromStart(RecyclerView.Recycler, int)
@see #recycleViewsFromEnd(RecyclerView.Recycler, int)
@see LayoutState#mLayoutDirection
"""
if (!layoutState.mRecycle) {
return;
}
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
recycleViewsFromEnd(recycler, layoutState.mScrollingOffset);
} else {
recycleViewsFromStart(recycler, layoutState.mScrollingOffset);
}
} | java | private void recycleByLayoutState(RecyclerView.Recycler recycler, LayoutState layoutState) {
if (!layoutState.mRecycle) {
return;
}
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
recycleViewsFromEnd(recycler, layoutState.mScrollingOffset);
} else {
recycleViewsFromStart(recycler, layoutState.mScrollingOffset);
}
} | [
"private",
"void",
"recycleByLayoutState",
"(",
"RecyclerView",
".",
"Recycler",
"recycler",
",",
"LayoutState",
"layoutState",
")",
"{",
"if",
"(",
"!",
"layoutState",
".",
"mRecycle",
")",
"{",
"return",
";",
"}",
"if",
"(",
"layoutState",
".",
"mLayoutDirection",
"==",
"LayoutState",
".",
"LAYOUT_START",
")",
"{",
"recycleViewsFromEnd",
"(",
"recycler",
",",
"layoutState",
".",
"mScrollingOffset",
")",
";",
"}",
"else",
"{",
"recycleViewsFromStart",
"(",
"recycler",
",",
"layoutState",
".",
"mScrollingOffset",
")",
";",
"}",
"}"
] | Helper method to call appropriate recycle method depending on current layout direction
@param recycler Current recycler that is attached to RecyclerView
@param layoutState Current layout state. Right now, this object does not change but
we may consider moving it out of this view so passing around as a
parameter for now, rather than accessing {@link #mLayoutState}
@see #recycleViewsFromStart(RecyclerView.Recycler, int)
@see #recycleViewsFromEnd(RecyclerView.Recycler, int)
@see LayoutState#mLayoutDirection | [
"Helper",
"method",
"to",
"call",
"appropriate",
"recycle",
"method",
"depending",
"on",
"current",
"layout",
"direction"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/android/support/v7/widget/ChatLinearLayoutManager.java#L1279-L1288 |
yasserg/crawler4j | crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java | CrawlController.startNonBlocking | public <T extends WebCrawler> void startNonBlocking(Class<T> clazz, int numberOfCrawlers) {
"""
Start the crawling session and return immediately.
This method utilizes default crawler factory that creates new crawler using Java reflection
@param clazz
the class that implements the logic for crawler threads
@param numberOfCrawlers
the number of concurrent threads that will be contributing in
this crawling session.
@param <T> Your class extending WebCrawler
"""
start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, false);
} | java | public <T extends WebCrawler> void startNonBlocking(Class<T> clazz, int numberOfCrawlers) {
start(new DefaultWebCrawlerFactory<>(clazz), numberOfCrawlers, false);
} | [
"public",
"<",
"T",
"extends",
"WebCrawler",
">",
"void",
"startNonBlocking",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"int",
"numberOfCrawlers",
")",
"{",
"start",
"(",
"new",
"DefaultWebCrawlerFactory",
"<>",
"(",
"clazz",
")",
",",
"numberOfCrawlers",
",",
"false",
")",
";",
"}"
] | Start the crawling session and return immediately.
This method utilizes default crawler factory that creates new crawler using Java reflection
@param clazz
the class that implements the logic for crawler threads
@param numberOfCrawlers
the number of concurrent threads that will be contributing in
this crawling session.
@param <T> Your class extending WebCrawler | [
"Start",
"the",
"crawling",
"session",
"and",
"return",
"immediately",
".",
"This",
"method",
"utilizes",
"default",
"crawler",
"factory",
"that",
"creates",
"new",
"crawler",
"using",
"Java",
"reflection"
] | train | https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java#L265-L267 |
bluelinelabs/Conductor | conductor/src/main/java/com/bluelinelabs/conductor/Controller.java | Controller.requestPermissions | @TargetApi(Build.VERSION_CODES.M)
public final void requestPermissions(@NonNull final String[] permissions, final int requestCode) {
"""
Calls requestPermission(String[], int) from this Controller's host Activity. Results for this request,
including {@link #shouldShowRequestPermissionRationale(String)} and
{@link #onRequestPermissionsResult(int, String[], int[])} will be forwarded back to this Controller by the system.
"""
requestedPermissions.addAll(Arrays.asList(permissions));
executeWithRouter(new RouterRequiringFunc() {
@Override public void execute() { router.requestPermissions(instanceId, permissions, requestCode); }
});
} | java | @TargetApi(Build.VERSION_CODES.M)
public final void requestPermissions(@NonNull final String[] permissions, final int requestCode) {
requestedPermissions.addAll(Arrays.asList(permissions));
executeWithRouter(new RouterRequiringFunc() {
@Override public void execute() { router.requestPermissions(instanceId, permissions, requestCode); }
});
} | [
"@",
"TargetApi",
"(",
"Build",
".",
"VERSION_CODES",
".",
"M",
")",
"public",
"final",
"void",
"requestPermissions",
"(",
"@",
"NonNull",
"final",
"String",
"[",
"]",
"permissions",
",",
"final",
"int",
"requestCode",
")",
"{",
"requestedPermissions",
".",
"addAll",
"(",
"Arrays",
".",
"asList",
"(",
"permissions",
")",
")",
";",
"executeWithRouter",
"(",
"new",
"RouterRequiringFunc",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"router",
".",
"requestPermissions",
"(",
"instanceId",
",",
"permissions",
",",
"requestCode",
")",
";",
"}",
"}",
")",
";",
"}"
] | Calls requestPermission(String[], int) from this Controller's host Activity. Results for this request,
including {@link #shouldShowRequestPermissionRationale(String)} and
{@link #onRequestPermissionsResult(int, String[], int[])} will be forwarded back to this Controller by the system. | [
"Calls",
"requestPermission",
"(",
"String",
"[]",
"int",
")",
"from",
"this",
"Controller",
"s",
"host",
"Activity",
".",
"Results",
"for",
"this",
"request",
"including",
"{"
] | train | https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/Controller.java#L563-L570 |
graphql-java/graphql-java | src/main/java/graphql/schema/idl/SchemaGenerator.java | SchemaGenerator.makeExecutableSchema | public GraphQLSchema makeExecutableSchema(Options options, TypeDefinitionRegistry typeRegistry, RuntimeWiring wiring) throws SchemaProblem {
"""
This will take a {@link TypeDefinitionRegistry} and a {@link RuntimeWiring} and put them together to create a executable schema
controlled by the provided options.
@param options the controlling options
@param typeRegistry this can be obtained via {@link SchemaParser#parse(String)}
@param wiring this can be built using {@link RuntimeWiring#newRuntimeWiring()}
@return an executable schema
@throws SchemaProblem if there are problems in assembling a schema such as missing type resolvers or no operations defined
"""
TypeDefinitionRegistry typeRegistryCopy = new TypeDefinitionRegistry();
typeRegistryCopy.merge(typeRegistry);
schemaGeneratorHelper.addDeprecatedDirectiveDefinition(typeRegistryCopy);
List<GraphQLError> errors = typeChecker.checkTypeRegistry(typeRegistryCopy, wiring, options.enforceSchemaDirectives);
if (!errors.isEmpty()) {
throw new SchemaProblem(errors);
}
BuildContext buildCtx = new BuildContext(typeRegistryCopy, wiring);
return makeExecutableSchemaImpl(buildCtx);
} | java | public GraphQLSchema makeExecutableSchema(Options options, TypeDefinitionRegistry typeRegistry, RuntimeWiring wiring) throws SchemaProblem {
TypeDefinitionRegistry typeRegistryCopy = new TypeDefinitionRegistry();
typeRegistryCopy.merge(typeRegistry);
schemaGeneratorHelper.addDeprecatedDirectiveDefinition(typeRegistryCopy);
List<GraphQLError> errors = typeChecker.checkTypeRegistry(typeRegistryCopy, wiring, options.enforceSchemaDirectives);
if (!errors.isEmpty()) {
throw new SchemaProblem(errors);
}
BuildContext buildCtx = new BuildContext(typeRegistryCopy, wiring);
return makeExecutableSchemaImpl(buildCtx);
} | [
"public",
"GraphQLSchema",
"makeExecutableSchema",
"(",
"Options",
"options",
",",
"TypeDefinitionRegistry",
"typeRegistry",
",",
"RuntimeWiring",
"wiring",
")",
"throws",
"SchemaProblem",
"{",
"TypeDefinitionRegistry",
"typeRegistryCopy",
"=",
"new",
"TypeDefinitionRegistry",
"(",
")",
";",
"typeRegistryCopy",
".",
"merge",
"(",
"typeRegistry",
")",
";",
"schemaGeneratorHelper",
".",
"addDeprecatedDirectiveDefinition",
"(",
"typeRegistryCopy",
")",
";",
"List",
"<",
"GraphQLError",
">",
"errors",
"=",
"typeChecker",
".",
"checkTypeRegistry",
"(",
"typeRegistryCopy",
",",
"wiring",
",",
"options",
".",
"enforceSchemaDirectives",
")",
";",
"if",
"(",
"!",
"errors",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"SchemaProblem",
"(",
"errors",
")",
";",
"}",
"BuildContext",
"buildCtx",
"=",
"new",
"BuildContext",
"(",
"typeRegistryCopy",
",",
"wiring",
")",
";",
"return",
"makeExecutableSchemaImpl",
"(",
"buildCtx",
")",
";",
"}"
] | This will take a {@link TypeDefinitionRegistry} and a {@link RuntimeWiring} and put them together to create a executable schema
controlled by the provided options.
@param options the controlling options
@param typeRegistry this can be obtained via {@link SchemaParser#parse(String)}
@param wiring this can be built using {@link RuntimeWiring#newRuntimeWiring()}
@return an executable schema
@throws SchemaProblem if there are problems in assembling a schema such as missing type resolvers or no operations defined | [
"This",
"will",
"take",
"a",
"{",
"@link",
"TypeDefinitionRegistry",
"}",
"and",
"a",
"{",
"@link",
"RuntimeWiring",
"}",
"and",
"put",
"them",
"together",
"to",
"create",
"a",
"executable",
"schema",
"controlled",
"by",
"the",
"provided",
"options",
"."
] | train | https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/idl/SchemaGenerator.java#L252-L266 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfAction.java | PdfAction.gotoRemotePage | public static PdfAction gotoRemotePage(String filename, String dest, boolean isName, boolean newWindow) {
"""
Creates a GoToR action to a named destination.
@param filename the file name to go to
@param dest the destination name
@param isName if true sets the destination as a name, if false sets it as a String
@param newWindow open the document in a new window if <CODE>true</CODE>, if false the current document is replaced by the new document.
@return a GoToR action
"""
PdfAction action = new PdfAction();
action.put(PdfName.F, new PdfString(filename));
action.put(PdfName.S, PdfName.GOTOR);
if (isName)
action.put(PdfName.D, new PdfName(dest));
else
action.put(PdfName.D, new PdfString(dest, null));
if (newWindow)
action.put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE);
return action;
} | java | public static PdfAction gotoRemotePage(String filename, String dest, boolean isName, boolean newWindow) {
PdfAction action = new PdfAction();
action.put(PdfName.F, new PdfString(filename));
action.put(PdfName.S, PdfName.GOTOR);
if (isName)
action.put(PdfName.D, new PdfName(dest));
else
action.put(PdfName.D, new PdfString(dest, null));
if (newWindow)
action.put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE);
return action;
} | [
"public",
"static",
"PdfAction",
"gotoRemotePage",
"(",
"String",
"filename",
",",
"String",
"dest",
",",
"boolean",
"isName",
",",
"boolean",
"newWindow",
")",
"{",
"PdfAction",
"action",
"=",
"new",
"PdfAction",
"(",
")",
";",
"action",
".",
"put",
"(",
"PdfName",
".",
"F",
",",
"new",
"PdfString",
"(",
"filename",
")",
")",
";",
"action",
".",
"put",
"(",
"PdfName",
".",
"S",
",",
"PdfName",
".",
"GOTOR",
")",
";",
"if",
"(",
"isName",
")",
"action",
".",
"put",
"(",
"PdfName",
".",
"D",
",",
"new",
"PdfName",
"(",
"dest",
")",
")",
";",
"else",
"action",
".",
"put",
"(",
"PdfName",
".",
"D",
",",
"new",
"PdfString",
"(",
"dest",
",",
"null",
")",
")",
";",
"if",
"(",
"newWindow",
")",
"action",
".",
"put",
"(",
"PdfName",
".",
"NEWWINDOW",
",",
"PdfBoolean",
".",
"PDFTRUE",
")",
";",
"return",
"action",
";",
"}"
] | Creates a GoToR action to a named destination.
@param filename the file name to go to
@param dest the destination name
@param isName if true sets the destination as a name, if false sets it as a String
@param newWindow open the document in a new window if <CODE>true</CODE>, if false the current document is replaced by the new document.
@return a GoToR action | [
"Creates",
"a",
"GoToR",
"action",
"to",
"a",
"named",
"destination",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfAction.java#L488-L499 |
ManfredTremmel/gwt-bean-validators | gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/util/ObjectUtils.java | ObjectUtils.containsConstant | public static boolean containsConstant(final Enum<?>[] enumValues, final String constant) {
"""
Check whether the given array of enum constants contains a constant with the given name,
ignoring case when determining a match.
@param enumValues the enum values to check, typically the product of a call to MyEnum.values()
@param constant the constant name to find (must not be null or empty string)
@return whether the constant has been found in the given array
"""
return ObjectUtils.containsConstant(enumValues, constant, false);
} | java | public static boolean containsConstant(final Enum<?>[] enumValues, final String constant) {
return ObjectUtils.containsConstant(enumValues, constant, false);
} | [
"public",
"static",
"boolean",
"containsConstant",
"(",
"final",
"Enum",
"<",
"?",
">",
"[",
"]",
"enumValues",
",",
"final",
"String",
"constant",
")",
"{",
"return",
"ObjectUtils",
".",
"containsConstant",
"(",
"enumValues",
",",
"constant",
",",
"false",
")",
";",
"}"
] | Check whether the given array of enum constants contains a constant with the given name,
ignoring case when determining a match.
@param enumValues the enum values to check, typically the product of a call to MyEnum.values()
@param constant the constant name to find (must not be null or empty string)
@return whether the constant has been found in the given array | [
"Check",
"whether",
"the",
"given",
"array",
"of",
"enum",
"constants",
"contains",
"a",
"constant",
"with",
"the",
"given",
"name",
"ignoring",
"case",
"when",
"determining",
"a",
"match",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/util/ObjectUtils.java#L218-L220 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDITimephasedWorkNormaliser.java | MSPDITimephasedWorkNormaliser.splitDays | private void splitDays(ProjectCalendar calendar, LinkedList<TimephasedWork> list) {
"""
This method breaks down spans of time into individual days.
@param calendar current project calendar
@param list list of assignment data
"""
LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
for (TimephasedWork assignment : list)
{
while (assignment != null)
{
Date startDay = DateHelper.getDayStartDate(assignment.getStart());
Date finishDay = DateHelper.getDayStartDate(assignment.getFinish());
// special case - when the finishday time is midnight, it's really the previous day...
if (assignment.getFinish().getTime() == finishDay.getTime())
{
finishDay = DateHelper.addDays(finishDay, -1);
}
if (startDay.getTime() == finishDay.getTime())
{
result.add(assignment);
break;
}
TimephasedWork[] split = splitFirstDay(calendar, assignment);
if (split[0] != null)
{
result.add(split[0]);
}
assignment = split[1];
}
}
list.clear();
list.addAll(result);
} | java | private void splitDays(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
{
LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
for (TimephasedWork assignment : list)
{
while (assignment != null)
{
Date startDay = DateHelper.getDayStartDate(assignment.getStart());
Date finishDay = DateHelper.getDayStartDate(assignment.getFinish());
// special case - when the finishday time is midnight, it's really the previous day...
if (assignment.getFinish().getTime() == finishDay.getTime())
{
finishDay = DateHelper.addDays(finishDay, -1);
}
if (startDay.getTime() == finishDay.getTime())
{
result.add(assignment);
break;
}
TimephasedWork[] split = splitFirstDay(calendar, assignment);
if (split[0] != null)
{
result.add(split[0]);
}
assignment = split[1];
}
}
list.clear();
list.addAll(result);
} | [
"private",
"void",
"splitDays",
"(",
"ProjectCalendar",
"calendar",
",",
"LinkedList",
"<",
"TimephasedWork",
">",
"list",
")",
"{",
"LinkedList",
"<",
"TimephasedWork",
">",
"result",
"=",
"new",
"LinkedList",
"<",
"TimephasedWork",
">",
"(",
")",
";",
"for",
"(",
"TimephasedWork",
"assignment",
":",
"list",
")",
"{",
"while",
"(",
"assignment",
"!=",
"null",
")",
"{",
"Date",
"startDay",
"=",
"DateHelper",
".",
"getDayStartDate",
"(",
"assignment",
".",
"getStart",
"(",
")",
")",
";",
"Date",
"finishDay",
"=",
"DateHelper",
".",
"getDayStartDate",
"(",
"assignment",
".",
"getFinish",
"(",
")",
")",
";",
"// special case - when the finishday time is midnight, it's really the previous day...",
"if",
"(",
"assignment",
".",
"getFinish",
"(",
")",
".",
"getTime",
"(",
")",
"==",
"finishDay",
".",
"getTime",
"(",
")",
")",
"{",
"finishDay",
"=",
"DateHelper",
".",
"addDays",
"(",
"finishDay",
",",
"-",
"1",
")",
";",
"}",
"if",
"(",
"startDay",
".",
"getTime",
"(",
")",
"==",
"finishDay",
".",
"getTime",
"(",
")",
")",
"{",
"result",
".",
"add",
"(",
"assignment",
")",
";",
"break",
";",
"}",
"TimephasedWork",
"[",
"]",
"split",
"=",
"splitFirstDay",
"(",
"calendar",
",",
"assignment",
")",
";",
"if",
"(",
"split",
"[",
"0",
"]",
"!=",
"null",
")",
"{",
"result",
".",
"add",
"(",
"split",
"[",
"0",
"]",
")",
";",
"}",
"assignment",
"=",
"split",
"[",
"1",
"]",
";",
"}",
"}",
"list",
".",
"clear",
"(",
")",
";",
"list",
".",
"addAll",
"(",
"result",
")",
";",
"}"
] | This method breaks down spans of time into individual days.
@param calendar current project calendar
@param list list of assignment data | [
"This",
"method",
"breaks",
"down",
"spans",
"of",
"time",
"into",
"individual",
"days",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDITimephasedWorkNormaliser.java#L81-L114 |
matomo-org/piwik-java-tracker | src/main/java/org/piwik/java/tracking/PiwikRequest.java | PiwikRequest.setRequestDatetime | public void setRequestDatetime(PiwikDate datetime) {
"""
Set the datetime of the request (normally the current time is used).
This can be used to record visits and page views in the past. The datetime
must be sent in UTC timezone. <em>Note: if you record data in the past, you will
need to <a href="http://piwik.org/faq/how-to/#faq_59">force Piwik to re-process
reports for the past dates</a>.</em> If you set the <em>Request Datetime</em> to a datetime
older than four hours then <em>Auth Token</em> must be set. If you set
<em>Request Datetime</em> with a datetime in the last four hours then you
don't need to pass <em>Auth Token</em>.
@param datetime the datetime of the request to set. A null value will remove this parameter
"""
if (datetime != null && new Date().getTime()-datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null){
throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.");
}
setParameter(REQUEST_DATETIME, datetime);
} | java | public void setRequestDatetime(PiwikDate datetime){
if (datetime != null && new Date().getTime()-datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null){
throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.");
}
setParameter(REQUEST_DATETIME, datetime);
} | [
"public",
"void",
"setRequestDatetime",
"(",
"PiwikDate",
"datetime",
")",
"{",
"if",
"(",
"datetime",
"!=",
"null",
"&&",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"datetime",
".",
"getTime",
"(",
")",
">",
"REQUEST_DATETIME_AUTH_LIMIT",
"&&",
"getAuthToken",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.\"",
")",
";",
"}",
"setParameter",
"(",
"REQUEST_DATETIME",
",",
"datetime",
")",
";",
"}"
] | Set the datetime of the request (normally the current time is used).
This can be used to record visits and page views in the past. The datetime
must be sent in UTC timezone. <em>Note: if you record data in the past, you will
need to <a href="http://piwik.org/faq/how-to/#faq_59">force Piwik to re-process
reports for the past dates</a>.</em> If you set the <em>Request Datetime</em> to a datetime
older than four hours then <em>Auth Token</em> must be set. If you set
<em>Request Datetime</em> with a datetime in the last four hours then you
don't need to pass <em>Auth Token</em>.
@param datetime the datetime of the request to set. A null value will remove this parameter | [
"Set",
"the",
"datetime",
"of",
"the",
"request",
"(",
"normally",
"the",
"current",
"time",
"is",
"used",
")",
".",
"This",
"can",
"be",
"used",
"to",
"record",
"visits",
"and",
"page",
"views",
"in",
"the",
"past",
".",
"The",
"datetime",
"must",
"be",
"sent",
"in",
"UTC",
"timezone",
".",
"<em",
">",
"Note",
":",
"if",
"you",
"record",
"data",
"in",
"the",
"past",
"you",
"will",
"need",
"to",
"<a",
"href",
"=",
"http",
":",
"//",
"piwik",
".",
"org",
"/",
"faq",
"/",
"how",
"-",
"to",
"/",
"#faq_59",
">",
"force",
"Piwik",
"to",
"re",
"-",
"process",
"reports",
"for",
"the",
"past",
"dates<",
"/",
"a",
">",
".",
"<",
"/",
"em",
">",
"If",
"you",
"set",
"the",
"<em",
">",
"Request",
"Datetime<",
"/",
"em",
">",
"to",
"a",
"datetime",
"older",
"than",
"four",
"hours",
"then",
"<em",
">",
"Auth",
"Token<",
"/",
"em",
">",
"must",
"be",
"set",
".",
"If",
"you",
"set",
"<em",
">",
"Request",
"Datetime<",
"/",
"em",
">",
"with",
"a",
"datetime",
"in",
"the",
"last",
"four",
"hours",
"then",
"you",
"don",
"t",
"need",
"to",
"pass",
"<em",
">",
"Auth",
"Token<",
"/",
"em",
">",
"."
] | train | https://github.com/matomo-org/piwik-java-tracker/blob/23df71d27a89e89dc7a539b2eda88c90a206458b/src/main/java/org/piwik/java/tracking/PiwikRequest.java#L1219-L1224 |
lodborg/interval-tree | src/main/java/com/lodborg/intervaltree/Interval.java | Interval.isRightOf | public boolean isRightOf(Interval<T> other) {
"""
This method checks, if this current interval is entirely to the right of another interval
with no common points. More formally, the method will return true, if for every point {@code x}
from the current interval and for every point {@code y} from the {@code other} interval the
inequality {@code x} > {@code y} holds. This formal definition implies in particular that if the start point
of the current interval is equal to the end point of the {@code other} interval, the method
will return {@code false} only if both points are inclusive and {@code true} in all other cases.
@param other The reference interval
@return {@code true}, if the current interval is entirely to the right of the {@code other}
interval, or {@code false} instead.
"""
if (other == null || other.isEmpty())
return false;
return isRightOf(other.end, other.isEndInclusive());
} | java | public boolean isRightOf(Interval<T> other){
if (other == null || other.isEmpty())
return false;
return isRightOf(other.end, other.isEndInclusive());
} | [
"public",
"boolean",
"isRightOf",
"(",
"Interval",
"<",
"T",
">",
"other",
")",
"{",
"if",
"(",
"other",
"==",
"null",
"||",
"other",
".",
"isEmpty",
"(",
")",
")",
"return",
"false",
";",
"return",
"isRightOf",
"(",
"other",
".",
"end",
",",
"other",
".",
"isEndInclusive",
"(",
")",
")",
";",
"}"
] | This method checks, if this current interval is entirely to the right of another interval
with no common points. More formally, the method will return true, if for every point {@code x}
from the current interval and for every point {@code y} from the {@code other} interval the
inequality {@code x} > {@code y} holds. This formal definition implies in particular that if the start point
of the current interval is equal to the end point of the {@code other} interval, the method
will return {@code false} only if both points are inclusive and {@code true} in all other cases.
@param other The reference interval
@return {@code true}, if the current interval is entirely to the right of the {@code other}
interval, or {@code false} instead. | [
"This",
"method",
"checks",
"if",
"this",
"current",
"interval",
"is",
"entirely",
"to",
"the",
"right",
"of",
"another",
"interval",
"with",
"no",
"common",
"points",
".",
"More",
"formally",
"the",
"method",
"will",
"return",
"true",
"if",
"for",
"every",
"point",
"{",
"@code",
"x",
"}",
"from",
"the",
"current",
"interval",
"and",
"for",
"every",
"point",
"{",
"@code",
"y",
"}",
"from",
"the",
"{",
"@code",
"other",
"}",
"interval",
"the",
"inequality",
"{",
"@code",
"x",
"}",
">",
";",
"{",
"@code",
"y",
"}",
"holds",
".",
"This",
"formal",
"definition",
"implies",
"in",
"particular",
"that",
"if",
"the",
"start",
"point",
"of",
"the",
"current",
"interval",
"is",
"equal",
"to",
"the",
"end",
"point",
"of",
"the",
"{",
"@code",
"other",
"}",
"interval",
"the",
"method",
"will",
"return",
"{",
"@code",
"false",
"}",
"only",
"if",
"both",
"points",
"are",
"inclusive",
"and",
"{",
"@code",
"true",
"}",
"in",
"all",
"other",
"cases",
"."
] | train | https://github.com/lodborg/interval-tree/blob/716b18fb0a5a53c9add9926176bc263f14c9bf90/src/main/java/com/lodborg/intervaltree/Interval.java#L415-L419 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigDecimalStream.java | BigDecimalStream.rangeClosed | public static Stream<BigDecimal> rangeClosed(BigDecimal startInclusive, BigDecimal endInclusive, BigDecimal step, MathContext mathContext) {
"""
Returns a sequential ordered {@code Stream<BigDecimal>} from {@code startInclusive}
(inclusive) to {@code endInclusive} (inclusive) by an incremental {@code step}.
<p>An equivalent sequence of increasing values can be produced
sequentially using a {@code for} loop as follows:
<pre>for (BigDecimal i = startInclusive; i.compareTo(endInclusive) <= 0; i = i.add(step, mathContext)) {
...
}</pre>
@param startInclusive the (inclusive) initial value
@param endInclusive the inclusive upper bound
@param step the step between elements
@param mathContext the {@link MathContext} used for all mathematical operations
@return a sequential {@code Stream<BigDecimal>}
@see #range(BigDecimal, BigDecimal, BigDecimal, MathContext)
"""
if (step.signum() == 0) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endInclusive.subtract(startInclusive).signum() == -step.signum()) {
return Stream.empty();
}
return StreamSupport.stream(new BigDecimalSpliterator(startInclusive, endInclusive, true, step, mathContext), false);
} | java | public static Stream<BigDecimal> rangeClosed(BigDecimal startInclusive, BigDecimal endInclusive, BigDecimal step, MathContext mathContext) {
if (step.signum() == 0) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endInclusive.subtract(startInclusive).signum() == -step.signum()) {
return Stream.empty();
}
return StreamSupport.stream(new BigDecimalSpliterator(startInclusive, endInclusive, true, step, mathContext), false);
} | [
"public",
"static",
"Stream",
"<",
"BigDecimal",
">",
"rangeClosed",
"(",
"BigDecimal",
"startInclusive",
",",
"BigDecimal",
"endInclusive",
",",
"BigDecimal",
"step",
",",
"MathContext",
"mathContext",
")",
"{",
"if",
"(",
"step",
".",
"signum",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"invalid step: 0\"",
")",
";",
"}",
"if",
"(",
"endInclusive",
".",
"subtract",
"(",
"startInclusive",
")",
".",
"signum",
"(",
")",
"==",
"-",
"step",
".",
"signum",
"(",
")",
")",
"{",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"}",
"return",
"StreamSupport",
".",
"stream",
"(",
"new",
"BigDecimalSpliterator",
"(",
"startInclusive",
",",
"endInclusive",
",",
"true",
",",
"step",
",",
"mathContext",
")",
",",
"false",
")",
";",
"}"
] | Returns a sequential ordered {@code Stream<BigDecimal>} from {@code startInclusive}
(inclusive) to {@code endInclusive} (inclusive) by an incremental {@code step}.
<p>An equivalent sequence of increasing values can be produced
sequentially using a {@code for} loop as follows:
<pre>for (BigDecimal i = startInclusive; i.compareTo(endInclusive) <= 0; i = i.add(step, mathContext)) {
...
}</pre>
@param startInclusive the (inclusive) initial value
@param endInclusive the inclusive upper bound
@param step the step between elements
@param mathContext the {@link MathContext} used for all mathematical operations
@return a sequential {@code Stream<BigDecimal>}
@see #range(BigDecimal, BigDecimal, BigDecimal, MathContext) | [
"Returns",
"a",
"sequential",
"ordered",
"{",
"@code",
"Stream<BigDecimal",
">",
"}",
"from",
"{",
"@code",
"startInclusive",
"}",
"(",
"inclusive",
")",
"to",
"{",
"@code",
"endInclusive",
"}",
"(",
"inclusive",
")",
"by",
"an",
"incremental",
"{",
"@code",
"step",
"}",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigDecimalStream.java#L96-L104 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/AccountsApi.java | AccountsApi.updatePermissionProfile | public PermissionProfile updatePermissionProfile(String accountId, String permissionProfileId, PermissionProfile permissionProfile) throws ApiException {
"""
Updates a permission profile within the specified account.
@param accountId The external account number (int) or account ID Guid. (required)
@param permissionProfileId (required)
@param permissionProfile (optional)
@return PermissionProfile
"""
return updatePermissionProfile(accountId, permissionProfileId, permissionProfile, null);
} | java | public PermissionProfile updatePermissionProfile(String accountId, String permissionProfileId, PermissionProfile permissionProfile) throws ApiException {
return updatePermissionProfile(accountId, permissionProfileId, permissionProfile, null);
} | [
"public",
"PermissionProfile",
"updatePermissionProfile",
"(",
"String",
"accountId",
",",
"String",
"permissionProfileId",
",",
"PermissionProfile",
"permissionProfile",
")",
"throws",
"ApiException",
"{",
"return",
"updatePermissionProfile",
"(",
"accountId",
",",
"permissionProfileId",
",",
"permissionProfile",
",",
"null",
")",
";",
"}"
] | Updates a permission profile within the specified account.
@param accountId The external account number (int) or account ID Guid. (required)
@param permissionProfileId (required)
@param permissionProfile (optional)
@return PermissionProfile | [
"Updates",
"a",
"permission",
"profile",
"within",
"the",
"specified",
"account",
"."
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/AccountsApi.java#L2907-L2909 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_instance_POST | public OvhInstanceDetail project_serviceName_instance_POST(String serviceName, String flavorId, String groupId, String imageId, Boolean monthlyBilling, String name, OvhNetworkParams[] networks, String region, String sshKeyId, String userData, String volumeId) throws IOException {
"""
Create a new instance
REST: POST /cloud/project/{serviceName}/instance
@param flavorId [required] Instance flavor id
@param groupId [required] Start instance in group
@param imageId [required] Instance image id
@param monthlyBilling [required] Active monthly billing
@param name [required] Instance name
@param networks [required] Create network interfaces
@param region [required] Instance region
@param serviceName [required] Project name
@param sshKeyId [required] SSH keypair id
@param userData [required] Configuration information or scripts to use upon launch
@param volumeId [required] Specify a volume id to boot from it
"""
String qPath = "/cloud/project/{serviceName}/instance";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "flavorId", flavorId);
addBody(o, "groupId", groupId);
addBody(o, "imageId", imageId);
addBody(o, "monthlyBilling", monthlyBilling);
addBody(o, "name", name);
addBody(o, "networks", networks);
addBody(o, "region", region);
addBody(o, "sshKeyId", sshKeyId);
addBody(o, "userData", userData);
addBody(o, "volumeId", volumeId);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhInstanceDetail.class);
} | java | public OvhInstanceDetail project_serviceName_instance_POST(String serviceName, String flavorId, String groupId, String imageId, Boolean monthlyBilling, String name, OvhNetworkParams[] networks, String region, String sshKeyId, String userData, String volumeId) throws IOException {
String qPath = "/cloud/project/{serviceName}/instance";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "flavorId", flavorId);
addBody(o, "groupId", groupId);
addBody(o, "imageId", imageId);
addBody(o, "monthlyBilling", monthlyBilling);
addBody(o, "name", name);
addBody(o, "networks", networks);
addBody(o, "region", region);
addBody(o, "sshKeyId", sshKeyId);
addBody(o, "userData", userData);
addBody(o, "volumeId", volumeId);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhInstanceDetail.class);
} | [
"public",
"OvhInstanceDetail",
"project_serviceName_instance_POST",
"(",
"String",
"serviceName",
",",
"String",
"flavorId",
",",
"String",
"groupId",
",",
"String",
"imageId",
",",
"Boolean",
"monthlyBilling",
",",
"String",
"name",
",",
"OvhNetworkParams",
"[",
"]",
"networks",
",",
"String",
"region",
",",
"String",
"sshKeyId",
",",
"String",
"userData",
",",
"String",
"volumeId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/instance\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"flavorId\"",
",",
"flavorId",
")",
";",
"addBody",
"(",
"o",
",",
"\"groupId\"",
",",
"groupId",
")",
";",
"addBody",
"(",
"o",
",",
"\"imageId\"",
",",
"imageId",
")",
";",
"addBody",
"(",
"o",
",",
"\"monthlyBilling\"",
",",
"monthlyBilling",
")",
";",
"addBody",
"(",
"o",
",",
"\"name\"",
",",
"name",
")",
";",
"addBody",
"(",
"o",
",",
"\"networks\"",
",",
"networks",
")",
";",
"addBody",
"(",
"o",
",",
"\"region\"",
",",
"region",
")",
";",
"addBody",
"(",
"o",
",",
"\"sshKeyId\"",
",",
"sshKeyId",
")",
";",
"addBody",
"(",
"o",
",",
"\"userData\"",
",",
"userData",
")",
";",
"addBody",
"(",
"o",
",",
"\"volumeId\"",
",",
"volumeId",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhInstanceDetail",
".",
"class",
")",
";",
"}"
] | Create a new instance
REST: POST /cloud/project/{serviceName}/instance
@param flavorId [required] Instance flavor id
@param groupId [required] Start instance in group
@param imageId [required] Instance image id
@param monthlyBilling [required] Active monthly billing
@param name [required] Instance name
@param networks [required] Create network interfaces
@param region [required] Instance region
@param serviceName [required] Project name
@param sshKeyId [required] SSH keypair id
@param userData [required] Configuration information or scripts to use upon launch
@param volumeId [required] Specify a volume id to boot from it | [
"Create",
"a",
"new",
"instance"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1791-L1807 |
acromusashi/acromusashi-stream | src/main/java/acromusashi/stream/bolt/hdfs/HdfsOutputSwitcher.java | HdfsOutputSwitcher.append | public void append(String target, long nowTime) throws IOException {
"""
メッセージをHDFSに出力する。
@param target 出力内容
@param nowTime 出力時刻
@throws IOException 入出力エラー発生時
"""
if (this.nextSwitchTime <= nowTime)
{
switchWriter(nowTime);
}
this.currentWriter.append(target);
} | java | public void append(String target, long nowTime) throws IOException
{
if (this.nextSwitchTime <= nowTime)
{
switchWriter(nowTime);
}
this.currentWriter.append(target);
} | [
"public",
"void",
"append",
"(",
"String",
"target",
",",
"long",
"nowTime",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"nextSwitchTime",
"<=",
"nowTime",
")",
"{",
"switchWriter",
"(",
"nowTime",
")",
";",
"}",
"this",
".",
"currentWriter",
".",
"append",
"(",
"target",
")",
";",
"}"
] | メッセージをHDFSに出力する。
@param target 出力内容
@param nowTime 出力時刻
@throws IOException 入出力エラー発生時 | [
"メッセージをHDFSに出力する。"
] | train | https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/bolt/hdfs/HdfsOutputSwitcher.java#L136-L144 |
kohsuke/args4j | args4j/src/org/kohsuke/args4j/spi/MapOptionHandler.java | MapOptionHandler.addToMap | protected void addToMap(String argument, Map m) throws CmdLineException {
"""
Encapsulates how a single string argument gets converted into key and value.
"""
if (String.valueOf(argument).indexOf('=') == -1) {
throw new CmdLineException(owner,Messages.FORMAT_ERROR_FOR_MAP);
}
String mapKey;
String mapValue;
//Splitting off the key from the value
int idx = argument.indexOf('=');
if (idx>=0) {
mapKey = argument.substring(0, idx);
mapValue = argument.substring(idx + 1);
if (mapValue.length()==0)
// Kohsuke: I think this is a bad choice, but this is needed to remain backward compatible
mapValue = null;
} else {
mapKey = argument;
mapValue = null;
}
if (mapKey.length()==0) {
throw new CmdLineException(owner,Messages.MAP_HAS_NO_KEY);
}
addToMap(m, mapKey, mapValue);
} | java | protected void addToMap(String argument, Map m) throws CmdLineException {
if (String.valueOf(argument).indexOf('=') == -1) {
throw new CmdLineException(owner,Messages.FORMAT_ERROR_FOR_MAP);
}
String mapKey;
String mapValue;
//Splitting off the key from the value
int idx = argument.indexOf('=');
if (idx>=0) {
mapKey = argument.substring(0, idx);
mapValue = argument.substring(idx + 1);
if (mapValue.length()==0)
// Kohsuke: I think this is a bad choice, but this is needed to remain backward compatible
mapValue = null;
} else {
mapKey = argument;
mapValue = null;
}
if (mapKey.length()==0) {
throw new CmdLineException(owner,Messages.MAP_HAS_NO_KEY);
}
addToMap(m, mapKey, mapValue);
} | [
"protected",
"void",
"addToMap",
"(",
"String",
"argument",
",",
"Map",
"m",
")",
"throws",
"CmdLineException",
"{",
"if",
"(",
"String",
".",
"valueOf",
"(",
"argument",
")",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"CmdLineException",
"(",
"owner",
",",
"Messages",
".",
"FORMAT_ERROR_FOR_MAP",
")",
";",
"}",
"String",
"mapKey",
";",
"String",
"mapValue",
";",
"//Splitting off the key from the value",
"int",
"idx",
"=",
"argument",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"idx",
">=",
"0",
")",
"{",
"mapKey",
"=",
"argument",
".",
"substring",
"(",
"0",
",",
"idx",
")",
";",
"mapValue",
"=",
"argument",
".",
"substring",
"(",
"idx",
"+",
"1",
")",
";",
"if",
"(",
"mapValue",
".",
"length",
"(",
")",
"==",
"0",
")",
"// Kohsuke: I think this is a bad choice, but this is needed to remain backward compatible",
"mapValue",
"=",
"null",
";",
"}",
"else",
"{",
"mapKey",
"=",
"argument",
";",
"mapValue",
"=",
"null",
";",
"}",
"if",
"(",
"mapKey",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"CmdLineException",
"(",
"owner",
",",
"Messages",
".",
"MAP_HAS_NO_KEY",
")",
";",
"}",
"addToMap",
"(",
"m",
",",
"mapKey",
",",
"mapValue",
")",
";",
"}"
] | Encapsulates how a single string argument gets converted into key and value. | [
"Encapsulates",
"how",
"a",
"single",
"string",
"argument",
"gets",
"converted",
"into",
"key",
"and",
"value",
"."
] | train | https://github.com/kohsuke/args4j/blob/dc2e7e265caf15a1a146e3389c1f16a8781f06cf/args4j/src/org/kohsuke/args4j/spi/MapOptionHandler.java#L60-L86 |
craftercms/engine | src/main/java/org/craftercms/engine/util/spring/BeanDefinitionUtils.java | BeanDefinitionUtils.addPropertyIfNotNull | public static void addPropertyIfNotNull(BeanDefinition definition, String propertyName, Object propertyValue) {
"""
Adds the property to the bean definition if the values it not empty
@param definition the bean definition
@param propertyName the property name
@param propertyValue the property value
"""
if (propertyValue != null) {
definition.getPropertyValues().add(propertyName, propertyValue);
}
} | java | public static void addPropertyIfNotNull(BeanDefinition definition, String propertyName, Object propertyValue) {
if (propertyValue != null) {
definition.getPropertyValues().add(propertyName, propertyValue);
}
} | [
"public",
"static",
"void",
"addPropertyIfNotNull",
"(",
"BeanDefinition",
"definition",
",",
"String",
"propertyName",
",",
"Object",
"propertyValue",
")",
"{",
"if",
"(",
"propertyValue",
"!=",
"null",
")",
"{",
"definition",
".",
"getPropertyValues",
"(",
")",
".",
"add",
"(",
"propertyName",
",",
"propertyValue",
")",
";",
"}",
"}"
] | Adds the property to the bean definition if the values it not empty
@param definition the bean definition
@param propertyName the property name
@param propertyValue the property value | [
"Adds",
"the",
"property",
"to",
"the",
"bean",
"definition",
"if",
"the",
"values",
"it",
"not",
"empty"
] | train | https://github.com/craftercms/engine/blob/6b3d0349b1598172926352cdbd97f495976a8187/src/main/java/org/craftercms/engine/util/spring/BeanDefinitionUtils.java#L75-L79 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java | JCudaDriver.cuStreamWriteValue64 | public static int cuStreamWriteValue64(CUstream stream, CUdeviceptr addr, long value, int flags) {
"""
Write a value to memory.<br>
<br>
Write a value to memory. Unless the
CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER flag is passed, the write is
preceded by a system-wide memory fence, equivalent to a
__threadfence_system() but scoped to the stream rather than a CUDA
thread.<br>
<br>
If the memory was registered via cuMemHostRegister(), the device pointer
should be obtained with cuMemHostGetDevicePointer(). This function cannot
be used with managed memory (cuMemAllocManaged).<br>
<br>
On Windows, the device must be using TCC, or the operation is not
supported. See cuDeviceGetAttribute().
@param stream The stream to do the write in.
@param addr The device address to write to.
@param value The value to write.
@param flags See {@link CUstreamWriteValue_flags}
@return CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED
@see JCudaDriver#cuStreamWaitValue64
@see JCudaDriver#cuStreamBatchMemOp
@see JCudaDriver#cuMemHostRegister
@see JCudaDriver#cuEventRecord
"""
return checkResult(cuStreamWriteValue64Native(stream, addr, value, flags));
} | java | public static int cuStreamWriteValue64(CUstream stream, CUdeviceptr addr, long value, int flags)
{
return checkResult(cuStreamWriteValue64Native(stream, addr, value, flags));
} | [
"public",
"static",
"int",
"cuStreamWriteValue64",
"(",
"CUstream",
"stream",
",",
"CUdeviceptr",
"addr",
",",
"long",
"value",
",",
"int",
"flags",
")",
"{",
"return",
"checkResult",
"(",
"cuStreamWriteValue64Native",
"(",
"stream",
",",
"addr",
",",
"value",
",",
"flags",
")",
")",
";",
"}"
] | Write a value to memory.<br>
<br>
Write a value to memory. Unless the
CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER flag is passed, the write is
preceded by a system-wide memory fence, equivalent to a
__threadfence_system() but scoped to the stream rather than a CUDA
thread.<br>
<br>
If the memory was registered via cuMemHostRegister(), the device pointer
should be obtained with cuMemHostGetDevicePointer(). This function cannot
be used with managed memory (cuMemAllocManaged).<br>
<br>
On Windows, the device must be using TCC, or the operation is not
supported. See cuDeviceGetAttribute().
@param stream The stream to do the write in.
@param addr The device address to write to.
@param value The value to write.
@param flags See {@link CUstreamWriteValue_flags}
@return CUDA_SUCCESS, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_NOT_SUPPORTED
@see JCudaDriver#cuStreamWaitValue64
@see JCudaDriver#cuStreamBatchMemOp
@see JCudaDriver#cuMemHostRegister
@see JCudaDriver#cuEventRecord | [
"Write",
"a",
"value",
"to",
"memory",
".",
"<br",
">",
"<br",
">",
"Write",
"a",
"value",
"to",
"memory",
".",
"Unless",
"the",
"CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER",
"flag",
"is",
"passed",
"the",
"write",
"is",
"preceded",
"by",
"a",
"system",
"-",
"wide",
"memory",
"fence",
"equivalent",
"to",
"a",
"__threadfence_system",
"()",
"but",
"scoped",
"to",
"the",
"stream",
"rather",
"than",
"a",
"CUDA",
"thread",
".",
"<br",
">",
"<br",
">",
"If",
"the",
"memory",
"was",
"registered",
"via",
"cuMemHostRegister",
"()",
"the",
"device",
"pointer",
"should",
"be",
"obtained",
"with",
"cuMemHostGetDevicePointer",
"()",
".",
"This",
"function",
"cannot",
"be",
"used",
"with",
"managed",
"memory",
"(",
"cuMemAllocManaged",
")",
".",
"<br",
">",
"<br",
">",
"On",
"Windows",
"the",
"device",
"must",
"be",
"using",
"TCC",
"or",
"the",
"operation",
"is",
"not",
"supported",
".",
"See",
"cuDeviceGetAttribute",
"()",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L13791-L13794 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWvWAbilityInfo | public void getWvWAbilityInfo(int[] ids, Callback<List<WvWAbility>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on WvW abilities API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/abilities">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of WvW abilities id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see WvWAbility WvW abilities info
"""
isParamValid(new ParamChecker(ids));
gw2API.getWvWAbilityInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getWvWAbilityInfo(int[] ids, Callback<List<WvWAbility>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getWvWAbilityInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getWvWAbilityInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"WvWAbility",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getWvWAbilityInfo",
"(",
"processIds",
"(",
"ids",
")",
",",
"GuildWars2",
".",
"lang",
".",
"getValue",
"(",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on WvW abilities API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/abilities">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of WvW abilities id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see WvWAbility WvW abilities info | [
"For",
"more",
"info",
"on",
"WvW",
"abilities",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"wvw",
"/",
"abilities",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2582-L2585 |
alkacon/opencms-core | src-modules/org/opencms/workplace/comparison/A_CmsDiffViewDialog.java | A_CmsDiffViewDialog.deactivatedEmphasizedButtonHtml | public String deactivatedEmphasizedButtonHtml(String name, String iconPath) {
"""
Returns the html code for a deactivated empfasized button.<p>
@param name the label of the button
@param iconPath the path to the icon
@return the html code for a deactivated empfasized button
"""
StringBuffer result = new StringBuffer();
result.append(
"<span style='vertical-align:middle;'><img style='width:20px;height:20px;display:inline;vertical-align:middle;text-decoration:none;' src=\'");
result.append(CmsWorkplace.getSkinUri());
result.append(iconPath);
result.append("\' alt=\'");
result.append(name);
result.append("\' title=\'");
result.append(name);
result.append("\'> <b>");
result.append(name);
result.append("</b></span>");
return result.toString();
} | java | public String deactivatedEmphasizedButtonHtml(String name, String iconPath) {
StringBuffer result = new StringBuffer();
result.append(
"<span style='vertical-align:middle;'><img style='width:20px;height:20px;display:inline;vertical-align:middle;text-decoration:none;' src=\'");
result.append(CmsWorkplace.getSkinUri());
result.append(iconPath);
result.append("\' alt=\'");
result.append(name);
result.append("\' title=\'");
result.append(name);
result.append("\'> <b>");
result.append(name);
result.append("</b></span>");
return result.toString();
} | [
"public",
"String",
"deactivatedEmphasizedButtonHtml",
"(",
"String",
"name",
",",
"String",
"iconPath",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"result",
".",
"append",
"(",
"\"<span style='vertical-align:middle;'><img style='width:20px;height:20px;display:inline;vertical-align:middle;text-decoration:none;' src=\\'\"",
")",
";",
"result",
".",
"append",
"(",
"CmsWorkplace",
".",
"getSkinUri",
"(",
")",
")",
";",
"result",
".",
"append",
"(",
"iconPath",
")",
";",
"result",
".",
"append",
"(",
"\"\\' alt=\\'\"",
")",
";",
"result",
".",
"append",
"(",
"name",
")",
";",
"result",
".",
"append",
"(",
"\"\\' title=\\'\"",
")",
";",
"result",
".",
"append",
"(",
"name",
")",
";",
"result",
".",
"append",
"(",
"\"\\'> <b>\"",
")",
";",
"result",
".",
"append",
"(",
"name",
")",
";",
"result",
".",
"append",
"(",
"\"</b></span>\"",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
] | Returns the html code for a deactivated empfasized button.<p>
@param name the label of the button
@param iconPath the path to the icon
@return the html code for a deactivated empfasized button | [
"Returns",
"the",
"html",
"code",
"for",
"a",
"deactivated",
"empfasized",
"button",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/comparison/A_CmsDiffViewDialog.java#L208-L223 |
GenesysPureEngage/authentication-client-java | src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java | AuthenticationApi.retrieveTokenAsync | public com.squareup.okhttp.Call retrieveTokenAsync(String grantType, String accept, String authorization, String clientId, String password, String refreshToken, String scope, String username, final ApiCallback<DefaultOAuth2AccessToken> callback) throws ApiException {
"""
Retrieve access token (asynchronously)
Retrieve an access token based on the grant type &mdash; Authorization Code Grant, Resource Owner Password Credentials Grant or Client Credentials Grant. For more information, see [Token Endpoint](https://tools.ietf.org/html/rfc6749). **Note:** For the optional **scope** parameter, the Authentication API supports only the `*` value.
@param grantType The grant type you use to implement authentication. (required)
@param accept The media type the Authentication API should should use for the response. For example: 'Accept: application/x-www-form-urlencoded' (optional)
@param authorization Basic authorization. For example: 'Authorization: Basic Y3...MQ==' (optional)
@param clientId The ID of the application or service that is registered as the client. You'll need to get this value from your PureEngage Cloud representative. (optional)
@param password The agent's password. (optional)
@param refreshToken See [Refresh Token](https://tools.ietf.org/html/rfc6749#section-1.5) for details. (optional)
@param scope The scope of the access request. The Authentication API supports only the `*` value. (optional)
@param username The agent's username. (optional)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object
"""
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = retrieveTokenValidateBeforeCall(grantType, accept, authorization, clientId, password, refreshToken, scope, username, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DefaultOAuth2AccessToken>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call retrieveTokenAsync(String grantType, String accept, String authorization, String clientId, String password, String refreshToken, String scope, String username, final ApiCallback<DefaultOAuth2AccessToken> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = retrieveTokenValidateBeforeCall(grantType, accept, authorization, clientId, password, refreshToken, scope, username, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DefaultOAuth2AccessToken>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"retrieveTokenAsync",
"(",
"String",
"grantType",
",",
"String",
"accept",
",",
"String",
"authorization",
",",
"String",
"clientId",
",",
"String",
"password",
",",
"String",
"refreshToken",
",",
"String",
"scope",
",",
"String",
"username",
",",
"final",
"ApiCallback",
"<",
"DefaultOAuth2AccessToken",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseBody",
".",
"ProgressListener",
"progressListener",
"=",
"null",
";",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"progressRequestListener",
"=",
"null",
";",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"progressListener",
"=",
"new",
"ProgressResponseBody",
".",
"ProgressListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"update",
"(",
"long",
"bytesRead",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onDownloadProgress",
"(",
"bytesRead",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"progressRequestListener",
"=",
"new",
"ProgressRequestBody",
".",
"ProgressRequestListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onRequestProgress",
"(",
"long",
"bytesWritten",
",",
"long",
"contentLength",
",",
"boolean",
"done",
")",
"{",
"callback",
".",
"onUploadProgress",
"(",
"bytesWritten",
",",
"contentLength",
",",
"done",
")",
";",
"}",
"}",
";",
"}",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"retrieveTokenValidateBeforeCall",
"(",
"grantType",
",",
"accept",
",",
"authorization",
",",
"clientId",
",",
"password",
",",
"refreshToken",
",",
"scope",
",",
"username",
",",
"progressListener",
",",
"progressRequestListener",
")",
";",
"Type",
"localVarReturnType",
"=",
"new",
"TypeToken",
"<",
"DefaultOAuth2AccessToken",
">",
"(",
")",
"{",
"}",
".",
"getType",
"(",
")",
";",
"apiClient",
".",
"executeAsync",
"(",
"call",
",",
"localVarReturnType",
",",
"callback",
")",
";",
"return",
"call",
";",
"}"
] | Retrieve access token (asynchronously)
Retrieve an access token based on the grant type &mdash; Authorization Code Grant, Resource Owner Password Credentials Grant or Client Credentials Grant. For more information, see [Token Endpoint](https://tools.ietf.org/html/rfc6749). **Note:** For the optional **scope** parameter, the Authentication API supports only the `*` value.
@param grantType The grant type you use to implement authentication. (required)
@param accept The media type the Authentication API should should use for the response. For example: 'Accept: application/x-www-form-urlencoded' (optional)
@param authorization Basic authorization. For example: 'Authorization: Basic Y3...MQ==' (optional)
@param clientId The ID of the application or service that is registered as the client. You'll need to get this value from your PureEngage Cloud representative. (optional)
@param password The agent's password. (optional)
@param refreshToken See [Refresh Token](https://tools.ietf.org/html/rfc6749#section-1.5) for details. (optional)
@param scope The scope of the access request. The Authentication API supports only the `*` value. (optional)
@param username The agent's username. (optional)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Retrieve",
"access",
"token",
"(",
"asynchronously",
")",
"Retrieve",
"an",
"access",
"token",
"based",
"on",
"the",
"grant",
"type",
"&",
";",
"mdash",
";",
"Authorization",
"Code",
"Grant",
"Resource",
"Owner",
"Password",
"Credentials",
"Grant",
"or",
"Client",
"Credentials",
"Grant",
".",
"For",
"more",
"information",
"see",
"[",
"Token",
"Endpoint",
"]",
"(",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc6749",
")",
".",
"**",
"Note",
":",
"**",
"For",
"the",
"optional",
"**",
"scope",
"**",
"parameter",
"the",
"Authentication",
"API",
"supports",
"only",
"the",
"`",
";",
"*",
"`",
";",
"value",
"."
] | train | https://github.com/GenesysPureEngage/authentication-client-java/blob/eb0d58343ee42ebd3c037163c1137f611dfcbb3a/src/main/java/com/genesys/internal/authentication/api/AuthenticationApi.java#L1089-L1114 |
vst/commons-math-extensions | src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java | DMatrixUtils.getOrder | public static int[] getOrder(int[] values, int[] indices, boolean descending) {
"""
Get the order of the specified elements in descending or ascending order.
@param values A vector of integer values.
@param indices The indices which will be considered for ordering.
@param descending Flag indicating if we go descending or not.
@return A vector of indices sorted in the provided order.
"""
// Create an index series:
Integer[] opIndices = ArrayUtils.toObject(indices);
// Sort indices:
Arrays.sort(opIndices, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (descending) {
return Double.compare(values[o2], values[o1]);
} else {
return Double.compare(values[o1], values[o2]);
}
}
});
return ArrayUtils.toPrimitive(opIndices);
} | java | public static int[] getOrder(int[] values, int[] indices, boolean descending) {
// Create an index series:
Integer[] opIndices = ArrayUtils.toObject(indices);
// Sort indices:
Arrays.sort(opIndices, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (descending) {
return Double.compare(values[o2], values[o1]);
} else {
return Double.compare(values[o1], values[o2]);
}
}
});
return ArrayUtils.toPrimitive(opIndices);
} | [
"public",
"static",
"int",
"[",
"]",
"getOrder",
"(",
"int",
"[",
"]",
"values",
",",
"int",
"[",
"]",
"indices",
",",
"boolean",
"descending",
")",
"{",
"// Create an index series:",
"Integer",
"[",
"]",
"opIndices",
"=",
"ArrayUtils",
".",
"toObject",
"(",
"indices",
")",
";",
"// Sort indices:",
"Arrays",
".",
"sort",
"(",
"opIndices",
",",
"new",
"Comparator",
"<",
"Integer",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"Integer",
"o1",
",",
"Integer",
"o2",
")",
"{",
"if",
"(",
"descending",
")",
"{",
"return",
"Double",
".",
"compare",
"(",
"values",
"[",
"o2",
"]",
",",
"values",
"[",
"o1",
"]",
")",
";",
"}",
"else",
"{",
"return",
"Double",
".",
"compare",
"(",
"values",
"[",
"o1",
"]",
",",
"values",
"[",
"o2",
"]",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"ArrayUtils",
".",
"toPrimitive",
"(",
"opIndices",
")",
";",
"}"
] | Get the order of the specified elements in descending or ascending order.
@param values A vector of integer values.
@param indices The indices which will be considered for ordering.
@param descending Flag indicating if we go descending or not.
@return A vector of indices sorted in the provided order. | [
"Get",
"the",
"order",
"of",
"the",
"specified",
"elements",
"in",
"descending",
"or",
"ascending",
"order",
"."
] | train | https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L264-L281 |
finmath/finmath-lib | src/main/java/net/finmath/functions/LinearAlgebra.java | LinearAlgebra.solveLinearEquationTikonov | public static double[] solveLinearEquationTikonov(double[][] matrixA, double[] b, double lambda) {
"""
Find a solution of the linear equation A x = b where
<ul>
<li>A is an n x m - matrix given as double[n][m]</li>
<li>b is an m - vector given as double[m],</li>
<li>x is an n - vector given as double[n],</li>
</ul>
using a standard Tikhonov regularization, i.e., we solve in the least square sense
A* x = b*
where A* = (A^T, lambda I)^T and b* = (b^T , 0)^T.
@param matrixA The matrix A (left hand side of the linear equation).
@param b The vector (right hand of the linear equation).
@param lambda The parameter lambda of the Tikhonov regularization. Lambda effectively measures which small numbers are considered zero.
@return A solution x to A x = b.
"""
if(lambda == 0) {
return solveLinearEquationLeastSquare(matrixA, b);
}
/*
* The copy of the array is inefficient, but the use cases for this method are currently limited.
* And SVD is an alternative to this method.
*/
int rows = matrixA.length;
int cols = matrixA[0].length;
double[][] matrixRegularized = new double[rows+cols][cols];
double[] bRegularized = new double[rows+cols]; // Note the JVM initializes arrays to zero.
for(int i=0; i<rows; i++) {
System.arraycopy(matrixA[i], 0, matrixRegularized[i], 0, cols);
}
System.arraycopy(b, 0, bRegularized, 0, rows);
for(int j=0; j<cols; j++) {
double[] matrixRow = matrixRegularized[rows+j];
matrixRow[j] = lambda;
}
// return solveLinearEquationLeastSquare(matrixRegularized, bRegularized);
DecompositionSolver solver = new QRDecomposition(new Array2DRowRealMatrix(matrixRegularized, false)).getSolver();
return solver.solve(new ArrayRealVector(bRegularized, false)).toArray();
} | java | public static double[] solveLinearEquationTikonov(double[][] matrixA, double[] b, double lambda) {
if(lambda == 0) {
return solveLinearEquationLeastSquare(matrixA, b);
}
/*
* The copy of the array is inefficient, but the use cases for this method are currently limited.
* And SVD is an alternative to this method.
*/
int rows = matrixA.length;
int cols = matrixA[0].length;
double[][] matrixRegularized = new double[rows+cols][cols];
double[] bRegularized = new double[rows+cols]; // Note the JVM initializes arrays to zero.
for(int i=0; i<rows; i++) {
System.arraycopy(matrixA[i], 0, matrixRegularized[i], 0, cols);
}
System.arraycopy(b, 0, bRegularized, 0, rows);
for(int j=0; j<cols; j++) {
double[] matrixRow = matrixRegularized[rows+j];
matrixRow[j] = lambda;
}
// return solveLinearEquationLeastSquare(matrixRegularized, bRegularized);
DecompositionSolver solver = new QRDecomposition(new Array2DRowRealMatrix(matrixRegularized, false)).getSolver();
return solver.solve(new ArrayRealVector(bRegularized, false)).toArray();
} | [
"public",
"static",
"double",
"[",
"]",
"solveLinearEquationTikonov",
"(",
"double",
"[",
"]",
"[",
"]",
"matrixA",
",",
"double",
"[",
"]",
"b",
",",
"double",
"lambda",
")",
"{",
"if",
"(",
"lambda",
"==",
"0",
")",
"{",
"return",
"solveLinearEquationLeastSquare",
"(",
"matrixA",
",",
"b",
")",
";",
"}",
"/*\n\t\t * The copy of the array is inefficient, but the use cases for this method are currently limited.\n\t\t * And SVD is an alternative to this method.\n\t\t */",
"int",
"rows",
"=",
"matrixA",
".",
"length",
";",
"int",
"cols",
"=",
"matrixA",
"[",
"0",
"]",
".",
"length",
";",
"double",
"[",
"]",
"[",
"]",
"matrixRegularized",
"=",
"new",
"double",
"[",
"rows",
"+",
"cols",
"]",
"[",
"cols",
"]",
";",
"double",
"[",
"]",
"bRegularized",
"=",
"new",
"double",
"[",
"rows",
"+",
"cols",
"]",
";",
"// Note the JVM initializes arrays to zero.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rows",
";",
"i",
"++",
")",
"{",
"System",
".",
"arraycopy",
"(",
"matrixA",
"[",
"i",
"]",
",",
"0",
",",
"matrixRegularized",
"[",
"i",
"]",
",",
"0",
",",
"cols",
")",
";",
"}",
"System",
".",
"arraycopy",
"(",
"b",
",",
"0",
",",
"bRegularized",
",",
"0",
",",
"rows",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"cols",
";",
"j",
"++",
")",
"{",
"double",
"[",
"]",
"matrixRow",
"=",
"matrixRegularized",
"[",
"rows",
"+",
"j",
"]",
";",
"matrixRow",
"[",
"j",
"]",
"=",
"lambda",
";",
"}",
"//\t\treturn solveLinearEquationLeastSquare(matrixRegularized, bRegularized);",
"DecompositionSolver",
"solver",
"=",
"new",
"QRDecomposition",
"(",
"new",
"Array2DRowRealMatrix",
"(",
"matrixRegularized",
",",
"false",
")",
")",
".",
"getSolver",
"(",
")",
";",
"return",
"solver",
".",
"solve",
"(",
"new",
"ArrayRealVector",
"(",
"bRegularized",
",",
"false",
")",
")",
".",
"toArray",
"(",
")",
";",
"}"
] | Find a solution of the linear equation A x = b where
<ul>
<li>A is an n x m - matrix given as double[n][m]</li>
<li>b is an m - vector given as double[m],</li>
<li>x is an n - vector given as double[n],</li>
</ul>
using a standard Tikhonov regularization, i.e., we solve in the least square sense
A* x = b*
where A* = (A^T, lambda I)^T and b* = (b^T , 0)^T.
@param matrixA The matrix A (left hand side of the linear equation).
@param b The vector (right hand of the linear equation).
@param lambda The parameter lambda of the Tikhonov regularization. Lambda effectively measures which small numbers are considered zero.
@return A solution x to A x = b. | [
"Find",
"a",
"solution",
"of",
"the",
"linear",
"equation",
"A",
"x",
"=",
"b",
"where",
"<ul",
">",
"<li",
">",
"A",
"is",
"an",
"n",
"x",
"m",
"-",
"matrix",
"given",
"as",
"double",
"[",
"n",
"]",
"[",
"m",
"]",
"<",
"/",
"li",
">",
"<li",
">",
"b",
"is",
"an",
"m",
"-",
"vector",
"given",
"as",
"double",
"[",
"m",
"]",
"<",
"/",
"li",
">",
"<li",
">",
"x",
"is",
"an",
"n",
"-",
"vector",
"given",
"as",
"double",
"[",
"n",
"]",
"<",
"/",
"li",
">",
"<",
"/",
"ul",
">",
"using",
"a",
"standard",
"Tikhonov",
"regularization",
"i",
".",
"e",
".",
"we",
"solve",
"in",
"the",
"least",
"square",
"sense",
"A",
"*",
"x",
"=",
"b",
"*",
"where",
"A",
"*",
"=",
"(",
"A^T",
"lambda",
"I",
")",
"^T",
"and",
"b",
"*",
"=",
"(",
"b^T",
"0",
")",
"^T",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/functions/LinearAlgebra.java#L81-L109 |
mgm-tp/jfunk | jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/DumpFileCreator.java | DumpFileCreator.createDumpFile | public File createDumpFile(final File dir, final String extension, final String urlString, final String additionalInfo) {
"""
Computes the best file to save the response to the current page.
"""
URI uri = URI.create(urlString);
String path = uri.getPath();
if (path == null) {
log.warn("Cannot create dump file for URI: " + uri);
return null;
}
String name = PATTERN_FIRST_LAST_SLASH.matcher(path).replaceAll("$1");
name = PATTERN_ILLEGAL_CHARS.matcher(name).replaceAll("_");
Key key = Key.get(dir.getPath(), extension);
MutableInt counter = countersMap.get(key);
if (counter == null) {
counter = new MutableInt();
countersMap.put(key, counter);
}
int counterValue = counter.intValue();
counter.increment();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%04d", counterValue));
sb.append('_');
sb.append(name);
if (StringUtils.isNotBlank(additionalInfo)) {
sb.append("_");
sb.append(additionalInfo);
}
sb.append(".");
sb.append(extension);
return new File(dir, sb.toString());
} | java | public File createDumpFile(final File dir, final String extension, final String urlString, final String additionalInfo) {
URI uri = URI.create(urlString);
String path = uri.getPath();
if (path == null) {
log.warn("Cannot create dump file for URI: " + uri);
return null;
}
String name = PATTERN_FIRST_LAST_SLASH.matcher(path).replaceAll("$1");
name = PATTERN_ILLEGAL_CHARS.matcher(name).replaceAll("_");
Key key = Key.get(dir.getPath(), extension);
MutableInt counter = countersMap.get(key);
if (counter == null) {
counter = new MutableInt();
countersMap.put(key, counter);
}
int counterValue = counter.intValue();
counter.increment();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%04d", counterValue));
sb.append('_');
sb.append(name);
if (StringUtils.isNotBlank(additionalInfo)) {
sb.append("_");
sb.append(additionalInfo);
}
sb.append(".");
sb.append(extension);
return new File(dir, sb.toString());
} | [
"public",
"File",
"createDumpFile",
"(",
"final",
"File",
"dir",
",",
"final",
"String",
"extension",
",",
"final",
"String",
"urlString",
",",
"final",
"String",
"additionalInfo",
")",
"{",
"URI",
"uri",
"=",
"URI",
".",
"create",
"(",
"urlString",
")",
";",
"String",
"path",
"=",
"uri",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"path",
"==",
"null",
")",
"{",
"log",
".",
"warn",
"(",
"\"Cannot create dump file for URI: \"",
"+",
"uri",
")",
";",
"return",
"null",
";",
"}",
"String",
"name",
"=",
"PATTERN_FIRST_LAST_SLASH",
".",
"matcher",
"(",
"path",
")",
".",
"replaceAll",
"(",
"\"$1\"",
")",
";",
"name",
"=",
"PATTERN_ILLEGAL_CHARS",
".",
"matcher",
"(",
"name",
")",
".",
"replaceAll",
"(",
"\"_\"",
")",
";",
"Key",
"key",
"=",
"Key",
".",
"get",
"(",
"dir",
".",
"getPath",
"(",
")",
",",
"extension",
")",
";",
"MutableInt",
"counter",
"=",
"countersMap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"counter",
"==",
"null",
")",
"{",
"counter",
"=",
"new",
"MutableInt",
"(",
")",
";",
"countersMap",
".",
"put",
"(",
"key",
",",
"counter",
")",
";",
"}",
"int",
"counterValue",
"=",
"counter",
".",
"intValue",
"(",
")",
";",
"counter",
".",
"increment",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"%04d\"",
",",
"counterValue",
")",
")",
";",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"sb",
".",
"append",
"(",
"name",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"additionalInfo",
")",
")",
"{",
"sb",
".",
"append",
"(",
"\"_\"",
")",
";",
"sb",
".",
"append",
"(",
"additionalInfo",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\".\"",
")",
";",
"sb",
".",
"append",
"(",
"extension",
")",
";",
"return",
"new",
"File",
"(",
"dir",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Computes the best file to save the response to the current page. | [
"Computes",
"the",
"best",
"file",
"to",
"save",
"the",
"response",
"to",
"the",
"current",
"page",
"."
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/DumpFileCreator.java#L52-L85 |
basho/riak-java-client | src/main/java/com/basho/riak/client/api/convert/reflection/AnnotationUtil.java | AnnotationUtil.getKey | public static <T> BinaryValue getKey(T domainObject, BinaryValue defaultKey) {
"""
Attempts to get a key from <code>domainObject</code> by looking for a
{@literal @RiakKey} annotated member. If non-present it simply returns
<code>defaultKey</code>
@param <T> the type of <code>domainObject</code>
@param domainObject the object to search for a key
@param defaultKey the pass through value that will get returned if no key
found on <code>domainObject</code>
@return either the value found on <code>domainObject</code>;s
{@literal @RiakKey} member or <code>defaultkey</code>
"""
BinaryValue key = getKey(domainObject);
if (key == null)
{
key = defaultKey;
}
return key;
} | java | public static <T> BinaryValue getKey(T domainObject, BinaryValue defaultKey)
{
BinaryValue key = getKey(domainObject);
if (key == null)
{
key = defaultKey;
}
return key;
} | [
"public",
"static",
"<",
"T",
">",
"BinaryValue",
"getKey",
"(",
"T",
"domainObject",
",",
"BinaryValue",
"defaultKey",
")",
"{",
"BinaryValue",
"key",
"=",
"getKey",
"(",
"domainObject",
")",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"key",
"=",
"defaultKey",
";",
"}",
"return",
"key",
";",
"}"
] | Attempts to get a key from <code>domainObject</code> by looking for a
{@literal @RiakKey} annotated member. If non-present it simply returns
<code>defaultKey</code>
@param <T> the type of <code>domainObject</code>
@param domainObject the object to search for a key
@param defaultKey the pass through value that will get returned if no key
found on <code>domainObject</code>
@return either the value found on <code>domainObject</code>;s
{@literal @RiakKey} member or <code>defaultkey</code> | [
"Attempts",
"to",
"get",
"a",
"key",
"from",
"<code",
">",
"domainObject<",
"/",
"code",
">",
"by",
"looking",
"for",
"a",
"{",
"@literal",
"@RiakKey",
"}",
"annotated",
"member",
".",
"If",
"non",
"-",
"present",
"it",
"simply",
"returns",
"<code",
">",
"defaultKey<",
"/",
"code",
">"
] | train | https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/api/convert/reflection/AnnotationUtil.java#L65-L73 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/taglib/jsf/AbstractHtmlImageTag.java | AbstractHtmlImageTag.prepareAttribute | protected void prepareAttribute(StringBuffer handlers, String name, Object value) {
"""
Prepares an attribute if the value is not null, appending it to the the
given StringBuffer.
@param handlers
The StringBuffer that output will be appended to.
@param name
the property name
@param value
the property value
"""
if (value != null) {
handlers.append(" ");
handlers.append(name);
handlers.append("=\"");
handlers.append(value);
handlers.append("\"");
}
} | java | protected void prepareAttribute(StringBuffer handlers, String name, Object value) {
if (value != null) {
handlers.append(" ");
handlers.append(name);
handlers.append("=\"");
handlers.append(value);
handlers.append("\"");
}
} | [
"protected",
"void",
"prepareAttribute",
"(",
"StringBuffer",
"handlers",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"handlers",
".",
"append",
"(",
"\" \"",
")",
";",
"handlers",
".",
"append",
"(",
"name",
")",
";",
"handlers",
".",
"append",
"(",
"\"=\\\"\"",
")",
";",
"handlers",
".",
"append",
"(",
"value",
")",
";",
"handlers",
".",
"append",
"(",
"\"\\\"\"",
")",
";",
"}",
"}"
] | Prepares an attribute if the value is not null, appending it to the the
given StringBuffer.
@param handlers
The StringBuffer that output will be appended to.
@param name
the property name
@param value
the property value | [
"Prepares",
"an",
"attribute",
"if",
"the",
"value",
"is",
"not",
"null",
"appending",
"it",
"to",
"the",
"the",
"given",
"StringBuffer",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/taglib/jsf/AbstractHtmlImageTag.java#L138-L146 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/Model.java | Model.setTS | @Deprecated
public void setTS(String name, java.util.Date date) {
"""
Performs a primitive conversion of <code>java.util.Date</code> to <code>java.sql.Timestamp</code>
based on the time value.
@param name name of field.
@param date date value.
@deprecated use {@link #setTimestamp(String, Object)} instead.
"""
if(date == null) {
set(name, null);
} else {
set(name, new java.sql.Timestamp(date.getTime()));
}
} | java | @Deprecated
public void setTS(String name, java.util.Date date) {
if(date == null) {
set(name, null);
} else {
set(name, new java.sql.Timestamp(date.getTime()));
}
} | [
"@",
"Deprecated",
"public",
"void",
"setTS",
"(",
"String",
"name",
",",
"java",
".",
"util",
".",
"Date",
"date",
")",
"{",
"if",
"(",
"date",
"==",
"null",
")",
"{",
"set",
"(",
"name",
",",
"null",
")",
";",
"}",
"else",
"{",
"set",
"(",
"name",
",",
"new",
"java",
".",
"sql",
".",
"Timestamp",
"(",
"date",
".",
"getTime",
"(",
")",
")",
")",
";",
"}",
"}"
] | Performs a primitive conversion of <code>java.util.Date</code> to <code>java.sql.Timestamp</code>
based on the time value.
@param name name of field.
@param date date value.
@deprecated use {@link #setTimestamp(String, Object)} instead. | [
"Performs",
"a",
"primitive",
"conversion",
"of",
"<code",
">",
"java",
".",
"util",
".",
"Date<",
"/",
"code",
">",
"to",
"<code",
">",
"java",
".",
"sql",
".",
"Timestamp<",
"/",
"code",
">",
"based",
"on",
"the",
"time",
"value",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L328-L335 |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java | VisualizeCamera2Activity.onDrawFrame | protected void onDrawFrame( SurfaceView view , Canvas canvas ) {
"""
Renders the visualizations. Override and invoke super to add your own
"""
// Code below is usefull when debugging display issues
// Paint paintFill = new Paint();
// paintFill.setColor(Color.RED);
// paintFill.setStyle(Paint.Style.FILL);
// Paint paintBorder = new Paint();
// paintBorder.setColor(Color.BLUE);
// paintBorder.setStyle(Paint.Style.STROKE);
// paintBorder.setStrokeWidth(6*displayMetrics.density);
//
// Rect r = new Rect(0,0,view.getWidth(),view.getHeight());
// canvas.drawRect(r,paintFill);
// canvas.drawRect(r,paintBorder);
switch( bitmapMode) {
case UNSAFE:
canvas.drawBitmap(this.bitmap, imageToView, null);
break;
case DOUBLE_BUFFER:
bitmapLock.lock();
try{
canvas.drawBitmap(this.bitmap, imageToView, null);
} finally {
bitmapLock.unlock();
}
break;
}
} | java | protected void onDrawFrame( SurfaceView view , Canvas canvas ) {
// Code below is usefull when debugging display issues
// Paint paintFill = new Paint();
// paintFill.setColor(Color.RED);
// paintFill.setStyle(Paint.Style.FILL);
// Paint paintBorder = new Paint();
// paintBorder.setColor(Color.BLUE);
// paintBorder.setStyle(Paint.Style.STROKE);
// paintBorder.setStrokeWidth(6*displayMetrics.density);
//
// Rect r = new Rect(0,0,view.getWidth(),view.getHeight());
// canvas.drawRect(r,paintFill);
// canvas.drawRect(r,paintBorder);
switch( bitmapMode) {
case UNSAFE:
canvas.drawBitmap(this.bitmap, imageToView, null);
break;
case DOUBLE_BUFFER:
bitmapLock.lock();
try{
canvas.drawBitmap(this.bitmap, imageToView, null);
} finally {
bitmapLock.unlock();
}
break;
}
} | [
"protected",
"void",
"onDrawFrame",
"(",
"SurfaceView",
"view",
",",
"Canvas",
"canvas",
")",
"{",
"// Code below is usefull when debugging display issues",
"//\t\tPaint paintFill = new Paint();",
"//\t\tpaintFill.setColor(Color.RED);",
"//\t\tpaintFill.setStyle(Paint.Style.FILL);",
"//\t\tPaint paintBorder = new Paint();",
"//\t\tpaintBorder.setColor(Color.BLUE);",
"//\t\tpaintBorder.setStyle(Paint.Style.STROKE);",
"//\t\tpaintBorder.setStrokeWidth(6*displayMetrics.density);",
"//",
"//\t\tRect r = new Rect(0,0,view.getWidth(),view.getHeight());",
"//\t\tcanvas.drawRect(r,paintFill);",
"//\t\tcanvas.drawRect(r,paintBorder);",
"switch",
"(",
"bitmapMode",
")",
"{",
"case",
"UNSAFE",
":",
"canvas",
".",
"drawBitmap",
"(",
"this",
".",
"bitmap",
",",
"imageToView",
",",
"null",
")",
";",
"break",
";",
"case",
"DOUBLE_BUFFER",
":",
"bitmapLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"canvas",
".",
"drawBitmap",
"(",
"this",
".",
"bitmap",
",",
"imageToView",
",",
"null",
")",
";",
"}",
"finally",
"{",
"bitmapLock",
".",
"unlock",
"(",
")",
";",
"}",
"break",
";",
"}",
"}"
] | Renders the visualizations. Override and invoke super to add your own | [
"Renders",
"the",
"visualizations",
".",
"Override",
"and",
"invoke",
"super",
"to",
"add",
"your",
"own"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L452-L480 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java | IdClassMetadata.findConstructor | private MethodHandle findConstructor() {
"""
Creates and returns the MethodHandle for the constructor.
@return the MethodHandle for the constructor.
"""
try {
MethodHandle mh = MethodHandles.publicLookup().findConstructor(clazz,
MethodType.methodType(void.class, getIdType()));
return mh;
} catch (NoSuchMethodException | IllegalAccessException exp) {
String pattern = "Class %s requires a public constructor with one parameter of type %s";
String error = String.format(pattern, clazz.getName(), getIdType());
throw new EntityManagerException(error, exp);
}
} | java | private MethodHandle findConstructor() {
try {
MethodHandle mh = MethodHandles.publicLookup().findConstructor(clazz,
MethodType.methodType(void.class, getIdType()));
return mh;
} catch (NoSuchMethodException | IllegalAccessException exp) {
String pattern = "Class %s requires a public constructor with one parameter of type %s";
String error = String.format(pattern, clazz.getName(), getIdType());
throw new EntityManagerException(error, exp);
}
} | [
"private",
"MethodHandle",
"findConstructor",
"(",
")",
"{",
"try",
"{",
"MethodHandle",
"mh",
"=",
"MethodHandles",
".",
"publicLookup",
"(",
")",
".",
"findConstructor",
"(",
"clazz",
",",
"MethodType",
".",
"methodType",
"(",
"void",
".",
"class",
",",
"getIdType",
"(",
")",
")",
")",
";",
"return",
"mh",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"|",
"IllegalAccessException",
"exp",
")",
"{",
"String",
"pattern",
"=",
"\"Class %s requires a public constructor with one parameter of type %s\"",
";",
"String",
"error",
"=",
"String",
".",
"format",
"(",
"pattern",
",",
"clazz",
".",
"getName",
"(",
")",
",",
"getIdType",
"(",
")",
")",
";",
"throw",
"new",
"EntityManagerException",
"(",
"error",
",",
"exp",
")",
";",
"}",
"}"
] | Creates and returns the MethodHandle for the constructor.
@return the MethodHandle for the constructor. | [
"Creates",
"and",
"returns",
"the",
"MethodHandle",
"for",
"the",
"constructor",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/IdClassMetadata.java#L131-L141 |
OpenLiberty/open-liberty | dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java | RecoveryDirectorImpl.removeRecoveryRecord | private boolean removeRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) {
"""
<p>
Internal method to remove the record of an outstanding 'initialRecoveryComplete'
call from the supplied RecoveryAgent for the given failure scope.
</p>
<p>
This call will wake up all threads waiting for initial recovery to be completed.
</p>
<p>
Just prior to requesting a RecoveryAgent to "initiateRecovery" of a
FailureScope, the addRecoveryRecord method is driven to record the request.
When the client service completes the initial portion of the recovery process and
invokes RecoveryDirector.initialRecoveryComplete, this method called to remove
this record.
</p>
<p>
[ SERIAL PHASE ] [ INITIAL PHASE ] [ RETRY PHASE ]
</p>
@param recoveryAgent The RecoveryAgent that has completed the initial recovery
processing phase.
@param failureScope The FailureScope that defined the scope of this recovery
processing.
@return boolean true if there was an oustanding recovery record, otherwise false.
"""
if (tc.isEntryEnabled())
Tr.entry(tc, "removeRecoveryRecord", new Object[] { recoveryAgent, failureScope, this });
boolean found = false;
synchronized (_outstandingRecoveryRecords) {
final HashSet recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope);
if (recoveryAgentSet != null) {
found = recoveryAgentSet.remove(recoveryAgent);
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "removeRecoveryRecord", found);
return found;
} | java | private boolean removeRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) {
if (tc.isEntryEnabled())
Tr.entry(tc, "removeRecoveryRecord", new Object[] { recoveryAgent, failureScope, this });
boolean found = false;
synchronized (_outstandingRecoveryRecords) {
final HashSet recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope);
if (recoveryAgentSet != null) {
found = recoveryAgentSet.remove(recoveryAgent);
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "removeRecoveryRecord", found);
return found;
} | [
"private",
"boolean",
"removeRecoveryRecord",
"(",
"RecoveryAgent",
"recoveryAgent",
",",
"FailureScope",
"failureScope",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"removeRecoveryRecord\"",
",",
"new",
"Object",
"[",
"]",
"{",
"recoveryAgent",
",",
"failureScope",
",",
"this",
"}",
")",
";",
"boolean",
"found",
"=",
"false",
";",
"synchronized",
"(",
"_outstandingRecoveryRecords",
")",
"{",
"final",
"HashSet",
"recoveryAgentSet",
"=",
"_outstandingRecoveryRecords",
".",
"get",
"(",
"failureScope",
")",
";",
"if",
"(",
"recoveryAgentSet",
"!=",
"null",
")",
"{",
"found",
"=",
"recoveryAgentSet",
".",
"remove",
"(",
"recoveryAgent",
")",
";",
"}",
"}",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"removeRecoveryRecord\"",
",",
"found",
")",
";",
"return",
"found",
";",
"}"
] | <p>
Internal method to remove the record of an outstanding 'initialRecoveryComplete'
call from the supplied RecoveryAgent for the given failure scope.
</p>
<p>
This call will wake up all threads waiting for initial recovery to be completed.
</p>
<p>
Just prior to requesting a RecoveryAgent to "initiateRecovery" of a
FailureScope, the addRecoveryRecord method is driven to record the request.
When the client service completes the initial portion of the recovery process and
invokes RecoveryDirector.initialRecoveryComplete, this method called to remove
this record.
</p>
<p>
[ SERIAL PHASE ] [ INITIAL PHASE ] [ RETRY PHASE ]
</p>
@param recoveryAgent The RecoveryAgent that has completed the initial recovery
processing phase.
@param failureScope The FailureScope that defined the scope of this recovery
processing.
@return boolean true if there was an oustanding recovery record, otherwise false. | [
"<p",
">",
"Internal",
"method",
"to",
"remove",
"the",
"record",
"of",
"an",
"outstanding",
"initialRecoveryComplete",
"call",
"from",
"the",
"supplied",
"RecoveryAgent",
"for",
"the",
"given",
"failure",
"scope",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java#L1223-L1240 |
ineunetOS/knife-commons | knife-commons-utils/src/main/java/com/ineunet/knife/util/DecimalUtils.java | DecimalUtils.isValueEquals | public static boolean isValueEquals(BigDecimal decimal1, BigDecimal decimal2) {
"""
e.g. 0.30 equals 0.3 && 0.30 equals 0.30 && 0.30 equals 0.300.
"""
if (decimal1 == null && decimal2 == null) return true;
if (decimal1 == null && decimal2 != null) return false;
if (decimal1 != null && decimal2 == null) return false;
return cutInvalidSacle(decimal1).equals(cutInvalidSacle(decimal2));
} | java | public static boolean isValueEquals(BigDecimal decimal1, BigDecimal decimal2) {
if (decimal1 == null && decimal2 == null) return true;
if (decimal1 == null && decimal2 != null) return false;
if (decimal1 != null && decimal2 == null) return false;
return cutInvalidSacle(decimal1).equals(cutInvalidSacle(decimal2));
} | [
"public",
"static",
"boolean",
"isValueEquals",
"(",
"BigDecimal",
"decimal1",
",",
"BigDecimal",
"decimal2",
")",
"{",
"if",
"(",
"decimal1",
"==",
"null",
"&&",
"decimal2",
"==",
"null",
")",
"return",
"true",
";",
"if",
"(",
"decimal1",
"==",
"null",
"&&",
"decimal2",
"!=",
"null",
")",
"return",
"false",
";",
"if",
"(",
"decimal1",
"!=",
"null",
"&&",
"decimal2",
"==",
"null",
")",
"return",
"false",
";",
"return",
"cutInvalidSacle",
"(",
"decimal1",
")",
".",
"equals",
"(",
"cutInvalidSacle",
"(",
"decimal2",
")",
")",
";",
"}"
] | e.g. 0.30 equals 0.3 && 0.30 equals 0.30 && 0.30 equals 0.300. | [
"e",
".",
"g",
".",
"0",
".",
"30",
"equals",
"0",
".",
"3",
"&&",
"0",
".",
"30",
"equals",
"0",
".",
"30",
"&&",
"0",
".",
"30",
"equals",
"0",
".",
"300",
"."
] | train | https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/DecimalUtils.java#L49-L54 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_user_userId_openrc_GET | public OvhOpenrc project_serviceName_user_userId_openrc_GET(String serviceName, Long userId, String region, OvhOpenrcVersionEnum version) throws IOException {
"""
Get RC file of OpenStack
REST: GET /cloud/project/{serviceName}/user/{userId}/openrc
@param region [required] Region
@param serviceName [required] Service name
@param userId [required] User id
@param version [required] Identity API version
"""
String qPath = "/cloud/project/{serviceName}/user/{userId}/openrc";
StringBuilder sb = path(qPath, serviceName, userId);
query(sb, "region", region);
query(sb, "version", version);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOpenrc.class);
} | java | public OvhOpenrc project_serviceName_user_userId_openrc_GET(String serviceName, Long userId, String region, OvhOpenrcVersionEnum version) throws IOException {
String qPath = "/cloud/project/{serviceName}/user/{userId}/openrc";
StringBuilder sb = path(qPath, serviceName, userId);
query(sb, "region", region);
query(sb, "version", version);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOpenrc.class);
} | [
"public",
"OvhOpenrc",
"project_serviceName_user_userId_openrc_GET",
"(",
"String",
"serviceName",
",",
"Long",
"userId",
",",
"String",
"region",
",",
"OvhOpenrcVersionEnum",
"version",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/user/{userId}/openrc\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"userId",
")",
";",
"query",
"(",
"sb",
",",
"\"region\"",
",",
"region",
")",
";",
"query",
"(",
"sb",
",",
"\"version\"",
",",
"version",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhOpenrc",
".",
"class",
")",
";",
"}"
] | Get RC file of OpenStack
REST: GET /cloud/project/{serviceName}/user/{userId}/openrc
@param region [required] Region
@param serviceName [required] Service name
@param userId [required] User id
@param version [required] Identity API version | [
"Get",
"RC",
"file",
"of",
"OpenStack"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L478-L485 |
betfair/cougar | cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java | IdlToDSMojo.derivePackageName | private String derivePackageName(Service service, Document iddDoc) {
"""
Package name comes from explicit plugin param (if set), else the namespace definition, else
skream and die.
<p>
Having the plugin override allows backwards compatibility as well as being useful for
fiddling and tweaking.
"""
String packageName = service.getPackageName();
if (packageName == null) {
packageName = readNamespaceAttr(iddDoc);
if (packageName == null) {
throw new PluginException("Cannot find a package name "
+ "(not specified in plugin and no namespace in IDD");
}
}
return packageName;
} | java | private String derivePackageName(Service service, Document iddDoc) {
String packageName = service.getPackageName();
if (packageName == null) {
packageName = readNamespaceAttr(iddDoc);
if (packageName == null) {
throw new PluginException("Cannot find a package name "
+ "(not specified in plugin and no namespace in IDD");
}
}
return packageName;
} | [
"private",
"String",
"derivePackageName",
"(",
"Service",
"service",
",",
"Document",
"iddDoc",
")",
"{",
"String",
"packageName",
"=",
"service",
".",
"getPackageName",
"(",
")",
";",
"if",
"(",
"packageName",
"==",
"null",
")",
"{",
"packageName",
"=",
"readNamespaceAttr",
"(",
"iddDoc",
")",
";",
"if",
"(",
"packageName",
"==",
"null",
")",
"{",
"throw",
"new",
"PluginException",
"(",
"\"Cannot find a package name \"",
"+",
"\"(not specified in plugin and no namespace in IDD\"",
")",
";",
"}",
"}",
"return",
"packageName",
";",
"}"
] | Package name comes from explicit plugin param (if set), else the namespace definition, else
skream and die.
<p>
Having the plugin override allows backwards compatibility as well as being useful for
fiddling and tweaking. | [
"Package",
"name",
"comes",
"from",
"explicit",
"plugin",
"param",
"(",
"if",
"set",
")",
"else",
"the",
"namespace",
"definition",
"else",
"skream",
"and",
"die",
".",
"<p",
">",
"Having",
"the",
"plugin",
"override",
"allows",
"backwards",
"compatibility",
"as",
"well",
"as",
"being",
"useful",
"for",
"fiddling",
"and",
"tweaking",
"."
] | train | https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-codegen-plugin/src/main/java/com/betfair/cougar/codegen/IdlToDSMojo.java#L478-L489 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java | VelocityUtil.toWriter | public static void toWriter(String templateFileName, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
"""
生成内容写到响应内容中<br>
模板的变量来自于Request的Attribute对象
@param templateFileName 模板文件
@param request 请求对象,用于获取模板中的变量值
@param response 响应对象
"""
final VelocityContext context = new VelocityContext();
parseRequest(context, request);
parseSession(context, request.getSession(false));
Writer writer = null;
try {
writer = response.getWriter();
toWriter(templateFileName, context, writer);
} catch (Exception e) {
throw new UtilException(e, "Write Velocity content template by [{}] to response error!", templateFileName);
} finally {
IoUtil.close(writer);
}
} | java | public static void toWriter(String templateFileName, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
final VelocityContext context = new VelocityContext();
parseRequest(context, request);
parseSession(context, request.getSession(false));
Writer writer = null;
try {
writer = response.getWriter();
toWriter(templateFileName, context, writer);
} catch (Exception e) {
throw new UtilException(e, "Write Velocity content template by [{}] to response error!", templateFileName);
} finally {
IoUtil.close(writer);
}
} | [
"public",
"static",
"void",
"toWriter",
"(",
"String",
"templateFileName",
",",
"javax",
".",
"servlet",
".",
"http",
".",
"HttpServletRequest",
"request",
",",
"javax",
".",
"servlet",
".",
"http",
".",
"HttpServletResponse",
"response",
")",
"{",
"final",
"VelocityContext",
"context",
"=",
"new",
"VelocityContext",
"(",
")",
";",
"parseRequest",
"(",
"context",
",",
"request",
")",
";",
"parseSession",
"(",
"context",
",",
"request",
".",
"getSession",
"(",
"false",
")",
")",
";",
"Writer",
"writer",
"=",
"null",
";",
"try",
"{",
"writer",
"=",
"response",
".",
"getWriter",
"(",
")",
";",
"toWriter",
"(",
"templateFileName",
",",
"context",
",",
"writer",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"UtilException",
"(",
"e",
",",
"\"Write Velocity content template by [{}] to response error!\"",
",",
"templateFileName",
")",
";",
"}",
"finally",
"{",
"IoUtil",
".",
"close",
"(",
"writer",
")",
";",
"}",
"}"
] | 生成内容写到响应内容中<br>
模板的变量来自于Request的Attribute对象
@param templateFileName 模板文件
@param request 请求对象,用于获取模板中的变量值
@param response 响应对象 | [
"生成内容写到响应内容中<br",
">",
"模板的变量来自于Request的Attribute对象"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/template/engine/velocity/VelocityUtil.java#L214-L228 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java | Utils.readPropertiesFileQuietly | public static Properties readPropertiesFileQuietly( File file, Logger logger ) {
"""
Reads properties from a file but does not throw any error in case of problem.
@param file a properties file (can be null)
@param logger a logger (not null)
@return a {@link Properties} instance (never null)
"""
Properties result = new Properties();
try {
if( file != null && file.exists())
result = readPropertiesFile( file );
} catch( Exception e ) {
logger.severe( "Properties file " + file + " could not be read." );
logException( logger, e );
}
return result;
} | java | public static Properties readPropertiesFileQuietly( File file, Logger logger ) {
Properties result = new Properties();
try {
if( file != null && file.exists())
result = readPropertiesFile( file );
} catch( Exception e ) {
logger.severe( "Properties file " + file + " could not be read." );
logException( logger, e );
}
return result;
} | [
"public",
"static",
"Properties",
"readPropertiesFileQuietly",
"(",
"File",
"file",
",",
"Logger",
"logger",
")",
"{",
"Properties",
"result",
"=",
"new",
"Properties",
"(",
")",
";",
"try",
"{",
"if",
"(",
"file",
"!=",
"null",
"&&",
"file",
".",
"exists",
"(",
")",
")",
"result",
"=",
"readPropertiesFile",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"severe",
"(",
"\"Properties file \"",
"+",
"file",
"+",
"\" could not be read.\"",
")",
";",
"logException",
"(",
"logger",
",",
"e",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Reads properties from a file but does not throw any error in case of problem.
@param file a properties file (can be null)
@param logger a logger (not null)
@return a {@link Properties} instance (never null) | [
"Reads",
"properties",
"from",
"a",
"file",
"but",
"does",
"not",
"throw",
"any",
"error",
"in",
"case",
"of",
"problem",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L555-L568 |
mapbox/mapbox-navigation-android | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java | DistanceFormatter.shouldUpdate | public boolean shouldUpdate(@NonNull String language, @NonNull String unitType, int roundingIncrement) {
"""
Method that can be used to check if an instance of {@link DistanceFormatter}
needs to be updated based on the passed language / unitType.
@param language to check against the current formatter language
@param unitType to check against the current formatter unitType
@return true if new formatter is needed, false otherwise
"""
return !this.language.equals(language) || !this.unitType.equals(unitType)
|| !(this.roundingIncrement == roundingIncrement);
} | java | public boolean shouldUpdate(@NonNull String language, @NonNull String unitType, int roundingIncrement) {
return !this.language.equals(language) || !this.unitType.equals(unitType)
|| !(this.roundingIncrement == roundingIncrement);
} | [
"public",
"boolean",
"shouldUpdate",
"(",
"@",
"NonNull",
"String",
"language",
",",
"@",
"NonNull",
"String",
"unitType",
",",
"int",
"roundingIncrement",
")",
"{",
"return",
"!",
"this",
".",
"language",
".",
"equals",
"(",
"language",
")",
"||",
"!",
"this",
".",
"unitType",
".",
"equals",
"(",
"unitType",
")",
"||",
"!",
"(",
"this",
".",
"roundingIncrement",
"==",
"roundingIncrement",
")",
";",
"}"
] | Method that can be used to check if an instance of {@link DistanceFormatter}
needs to be updated based on the passed language / unitType.
@param language to check against the current formatter language
@param unitType to check against the current formatter unitType
@return true if new formatter is needed, false otherwise | [
"Method",
"that",
"can",
"be",
"used",
"to",
"check",
"if",
"an",
"instance",
"of",
"{",
"@link",
"DistanceFormatter",
"}",
"needs",
"to",
"be",
"updated",
"based",
"on",
"the",
"passed",
"language",
"/",
"unitType",
"."
] | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/utils/DistanceFormatter.java#L116-L119 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/composite/AttributeHandler.java | AttributeHandler._createPropertyDescriptor | private PropertyDescriptor _createPropertyDescriptor(boolean development) {
"""
This method could be called only if it is not necessary to set the following properties:
targets, default, required, methodSignature and type
@param development true if the current ProjectStage is Development
@return
"""
try
{
CompositeComponentPropertyDescriptor attributeDescriptor =
new CompositeComponentPropertyDescriptor(_name.getValue());
// If ProjectStage is Development, The "displayName", "shortDescription",
// "expert", "hidden", and "preferred" attributes are exposed
if (development)
{
CompositeTagAttributeUtils.addDevelopmentAttributesLiteral(attributeDescriptor,
_displayName, _shortDescription, _expert, _hidden, _preferred);
}
// note that no unspecified attributes are handled here, because the current
// tag does not contain any, otherwise this code would not have been called.
return attributeDescriptor;
}
catch (IntrospectionException e)
{
if (log.isLoggable(Level.SEVERE))
{
log.log(Level.SEVERE, "Cannot create PropertyDescriptor for attribute ",e);
}
throw new TagException(tag,e);
}
} | java | private PropertyDescriptor _createPropertyDescriptor(boolean development)
{
try
{
CompositeComponentPropertyDescriptor attributeDescriptor =
new CompositeComponentPropertyDescriptor(_name.getValue());
// If ProjectStage is Development, The "displayName", "shortDescription",
// "expert", "hidden", and "preferred" attributes are exposed
if (development)
{
CompositeTagAttributeUtils.addDevelopmentAttributesLiteral(attributeDescriptor,
_displayName, _shortDescription, _expert, _hidden, _preferred);
}
// note that no unspecified attributes are handled here, because the current
// tag does not contain any, otherwise this code would not have been called.
return attributeDescriptor;
}
catch (IntrospectionException e)
{
if (log.isLoggable(Level.SEVERE))
{
log.log(Level.SEVERE, "Cannot create PropertyDescriptor for attribute ",e);
}
throw new TagException(tag,e);
}
} | [
"private",
"PropertyDescriptor",
"_createPropertyDescriptor",
"(",
"boolean",
"development",
")",
"{",
"try",
"{",
"CompositeComponentPropertyDescriptor",
"attributeDescriptor",
"=",
"new",
"CompositeComponentPropertyDescriptor",
"(",
"_name",
".",
"getValue",
"(",
")",
")",
";",
"// If ProjectStage is Development, The \"displayName\", \"shortDescription\",",
"// \"expert\", \"hidden\", and \"preferred\" attributes are exposed",
"if",
"(",
"development",
")",
"{",
"CompositeTagAttributeUtils",
".",
"addDevelopmentAttributesLiteral",
"(",
"attributeDescriptor",
",",
"_displayName",
",",
"_shortDescription",
",",
"_expert",
",",
"_hidden",
",",
"_preferred",
")",
";",
"}",
"// note that no unspecified attributes are handled here, because the current",
"// tag does not contain any, otherwise this code would not have been called.",
"return",
"attributeDescriptor",
";",
"}",
"catch",
"(",
"IntrospectionException",
"e",
")",
"{",
"if",
"(",
"log",
".",
"isLoggable",
"(",
"Level",
".",
"SEVERE",
")",
")",
"{",
"log",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Cannot create PropertyDescriptor for attribute \"",
",",
"e",
")",
";",
"}",
"throw",
"new",
"TagException",
"(",
"tag",
",",
"e",
")",
";",
"}",
"}"
] | This method could be called only if it is not necessary to set the following properties:
targets, default, required, methodSignature and type
@param development true if the current ProjectStage is Development
@return | [
"This",
"method",
"could",
"be",
"called",
"only",
"if",
"it",
"is",
"not",
"necessary",
"to",
"set",
"the",
"following",
"properties",
":",
"targets",
"default",
"required",
"methodSignature",
"and",
"type"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/composite/AttributeHandler.java#L284-L312 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/memorymanager/CheckedMemorySegment.java | CheckedMemorySegment.putShort | public final CheckedMemorySegment putShort(int index, short value) {
"""
Writes two memory containing the given short value, in the current byte
order, into this buffer at the given position.
@param position The position at which the memory will be written.
@param value The short value to be written.
@return This view itself.
@throws IndexOutOfBoundsException Thrown, if the index is negative, or larger then the segment
size minus 2.
"""
if (index >= 0 && index < this.size - 1) {
this.memory[this.offset + index + 0] = (byte) (value >> 8);
this.memory[this.offset + index + 1] = (byte) value;
return this;
} else {
throw new IndexOutOfBoundsException();
}
} | java | public final CheckedMemorySegment putShort(int index, short value) {
if (index >= 0 && index < this.size - 1) {
this.memory[this.offset + index + 0] = (byte) (value >> 8);
this.memory[this.offset + index + 1] = (byte) value;
return this;
} else {
throw new IndexOutOfBoundsException();
}
} | [
"public",
"final",
"CheckedMemorySegment",
"putShort",
"(",
"int",
"index",
",",
"short",
"value",
")",
"{",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"this",
".",
"size",
"-",
"1",
")",
"{",
"this",
".",
"memory",
"[",
"this",
".",
"offset",
"+",
"index",
"+",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"value",
">>",
"8",
")",
";",
"this",
".",
"memory",
"[",
"this",
".",
"offset",
"+",
"index",
"+",
"1",
"]",
"=",
"(",
"byte",
")",
"value",
";",
"return",
"this",
";",
"}",
"else",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"}"
] | Writes two memory containing the given short value, in the current byte
order, into this buffer at the given position.
@param position The position at which the memory will be written.
@param value The short value to be written.
@return This view itself.
@throws IndexOutOfBoundsException Thrown, if the index is negative, or larger then the segment
size minus 2. | [
"Writes",
"two",
"memory",
"containing",
"the",
"given",
"short",
"value",
"in",
"the",
"current",
"byte",
"order",
"into",
"this",
"buffer",
"at",
"the",
"given",
"position",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/memorymanager/CheckedMemorySegment.java#L427-L435 |
xmlunit/xmlunit | xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java | DefaultComparisonFormatter.getFullFormattedXml | protected String getFullFormattedXml(final Node node, ComparisonType type, boolean formatXml) {
"""
Formats the node using a format suitable for the node type and comparison.
<p>The implementation outputs the document prolog and start element for {@code Document} and {@code DocumentType}
nodes and may elect to format the node's parent element rather than just the node depending on the node and
comparison type. It delegates to {@link #appendFullDocumentHeader} or {@link #getFormattedNodeXml}.</p>
@param node the node to format
@param type the comparison type
@param formatXml true if the Comparison was generated with {@link
org.xmlunit.builder.DiffBuilder#ignoreWhitespace()} - this affects the indentation of the generated output
@return the fomatted XML
@since XMLUnit 2.4.0
"""
StringBuilder sb = new StringBuilder();
final Node nodeToConvert;
if (type == ComparisonType.CHILD_NODELIST_SEQUENCE) {
nodeToConvert = node.getParentNode();
} else if (node instanceof Document) {
Document doc = (Document) node;
appendFullDocumentHeader(sb, doc);
return sb.toString();
} else if (node instanceof DocumentType) {
Document doc = node.getOwnerDocument();
appendFullDocumentHeader(sb, doc);
return sb.toString();
} else if (node instanceof Attr) {
nodeToConvert = ((Attr) node).getOwnerElement();
} else if (node instanceof org.w3c.dom.CharacterData) {
// in case of a simple text node, show the parent TAGs: "<a>xy</a>" instead "xy".
nodeToConvert = node.getParentNode();
} else {
nodeToConvert = node;
}
sb.append(getFormattedNodeXml(nodeToConvert, formatXml));
return sb.toString().trim();
} | java | protected String getFullFormattedXml(final Node node, ComparisonType type, boolean formatXml) {
StringBuilder sb = new StringBuilder();
final Node nodeToConvert;
if (type == ComparisonType.CHILD_NODELIST_SEQUENCE) {
nodeToConvert = node.getParentNode();
} else if (node instanceof Document) {
Document doc = (Document) node;
appendFullDocumentHeader(sb, doc);
return sb.toString();
} else if (node instanceof DocumentType) {
Document doc = node.getOwnerDocument();
appendFullDocumentHeader(sb, doc);
return sb.toString();
} else if (node instanceof Attr) {
nodeToConvert = ((Attr) node).getOwnerElement();
} else if (node instanceof org.w3c.dom.CharacterData) {
// in case of a simple text node, show the parent TAGs: "<a>xy</a>" instead "xy".
nodeToConvert = node.getParentNode();
} else {
nodeToConvert = node;
}
sb.append(getFormattedNodeXml(nodeToConvert, formatXml));
return sb.toString().trim();
} | [
"protected",
"String",
"getFullFormattedXml",
"(",
"final",
"Node",
"node",
",",
"ComparisonType",
"type",
",",
"boolean",
"formatXml",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"Node",
"nodeToConvert",
";",
"if",
"(",
"type",
"==",
"ComparisonType",
".",
"CHILD_NODELIST_SEQUENCE",
")",
"{",
"nodeToConvert",
"=",
"node",
".",
"getParentNode",
"(",
")",
";",
"}",
"else",
"if",
"(",
"node",
"instanceof",
"Document",
")",
"{",
"Document",
"doc",
"=",
"(",
"Document",
")",
"node",
";",
"appendFullDocumentHeader",
"(",
"sb",
",",
"doc",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"node",
"instanceof",
"DocumentType",
")",
"{",
"Document",
"doc",
"=",
"node",
".",
"getOwnerDocument",
"(",
")",
";",
"appendFullDocumentHeader",
"(",
"sb",
",",
"doc",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"node",
"instanceof",
"Attr",
")",
"{",
"nodeToConvert",
"=",
"(",
"(",
"Attr",
")",
"node",
")",
".",
"getOwnerElement",
"(",
")",
";",
"}",
"else",
"if",
"(",
"node",
"instanceof",
"org",
".",
"w3c",
".",
"dom",
".",
"CharacterData",
")",
"{",
"// in case of a simple text node, show the parent TAGs: \"<a>xy</a>\" instead \"xy\".",
"nodeToConvert",
"=",
"node",
".",
"getParentNode",
"(",
")",
";",
"}",
"else",
"{",
"nodeToConvert",
"=",
"node",
";",
"}",
"sb",
".",
"append",
"(",
"getFormattedNodeXml",
"(",
"nodeToConvert",
",",
"formatXml",
")",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
";",
"}"
] | Formats the node using a format suitable for the node type and comparison.
<p>The implementation outputs the document prolog and start element for {@code Document} and {@code DocumentType}
nodes and may elect to format the node's parent element rather than just the node depending on the node and
comparison type. It delegates to {@link #appendFullDocumentHeader} or {@link #getFormattedNodeXml}.</p>
@param node the node to format
@param type the comparison type
@param formatXml true if the Comparison was generated with {@link
org.xmlunit.builder.DiffBuilder#ignoreWhitespace()} - this affects the indentation of the generated output
@return the fomatted XML
@since XMLUnit 2.4.0 | [
"Formats",
"the",
"node",
"using",
"a",
"format",
"suitable",
"for",
"the",
"node",
"type",
"and",
"comparison",
"."
] | train | https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java#L359-L382 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java | TransformerHandlerImpl.processingInstruction | public void processingInstruction(String target, String data)
throws SAXException {
"""
Filter a processing instruction event.
@param target The processing instruction target.
@param data The text following the target.
@throws SAXException The client may throw
an exception during processing.
@see org.xml.sax.ContentHandler#processingInstruction
"""
if (DEBUG)
System.out.println("TransformerHandlerImpl#processingInstruction: "
+ target + ", " + data);
if (m_contentHandler != null)
{
m_contentHandler.processingInstruction(target, data);
}
} | java | public void processingInstruction(String target, String data)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#processingInstruction: "
+ target + ", " + data);
if (m_contentHandler != null)
{
m_contentHandler.processingInstruction(target, data);
}
} | [
"public",
"void",
"processingInstruction",
"(",
"String",
"target",
",",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"DEBUG",
")",
"System",
".",
"out",
".",
"println",
"(",
"\"TransformerHandlerImpl#processingInstruction: \"",
"+",
"target",
"+",
"\", \"",
"+",
"data",
")",
";",
"if",
"(",
"m_contentHandler",
"!=",
"null",
")",
"{",
"m_contentHandler",
".",
"processingInstruction",
"(",
"target",
",",
"data",
")",
";",
"}",
"}"
] | Filter a processing instruction event.
@param target The processing instruction target.
@param data The text following the target.
@throws SAXException The client may throw
an exception during processing.
@see org.xml.sax.ContentHandler#processingInstruction | [
"Filter",
"a",
"processing",
"instruction",
"event",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java#L584-L596 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.telephony_billingAccount_line_GET | public OvhOrder telephony_billingAccount_line_GET(String billingAccount, String brand, Boolean[] displayUniversalDirectories, Long[] extraSimultaneousLines, String mondialRelayId, String[] offers, Long[] ownerContactIds, Long quantity, Boolean retractation, Long shippingContactId, OvhLineTypeEnum[] types, String[] zones) throws IOException {
"""
Get prices and contracts information
REST: GET /order/telephony/{billingAccount}/line
@param extraSimultaneousLines [required] Additional simultaneous numbers. Set several simultaneous lines for each line per phone
@param quantity [required] Quantity of request repetition in this configuration
@param retractation [required] Retractation rights if set
@param zones [required] Geographic zones. Let empty for nogeographic type. Set several zones for each line per phone
@param ownerContactIds [required] Owner contact information id from /me entry point for each line
@param mondialRelayId [required] Use /supply/mondialRelay entry point to specify a relay point and ignore shipping address information entry.
@param brand [required] Phone brands wanted with the offer. Set null for NO phone
@param displayUniversalDirectories [required] Publish owner contact informations on universal directories or not
@param offers [required] The line offers. Set several offers for each line per phone (Deprecated, use offer method instead)
@param shippingContactId [required] Shipping contact information id from /me entry point
@param types [required] Number type. Set several types for each line per phone
@param billingAccount [required] The name of your billingAccount
"""
String qPath = "/order/telephony/{billingAccount}/line";
StringBuilder sb = path(qPath, billingAccount);
query(sb, "brand", brand);
query(sb, "displayUniversalDirectories", displayUniversalDirectories);
query(sb, "extraSimultaneousLines", extraSimultaneousLines);
query(sb, "mondialRelayId", mondialRelayId);
query(sb, "offers", offers);
query(sb, "ownerContactIds", ownerContactIds);
query(sb, "quantity", quantity);
query(sb, "retractation", retractation);
query(sb, "shippingContactId", shippingContactId);
query(sb, "types", types);
query(sb, "zones", zones);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder telephony_billingAccount_line_GET(String billingAccount, String brand, Boolean[] displayUniversalDirectories, Long[] extraSimultaneousLines, String mondialRelayId, String[] offers, Long[] ownerContactIds, Long quantity, Boolean retractation, Long shippingContactId, OvhLineTypeEnum[] types, String[] zones) throws IOException {
String qPath = "/order/telephony/{billingAccount}/line";
StringBuilder sb = path(qPath, billingAccount);
query(sb, "brand", brand);
query(sb, "displayUniversalDirectories", displayUniversalDirectories);
query(sb, "extraSimultaneousLines", extraSimultaneousLines);
query(sb, "mondialRelayId", mondialRelayId);
query(sb, "offers", offers);
query(sb, "ownerContactIds", ownerContactIds);
query(sb, "quantity", quantity);
query(sb, "retractation", retractation);
query(sb, "shippingContactId", shippingContactId);
query(sb, "types", types);
query(sb, "zones", zones);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"telephony_billingAccount_line_GET",
"(",
"String",
"billingAccount",
",",
"String",
"brand",
",",
"Boolean",
"[",
"]",
"displayUniversalDirectories",
",",
"Long",
"[",
"]",
"extraSimultaneousLines",
",",
"String",
"mondialRelayId",
",",
"String",
"[",
"]",
"offers",
",",
"Long",
"[",
"]",
"ownerContactIds",
",",
"Long",
"quantity",
",",
"Boolean",
"retractation",
",",
"Long",
"shippingContactId",
",",
"OvhLineTypeEnum",
"[",
"]",
"types",
",",
"String",
"[",
"]",
"zones",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/telephony/{billingAccount}/line\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
")",
";",
"query",
"(",
"sb",
",",
"\"brand\"",
",",
"brand",
")",
";",
"query",
"(",
"sb",
",",
"\"displayUniversalDirectories\"",
",",
"displayUniversalDirectories",
")",
";",
"query",
"(",
"sb",
",",
"\"extraSimultaneousLines\"",
",",
"extraSimultaneousLines",
")",
";",
"query",
"(",
"sb",
",",
"\"mondialRelayId\"",
",",
"mondialRelayId",
")",
";",
"query",
"(",
"sb",
",",
"\"offers\"",
",",
"offers",
")",
";",
"query",
"(",
"sb",
",",
"\"ownerContactIds\"",
",",
"ownerContactIds",
")",
";",
"query",
"(",
"sb",
",",
"\"quantity\"",
",",
"quantity",
")",
";",
"query",
"(",
"sb",
",",
"\"retractation\"",
",",
"retractation",
")",
";",
"query",
"(",
"sb",
",",
"\"shippingContactId\"",
",",
"shippingContactId",
")",
";",
"query",
"(",
"sb",
",",
"\"types\"",
",",
"types",
")",
";",
"query",
"(",
"sb",
",",
"\"zones\"",
",",
"zones",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhOrder",
".",
"class",
")",
";",
"}"
] | Get prices and contracts information
REST: GET /order/telephony/{billingAccount}/line
@param extraSimultaneousLines [required] Additional simultaneous numbers. Set several simultaneous lines for each line per phone
@param quantity [required] Quantity of request repetition in this configuration
@param retractation [required] Retractation rights if set
@param zones [required] Geographic zones. Let empty for nogeographic type. Set several zones for each line per phone
@param ownerContactIds [required] Owner contact information id from /me entry point for each line
@param mondialRelayId [required] Use /supply/mondialRelay entry point to specify a relay point and ignore shipping address information entry.
@param brand [required] Phone brands wanted with the offer. Set null for NO phone
@param displayUniversalDirectories [required] Publish owner contact informations on universal directories or not
@param offers [required] The line offers. Set several offers for each line per phone (Deprecated, use offer method instead)
@param shippingContactId [required] Shipping contact information id from /me entry point
@param types [required] Number type. Set several types for each line per phone
@param billingAccount [required] The name of your billingAccount | [
"Get",
"prices",
"and",
"contracts",
"information"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L6335-L6351 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/cache/RepositoryCache.java | RepositoryCache.createExternalWorkspace | public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) {
"""
Creates a new workspace in the repository coupled with external document
store.
@param name the name of the repository
@param connectors connectors to the external systems.
@return workspace cache for the new workspace.
"""
String[] tokens = name.split(":");
String sourceName = tokens[0];
String workspaceName = tokens[1];
this.workspaceNames.add(workspaceName);
refreshRepositoryMetadata(true);
ConcurrentMap<NodeKey, CachedNode> nodeCache = cacheForWorkspace().asMap();
ExecutionContext context = context();
//the name of the external connector is used for source name and workspace name
String sourceKey = NodeKey.keyForSourceName(sourceName);
String workspaceKey = NodeKey.keyForWorkspaceName(workspaceName);
//ask external system to determine root identifier.
Connector connector = connectors.getConnectorForSourceName(sourceName);
if (connector == null) {
throw new IllegalArgumentException(JcrI18n.connectorNotFound.text(sourceName));
}
FederatedDocumentStore documentStore = new FederatedDocumentStore(connectors, this.documentStore().localStore());
String rootId = connector.getRootDocumentId();
// Compute the root key for this workspace ...
NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId);
// We know that this workspace is not the system workspace, so find it ...
final WorkspaceCache systemWorkspaceCache = workspaceCachesByName.get(systemWorkspaceName);
WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(),
workspaceName, systemWorkspaceCache, documentStore, translator, rootKey, nodeCache, changeBus, repositoryEnvironment());
workspaceCachesByName.put(workspaceName, workspaceCache);
return workspace(workspaceName);
} | java | public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) {
String[] tokens = name.split(":");
String sourceName = tokens[0];
String workspaceName = tokens[1];
this.workspaceNames.add(workspaceName);
refreshRepositoryMetadata(true);
ConcurrentMap<NodeKey, CachedNode> nodeCache = cacheForWorkspace().asMap();
ExecutionContext context = context();
//the name of the external connector is used for source name and workspace name
String sourceKey = NodeKey.keyForSourceName(sourceName);
String workspaceKey = NodeKey.keyForWorkspaceName(workspaceName);
//ask external system to determine root identifier.
Connector connector = connectors.getConnectorForSourceName(sourceName);
if (connector == null) {
throw new IllegalArgumentException(JcrI18n.connectorNotFound.text(sourceName));
}
FederatedDocumentStore documentStore = new FederatedDocumentStore(connectors, this.documentStore().localStore());
String rootId = connector.getRootDocumentId();
// Compute the root key for this workspace ...
NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId);
// We know that this workspace is not the system workspace, so find it ...
final WorkspaceCache systemWorkspaceCache = workspaceCachesByName.get(systemWorkspaceName);
WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(),
workspaceName, systemWorkspaceCache, documentStore, translator, rootKey, nodeCache, changeBus, repositoryEnvironment());
workspaceCachesByName.put(workspaceName, workspaceCache);
return workspace(workspaceName);
} | [
"public",
"WorkspaceCache",
"createExternalWorkspace",
"(",
"String",
"name",
",",
"Connectors",
"connectors",
")",
"{",
"String",
"[",
"]",
"tokens",
"=",
"name",
".",
"split",
"(",
"\":\"",
")",
";",
"String",
"sourceName",
"=",
"tokens",
"[",
"0",
"]",
";",
"String",
"workspaceName",
"=",
"tokens",
"[",
"1",
"]",
";",
"this",
".",
"workspaceNames",
".",
"add",
"(",
"workspaceName",
")",
";",
"refreshRepositoryMetadata",
"(",
"true",
")",
";",
"ConcurrentMap",
"<",
"NodeKey",
",",
"CachedNode",
">",
"nodeCache",
"=",
"cacheForWorkspace",
"(",
")",
".",
"asMap",
"(",
")",
";",
"ExecutionContext",
"context",
"=",
"context",
"(",
")",
";",
"//the name of the external connector is used for source name and workspace name",
"String",
"sourceKey",
"=",
"NodeKey",
".",
"keyForSourceName",
"(",
"sourceName",
")",
";",
"String",
"workspaceKey",
"=",
"NodeKey",
".",
"keyForWorkspaceName",
"(",
"workspaceName",
")",
";",
"//ask external system to determine root identifier.",
"Connector",
"connector",
"=",
"connectors",
".",
"getConnectorForSourceName",
"(",
"sourceName",
")",
";",
"if",
"(",
"connector",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"JcrI18n",
".",
"connectorNotFound",
".",
"text",
"(",
"sourceName",
")",
")",
";",
"}",
"FederatedDocumentStore",
"documentStore",
"=",
"new",
"FederatedDocumentStore",
"(",
"connectors",
",",
"this",
".",
"documentStore",
"(",
")",
".",
"localStore",
"(",
")",
")",
";",
"String",
"rootId",
"=",
"connector",
".",
"getRootDocumentId",
"(",
")",
";",
"// Compute the root key for this workspace ...",
"NodeKey",
"rootKey",
"=",
"new",
"NodeKey",
"(",
"sourceKey",
",",
"workspaceKey",
",",
"rootId",
")",
";",
"// We know that this workspace is not the system workspace, so find it ...",
"final",
"WorkspaceCache",
"systemWorkspaceCache",
"=",
"workspaceCachesByName",
".",
"get",
"(",
"systemWorkspaceName",
")",
";",
"WorkspaceCache",
"workspaceCache",
"=",
"new",
"WorkspaceCache",
"(",
"context",
",",
"getKey",
"(",
")",
",",
"workspaceName",
",",
"systemWorkspaceCache",
",",
"documentStore",
",",
"translator",
",",
"rootKey",
",",
"nodeCache",
",",
"changeBus",
",",
"repositoryEnvironment",
"(",
")",
")",
";",
"workspaceCachesByName",
".",
"put",
"(",
"workspaceName",
",",
"workspaceCache",
")",
";",
"return",
"workspace",
"(",
"workspaceName",
")",
";",
"}"
] | Creates a new workspace in the repository coupled with external document
store.
@param name the name of the repository
@param connectors connectors to the external systems.
@return workspace cache for the new workspace. | [
"Creates",
"a",
"new",
"workspace",
"in",
"the",
"repository",
"coupled",
"with",
"external",
"document",
"store",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/cache/RepositoryCache.java#L891-L927 |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.buildStruct | private LocalVariableDefinition buildStruct(MethodDefinition read, Map<Short, LocalVariableDefinition> structData) {
"""
Defines the code to build the struct instance using the data in the local variables.
"""
// construct the instance and store it in the instance local variable
LocalVariableDefinition instance = constructStructInstance(read, structData);
// inject fields
injectStructFields(read, instance, structData);
// inject methods
injectStructMethods(read, instance, structData);
// invoke factory method if present
invokeFactoryMethod(read, structData, instance);
return instance;
} | java | private LocalVariableDefinition buildStruct(MethodDefinition read, Map<Short, LocalVariableDefinition> structData)
{
// construct the instance and store it in the instance local variable
LocalVariableDefinition instance = constructStructInstance(read, structData);
// inject fields
injectStructFields(read, instance, structData);
// inject methods
injectStructMethods(read, instance, structData);
// invoke factory method if present
invokeFactoryMethod(read, structData, instance);
return instance;
} | [
"private",
"LocalVariableDefinition",
"buildStruct",
"(",
"MethodDefinition",
"read",
",",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"structData",
")",
"{",
"// construct the instance and store it in the instance local variable",
"LocalVariableDefinition",
"instance",
"=",
"constructStructInstance",
"(",
"read",
",",
"structData",
")",
";",
"// inject fields",
"injectStructFields",
"(",
"read",
",",
"instance",
",",
"structData",
")",
";",
"// inject methods",
"injectStructMethods",
"(",
"read",
",",
"instance",
",",
"structData",
")",
";",
"// invoke factory method if present",
"invokeFactoryMethod",
"(",
"read",
",",
"structData",
",",
"instance",
")",
";",
"return",
"instance",
";",
"}"
] | Defines the code to build the struct instance using the data in the local variables. | [
"Defines",
"the",
"code",
"to",
"build",
"the",
"struct",
"instance",
"using",
"the",
"data",
"in",
"the",
"local",
"variables",
"."
] | train | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L404-L419 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.cut | public static void cut(Image srcImage, ImageOutputStream destImageStream, Rectangle rectangle) throws IORuntimeException {
"""
图像切割(按指定起点坐标和宽高切割),此方法并不关闭流
@param srcImage 源图像
@param destImageStream 切片后的图像输出流
@param rectangle 矩形对象,表示矩形区域的x,y,width,height
@since 3.1.0
@throws IORuntimeException IO异常
"""
writeJpg(cut(srcImage, rectangle), destImageStream);
} | java | public static void cut(Image srcImage, ImageOutputStream destImageStream, Rectangle rectangle) throws IORuntimeException {
writeJpg(cut(srcImage, rectangle), destImageStream);
} | [
"public",
"static",
"void",
"cut",
"(",
"Image",
"srcImage",
",",
"ImageOutputStream",
"destImageStream",
",",
"Rectangle",
"rectangle",
")",
"throws",
"IORuntimeException",
"{",
"writeJpg",
"(",
"cut",
"(",
"srcImage",
",",
"rectangle",
")",
",",
"destImageStream",
")",
";",
"}"
] | 图像切割(按指定起点坐标和宽高切割),此方法并不关闭流
@param srcImage 源图像
@param destImageStream 切片后的图像输出流
@param rectangle 矩形对象,表示矩形区域的x,y,width,height
@since 3.1.0
@throws IORuntimeException IO异常 | [
"图像切割",
"(",
"按指定起点坐标和宽高切割",
")",
",此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L319-L321 |
jcuda/jnvgraph | JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java | JNvgraph.nvgraphContractGraph | public static int nvgraphContractGraph(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
nvgraphGraphDescr contrdescrG,
Pointer aggregates,
long numaggregates,
int VertexCombineOp,
int VertexReduceOp,
int EdgeCombineOp,
int EdgeReduceOp,
int flag) {
"""
<pre>
nvGRAPH contraction
given array of agregates contract graph with
given (Combine, Reduce) operators for Vertex Set
and Edge Set;
</pre>
"""
return checkResult(nvgraphContractGraphNative(handle, descrG, contrdescrG, aggregates, numaggregates, VertexCombineOp, VertexReduceOp, EdgeCombineOp, EdgeReduceOp, flag));
} | java | public static int nvgraphContractGraph(
nvgraphHandle handle,
nvgraphGraphDescr descrG,
nvgraphGraphDescr contrdescrG,
Pointer aggregates,
long numaggregates,
int VertexCombineOp,
int VertexReduceOp,
int EdgeCombineOp,
int EdgeReduceOp,
int flag)
{
return checkResult(nvgraphContractGraphNative(handle, descrG, contrdescrG, aggregates, numaggregates, VertexCombineOp, VertexReduceOp, EdgeCombineOp, EdgeReduceOp, flag));
} | [
"public",
"static",
"int",
"nvgraphContractGraph",
"(",
"nvgraphHandle",
"handle",
",",
"nvgraphGraphDescr",
"descrG",
",",
"nvgraphGraphDescr",
"contrdescrG",
",",
"Pointer",
"aggregates",
",",
"long",
"numaggregates",
",",
"int",
"VertexCombineOp",
",",
"int",
"VertexReduceOp",
",",
"int",
"EdgeCombineOp",
",",
"int",
"EdgeReduceOp",
",",
"int",
"flag",
")",
"{",
"return",
"checkResult",
"(",
"nvgraphContractGraphNative",
"(",
"handle",
",",
"descrG",
",",
"contrdescrG",
",",
"aggregates",
",",
"numaggregates",
",",
"VertexCombineOp",
",",
"VertexReduceOp",
",",
"EdgeCombineOp",
",",
"EdgeReduceOp",
",",
"flag",
")",
")",
";",
"}"
] | <pre>
nvGRAPH contraction
given array of agregates contract graph with
given (Combine, Reduce) operators for Vertex Set
and Edge Set;
</pre> | [
"<pre",
">",
"nvGRAPH",
"contraction",
"given",
"array",
"of",
"agregates",
"contract",
"graph",
"with",
"given",
"(",
"Combine",
"Reduce",
")",
"operators",
"for",
"Vertex",
"Set",
"and",
"Edge",
"Set",
";",
"<",
"/",
"pre",
">"
] | train | https://github.com/jcuda/jnvgraph/blob/2c6bd7c58edac181753bacf30af2cceeb1989a78/JNvgraphJava/src/main/java/jcuda/jnvgraph/JNvgraph.java#L678-L691 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java | FastaAFPChainConverter.fastaFileToAfpChain | public static AFPChain fastaFileToAfpChain(File fastaFile, Structure structure1, Structure structure2)
throws IOException, StructureException {
"""
Reads the file {@code fastaFile}, expecting exactly two sequences which give a pairwise alignment. Uses this and two structures to create an AFPChain corresponding to the alignment. Uses a
{@link CasePreservingProteinSequenceCreator} and assumes that a residue is aligned if and only if it is given by an uppercase letter.
@see #fastaToAfpChain(ProteinSequence, ProteinSequence, Structure, Structure)
@throws IOException
@throws StructureException
"""
InputStream inStream = new FileInputStream(fastaFile);
SequenceCreatorInterface<AminoAcidCompound> creator = new CasePreservingProteinSequenceCreator(
AminoAcidCompoundSet.getAminoAcidCompoundSet());
SequenceHeaderParserInterface<ProteinSequence, AminoAcidCompound> headerParser = new GenericFastaHeaderParser<ProteinSequence, AminoAcidCompound>();
FastaReader<ProteinSequence, AminoAcidCompound> fastaReader = new FastaReader<ProteinSequence, AminoAcidCompound>(
inStream, headerParser, creator);
LinkedHashMap<String, ProteinSequence> sequences = fastaReader.process();
inStream.close();
return fastaToAfpChain(sequences, structure1, structure2);
} | java | public static AFPChain fastaFileToAfpChain(File fastaFile, Structure structure1, Structure structure2)
throws IOException, StructureException {
InputStream inStream = new FileInputStream(fastaFile);
SequenceCreatorInterface<AminoAcidCompound> creator = new CasePreservingProteinSequenceCreator(
AminoAcidCompoundSet.getAminoAcidCompoundSet());
SequenceHeaderParserInterface<ProteinSequence, AminoAcidCompound> headerParser = new GenericFastaHeaderParser<ProteinSequence, AminoAcidCompound>();
FastaReader<ProteinSequence, AminoAcidCompound> fastaReader = new FastaReader<ProteinSequence, AminoAcidCompound>(
inStream, headerParser, creator);
LinkedHashMap<String, ProteinSequence> sequences = fastaReader.process();
inStream.close();
return fastaToAfpChain(sequences, structure1, structure2);
} | [
"public",
"static",
"AFPChain",
"fastaFileToAfpChain",
"(",
"File",
"fastaFile",
",",
"Structure",
"structure1",
",",
"Structure",
"structure2",
")",
"throws",
"IOException",
",",
"StructureException",
"{",
"InputStream",
"inStream",
"=",
"new",
"FileInputStream",
"(",
"fastaFile",
")",
";",
"SequenceCreatorInterface",
"<",
"AminoAcidCompound",
">",
"creator",
"=",
"new",
"CasePreservingProteinSequenceCreator",
"(",
"AminoAcidCompoundSet",
".",
"getAminoAcidCompoundSet",
"(",
")",
")",
";",
"SequenceHeaderParserInterface",
"<",
"ProteinSequence",
",",
"AminoAcidCompound",
">",
"headerParser",
"=",
"new",
"GenericFastaHeaderParser",
"<",
"ProteinSequence",
",",
"AminoAcidCompound",
">",
"(",
")",
";",
"FastaReader",
"<",
"ProteinSequence",
",",
"AminoAcidCompound",
">",
"fastaReader",
"=",
"new",
"FastaReader",
"<",
"ProteinSequence",
",",
"AminoAcidCompound",
">",
"(",
"inStream",
",",
"headerParser",
",",
"creator",
")",
";",
"LinkedHashMap",
"<",
"String",
",",
"ProteinSequence",
">",
"sequences",
"=",
"fastaReader",
".",
"process",
"(",
")",
";",
"inStream",
".",
"close",
"(",
")",
";",
"return",
"fastaToAfpChain",
"(",
"sequences",
",",
"structure1",
",",
"structure2",
")",
";",
"}"
] | Reads the file {@code fastaFile}, expecting exactly two sequences which give a pairwise alignment. Uses this and two structures to create an AFPChain corresponding to the alignment. Uses a
{@link CasePreservingProteinSequenceCreator} and assumes that a residue is aligned if and only if it is given by an uppercase letter.
@see #fastaToAfpChain(ProteinSequence, ProteinSequence, Structure, Structure)
@throws IOException
@throws StructureException | [
"Reads",
"the",
"file",
"{",
"@code",
"fastaFile",
"}",
"expecting",
"exactly",
"two",
"sequences",
"which",
"give",
"a",
"pairwise",
"alignment",
".",
"Uses",
"this",
"and",
"two",
"structures",
"to",
"create",
"an",
"AFPChain",
"corresponding",
"to",
"the",
"alignment",
".",
"Uses",
"a",
"{",
"@link",
"CasePreservingProteinSequenceCreator",
"}",
"and",
"assumes",
"that",
"a",
"residue",
"is",
"aligned",
"if",
"and",
"only",
"if",
"it",
"is",
"given",
"by",
"an",
"uppercase",
"letter",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java#L194-L205 |
gallandarakhneorg/afc | core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/filetype/FileType.java | FileType.isContentType | public static boolean isContentType(URL filename, String desiredMimeType) {
"""
Replies if the given file is compatible with the given MIME type.
@param filename is the name of the file to test.
@param desiredMimeType is the desired MIME type.
@return <code>true</code> if the given file has type equal to the given MIME type,
otherwise <code>false</code>.
"""
final ContentFileTypeMap map = ensureContentTypeManager();
return map.isContentType(filename, desiredMimeType);
} | java | public static boolean isContentType(URL filename, String desiredMimeType) {
final ContentFileTypeMap map = ensureContentTypeManager();
return map.isContentType(filename, desiredMimeType);
} | [
"public",
"static",
"boolean",
"isContentType",
"(",
"URL",
"filename",
",",
"String",
"desiredMimeType",
")",
"{",
"final",
"ContentFileTypeMap",
"map",
"=",
"ensureContentTypeManager",
"(",
")",
";",
"return",
"map",
".",
"isContentType",
"(",
"filename",
",",
"desiredMimeType",
")",
";",
"}"
] | Replies if the given file is compatible with the given MIME type.
@param filename is the name of the file to test.
@param desiredMimeType is the desired MIME type.
@return <code>true</code> if the given file has type equal to the given MIME type,
otherwise <code>false</code>. | [
"Replies",
"if",
"the",
"given",
"file",
"is",
"compatible",
"with",
"the",
"given",
"MIME",
"type",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/filetype/FileType.java#L196-L199 |
HubSpot/Singularity | SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java | SingularityClient.getHistoryForRequest | public Collection<SingularityRequestHistory> getHistoryForRequest(String requestId, Optional<Integer> count, Optional<Integer> page) {
"""
Retrieve a paged list of updates for a particular {@link SingularityRequest}
@param requestId
Request ID to look up
@param count
Number of items to return per page
@param page
Which page of items to return
@return
A list of {@link SingularityRequestHistory}
"""
final Function<String, String> requestUri = (host) -> String.format(REQUEST_HISTORY_FORMAT, getApiBase(host), requestId);
Optional<Map<String, Object>> maybeQueryParams = Optional.absent();
ImmutableMap.Builder<String, Object> queryParamsBuilder = ImmutableMap.builder();
if (count.isPresent() ) {
queryParamsBuilder.put("count", count.get());
}
if (page.isPresent()) {
queryParamsBuilder.put("page", page.get());
}
Map<String, Object> queryParams = queryParamsBuilder.build();
if (!queryParams.isEmpty()) {
maybeQueryParams = Optional.of(queryParams);
}
return getCollectionWithParams(requestUri, "request history", maybeQueryParams, REQUEST_HISTORY_COLLECTION);
} | java | public Collection<SingularityRequestHistory> getHistoryForRequest(String requestId, Optional<Integer> count, Optional<Integer> page) {
final Function<String, String> requestUri = (host) -> String.format(REQUEST_HISTORY_FORMAT, getApiBase(host), requestId);
Optional<Map<String, Object>> maybeQueryParams = Optional.absent();
ImmutableMap.Builder<String, Object> queryParamsBuilder = ImmutableMap.builder();
if (count.isPresent() ) {
queryParamsBuilder.put("count", count.get());
}
if (page.isPresent()) {
queryParamsBuilder.put("page", page.get());
}
Map<String, Object> queryParams = queryParamsBuilder.build();
if (!queryParams.isEmpty()) {
maybeQueryParams = Optional.of(queryParams);
}
return getCollectionWithParams(requestUri, "request history", maybeQueryParams, REQUEST_HISTORY_COLLECTION);
} | [
"public",
"Collection",
"<",
"SingularityRequestHistory",
">",
"getHistoryForRequest",
"(",
"String",
"requestId",
",",
"Optional",
"<",
"Integer",
">",
"count",
",",
"Optional",
"<",
"Integer",
">",
"page",
")",
"{",
"final",
"Function",
"<",
"String",
",",
"String",
">",
"requestUri",
"=",
"(",
"host",
")",
"-",
">",
"String",
".",
"format",
"(",
"REQUEST_HISTORY_FORMAT",
",",
"getApiBase",
"(",
"host",
")",
",",
"requestId",
")",
";",
"Optional",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"maybeQueryParams",
"=",
"Optional",
".",
"absent",
"(",
")",
";",
"ImmutableMap",
".",
"Builder",
"<",
"String",
",",
"Object",
">",
"queryParamsBuilder",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"if",
"(",
"count",
".",
"isPresent",
"(",
")",
")",
"{",
"queryParamsBuilder",
".",
"put",
"(",
"\"count\"",
",",
"count",
".",
"get",
"(",
")",
")",
";",
"}",
"if",
"(",
"page",
".",
"isPresent",
"(",
")",
")",
"{",
"queryParamsBuilder",
".",
"put",
"(",
"\"page\"",
",",
"page",
".",
"get",
"(",
")",
")",
";",
"}",
"Map",
"<",
"String",
",",
"Object",
">",
"queryParams",
"=",
"queryParamsBuilder",
".",
"build",
"(",
")",
";",
"if",
"(",
"!",
"queryParams",
".",
"isEmpty",
"(",
")",
")",
"{",
"maybeQueryParams",
"=",
"Optional",
".",
"of",
"(",
"queryParams",
")",
";",
"}",
"return",
"getCollectionWithParams",
"(",
"requestUri",
",",
"\"request history\"",
",",
"maybeQueryParams",
",",
"REQUEST_HISTORY_COLLECTION",
")",
";",
"}"
] | Retrieve a paged list of updates for a particular {@link SingularityRequest}
@param requestId
Request ID to look up
@param count
Number of items to return per page
@param page
Which page of items to return
@return
A list of {@link SingularityRequestHistory} | [
"Retrieve",
"a",
"paged",
"list",
"of",
"updates",
"for",
"a",
"particular",
"{",
"@link",
"SingularityRequest",
"}"
] | train | https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L1023-L1044 |
OpenLiberty/open-liberty | dev/com.ibm.ws.diagnostics/src/com/ibm/ws/diagnostics/AbstractMBeanIntrospector.java | AbstractMBeanIntrospector.getFormattedTabularData | @SuppressWarnings("unchecked")
String getFormattedTabularData(TabularData td, String indent) {
"""
Format an open MBean tabular data attribute.
@param td the tabular data attribute
@param indent the current indent level of the formatted report
@return the formatted composite data
"""
StringBuilder sb = new StringBuilder();
indent += INDENT;
sb.append("{");
Collection<CompositeData> values = (Collection<CompositeData>) td.values();
int valuesRemaining = values.size();
for (CompositeData cd : values) {
sb.append(getFormattedCompositeData(cd, indent));
if (--valuesRemaining > 0) {
sb.append("\n").append(indent).append("}, {");
}
}
sb.append("}");
return String.valueOf(sb);
} | java | @SuppressWarnings("unchecked")
String getFormattedTabularData(TabularData td, String indent) {
StringBuilder sb = new StringBuilder();
indent += INDENT;
sb.append("{");
Collection<CompositeData> values = (Collection<CompositeData>) td.values();
int valuesRemaining = values.size();
for (CompositeData cd : values) {
sb.append(getFormattedCompositeData(cd, indent));
if (--valuesRemaining > 0) {
sb.append("\n").append(indent).append("}, {");
}
}
sb.append("}");
return String.valueOf(sb);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"String",
"getFormattedTabularData",
"(",
"TabularData",
"td",
",",
"String",
"indent",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"indent",
"+=",
"INDENT",
";",
"sb",
".",
"append",
"(",
"\"{\"",
")",
";",
"Collection",
"<",
"CompositeData",
">",
"values",
"=",
"(",
"Collection",
"<",
"CompositeData",
">",
")",
"td",
".",
"values",
"(",
")",
";",
"int",
"valuesRemaining",
"=",
"values",
".",
"size",
"(",
")",
";",
"for",
"(",
"CompositeData",
"cd",
":",
"values",
")",
"{",
"sb",
".",
"append",
"(",
"getFormattedCompositeData",
"(",
"cd",
",",
"indent",
")",
")",
";",
"if",
"(",
"--",
"valuesRemaining",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"indent",
")",
".",
"append",
"(",
"\"}, {\"",
")",
";",
"}",
"}",
"sb",
".",
"append",
"(",
"\"}\"",
")",
";",
"return",
"String",
".",
"valueOf",
"(",
"sb",
")",
";",
"}"
] | Format an open MBean tabular data attribute.
@param td the tabular data attribute
@param indent the current indent level of the formatted report
@return the formatted composite data | [
"Format",
"an",
"open",
"MBean",
"tabular",
"data",
"attribute",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.diagnostics/src/com/ibm/ws/diagnostics/AbstractMBeanIntrospector.java#L271-L288 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java | VMath.setMatrix | public static void setMatrix(final double[][] m1, final int r0, final int r1, final int[] c, final double[][] m2) {
"""
Set a submatrix.
@param m1 Input matrix
@param r0 Initial row index
@param r1 Final row index
@param c Array of column indices.
@param m2 New values for m1(r0:r1-1,c(:))
"""
assert r0 <= r1 : ERR_INVALID_RANGE;
assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
for(int i = r0; i < r1; i++) {
final double[] row1 = m1[i], row2 = m2[i - r0];
for(int j = 0; j < c.length; j++) {
row1[c[j]] = row2[j];
}
}
} | java | public static void setMatrix(final double[][] m1, final int r0, final int r1, final int[] c, final double[][] m2) {
assert r0 <= r1 : ERR_INVALID_RANGE;
assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
for(int i = r0; i < r1; i++) {
final double[] row1 = m1[i], row2 = m2[i - r0];
for(int j = 0; j < c.length; j++) {
row1[c[j]] = row2[j];
}
}
} | [
"public",
"static",
"void",
"setMatrix",
"(",
"final",
"double",
"[",
"]",
"[",
"]",
"m1",
",",
"final",
"int",
"r0",
",",
"final",
"int",
"r1",
",",
"final",
"int",
"[",
"]",
"c",
",",
"final",
"double",
"[",
"]",
"[",
"]",
"m2",
")",
"{",
"assert",
"r0",
"<=",
"r1",
":",
"ERR_INVALID_RANGE",
";",
"assert",
"r1",
"<=",
"m1",
".",
"length",
":",
"ERR_MATRIX_DIMENSIONS",
";",
"for",
"(",
"int",
"i",
"=",
"r0",
";",
"i",
"<",
"r1",
";",
"i",
"++",
")",
"{",
"final",
"double",
"[",
"]",
"row1",
"=",
"m1",
"[",
"i",
"]",
",",
"row2",
"=",
"m2",
"[",
"i",
"-",
"r0",
"]",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"c",
".",
"length",
";",
"j",
"++",
")",
"{",
"row1",
"[",
"c",
"[",
"j",
"]",
"]",
"=",
"row2",
"[",
"j",
"]",
";",
"}",
"}",
"}"
] | Set a submatrix.
@param m1 Input matrix
@param r0 Initial row index
@param r1 Final row index
@param c Array of column indices.
@param m2 New values for m1(r0:r1-1,c(:)) | [
"Set",
"a",
"submatrix",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java#L1049-L1058 |
jhalterman/failsafe | src/main/java/net/jodah/failsafe/PolicyExecutor.java | PolicyExecutor.postExecuteAsync | protected CompletableFuture<ExecutionResult> postExecuteAsync(ExecutionResult result, Scheduler scheduler,
FailsafeFuture<Object> future) {
"""
Performs potentially asynchronous post-execution handling for a {@code result}.
"""
if (isFailure(result)) {
result = result.with(false, false);
return onFailureAsync(result, scheduler, future).whenComplete((postResult, error) -> {
callFailureListener(postResult);
});
} else {
result = result.with(true, true);
onSuccess(result);
callSuccessListener(result);
return CompletableFuture.completedFuture(result);
}
} | java | protected CompletableFuture<ExecutionResult> postExecuteAsync(ExecutionResult result, Scheduler scheduler,
FailsafeFuture<Object> future) {
if (isFailure(result)) {
result = result.with(false, false);
return onFailureAsync(result, scheduler, future).whenComplete((postResult, error) -> {
callFailureListener(postResult);
});
} else {
result = result.with(true, true);
onSuccess(result);
callSuccessListener(result);
return CompletableFuture.completedFuture(result);
}
} | [
"protected",
"CompletableFuture",
"<",
"ExecutionResult",
">",
"postExecuteAsync",
"(",
"ExecutionResult",
"result",
",",
"Scheduler",
"scheduler",
",",
"FailsafeFuture",
"<",
"Object",
">",
"future",
")",
"{",
"if",
"(",
"isFailure",
"(",
"result",
")",
")",
"{",
"result",
"=",
"result",
".",
"with",
"(",
"false",
",",
"false",
")",
";",
"return",
"onFailureAsync",
"(",
"result",
",",
"scheduler",
",",
"future",
")",
".",
"whenComplete",
"(",
"(",
"postResult",
",",
"error",
")",
"->",
"{",
"callFailureListener",
"(",
"postResult",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"result",
"=",
"result",
".",
"with",
"(",
"true",
",",
"true",
")",
";",
"onSuccess",
"(",
"result",
")",
";",
"callSuccessListener",
"(",
"result",
")",
";",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"result",
")",
";",
"}",
"}"
] | Performs potentially asynchronous post-execution handling for a {@code result}. | [
"Performs",
"potentially",
"asynchronous",
"post",
"-",
"execution",
"handling",
"for",
"a",
"{"
] | train | https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/PolicyExecutor.java#L95-L108 |
atomix/atomix | cluster/src/main/java/io/atomix/cluster/MemberBuilder.java | MemberBuilder.withProperty | public MemberBuilder withProperty(String key, String value) {
"""
Sets a member property.
@param key the property key to set
@param value the property value to set
@return the member builder
@throws NullPointerException if the property is null
"""
config.setProperty(key, value);
return this;
} | java | public MemberBuilder withProperty(String key, String value) {
config.setProperty(key, value);
return this;
} | [
"public",
"MemberBuilder",
"withProperty",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"config",
".",
"setProperty",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Sets a member property.
@param key the property key to set
@param value the property value to set
@return the member builder
@throws NullPointerException if the property is null | [
"Sets",
"a",
"member",
"property",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/MemberBuilder.java#L198-L201 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java | SegmentMetadataUpdateTransaction.acceptAsTargetSegment | void acceptAsTargetSegment(MergeSegmentOperation operation, SegmentMetadataUpdateTransaction sourceMetadata) throws MetadataUpdateException {
"""
Accepts the given MergeSegmentOperation as a Target Segment (where it will be merged into).
@param operation The operation to accept.
@param sourceMetadata The metadata for the Source Segment to merge.
@throws MetadataUpdateException If the operation cannot be processed because of the current state of the metadata.
@throws IllegalArgumentException If the operation is for a different Segment.
"""
ensureSegmentId(operation);
if (operation.getStreamSegmentOffset() != this.length) {
throw new MetadataUpdateException(containerId,
String.format("MergeSegmentOperation target offset mismatch. Expected %d, actual %d.",
this.length, operation.getStreamSegmentOffset()));
}
long transLength = operation.getLength();
if (transLength < 0 || transLength != sourceMetadata.length) {
throw new MetadataUpdateException(containerId,
"MergeSegmentOperation does not seem to have been pre-processed: " + operation.toString());
}
this.length += transLength;
this.isChanged = true;
} | java | void acceptAsTargetSegment(MergeSegmentOperation operation, SegmentMetadataUpdateTransaction sourceMetadata) throws MetadataUpdateException {
ensureSegmentId(operation);
if (operation.getStreamSegmentOffset() != this.length) {
throw new MetadataUpdateException(containerId,
String.format("MergeSegmentOperation target offset mismatch. Expected %d, actual %d.",
this.length, operation.getStreamSegmentOffset()));
}
long transLength = operation.getLength();
if (transLength < 0 || transLength != sourceMetadata.length) {
throw new MetadataUpdateException(containerId,
"MergeSegmentOperation does not seem to have been pre-processed: " + operation.toString());
}
this.length += transLength;
this.isChanged = true;
} | [
"void",
"acceptAsTargetSegment",
"(",
"MergeSegmentOperation",
"operation",
",",
"SegmentMetadataUpdateTransaction",
"sourceMetadata",
")",
"throws",
"MetadataUpdateException",
"{",
"ensureSegmentId",
"(",
"operation",
")",
";",
"if",
"(",
"operation",
".",
"getStreamSegmentOffset",
"(",
")",
"!=",
"this",
".",
"length",
")",
"{",
"throw",
"new",
"MetadataUpdateException",
"(",
"containerId",
",",
"String",
".",
"format",
"(",
"\"MergeSegmentOperation target offset mismatch. Expected %d, actual %d.\"",
",",
"this",
".",
"length",
",",
"operation",
".",
"getStreamSegmentOffset",
"(",
")",
")",
")",
";",
"}",
"long",
"transLength",
"=",
"operation",
".",
"getLength",
"(",
")",
";",
"if",
"(",
"transLength",
"<",
"0",
"||",
"transLength",
"!=",
"sourceMetadata",
".",
"length",
")",
"{",
"throw",
"new",
"MetadataUpdateException",
"(",
"containerId",
",",
"\"MergeSegmentOperation does not seem to have been pre-processed: \"",
"+",
"operation",
".",
"toString",
"(",
")",
")",
";",
"}",
"this",
".",
"length",
"+=",
"transLength",
";",
"this",
".",
"isChanged",
"=",
"true",
";",
"}"
] | Accepts the given MergeSegmentOperation as a Target Segment (where it will be merged into).
@param operation The operation to accept.
@param sourceMetadata The metadata for the Source Segment to merge.
@throws MetadataUpdateException If the operation cannot be processed because of the current state of the metadata.
@throws IllegalArgumentException If the operation is for a different Segment. | [
"Accepts",
"the",
"given",
"MergeSegmentOperation",
"as",
"a",
"Target",
"Segment",
"(",
"where",
"it",
"will",
"be",
"merged",
"into",
")",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java#L574-L591 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserWpt.java | AbstractGpxParserWpt.endElement | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
"""
Fires whenever an XML end markup is encountered. It catches attributes of
the waypoint and saves them in corresponding values[].
@param uri URI of the local element
@param localName Name of the local element (without prefix)
@param qName qName of the local element (with prefix)
@throws SAXException Any SAX exception, possibly wrapping another
exception
"""
// currentElement represents the last string encountered in the document
setCurrentElement(getElementNames().pop());
if (getCurrentElement().equalsIgnoreCase(GPXTags.WPT)) {
//if </wpt> markup is found, the currentPoint is added in the table wptdbd and the default contentHandler is setted.
try {
PreparedStatement pStm = getWptPreparedStmt();
int i = 1;
Object[] values = getCurrentPoint().getValues();
for (Object object : values) {
pStm.setObject(i, object);
i++;
}
pStm.execute();
} catch (SQLException ex) {
throw new SAXException("Cannot import the waypoint.", ex);
}
getReader().setContentHandler(parent);
} else {
getCurrentPoint().setAttribute(getCurrentElement(), getContentBuffer());
}
} | java | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// currentElement represents the last string encountered in the document
setCurrentElement(getElementNames().pop());
if (getCurrentElement().equalsIgnoreCase(GPXTags.WPT)) {
//if </wpt> markup is found, the currentPoint is added in the table wptdbd and the default contentHandler is setted.
try {
PreparedStatement pStm = getWptPreparedStmt();
int i = 1;
Object[] values = getCurrentPoint().getValues();
for (Object object : values) {
pStm.setObject(i, object);
i++;
}
pStm.execute();
} catch (SQLException ex) {
throw new SAXException("Cannot import the waypoint.", ex);
}
getReader().setContentHandler(parent);
} else {
getCurrentPoint().setAttribute(getCurrentElement(), getContentBuffer());
}
} | [
"@",
"Override",
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"// currentElement represents the last string encountered in the document",
"setCurrentElement",
"(",
"getElementNames",
"(",
")",
".",
"pop",
"(",
")",
")",
";",
"if",
"(",
"getCurrentElement",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"GPXTags",
".",
"WPT",
")",
")",
"{",
"//if </wpt> markup is found, the currentPoint is added in the table wptdbd and the default contentHandler is setted.",
"try",
"{",
"PreparedStatement",
"pStm",
"=",
"getWptPreparedStmt",
"(",
")",
";",
"int",
"i",
"=",
"1",
";",
"Object",
"[",
"]",
"values",
"=",
"getCurrentPoint",
"(",
")",
".",
"getValues",
"(",
")",
";",
"for",
"(",
"Object",
"object",
":",
"values",
")",
"{",
"pStm",
".",
"setObject",
"(",
"i",
",",
"object",
")",
";",
"i",
"++",
";",
"}",
"pStm",
".",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"SAXException",
"(",
"\"Cannot import the waypoint.\"",
",",
"ex",
")",
";",
"}",
"getReader",
"(",
")",
".",
"setContentHandler",
"(",
"parent",
")",
";",
"}",
"else",
"{",
"getCurrentPoint",
"(",
")",
".",
"setAttribute",
"(",
"getCurrentElement",
"(",
")",
",",
"getContentBuffer",
"(",
")",
")",
";",
"}",
"}"
] | Fires whenever an XML end markup is encountered. It catches attributes of
the waypoint and saves them in corresponding values[].
@param uri URI of the local element
@param localName Name of the local element (without prefix)
@param qName qName of the local element (with prefix)
@throws SAXException Any SAX exception, possibly wrapping another
exception | [
"Fires",
"whenever",
"an",
"XML",
"end",
"markup",
"is",
"encountered",
".",
"It",
"catches",
"attributes",
"of",
"the",
"waypoint",
"and",
"saves",
"them",
"in",
"corresponding",
"values",
"[]",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserWpt.java#L86-L110 |
michael-rapp/AndroidPreferenceActivity | example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java | AppearancePreferenceFragment.createNavigationWidthChangeListener | private OnPreferenceChangeListener createNavigationWidthChangeListener() {
"""
Creates and returns a listener, which allows to adapt the width of the navigation, when the
value of the corresponding preference has been changed.
@return The listener, which has been created, as an instance of the type {@link
OnPreferenceChangeListener}
"""
return new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
int width = Integer.valueOf((String) newValue);
((PreferenceActivity) getActivity())
.setNavigationWidth(dpToPixels(getActivity(), width));
return true;
}
};
} | java | private OnPreferenceChangeListener createNavigationWidthChangeListener() {
return new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
int width = Integer.valueOf((String) newValue);
((PreferenceActivity) getActivity())
.setNavigationWidth(dpToPixels(getActivity(), width));
return true;
}
};
} | [
"private",
"OnPreferenceChangeListener",
"createNavigationWidthChangeListener",
"(",
")",
"{",
"return",
"new",
"OnPreferenceChangeListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onPreferenceChange",
"(",
"final",
"Preference",
"preference",
",",
"final",
"Object",
"newValue",
")",
"{",
"int",
"width",
"=",
"Integer",
".",
"valueOf",
"(",
"(",
"String",
")",
"newValue",
")",
";",
"(",
"(",
"PreferenceActivity",
")",
"getActivity",
"(",
")",
")",
".",
"setNavigationWidth",
"(",
"dpToPixels",
"(",
"getActivity",
"(",
")",
",",
"width",
")",
")",
";",
"return",
"true",
";",
"}",
"}",
";",
"}"
] | Creates and returns a listener, which allows to adapt the width of the navigation, when the
value of the corresponding preference has been changed.
@return The listener, which has been created, as an instance of the type {@link
OnPreferenceChangeListener} | [
"Creates",
"and",
"returns",
"a",
"listener",
"which",
"allows",
"to",
"adapt",
"the",
"width",
"of",
"the",
"navigation",
"when",
"the",
"value",
"of",
"the",
"corresponding",
"preference",
"has",
"been",
"changed",
"."
] | train | https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java#L87-L99 |
youseries/urule | urule-console/src/main/java/com/bstek/urule/console/repository/database/journal/DatabaseJournal.java | DatabaseJournal.doSync | @Override
protected void doSync(long startRevision, boolean startup) throws JournalException {
"""
Synchronize contents from journal. May be overridden by subclasses.
Do the initial sync in batchMode, since some databases (PSQL) when
not in transactional mode, load all results in memory which causes
out of memory. See JCR-2832
@param startRevision start point (exclusive)
@param startup indicates if the cluster node is syncing on startup
or does a normal sync.
@throws JournalException if an error occurs
"""
if (!startup) {
// if the cluster node is not starting do a normal sync
doSync(startRevision);
} else {
try {
startBatch();
try {
doSync(startRevision);
} finally {
endBatch(true);
}
} catch (SQLException e) {
throw new JournalException("Couldn't sync the cluster node", e);
}
}
} | java | @Override
protected void doSync(long startRevision, boolean startup) throws JournalException {
if (!startup) {
// if the cluster node is not starting do a normal sync
doSync(startRevision);
} else {
try {
startBatch();
try {
doSync(startRevision);
} finally {
endBatch(true);
}
} catch (SQLException e) {
throw new JournalException("Couldn't sync the cluster node", e);
}
}
} | [
"@",
"Override",
"protected",
"void",
"doSync",
"(",
"long",
"startRevision",
",",
"boolean",
"startup",
")",
"throws",
"JournalException",
"{",
"if",
"(",
"!",
"startup",
")",
"{",
"// if the cluster node is not starting do a normal sync",
"doSync",
"(",
"startRevision",
")",
";",
"}",
"else",
"{",
"try",
"{",
"startBatch",
"(",
")",
";",
"try",
"{",
"doSync",
"(",
"startRevision",
")",
";",
"}",
"finally",
"{",
"endBatch",
"(",
"true",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"JournalException",
"(",
"\"Couldn't sync the cluster node\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Synchronize contents from journal. May be overridden by subclasses.
Do the initial sync in batchMode, since some databases (PSQL) when
not in transactional mode, load all results in memory which causes
out of memory. See JCR-2832
@param startRevision start point (exclusive)
@param startup indicates if the cluster node is syncing on startup
or does a normal sync.
@throws JournalException if an error occurs | [
"Synchronize",
"contents",
"from",
"journal",
".",
"May",
"be",
"overridden",
"by",
"subclasses",
".",
"Do",
"the",
"initial",
"sync",
"in",
"batchMode",
"since",
"some",
"databases",
"(",
"PSQL",
")",
"when",
"not",
"in",
"transactional",
"mode",
"load",
"all",
"results",
"in",
"memory",
"which",
"causes",
"out",
"of",
"memory",
".",
"See",
"JCR",
"-",
"2832"
] | train | https://github.com/youseries/urule/blob/3fa0eb4439e97aa292e744bcbd88a9faa36661d8/urule-console/src/main/java/com/bstek/urule/console/repository/database/journal/DatabaseJournal.java#L375-L392 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.fromRunnable | public static <R> Observable<R> fromRunnable(final Runnable run, final R result) {
"""
Return an Observable that calls the given Runnable and emits the given result when an Observer
subscribes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromRunnable.png" alt="">
<p>
The Runnable is called on the default thread pool for computation.
@param <R> the return type
@param run the runnable to invoke on each subscription
@param result the result to emit to observers
@return an Observable that calls the given Runnable and emits the given result when an Observer
subscribes
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-fromrunnable">RxJava Wiki: fromRunnable()</a>
"""
return fromRunnable(run, result, Schedulers.computation());
} | java | public static <R> Observable<R> fromRunnable(final Runnable run, final R result) {
return fromRunnable(run, result, Schedulers.computation());
} | [
"public",
"static",
"<",
"R",
">",
"Observable",
"<",
"R",
">",
"fromRunnable",
"(",
"final",
"Runnable",
"run",
",",
"final",
"R",
"result",
")",
"{",
"return",
"fromRunnable",
"(",
"run",
",",
"result",
",",
"Schedulers",
".",
"computation",
"(",
")",
")",
";",
"}"
] | Return an Observable that calls the given Runnable and emits the given result when an Observer
subscribes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromRunnable.png" alt="">
<p>
The Runnable is called on the default thread pool for computation.
@param <R> the return type
@param run the runnable to invoke on each subscription
@param result the result to emit to observers
@return an Observable that calls the given Runnable and emits the given result when an Observer
subscribes
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-fromrunnable">RxJava Wiki: fromRunnable()</a> | [
"Return",
"an",
"Observable",
"that",
"calls",
"the",
"given",
"Runnable",
"and",
"emits",
"the",
"given",
"result",
"when",
"an",
"Observer",
"subscribes",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"fromRunnable",
".",
"png",
"alt",
"=",
">",
"<p",
">",
"The",
"Runnable",
"is",
"called",
"on",
"the",
"default",
"thread",
"pool",
"for",
"computation",
"."
] | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L2025-L2027 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.readFile | public CmsFile readFile(CmsRequestContext context, CmsResource resource) throws CmsException {
"""
Reads a file resource (including it's binary content) from the VFS.<p>
In case you do not need the file content,
use <code>{@link #readResource(CmsRequestContext, String, CmsResourceFilter)}</code> instead.<p>
@param context the current request context
@param resource the resource to be read
@return the file read from the VFS
@throws CmsException if something goes wrong
"""
CmsFile result = null;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
result = m_driverManager.readFile(dbc, resource);
} catch (Exception e) {
if (resource instanceof I_CmsHistoryResource) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_READ_FILE_HISTORY_2,
context.getSitePath(resource),
new Integer(resource.getVersion())),
e);
} else {
dbc.report(null, Messages.get().container(Messages.ERR_READ_FILE_1, context.getSitePath(resource)), e);
}
} finally {
dbc.clear();
}
return result;
} | java | public CmsFile readFile(CmsRequestContext context, CmsResource resource) throws CmsException {
CmsFile result = null;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
result = m_driverManager.readFile(dbc, resource);
} catch (Exception e) {
if (resource instanceof I_CmsHistoryResource) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_READ_FILE_HISTORY_2,
context.getSitePath(resource),
new Integer(resource.getVersion())),
e);
} else {
dbc.report(null, Messages.get().container(Messages.ERR_READ_FILE_1, context.getSitePath(resource)), e);
}
} finally {
dbc.clear();
}
return result;
} | [
"public",
"CmsFile",
"readFile",
"(",
"CmsRequestContext",
"context",
",",
"CmsResource",
"resource",
")",
"throws",
"CmsException",
"{",
"CmsFile",
"result",
"=",
"null",
";",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"try",
"{",
"result",
"=",
"m_driverManager",
".",
"readFile",
"(",
"dbc",
",",
"resource",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"resource",
"instanceof",
"I_CmsHistoryResource",
")",
"{",
"dbc",
".",
"report",
"(",
"null",
",",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_READ_FILE_HISTORY_2",
",",
"context",
".",
"getSitePath",
"(",
"resource",
")",
",",
"new",
"Integer",
"(",
"resource",
".",
"getVersion",
"(",
")",
")",
")",
",",
"e",
")",
";",
"}",
"else",
"{",
"dbc",
".",
"report",
"(",
"null",
",",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_READ_FILE_1",
",",
"context",
".",
"getSitePath",
"(",
"resource",
")",
")",
",",
"e",
")",
";",
"}",
"}",
"finally",
"{",
"dbc",
".",
"clear",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Reads a file resource (including it's binary content) from the VFS.<p>
In case you do not need the file content,
use <code>{@link #readResource(CmsRequestContext, String, CmsResourceFilter)}</code> instead.<p>
@param context the current request context
@param resource the resource to be read
@return the file read from the VFS
@throws CmsException if something goes wrong | [
"Reads",
"a",
"file",
"resource",
"(",
"including",
"it",
"s",
"binary",
"content",
")",
"from",
"the",
"VFS",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L4263-L4285 |
spotify/async-google-pubsub-client | src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java | Pubsub.getSubscription | public PubsubFuture<Subscription> getSubscription(final String project, final String subscription) {
"""
Get a Pub/Sub subscription.
@param project The Google Cloud project.
@param subscription The name of the subscription to get.
@return A future that is completed when this request is completed. The future will be completed with {@code null}
if the response is 404.
"""
return getSubscription(canonicalSubscription(project, subscription));
} | java | public PubsubFuture<Subscription> getSubscription(final String project, final String subscription) {
return getSubscription(canonicalSubscription(project, subscription));
} | [
"public",
"PubsubFuture",
"<",
"Subscription",
">",
"getSubscription",
"(",
"final",
"String",
"project",
",",
"final",
"String",
"subscription",
")",
"{",
"return",
"getSubscription",
"(",
"canonicalSubscription",
"(",
"project",
",",
"subscription",
")",
")",
";",
"}"
] | Get a Pub/Sub subscription.
@param project The Google Cloud project.
@param subscription The name of the subscription to get.
@return A future that is completed when this request is completed. The future will be completed with {@code null}
if the response is 404. | [
"Get",
"a",
"Pub",
"/",
"Sub",
"subscription",
"."
] | train | https://github.com/spotify/async-google-pubsub-client/blob/7d021528fa5bc29be458e6f210fa62f59b71d004/src/main/java/com/spotify/google/cloud/pubsub/client/Pubsub.java#L432-L434 |
actframework/actframework | src/main/java/act/util/JsonUtilConfig.java | JsonUtilConfig.writeJson | private static final void writeJson(Writer os, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
DateFormat dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
"""
FastJSON does not provide the API so we have to create our own
"""
SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(writer, config);
if (dateFormat != null) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
} finally {
writer.close();
}
} | java | private static final void writeJson(Writer os, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
DateFormat dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(writer, config);
if (dateFormat != null) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
} finally {
writer.close();
}
} | [
"private",
"static",
"final",
"void",
"writeJson",
"(",
"Writer",
"os",
",",
"//",
"Object",
"object",
",",
"//",
"SerializeConfig",
"config",
",",
"//",
"SerializeFilter",
"[",
"]",
"filters",
",",
"//",
"DateFormat",
"dateFormat",
",",
"//",
"int",
"defaultFeatures",
",",
"//",
"SerializerFeature",
"...",
"features",
")",
"{",
"SerializeWriter",
"writer",
"=",
"new",
"SerializeWriter",
"(",
"os",
",",
"defaultFeatures",
",",
"features",
")",
";",
"try",
"{",
"JSONSerializer",
"serializer",
"=",
"new",
"JSONSerializer",
"(",
"writer",
",",
"config",
")",
";",
"if",
"(",
"dateFormat",
"!=",
"null",
")",
"{",
"serializer",
".",
"setDateFormat",
"(",
"dateFormat",
")",
";",
"serializer",
".",
"config",
"(",
"SerializerFeature",
".",
"WriteDateUseDateFormat",
",",
"true",
")",
";",
"}",
"if",
"(",
"filters",
"!=",
"null",
")",
"{",
"for",
"(",
"SerializeFilter",
"filter",
":",
"filters",
")",
"{",
"serializer",
".",
"addFilter",
"(",
"filter",
")",
";",
"}",
"}",
"serializer",
".",
"write",
"(",
"object",
")",
";",
"}",
"finally",
"{",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}"
] | FastJSON does not provide the API so we have to create our own | [
"FastJSON",
"does",
"not",
"provide",
"the",
"API",
"so",
"we",
"have",
"to",
"create",
"our",
"own"
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/JsonUtilConfig.java#L235-L261 |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceIndividualGroupService.java | ReferenceIndividualGroupService.updateGroup | @Override
public void updateGroup(ILockableEntityGroup group, boolean renewLock) throws GroupsException {
"""
Updates the <code>ILockableEntityGroup</code> in the store and removes it from the cache.
@param group ILockableEntityGroup
"""
throwExceptionIfNotInternallyManaged();
try {
if (!group.getLock().isValid()) {
throw new GroupsException(
"Could not update group " + group.getKey() + " has invalid lock.");
}
// updateGroup((IEntityGroup)group);
getGroupStore().update(group);
if (cacheInUse()) {
cacheRemove(group);
}
synchronizeGroupMembersOnUpdate(group);
if (renewLock) {
group.getLock().renew();
} else {
group.getLock().release();
}
} catch (LockingException le) {
throw new GroupsException("Problem updating group " + group.getKey(), le);
}
} | java | @Override
public void updateGroup(ILockableEntityGroup group, boolean renewLock) throws GroupsException {
throwExceptionIfNotInternallyManaged();
try {
if (!group.getLock().isValid()) {
throw new GroupsException(
"Could not update group " + group.getKey() + " has invalid lock.");
}
// updateGroup((IEntityGroup)group);
getGroupStore().update(group);
if (cacheInUse()) {
cacheRemove(group);
}
synchronizeGroupMembersOnUpdate(group);
if (renewLock) {
group.getLock().renew();
} else {
group.getLock().release();
}
} catch (LockingException le) {
throw new GroupsException("Problem updating group " + group.getKey(), le);
}
} | [
"@",
"Override",
"public",
"void",
"updateGroup",
"(",
"ILockableEntityGroup",
"group",
",",
"boolean",
"renewLock",
")",
"throws",
"GroupsException",
"{",
"throwExceptionIfNotInternallyManaged",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"group",
".",
"getLock",
"(",
")",
".",
"isValid",
"(",
")",
")",
"{",
"throw",
"new",
"GroupsException",
"(",
"\"Could not update group \"",
"+",
"group",
".",
"getKey",
"(",
")",
"+",
"\" has invalid lock.\"",
")",
";",
"}",
"// updateGroup((IEntityGroup)group);",
"getGroupStore",
"(",
")",
".",
"update",
"(",
"group",
")",
";",
"if",
"(",
"cacheInUse",
"(",
")",
")",
"{",
"cacheRemove",
"(",
"group",
")",
";",
"}",
"synchronizeGroupMembersOnUpdate",
"(",
"group",
")",
";",
"if",
"(",
"renewLock",
")",
"{",
"group",
".",
"getLock",
"(",
")",
".",
"renew",
"(",
")",
";",
"}",
"else",
"{",
"group",
".",
"getLock",
"(",
")",
".",
"release",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"LockingException",
"le",
")",
"{",
"throw",
"new",
"GroupsException",
"(",
"\"Problem updating group \"",
"+",
"group",
".",
"getKey",
"(",
")",
",",
"le",
")",
";",
"}",
"}"
] | Updates the <code>ILockableEntityGroup</code> in the store and removes it from the cache.
@param group ILockableEntityGroup | [
"Updates",
"the",
"<code",
">",
"ILockableEntityGroup<",
"/",
"code",
">",
"in",
"the",
"store",
"and",
"removes",
"it",
"from",
"the",
"cache",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceIndividualGroupService.java#L613-L639 |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Operation.java | Operation.shouldProtect | private boolean shouldProtect(Expression operand, OperandPosition operandPosition) {
"""
An operand needs to be protected with parens if
<ul>
<li>its {@link #precedence} is lower than the operator's precedence, or
<li>its precedence is the same as the operator's, it is {@link Associativity#LEFT left
associative}, and it appears to the right of the operator, or
<li>its precedence is the same as the operator's, it is {@link Associativity#RIGHT right
associative}, and it appears to the left of the operator.
</ul>
"""
if (operand instanceof Operation) {
Operation operation = (Operation) operand;
return operation.precedence() < this.precedence()
|| (operation.precedence() == this.precedence()
&& operandPosition.shouldParenthesize(operation.associativity()));
} else if (operand instanceof Leaf) {
// JsExprs have precedence info, but not associativity. So at least check the precedence.
JsExpr expr = ((Leaf) operand).value();
return expr.getPrecedence() < this.precedence();
} else {
return false;
}
} | java | private boolean shouldProtect(Expression operand, OperandPosition operandPosition) {
if (operand instanceof Operation) {
Operation operation = (Operation) operand;
return operation.precedence() < this.precedence()
|| (operation.precedence() == this.precedence()
&& operandPosition.shouldParenthesize(operation.associativity()));
} else if (operand instanceof Leaf) {
// JsExprs have precedence info, but not associativity. So at least check the precedence.
JsExpr expr = ((Leaf) operand).value();
return expr.getPrecedence() < this.precedence();
} else {
return false;
}
} | [
"private",
"boolean",
"shouldProtect",
"(",
"Expression",
"operand",
",",
"OperandPosition",
"operandPosition",
")",
"{",
"if",
"(",
"operand",
"instanceof",
"Operation",
")",
"{",
"Operation",
"operation",
"=",
"(",
"Operation",
")",
"operand",
";",
"return",
"operation",
".",
"precedence",
"(",
")",
"<",
"this",
".",
"precedence",
"(",
")",
"||",
"(",
"operation",
".",
"precedence",
"(",
")",
"==",
"this",
".",
"precedence",
"(",
")",
"&&",
"operandPosition",
".",
"shouldParenthesize",
"(",
"operation",
".",
"associativity",
"(",
")",
")",
")",
";",
"}",
"else",
"if",
"(",
"operand",
"instanceof",
"Leaf",
")",
"{",
"// JsExprs have precedence info, but not associativity. So at least check the precedence.",
"JsExpr",
"expr",
"=",
"(",
"(",
"Leaf",
")",
"operand",
")",
".",
"value",
"(",
")",
";",
"return",
"expr",
".",
"getPrecedence",
"(",
")",
"<",
"this",
".",
"precedence",
"(",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | An operand needs to be protected with parens if
<ul>
<li>its {@link #precedence} is lower than the operator's precedence, or
<li>its precedence is the same as the operator's, it is {@link Associativity#LEFT left
associative}, and it appears to the right of the operator, or
<li>its precedence is the same as the operator's, it is {@link Associativity#RIGHT right
associative}, and it appears to the left of the operator.
</ul> | [
"An",
"operand",
"needs",
"to",
"be",
"protected",
"with",
"parens",
"if"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Operation.java#L64-L77 |
microfocus-idol/java-content-parameter-api | src/main/java/com/hp/autonomy/aci/content/fieldtext/FieldTextBuilder.java | FieldTextBuilder.WHEN | @Override
public FieldTextBuilder WHEN(final FieldText fieldText) {
"""
Appends the specified fieldtext onto the builder using the WHEN operator. A simplification is made in the case
where the passed {@code fieldText} is equal to {@code this}:
<p>
<pre>(A WHEN A) {@literal =>} A</pre>
@param fieldText A fieldtext expression or specifier.
@return {@code this}
"""
Validate.notNull(fieldText, "FieldText should not be null");
Validate.isTrue(fieldText.size() >= 1, "FieldText must have a size greater or equal to 1");
if(size() < 1) {
throw new IllegalStateException("Size must be greater than or equal to 1");
}
// Here we assume that A WHEN A => A but is there an edge case where this doesn't work?
if(fieldText == this || toString().equals(fieldText.toString())) {
return this;
}
if(MATCHNOTHING.equals(this) || MATCHNOTHING.equals(fieldText)) {
return setFieldText(MATCHNOTHING);
}
return binaryOperation("WHEN", fieldText);
} | java | @Override
public FieldTextBuilder WHEN(final FieldText fieldText) {
Validate.notNull(fieldText, "FieldText should not be null");
Validate.isTrue(fieldText.size() >= 1, "FieldText must have a size greater or equal to 1");
if(size() < 1) {
throw new IllegalStateException("Size must be greater than or equal to 1");
}
// Here we assume that A WHEN A => A but is there an edge case where this doesn't work?
if(fieldText == this || toString().equals(fieldText.toString())) {
return this;
}
if(MATCHNOTHING.equals(this) || MATCHNOTHING.equals(fieldText)) {
return setFieldText(MATCHNOTHING);
}
return binaryOperation("WHEN", fieldText);
} | [
"@",
"Override",
"public",
"FieldTextBuilder",
"WHEN",
"(",
"final",
"FieldText",
"fieldText",
")",
"{",
"Validate",
".",
"notNull",
"(",
"fieldText",
",",
"\"FieldText should not be null\"",
")",
";",
"Validate",
".",
"isTrue",
"(",
"fieldText",
".",
"size",
"(",
")",
">=",
"1",
",",
"\"FieldText must have a size greater or equal to 1\"",
")",
";",
"if",
"(",
"size",
"(",
")",
"<",
"1",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Size must be greater than or equal to 1\"",
")",
";",
"}",
"// Here we assume that A WHEN A => A but is there an edge case where this doesn't work?",
"if",
"(",
"fieldText",
"==",
"this",
"||",
"toString",
"(",
")",
".",
"equals",
"(",
"fieldText",
".",
"toString",
"(",
")",
")",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"MATCHNOTHING",
".",
"equals",
"(",
"this",
")",
"||",
"MATCHNOTHING",
".",
"equals",
"(",
"fieldText",
")",
")",
"{",
"return",
"setFieldText",
"(",
"MATCHNOTHING",
")",
";",
"}",
"return",
"binaryOperation",
"(",
"\"WHEN\"",
",",
"fieldText",
")",
";",
"}"
] | Appends the specified fieldtext onto the builder using the WHEN operator. A simplification is made in the case
where the passed {@code fieldText} is equal to {@code this}:
<p>
<pre>(A WHEN A) {@literal =>} A</pre>
@param fieldText A fieldtext expression or specifier.
@return {@code this} | [
"Appends",
"the",
"specified",
"fieldtext",
"onto",
"the",
"builder",
"using",
"the",
"WHEN",
"operator",
".",
"A",
"simplification",
"is",
"made",
"in",
"the",
"case",
"where",
"the",
"passed",
"{",
"@code",
"fieldText",
"}",
"is",
"equal",
"to",
"{",
"@code",
"this",
"}",
":",
"<p",
">",
"<pre",
">",
"(",
"A",
"WHEN",
"A",
")",
"{",
"@literal",
"=",
">",
"}",
"A<",
"/",
"pre",
">"
] | train | https://github.com/microfocus-idol/java-content-parameter-api/blob/8d33dc633f8df2a470a571ac7694e423e7004ad0/src/main/java/com/hp/autonomy/aci/content/fieldtext/FieldTextBuilder.java#L228-L247 |
rollbar/rollbar-java | rollbar-android/src/main/java/com/rollbar/android/Rollbar.java | Rollbar.log | public void log(String message, Map<String, Object> custom, Level level) {
"""
Record a message with extra information attached at the specified level.
@param message the message.
@param custom the extra information.
@param level the level.
"""
log(null, custom, message, level);
} | java | public void log(String message, Map<String, Object> custom, Level level) {
log(null, custom, message, level);
} | [
"public",
"void",
"log",
"(",
"String",
"message",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"custom",
",",
"Level",
"level",
")",
"{",
"log",
"(",
"null",
",",
"custom",
",",
"message",
",",
"level",
")",
";",
"}"
] | Record a message with extra information attached at the specified level.
@param message the message.
@param custom the extra information.
@param level the level. | [
"Record",
"a",
"message",
"with",
"extra",
"information",
"attached",
"at",
"the",
"specified",
"level",
"."
] | train | https://github.com/rollbar/rollbar-java/blob/5eb4537d1363722b51cfcce55b427cbd8489f17b/rollbar-android/src/main/java/com/rollbar/android/Rollbar.java#L776-L778 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/connector/filesystem/FileSystemConnector.java | FileSystemConnector.idFor | protected String idFor( File file ) {
"""
Utility method for determining the node identifier for the supplied file. Subclasses may override this method to change the
format of the identifiers, but in that case should also override the {@link #fileFor(String)},
{@link #isContentNode(String)}, and {@link #isRoot(String)} methods.
@param file the file; may not be null
@return the node identifier; never null
@see #isRoot(String)
@see #isContentNode(String)
@see #fileFor(String)
"""
String path = file.getAbsolutePath();
if (!path.startsWith(directoryAbsolutePath)) {
if (directory.getAbsolutePath().equals(path)) {
// This is the root
return DELIMITER;
}
String msg = JcrI18n.fileConnectorNodeIdentifierIsNotWithinScopeOfConnector.text(getSourceName(), directoryPath, path);
throw new DocumentStoreException(path, msg);
}
String id = path.substring(directoryAbsolutePathLength);
id = id.replaceAll(Pattern.quote(FILE_SEPARATOR), DELIMITER);
assert id.startsWith(DELIMITER);
return id;
} | java | protected String idFor( File file ) {
String path = file.getAbsolutePath();
if (!path.startsWith(directoryAbsolutePath)) {
if (directory.getAbsolutePath().equals(path)) {
// This is the root
return DELIMITER;
}
String msg = JcrI18n.fileConnectorNodeIdentifierIsNotWithinScopeOfConnector.text(getSourceName(), directoryPath, path);
throw new DocumentStoreException(path, msg);
}
String id = path.substring(directoryAbsolutePathLength);
id = id.replaceAll(Pattern.quote(FILE_SEPARATOR), DELIMITER);
assert id.startsWith(DELIMITER);
return id;
} | [
"protected",
"String",
"idFor",
"(",
"File",
"file",
")",
"{",
"String",
"path",
"=",
"file",
".",
"getAbsolutePath",
"(",
")",
";",
"if",
"(",
"!",
"path",
".",
"startsWith",
"(",
"directoryAbsolutePath",
")",
")",
"{",
"if",
"(",
"directory",
".",
"getAbsolutePath",
"(",
")",
".",
"equals",
"(",
"path",
")",
")",
"{",
"// This is the root",
"return",
"DELIMITER",
";",
"}",
"String",
"msg",
"=",
"JcrI18n",
".",
"fileConnectorNodeIdentifierIsNotWithinScopeOfConnector",
".",
"text",
"(",
"getSourceName",
"(",
")",
",",
"directoryPath",
",",
"path",
")",
";",
"throw",
"new",
"DocumentStoreException",
"(",
"path",
",",
"msg",
")",
";",
"}",
"String",
"id",
"=",
"path",
".",
"substring",
"(",
"directoryAbsolutePathLength",
")",
";",
"id",
"=",
"id",
".",
"replaceAll",
"(",
"Pattern",
".",
"quote",
"(",
"FILE_SEPARATOR",
")",
",",
"DELIMITER",
")",
";",
"assert",
"id",
".",
"startsWith",
"(",
"DELIMITER",
")",
";",
"return",
"id",
";",
"}"
] | Utility method for determining the node identifier for the supplied file. Subclasses may override this method to change the
format of the identifiers, but in that case should also override the {@link #fileFor(String)},
{@link #isContentNode(String)}, and {@link #isRoot(String)} methods.
@param file the file; may not be null
@return the node identifier; never null
@see #isRoot(String)
@see #isContentNode(String)
@see #fileFor(String) | [
"Utility",
"method",
"for",
"determining",
"the",
"node",
"identifier",
"for",
"the",
"supplied",
"file",
".",
"Subclasses",
"may",
"override",
"this",
"method",
"to",
"change",
"the",
"format",
"of",
"the",
"identifiers",
"but",
"in",
"that",
"case",
"should",
"also",
"override",
"the",
"{",
"@link",
"#fileFor",
"(",
"String",
")",
"}",
"{",
"@link",
"#isContentNode",
"(",
"String",
")",
"}",
"and",
"{",
"@link",
"#isRoot",
"(",
"String",
")",
"}",
"methods",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/connector/filesystem/FileSystemConnector.java#L363-L377 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/utils/CommonMBeanConnection.java | CommonMBeanConnection.createPromptingTrustManager | private X509TrustManager createPromptingTrustManager() {
"""
Create a custom trust manager which will prompt for trust acceptance.
@return
"""
TrustManager[] trustManagers = null;
try {
String defaultAlg = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlg);
tmf.init((KeyStore) null);
trustManagers = tmf.getTrustManagers();
} catch (KeyStoreException e) {
// Unable to initialize the default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
} catch (NoSuchAlgorithmException e) {
// Unable to get default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
}
boolean autoAccept = Boolean.valueOf(System.getProperty(SYS_PROP_AUTO_ACCEPT, "false"));
return new PromptX509TrustManager(stdin, stdout, trustManagers, autoAccept);
} | java | private X509TrustManager createPromptingTrustManager() {
TrustManager[] trustManagers = null;
try {
String defaultAlg = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlg);
tmf.init((KeyStore) null);
trustManagers = tmf.getTrustManagers();
} catch (KeyStoreException e) {
// Unable to initialize the default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
} catch (NoSuchAlgorithmException e) {
// Unable to get default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
}
boolean autoAccept = Boolean.valueOf(System.getProperty(SYS_PROP_AUTO_ACCEPT, "false"));
return new PromptX509TrustManager(stdin, stdout, trustManagers, autoAccept);
} | [
"private",
"X509TrustManager",
"createPromptingTrustManager",
"(",
")",
"{",
"TrustManager",
"[",
"]",
"trustManagers",
"=",
"null",
";",
"try",
"{",
"String",
"defaultAlg",
"=",
"TrustManagerFactory",
".",
"getDefaultAlgorithm",
"(",
")",
";",
"TrustManagerFactory",
"tmf",
"=",
"TrustManagerFactory",
".",
"getInstance",
"(",
"defaultAlg",
")",
";",
"tmf",
".",
"init",
"(",
"(",
"KeyStore",
")",
"null",
")",
";",
"trustManagers",
"=",
"tmf",
".",
"getTrustManagers",
"(",
")",
";",
"}",
"catch",
"(",
"KeyStoreException",
"e",
")",
"{",
"// Unable to initialize the default trust managers.",
"// This is not a problem as PromptX509rustManager can handle null.",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"e",
")",
"{",
"// Unable to get default trust managers.",
"// This is not a problem as PromptX509rustManager can handle null.",
"}",
"boolean",
"autoAccept",
"=",
"Boolean",
".",
"valueOf",
"(",
"System",
".",
"getProperty",
"(",
"SYS_PROP_AUTO_ACCEPT",
",",
"\"false\"",
")",
")",
";",
"return",
"new",
"PromptX509TrustManager",
"(",
"stdin",
",",
"stdout",
",",
"trustManagers",
",",
"autoAccept",
")",
";",
"}"
] | Create a custom trust manager which will prompt for trust acceptance.
@return | [
"Create",
"a",
"custom",
"trust",
"manager",
"which",
"will",
"prompt",
"for",
"trust",
"acceptance",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/utils/CommonMBeanConnection.java#L55-L72 |
atomix/copycat | server/src/main/java/io/atomix/copycat/server/storage/snapshot/SnapshotFile.java | SnapshotFile.createSnapshotFile | static File createSnapshotFile(String name, File directory, long index, long timestamp) {
"""
Creates a snapshot file for the given directory, log name, and snapshot index.
"""
return new File(directory, String.format("%s-%d-%s.snapshot", Assert.notNull(name, "name"), index, TIMESTAMP_FORMAT.format(new Date(timestamp))));
} | java | static File createSnapshotFile(String name, File directory, long index, long timestamp) {
return new File(directory, String.format("%s-%d-%s.snapshot", Assert.notNull(name, "name"), index, TIMESTAMP_FORMAT.format(new Date(timestamp))));
} | [
"static",
"File",
"createSnapshotFile",
"(",
"String",
"name",
",",
"File",
"directory",
",",
"long",
"index",
",",
"long",
"timestamp",
")",
"{",
"return",
"new",
"File",
"(",
"directory",
",",
"String",
".",
"format",
"(",
"\"%s-%d-%s.snapshot\"",
",",
"Assert",
".",
"notNull",
"(",
"name",
",",
"\"name\"",
")",
",",
"index",
",",
"TIMESTAMP_FORMAT",
".",
"format",
"(",
"new",
"Date",
"(",
"timestamp",
")",
")",
")",
")",
";",
"}"
] | Creates a snapshot file for the given directory, log name, and snapshot index. | [
"Creates",
"a",
"snapshot",
"file",
"for",
"the",
"given",
"directory",
"log",
"name",
"and",
"snapshot",
"index",
"."
] | train | https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/storage/snapshot/SnapshotFile.java#L69-L71 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java | KeyVaultClientCustomImpl.listCertificates | public PagedList<CertificateItem> listCertificates(final String vaultBaseUrl, final Integer maxresults) {
"""
List certificates in the specified vault.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param maxresults
Maximum number of results to return in a page. If not specified
the service will return up to 25 results.
@return the PagedList<CertificateItem> if successful.
"""
return getCertificates(vaultBaseUrl, maxresults);
} | java | public PagedList<CertificateItem> listCertificates(final String vaultBaseUrl, final Integer maxresults) {
return getCertificates(vaultBaseUrl, maxresults);
} | [
"public",
"PagedList",
"<",
"CertificateItem",
">",
"listCertificates",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"Integer",
"maxresults",
")",
"{",
"return",
"getCertificates",
"(",
"vaultBaseUrl",
",",
"maxresults",
")",
";",
"}"
] | List certificates in the specified vault.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param maxresults
Maximum number of results to return in a page. If not specified
the service will return up to 25 results.
@return the PagedList<CertificateItem> if successful. | [
"List",
"certificates",
"in",
"the",
"specified",
"vault",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1323-L1325 |
Subsets and Splits