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
|
---|---|---|---|---|---|---|---|---|---|---|
joniles/mpxj | src/main/java/net/sf/mpxj/ProjectCalendar.java | ProjectCalendar.getTime | private long getTime(Date start, Date end, long target, boolean after) {
"""
Calculates how much of a time range is before or after a
target intersection point.
@param start time range start
@param end time range end
@param target target intersection point
@param after true if time after target required, false for time before
@return length of time in milliseconds
"""
long total = 0;
if (start != null && end != null)
{
Date startTime = DateHelper.getCanonicalTime(start);
Date endTime = DateHelper.getCanonicalTime(end);
Date startDay = DateHelper.getDayStartDate(start);
Date finishDay = DateHelper.getDayStartDate(end);
//
// Handle the case where the end of the range is at midnight -
// this will show up as the start and end days not matching
//
if (startDay.getTime() != finishDay.getTime())
{
endTime = DateHelper.addDays(endTime, 1);
}
int diff = DateHelper.compare(startTime, endTime, target);
if (diff == 0)
{
if (after == true)
{
total = (endTime.getTime() - target);
}
else
{
total = (target - startTime.getTime());
}
}
else
{
if ((after == true && diff < 0) || (after == false && diff > 0))
{
total = (endTime.getTime() - startTime.getTime());
}
}
}
return (total);
} | java | private long getTime(Date start, Date end, long target, boolean after)
{
long total = 0;
if (start != null && end != null)
{
Date startTime = DateHelper.getCanonicalTime(start);
Date endTime = DateHelper.getCanonicalTime(end);
Date startDay = DateHelper.getDayStartDate(start);
Date finishDay = DateHelper.getDayStartDate(end);
//
// Handle the case where the end of the range is at midnight -
// this will show up as the start and end days not matching
//
if (startDay.getTime() != finishDay.getTime())
{
endTime = DateHelper.addDays(endTime, 1);
}
int diff = DateHelper.compare(startTime, endTime, target);
if (diff == 0)
{
if (after == true)
{
total = (endTime.getTime() - target);
}
else
{
total = (target - startTime.getTime());
}
}
else
{
if ((after == true && diff < 0) || (after == false && diff > 0))
{
total = (endTime.getTime() - startTime.getTime());
}
}
}
return (total);
} | [
"private",
"long",
"getTime",
"(",
"Date",
"start",
",",
"Date",
"end",
",",
"long",
"target",
",",
"boolean",
"after",
")",
"{",
"long",
"total",
"=",
"0",
";",
"if",
"(",
"start",
"!=",
"null",
"&&",
"end",
"!=",
"null",
")",
"{",
"Date",
"startTime",
"=",
"DateHelper",
".",
"getCanonicalTime",
"(",
"start",
")",
";",
"Date",
"endTime",
"=",
"DateHelper",
".",
"getCanonicalTime",
"(",
"end",
")",
";",
"Date",
"startDay",
"=",
"DateHelper",
".",
"getDayStartDate",
"(",
"start",
")",
";",
"Date",
"finishDay",
"=",
"DateHelper",
".",
"getDayStartDate",
"(",
"end",
")",
";",
"//",
"// Handle the case where the end of the range is at midnight -",
"// this will show up as the start and end days not matching",
"//",
"if",
"(",
"startDay",
".",
"getTime",
"(",
")",
"!=",
"finishDay",
".",
"getTime",
"(",
")",
")",
"{",
"endTime",
"=",
"DateHelper",
".",
"addDays",
"(",
"endTime",
",",
"1",
")",
";",
"}",
"int",
"diff",
"=",
"DateHelper",
".",
"compare",
"(",
"startTime",
",",
"endTime",
",",
"target",
")",
";",
"if",
"(",
"diff",
"==",
"0",
")",
"{",
"if",
"(",
"after",
"==",
"true",
")",
"{",
"total",
"=",
"(",
"endTime",
".",
"getTime",
"(",
")",
"-",
"target",
")",
";",
"}",
"else",
"{",
"total",
"=",
"(",
"target",
"-",
"startTime",
".",
"getTime",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"(",
"after",
"==",
"true",
"&&",
"diff",
"<",
"0",
")",
"||",
"(",
"after",
"==",
"false",
"&&",
"diff",
">",
"0",
")",
")",
"{",
"total",
"=",
"(",
"endTime",
".",
"getTime",
"(",
")",
"-",
"startTime",
".",
"getTime",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"(",
"total",
")",
";",
"}"
] | Calculates how much of a time range is before or after a
target intersection point.
@param start time range start
@param end time range end
@param target target intersection point
@param after true if time after target required, false for time before
@return length of time in milliseconds | [
"Calculates",
"how",
"much",
"of",
"a",
"time",
"range",
"is",
"before",
"or",
"after",
"a",
"target",
"intersection",
"point",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectCalendar.java#L1514-L1555 |
dbracewell/hermes | hermes-core/src/main/java/com/davidbracewell/hermes/Document.java | Document.create | public static Document create(@NonNull String id, @NonNull String text, @NonNull Language language, @NonNull Map<AttributeType, ?> attributes) {
"""
Convenience method for creating a document using the default document factory.
@param id the document id
@param text the text content making up the document
@param language the language of the content
@param attributes the attributes, i.e. metadata, associated with the document
@return the document
"""
return DocumentFactory.getInstance().create(id, text, language, attributes);
} | java | public static Document create(@NonNull String id, @NonNull String text, @NonNull Language language, @NonNull Map<AttributeType, ?> attributes) {
return DocumentFactory.getInstance().create(id, text, language, attributes);
} | [
"public",
"static",
"Document",
"create",
"(",
"@",
"NonNull",
"String",
"id",
",",
"@",
"NonNull",
"String",
"text",
",",
"@",
"NonNull",
"Language",
"language",
",",
"@",
"NonNull",
"Map",
"<",
"AttributeType",
",",
"?",
">",
"attributes",
")",
"{",
"return",
"DocumentFactory",
".",
"getInstance",
"(",
")",
".",
"create",
"(",
"id",
",",
"text",
",",
"language",
",",
"attributes",
")",
";",
"}"
] | Convenience method for creating a document using the default document factory.
@param id the document id
@param text the text content making up the document
@param language the language of the content
@param attributes the attributes, i.e. metadata, associated with the document
@return the document | [
"Convenience",
"method",
"for",
"creating",
"a",
"document",
"using",
"the",
"default",
"document",
"factory",
"."
] | train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/Document.java#L174-L176 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_line_serviceName_phone_merchandiseAvailable_GET | public ArrayList<OvhHardwareOffer> billingAccount_line_serviceName_phone_merchandiseAvailable_GET(String billingAccount, String serviceName) throws IOException {
"""
List of available exchange merchandise brand
REST: GET /telephony/{billingAccount}/line/{serviceName}/phone/merchandiseAvailable
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
"""
String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone/merchandiseAvailable";
StringBuilder sb = path(qPath, billingAccount, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t7);
} | java | public ArrayList<OvhHardwareOffer> billingAccount_line_serviceName_phone_merchandiseAvailable_GET(String billingAccount, String serviceName) throws IOException {
String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone/merchandiseAvailable";
StringBuilder sb = path(qPath, billingAccount, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t7);
} | [
"public",
"ArrayList",
"<",
"OvhHardwareOffer",
">",
"billingAccount_line_serviceName_phone_merchandiseAvailable_GET",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/line/{serviceName}/phone/merchandiseAvailable\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
",",
"serviceName",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"t7",
")",
";",
"}"
] | List of available exchange merchandise brand
REST: GET /telephony/{billingAccount}/line/{serviceName}/phone/merchandiseAvailable
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"List",
"of",
"available",
"exchange",
"merchandise",
"brand"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1191-L1196 |
Alluxio/alluxio | core/common/src/main/java/alluxio/conf/AlluxioProperties.java | AlluxioProperties.setSource | @VisibleForTesting
public void setSource(PropertyKey key, Source source) {
"""
Sets the source for a given key.
@param key property key
@param source the source
"""
mSources.put(key, source);
} | java | @VisibleForTesting
public void setSource(PropertyKey key, Source source) {
mSources.put(key, source);
} | [
"@",
"VisibleForTesting",
"public",
"void",
"setSource",
"(",
"PropertyKey",
"key",
",",
"Source",
"source",
")",
"{",
"mSources",
".",
"put",
"(",
"key",
",",
"source",
")",
";",
"}"
] | Sets the source for a given key.
@param key property key
@param source the source | [
"Sets",
"the",
"source",
"for",
"a",
"given",
"key",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/conf/AlluxioProperties.java#L240-L243 |
graknlabs/grakn | server/src/server/exception/TransactionException.java | TransactionException.closingFailed | public static TransactionException closingFailed(TransactionOLTP tx, Exception e) {
"""
Thrown when the graph can not be closed due to an unknown reason.
"""
return new TransactionException(CLOSE_FAILURE.getMessage(tx.keyspace()), e);
} | java | public static TransactionException closingFailed(TransactionOLTP tx, Exception e) {
return new TransactionException(CLOSE_FAILURE.getMessage(tx.keyspace()), e);
} | [
"public",
"static",
"TransactionException",
"closingFailed",
"(",
"TransactionOLTP",
"tx",
",",
"Exception",
"e",
")",
"{",
"return",
"new",
"TransactionException",
"(",
"CLOSE_FAILURE",
".",
"getMessage",
"(",
"tx",
".",
"keyspace",
"(",
")",
")",
",",
"e",
")",
";",
"}"
] | Thrown when the graph can not be closed due to an unknown reason. | [
"Thrown",
"when",
"the",
"graph",
"can",
"not",
"be",
"closed",
"due",
"to",
"an",
"unknown",
"reason",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L227-L229 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/Record.java | Record.getDateTime | public Date getDateTime(int field) throws MPXJException {
"""
Accessor method used to retrieve an Date instance representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails
"""
Date result = null;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getDateTimeFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
// Failed to parse a full date time.
}
//
// Fall back to trying just parsing the date component
//
if (result == null)
{
try
{
result = m_formats.getDateFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse date time", ex);
}
}
}
return result;
} | java | public Date getDateTime(int field) throws MPXJException
{
Date result = null;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getDateTimeFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
// Failed to parse a full date time.
}
//
// Fall back to trying just parsing the date component
//
if (result == null)
{
try
{
result = m_formats.getDateFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse date time", ex);
}
}
}
return result;
} | [
"public",
"Date",
"getDateTime",
"(",
"int",
"field",
")",
"throws",
"MPXJException",
"{",
"Date",
"result",
"=",
"null",
";",
"if",
"(",
"(",
"field",
"<",
"m_fields",
".",
"length",
")",
"&&",
"(",
"m_fields",
"[",
"field",
"]",
".",
"length",
"(",
")",
"!=",
"0",
")",
")",
"{",
"try",
"{",
"result",
"=",
"m_formats",
".",
"getDateTimeFormat",
"(",
")",
".",
"parse",
"(",
"m_fields",
"[",
"field",
"]",
")",
";",
"}",
"catch",
"(",
"ParseException",
"ex",
")",
"{",
"// Failed to parse a full date time.",
"}",
"//",
"// Fall back to trying just parsing the date component",
"//",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"try",
"{",
"result",
"=",
"m_formats",
".",
"getDateFormat",
"(",
")",
".",
"parse",
"(",
"m_fields",
"[",
"field",
"]",
")",
";",
"}",
"catch",
"(",
"ParseException",
"ex",
")",
"{",
"throw",
"new",
"MPXJException",
"(",
"\"Failed to parse date time\"",
",",
"ex",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Accessor method used to retrieve an Date instance representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails | [
"Accessor",
"method",
"used",
"to",
"retrieve",
"an",
"Date",
"instance",
"representing",
"the",
"contents",
"of",
"an",
"individual",
"field",
".",
"If",
"the",
"field",
"does",
"not",
"exist",
"in",
"the",
"record",
"null",
"is",
"returned",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/Record.java#L238-L272 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementTreeView.java | ElementTreeView.afterMoveChild | @Override
protected void afterMoveChild(ElementBase child, ElementBase before) {
"""
Only the node needs to be resequenced, since pane sequencing is arbitrary.
"""
ElementTreePane childpane = (ElementTreePane) child;
ElementTreePane beforepane = (ElementTreePane) before;
moveChild(childpane.getNode(), beforepane.getNode());
} | java | @Override
protected void afterMoveChild(ElementBase child, ElementBase before) {
ElementTreePane childpane = (ElementTreePane) child;
ElementTreePane beforepane = (ElementTreePane) before;
moveChild(childpane.getNode(), beforepane.getNode());
} | [
"@",
"Override",
"protected",
"void",
"afterMoveChild",
"(",
"ElementBase",
"child",
",",
"ElementBase",
"before",
")",
"{",
"ElementTreePane",
"childpane",
"=",
"(",
"ElementTreePane",
")",
"child",
";",
"ElementTreePane",
"beforepane",
"=",
"(",
"ElementTreePane",
")",
"before",
";",
"moveChild",
"(",
"childpane",
".",
"getNode",
"(",
")",
",",
"beforepane",
".",
"getNode",
"(",
")",
")",
";",
"}"
] | Only the node needs to be resequenced, since pane sequencing is arbitrary. | [
"Only",
"the",
"node",
"needs",
"to",
"be",
"resequenced",
"since",
"pane",
"sequencing",
"is",
"arbitrary",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementTreeView.java#L70-L75 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/authentication/authenticationsamlpolicy_binding.java | authenticationsamlpolicy_binding.get | public static authenticationsamlpolicy_binding get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch authenticationsamlpolicy_binding resource of given name .
"""
authenticationsamlpolicy_binding obj = new authenticationsamlpolicy_binding();
obj.set_name(name);
authenticationsamlpolicy_binding response = (authenticationsamlpolicy_binding) obj.get_resource(service);
return response;
} | java | public static authenticationsamlpolicy_binding get(nitro_service service, String name) throws Exception{
authenticationsamlpolicy_binding obj = new authenticationsamlpolicy_binding();
obj.set_name(name);
authenticationsamlpolicy_binding response = (authenticationsamlpolicy_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"authenticationsamlpolicy_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"authenticationsamlpolicy_binding",
"obj",
"=",
"new",
"authenticationsamlpolicy_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"authenticationsamlpolicy_binding",
"response",
"=",
"(",
"authenticationsamlpolicy_binding",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] | Use this API to fetch authenticationsamlpolicy_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"authenticationsamlpolicy_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/authentication/authenticationsamlpolicy_binding.java#L103-L108 |
apache/groovy | subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java | Sql.newInstance | public static Sql newInstance(String url, String user, String password, String driverClassName)
throws SQLException, ClassNotFoundException {
"""
Creates a new Sql instance given a JDBC connection URL,
a username, a password and a driver class name.
@param url a database url of the form
<code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
@param user the database user on whose behalf the connection
is being made
@param password the user's password
@param driverClassName the fully qualified class name of the driver class
@return a new Sql instance with a connection
@throws SQLException if a database access error occurs
@throws ClassNotFoundException if the driver class cannot be found or loaded
"""
loadDriver(driverClassName);
return newInstance(url, user, password);
} | java | public static Sql newInstance(String url, String user, String password, String driverClassName)
throws SQLException, ClassNotFoundException {
loadDriver(driverClassName);
return newInstance(url, user, password);
} | [
"public",
"static",
"Sql",
"newInstance",
"(",
"String",
"url",
",",
"String",
"user",
",",
"String",
"password",
",",
"String",
"driverClassName",
")",
"throws",
"SQLException",
",",
"ClassNotFoundException",
"{",
"loadDriver",
"(",
"driverClassName",
")",
";",
"return",
"newInstance",
"(",
"url",
",",
"user",
",",
"password",
")",
";",
"}"
] | Creates a new Sql instance given a JDBC connection URL,
a username, a password and a driver class name.
@param url a database url of the form
<code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
@param user the database user on whose behalf the connection
is being made
@param password the user's password
@param driverClassName the fully qualified class name of the driver class
@return a new Sql instance with a connection
@throws SQLException if a database access error occurs
@throws ClassNotFoundException if the driver class cannot be found or loaded | [
"Creates",
"a",
"new",
"Sql",
"instance",
"given",
"a",
"JDBC",
"connection",
"URL",
"a",
"username",
"a",
"password",
"and",
"a",
"driver",
"class",
"name",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L431-L435 |
JM-Lab/utils-elasticsearch | src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java | JMElasticsearchIndex.upsertDataAsync | public ActionFuture<UpdateResponse> upsertDataAsync(
Map<String, ?> source, String index, String type, String id) {
"""
Upsert data async action future.
@param source the source
@param index the index
@param type the type
@param id the id
@return the action future
"""
return upsertQueryAsync(buildPrepareUpsert(index, type, id, source));
} | java | public ActionFuture<UpdateResponse> upsertDataAsync(
Map<String, ?> source, String index, String type, String id) {
return upsertQueryAsync(buildPrepareUpsert(index, type, id, source));
} | [
"public",
"ActionFuture",
"<",
"UpdateResponse",
">",
"upsertDataAsync",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"source",
",",
"String",
"index",
",",
"String",
"type",
",",
"String",
"id",
")",
"{",
"return",
"upsertQueryAsync",
"(",
"buildPrepareUpsert",
"(",
"index",
",",
"type",
",",
"id",
",",
"source",
")",
")",
";",
"}"
] | Upsert data async action future.
@param source the source
@param index the index
@param type the type
@param id the id
@return the action future | [
"Upsert",
"data",
"async",
"action",
"future",
"."
] | train | https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchIndex.java#L132-L135 |
mockito/mockito | src/main/java/org/mockito/Mockito.java | Mockito.doReturn | @SuppressWarnings( {
"""
Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
<code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
<p>
<b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
and more readable</b> (especially when stubbing consecutive calls).
<p>
Here are those rare occasions when doReturn() comes handy:
<p>
<ol>
<li>When spying real objects and calling real methods on a spy brings side effects
<pre class="code"><code class="java">
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo", "bar", "qix");
//You have to use doReturn() for stubbing:
doReturn("foo", "bar", "qix").when(spy).get(0);
</code></pre>
</li>
<li>Overriding a previous exception-stubbing:
<pre class="code"><code class="java">
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar", "foo", "qix");
//You have to use doReturn() for stubbing:
doReturn("bar", "foo", "qix").when(mock).foo();
</code></pre>
</li>
</ol>
Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
overridding stubbing is a potential code smell that points out too much stubbing.
<p>
See examples in javadoc for {@link Mockito} class
@param toBeReturned to be returned when the stubbed method is called
@param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
@return stubber - to select a method for stubbing
@since 2.1.0
""""unchecked", "varargs"})
@CheckReturnValue
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
} | java | @SuppressWarnings({"unchecked", "varargs"})
@CheckReturnValue
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"varargs\"",
"}",
")",
"@",
"CheckReturnValue",
"public",
"static",
"Stubber",
"doReturn",
"(",
"Object",
"toBeReturned",
",",
"Object",
"...",
"toBeReturnedNext",
")",
"{",
"return",
"MOCKITO_CORE",
".",
"stubber",
"(",
")",
".",
"doReturn",
"(",
"toBeReturned",
",",
"toBeReturnedNext",
")",
";",
"}"
] | Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
<code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
<p>
<b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
and more readable</b> (especially when stubbing consecutive calls).
<p>
Here are those rare occasions when doReturn() comes handy:
<p>
<ol>
<li>When spying real objects and calling real methods on a spy brings side effects
<pre class="code"><code class="java">
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo", "bar", "qix");
//You have to use doReturn() for stubbing:
doReturn("foo", "bar", "qix").when(spy).get(0);
</code></pre>
</li>
<li>Overriding a previous exception-stubbing:
<pre class="code"><code class="java">
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar", "foo", "qix");
//You have to use doReturn() for stubbing:
doReturn("bar", "foo", "qix").when(mock).foo();
</code></pre>
</li>
</ol>
Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
overridding stubbing is a potential code smell that points out too much stubbing.
<p>
See examples in javadoc for {@link Mockito} class
@param toBeReturned to be returned when the stubbed method is called
@param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
@return stubber - to select a method for stubbing
@since 2.1.0 | [
"Same",
"as",
"{",
"@link",
"#doReturn",
"(",
"Object",
")",
"}",
"but",
"sets",
"consecutive",
"values",
"to",
"be",
"returned",
".",
"Remember",
"to",
"use",
"<code",
">",
"doReturn",
"()",
"<",
"/",
"code",
">",
"in",
"those",
"rare",
"occasions",
"when",
"you",
"cannot",
"use",
"{",
"@link",
"Mockito#when",
"(",
"Object",
")",
"}",
".",
"<p",
">",
"<b",
">",
"Beware",
"that",
"{",
"@link",
"Mockito#when",
"(",
"Object",
")",
"}",
"is",
"always",
"recommended",
"for",
"stubbing",
"because",
"it",
"is",
"argument",
"type",
"-",
"safe",
"and",
"more",
"readable<",
"/",
"b",
">",
"(",
"especially",
"when",
"stubbing",
"consecutive",
"calls",
")",
".",
"<p",
">",
"Here",
"are",
"those",
"rare",
"occasions",
"when",
"doReturn",
"()",
"comes",
"handy",
":",
"<p",
">"
] | train | https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/Mockito.java#L2533-L2537 |
OpenLiberty/open-liberty | dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java | SessionManager.processConfig | public void processConfig(Dictionary<?, ?> props) {
"""
Method called when the properties for the session manager have been
found or udpated.
@param props
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Session manager configuration updated");
}
this.myConfig.updated(props);
String value = (String) props.get("purge.interval");
if (null != value) {
try {
// convert the configuration in seconds to runtime milliseconds
this.purgeInterval = Long.parseLong(value.trim());
} catch (NumberFormatException nfe) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Ignoring incorrect purge interval [" + value + "]", nfe.getMessage());
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: purge interval [" + this.purgeInterval + "]");
}
} | java | public void processConfig(Dictionary<?, ?> props) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Session manager configuration updated");
}
this.myConfig.updated(props);
String value = (String) props.get("purge.interval");
if (null != value) {
try {
// convert the configuration in seconds to runtime milliseconds
this.purgeInterval = Long.parseLong(value.trim());
} catch (NumberFormatException nfe) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Ignoring incorrect purge interval [" + value + "]", nfe.getMessage());
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: purge interval [" + this.purgeInterval + "]");
}
} | [
"public",
"void",
"processConfig",
"(",
"Dictionary",
"<",
"?",
",",
"?",
">",
"props",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEventEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"event",
"(",
"tc",
",",
"\"Session manager configuration updated\"",
")",
";",
"}",
"this",
".",
"myConfig",
".",
"updated",
"(",
"props",
")",
";",
"String",
"value",
"=",
"(",
"String",
")",
"props",
".",
"get",
"(",
"\"purge.interval\"",
")",
";",
"if",
"(",
"null",
"!=",
"value",
")",
"{",
"try",
"{",
"// convert the configuration in seconds to runtime milliseconds",
"this",
".",
"purgeInterval",
"=",
"Long",
".",
"parseLong",
"(",
"value",
".",
"trim",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"nfe",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEventEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"event",
"(",
"tc",
",",
"\"Ignoring incorrect purge interval [\"",
"+",
"value",
"+",
"\"]\"",
",",
"nfe",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEventEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"event",
"(",
"tc",
",",
"\"Config: purge interval [\"",
"+",
"this",
".",
"purgeInterval",
"+",
"\"]\"",
")",
";",
"}",
"}"
] | Method called when the properties for the session manager have been
found or udpated.
@param props | [
"Method",
"called",
"when",
"the",
"properties",
"for",
"the",
"session",
"manager",
"have",
"been",
"found",
"or",
"udpated",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java#L112-L132 |
JadiraOrg/jadira | cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java | UnsafeOperations.copyPrimitiveField | public final void copyPrimitiveField(Object source, Object copy, Field field) {
"""
Copy the value from the given field from the source into the target.
The field specified must contain a primitive
@param source The object to copy from
@param copy The target object
@param field Field to be copied
"""
copyPrimitiveAtOffset(source, copy, field.getType(), getObjectFieldOffset(field));
} | java | public final void copyPrimitiveField(Object source, Object copy, Field field) {
copyPrimitiveAtOffset(source, copy, field.getType(), getObjectFieldOffset(field));
} | [
"public",
"final",
"void",
"copyPrimitiveField",
"(",
"Object",
"source",
",",
"Object",
"copy",
",",
"Field",
"field",
")",
"{",
"copyPrimitiveAtOffset",
"(",
"source",
",",
"copy",
",",
"field",
".",
"getType",
"(",
")",
",",
"getObjectFieldOffset",
"(",
"field",
")",
")",
";",
"}"
] | Copy the value from the given field from the source into the target.
The field specified must contain a primitive
@param source The object to copy from
@param copy The target object
@param field Field to be copied | [
"Copy",
"the",
"value",
"from",
"the",
"given",
"field",
"from",
"the",
"source",
"into",
"the",
"target",
".",
"The",
"field",
"specified",
"must",
"contain",
"a",
"primitive"
] | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L194-L196 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java | NetworkEnvironmentConfiguration.calculateNewNetworkBufferMemory | @VisibleForTesting
public static long calculateNewNetworkBufferMemory(Configuration config, long maxJvmHeapMemory) {
"""
Calculates the amount of memory used for network buffers inside the current JVM instance
based on the available heap or the max heap size and the according configuration parameters.
<p>For containers or when started via scripts, if started with a memory limit and set to use
off-heap memory, the maximum heap size for the JVM is adjusted accordingly and we are able
to extract the intended values from this.
<p>The following configuration parameters are involved:
<ul>
<li>{@link TaskManagerOptions#MANAGED_MEMORY_SIZE},</li>
<li>{@link TaskManagerOptions#MANAGED_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MIN},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MAX}, and</li>
<li>{@link TaskManagerOptions#NETWORK_NUM_BUFFERS} (fallback if the ones above do not exist)</li>
</ul>.
@param config configuration object
@param maxJvmHeapMemory the maximum JVM heap size (in bytes)
@return memory to use for network buffers (in bytes)
"""
// The maximum heap memory has been adjusted as in TaskManagerServices#calculateHeapSizeMB
// and we need to invert these calculations.
final long jvmHeapNoNet;
final MemoryType memoryType = ConfigurationParserUtils.getMemoryType(config);
if (memoryType == MemoryType.HEAP) {
jvmHeapNoNet = maxJvmHeapMemory;
} else if (memoryType == MemoryType.OFF_HEAP) {
long configuredMemory = ConfigurationParserUtils.getManagedMemorySize(config) << 20; // megabytes to bytes
if (configuredMemory > 0) {
// The maximum heap memory has been adjusted according to configuredMemory, i.e.
// maxJvmHeap = jvmHeapNoNet - configuredMemory
jvmHeapNoNet = maxJvmHeapMemory + configuredMemory;
} else {
// The maximum heap memory has been adjusted according to the fraction, i.e.
// maxJvmHeap = jvmHeapNoNet - jvmHeapNoNet * managedFraction = jvmHeapNoNet * (1 - managedFraction)
jvmHeapNoNet = (long) (maxJvmHeapMemory / (1.0 - ConfigurationParserUtils.getManagedMemoryFraction(config)));
}
} else {
throw new RuntimeException("No supported memory type detected.");
}
// finally extract the network buffer memory size again from:
// jvmHeapNoNet = jvmHeap - networkBufBytes
// = jvmHeap - Math.min(networkBufMax, Math.max(networkBufMin, jvmHeap * netFraction)
// jvmHeap = jvmHeapNoNet / (1.0 - networkBufFraction)
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufSize = (long) (jvmHeapNoNet / (1.0 - networkBufFraction) * networkBufFraction);
return calculateNewNetworkBufferMemory(config, networkBufSize, maxJvmHeapMemory);
} | java | @VisibleForTesting
public static long calculateNewNetworkBufferMemory(Configuration config, long maxJvmHeapMemory) {
// The maximum heap memory has been adjusted as in TaskManagerServices#calculateHeapSizeMB
// and we need to invert these calculations.
final long jvmHeapNoNet;
final MemoryType memoryType = ConfigurationParserUtils.getMemoryType(config);
if (memoryType == MemoryType.HEAP) {
jvmHeapNoNet = maxJvmHeapMemory;
} else if (memoryType == MemoryType.OFF_HEAP) {
long configuredMemory = ConfigurationParserUtils.getManagedMemorySize(config) << 20; // megabytes to bytes
if (configuredMemory > 0) {
// The maximum heap memory has been adjusted according to configuredMemory, i.e.
// maxJvmHeap = jvmHeapNoNet - configuredMemory
jvmHeapNoNet = maxJvmHeapMemory + configuredMemory;
} else {
// The maximum heap memory has been adjusted according to the fraction, i.e.
// maxJvmHeap = jvmHeapNoNet - jvmHeapNoNet * managedFraction = jvmHeapNoNet * (1 - managedFraction)
jvmHeapNoNet = (long) (maxJvmHeapMemory / (1.0 - ConfigurationParserUtils.getManagedMemoryFraction(config)));
}
} else {
throw new RuntimeException("No supported memory type detected.");
}
// finally extract the network buffer memory size again from:
// jvmHeapNoNet = jvmHeap - networkBufBytes
// = jvmHeap - Math.min(networkBufMax, Math.max(networkBufMin, jvmHeap * netFraction)
// jvmHeap = jvmHeapNoNet / (1.0 - networkBufFraction)
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufSize = (long) (jvmHeapNoNet / (1.0 - networkBufFraction) * networkBufFraction);
return calculateNewNetworkBufferMemory(config, networkBufSize, maxJvmHeapMemory);
} | [
"@",
"VisibleForTesting",
"public",
"static",
"long",
"calculateNewNetworkBufferMemory",
"(",
"Configuration",
"config",
",",
"long",
"maxJvmHeapMemory",
")",
"{",
"// The maximum heap memory has been adjusted as in TaskManagerServices#calculateHeapSizeMB",
"// and we need to invert these calculations.",
"final",
"long",
"jvmHeapNoNet",
";",
"final",
"MemoryType",
"memoryType",
"=",
"ConfigurationParserUtils",
".",
"getMemoryType",
"(",
"config",
")",
";",
"if",
"(",
"memoryType",
"==",
"MemoryType",
".",
"HEAP",
")",
"{",
"jvmHeapNoNet",
"=",
"maxJvmHeapMemory",
";",
"}",
"else",
"if",
"(",
"memoryType",
"==",
"MemoryType",
".",
"OFF_HEAP",
")",
"{",
"long",
"configuredMemory",
"=",
"ConfigurationParserUtils",
".",
"getManagedMemorySize",
"(",
"config",
")",
"<<",
"20",
";",
"// megabytes to bytes",
"if",
"(",
"configuredMemory",
">",
"0",
")",
"{",
"// The maximum heap memory has been adjusted according to configuredMemory, i.e.",
"// maxJvmHeap = jvmHeapNoNet - configuredMemory",
"jvmHeapNoNet",
"=",
"maxJvmHeapMemory",
"+",
"configuredMemory",
";",
"}",
"else",
"{",
"// The maximum heap memory has been adjusted according to the fraction, i.e.",
"// maxJvmHeap = jvmHeapNoNet - jvmHeapNoNet * managedFraction = jvmHeapNoNet * (1 - managedFraction)",
"jvmHeapNoNet",
"=",
"(",
"long",
")",
"(",
"maxJvmHeapMemory",
"/",
"(",
"1.0",
"-",
"ConfigurationParserUtils",
".",
"getManagedMemoryFraction",
"(",
"config",
")",
")",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"No supported memory type detected.\"",
")",
";",
"}",
"// finally extract the network buffer memory size again from:",
"// jvmHeapNoNet = jvmHeap - networkBufBytes",
"// = jvmHeap - Math.min(networkBufMax, Math.max(networkBufMin, jvmHeap * netFraction)",
"// jvmHeap = jvmHeapNoNet / (1.0 - networkBufFraction)",
"float",
"networkBufFraction",
"=",
"config",
".",
"getFloat",
"(",
"TaskManagerOptions",
".",
"NETWORK_BUFFERS_MEMORY_FRACTION",
")",
";",
"long",
"networkBufSize",
"=",
"(",
"long",
")",
"(",
"jvmHeapNoNet",
"/",
"(",
"1.0",
"-",
"networkBufFraction",
")",
"*",
"networkBufFraction",
")",
";",
"return",
"calculateNewNetworkBufferMemory",
"(",
"config",
",",
"networkBufSize",
",",
"maxJvmHeapMemory",
")",
";",
"}"
] | Calculates the amount of memory used for network buffers inside the current JVM instance
based on the available heap or the max heap size and the according configuration parameters.
<p>For containers or when started via scripts, if started with a memory limit and set to use
off-heap memory, the maximum heap size for the JVM is adjusted accordingly and we are able
to extract the intended values from this.
<p>The following configuration parameters are involved:
<ul>
<li>{@link TaskManagerOptions#MANAGED_MEMORY_SIZE},</li>
<li>{@link TaskManagerOptions#MANAGED_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MIN},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MAX}, and</li>
<li>{@link TaskManagerOptions#NETWORK_NUM_BUFFERS} (fallback if the ones above do not exist)</li>
</ul>.
@param config configuration object
@param maxJvmHeapMemory the maximum JVM heap size (in bytes)
@return memory to use for network buffers (in bytes) | [
"Calculates",
"the",
"amount",
"of",
"memory",
"used",
"for",
"network",
"buffers",
"inside",
"the",
"current",
"JVM",
"instance",
"based",
"on",
"the",
"available",
"heap",
"or",
"the",
"max",
"heap",
"size",
"and",
"the",
"according",
"configuration",
"parameters",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java#L187-L217 |
vipshop/vjtools | vjkit/src/main/java/com/vip/vjtools/vjkit/io/FileUtil.java | FileUtil.copy | public static void copy(@NotNull Path from, @NotNull Path to) throws IOException {
"""
复制文件或目录, not following links.
@param from 如果为null,或者是不存在的文件或目录,抛出异常.
@param to 如果为null,或者from是目录而to是已存在文件,或相反
"""
Validate.notNull(from);
Validate.notNull(to);
if (Files.isDirectory(from)) {
copyDir(from, to);
} else {
copyFile(from, to);
}
} | java | public static void copy(@NotNull Path from, @NotNull Path to) throws IOException {
Validate.notNull(from);
Validate.notNull(to);
if (Files.isDirectory(from)) {
copyDir(from, to);
} else {
copyFile(from, to);
}
} | [
"public",
"static",
"void",
"copy",
"(",
"@",
"NotNull",
"Path",
"from",
",",
"@",
"NotNull",
"Path",
"to",
")",
"throws",
"IOException",
"{",
"Validate",
".",
"notNull",
"(",
"from",
")",
";",
"Validate",
".",
"notNull",
"(",
"to",
")",
";",
"if",
"(",
"Files",
".",
"isDirectory",
"(",
"from",
")",
")",
"{",
"copyDir",
"(",
"from",
",",
"to",
")",
";",
"}",
"else",
"{",
"copyFile",
"(",
"from",
",",
"to",
")",
";",
"}",
"}"
] | 复制文件或目录, not following links.
@param from 如果为null,或者是不存在的文件或目录,抛出异常.
@param to 如果为null,或者from是目录而to是已存在文件,或相反 | [
"复制文件或目录",
"not",
"following",
"links",
"."
] | train | https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjkit/src/main/java/com/vip/vjtools/vjkit/io/FileUtil.java#L220-L229 |
att/AAF | authz/authz-cass/src/main/java/com/att/dao/Loader.java | Loader.readString | public static String readString(DataInputStream is, byte[] _buff) throws IOException {
"""
We use bytes here to set a Maximum
@param is
@param MAX
@return
@throws IOException
"""
int l = is.readInt();
byte[] buff = _buff;
switch(l) {
case -1: return null;
case 0: return "";
default:
// Cover case where there is a large string, without always allocating a large buffer.
if(l>buff.length) {
buff = new byte[l];
}
is.read(buff,0,l);
return new String(buff,0,l);
}
} | java | public static String readString(DataInputStream is, byte[] _buff) throws IOException {
int l = is.readInt();
byte[] buff = _buff;
switch(l) {
case -1: return null;
case 0: return "";
default:
// Cover case where there is a large string, without always allocating a large buffer.
if(l>buff.length) {
buff = new byte[l];
}
is.read(buff,0,l);
return new String(buff,0,l);
}
} | [
"public",
"static",
"String",
"readString",
"(",
"DataInputStream",
"is",
",",
"byte",
"[",
"]",
"_buff",
")",
"throws",
"IOException",
"{",
"int",
"l",
"=",
"is",
".",
"readInt",
"(",
")",
";",
"byte",
"[",
"]",
"buff",
"=",
"_buff",
";",
"switch",
"(",
"l",
")",
"{",
"case",
"-",
"1",
":",
"return",
"null",
";",
"case",
"0",
":",
"return",
"\"\"",
";",
"default",
":",
"// Cover case where there is a large string, without always allocating a large buffer.",
"if",
"(",
"l",
">",
"buff",
".",
"length",
")",
"{",
"buff",
"=",
"new",
"byte",
"[",
"l",
"]",
";",
"}",
"is",
".",
"read",
"(",
"buff",
",",
"0",
",",
"l",
")",
";",
"return",
"new",
"String",
"(",
"buff",
",",
"0",
",",
"l",
")",
";",
"}",
"}"
] | We use bytes here to set a Maximum
@param is
@param MAX
@return
@throws IOException | [
"We",
"use",
"bytes",
"here",
"to",
"set",
"a",
"Maximum"
] | train | https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/authz/authz-cass/src/main/java/com/att/dao/Loader.java#L84-L98 |
tvesalainen/util | util/src/main/java/org/vesalainen/bean/BeanHelper.java | BeanHelper.addList | public static final <T> void addList(Object bean, String property, T value) {
"""
Adds pattern item to end of list
@param <T>
@param bean
@param property
@param value
"""
addList(bean, property, null, (Class<T> c, String h)->{return value;});
} | java | public static final <T> void addList(Object bean, String property, T value)
{
addList(bean, property, null, (Class<T> c, String h)->{return value;});
} | [
"public",
"static",
"final",
"<",
"T",
">",
"void",
"addList",
"(",
"Object",
"bean",
",",
"String",
"property",
",",
"T",
"value",
")",
"{",
"addList",
"(",
"bean",
",",
"property",
",",
"null",
",",
"(",
"Class",
"<",
"T",
">",
"c",
",",
"String",
"h",
")",
"->",
"{",
"return",
"value",
";",
"}",
")",
";",
"}"
] | Adds pattern item to end of list
@param <T>
@param bean
@param property
@param value | [
"Adds",
"pattern",
"item",
"to",
"end",
"of",
"list"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/bean/BeanHelper.java#L582-L585 |
mangstadt/biweekly | src/main/java/biweekly/util/XmlUtils.java | XmlUtils.toWriter | public static void toWriter(Node node, Writer writer, Map<String, String> outputProperties) throws TransformerException {
"""
Writes an XML node to a writer.
@param node the XML node
@param writer the writer
@param outputProperties the output properties
@throws TransformerException if there's a problem writing to the writer
"""
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
for (Map.Entry<String, String> property : outputProperties.entrySet()) {
try {
transformer.setOutputProperty(property.getKey(), property.getValue());
} catch (IllegalArgumentException e) {
//ignore invalid output properties
}
}
DOMSource source = new DOMSource(node);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
//no complex configurations
} catch (TransformerFactoryConfigurationError e) {
//no complex configurations
}
} | java | public static void toWriter(Node node, Writer writer, Map<String, String> outputProperties) throws TransformerException {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
for (Map.Entry<String, String> property : outputProperties.entrySet()) {
try {
transformer.setOutputProperty(property.getKey(), property.getValue());
} catch (IllegalArgumentException e) {
//ignore invalid output properties
}
}
DOMSource source = new DOMSource(node);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
//no complex configurations
} catch (TransformerFactoryConfigurationError e) {
//no complex configurations
}
} | [
"public",
"static",
"void",
"toWriter",
"(",
"Node",
"node",
",",
"Writer",
"writer",
",",
"Map",
"<",
"String",
",",
"String",
">",
"outputProperties",
")",
"throws",
"TransformerException",
"{",
"try",
"{",
"Transformer",
"transformer",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
".",
"newTransformer",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"property",
":",
"outputProperties",
".",
"entrySet",
"(",
")",
")",
"{",
"try",
"{",
"transformer",
".",
"setOutputProperty",
"(",
"property",
".",
"getKey",
"(",
")",
",",
"property",
".",
"getValue",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"//ignore invalid output properties",
"}",
"}",
"DOMSource",
"source",
"=",
"new",
"DOMSource",
"(",
"node",
")",
";",
"StreamResult",
"result",
"=",
"new",
"StreamResult",
"(",
"writer",
")",
";",
"transformer",
".",
"transform",
"(",
"source",
",",
"result",
")",
";",
"}",
"catch",
"(",
"TransformerConfigurationException",
"e",
")",
"{",
"//no complex configurations",
"}",
"catch",
"(",
"TransformerFactoryConfigurationError",
"e",
")",
"{",
"//no complex configurations",
"}",
"}"
] | Writes an XML node to a writer.
@param node the XML node
@param writer the writer
@param outputProperties the output properties
@throws TransformerException if there's a problem writing to the writer | [
"Writes",
"an",
"XML",
"node",
"to",
"a",
"writer",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/util/XmlUtils.java#L284-L303 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/MediaApi.java | MediaApi.mediaSwicthToBargeIn | public ApiSuccessResponse mediaSwicthToBargeIn(String mediatype, String id, MediaSwicthToCoachData mediaSwicthToCoachData) throws ApiException {
"""
Switch to barge-in
Switch to the barge-in monitoring mode for the specified chat. Both the agent and the customer can see the supervisor's messages.
@param mediatype The media channel. (required)
@param id The ID of the chat interaction. (required)
@param mediaSwicthToCoachData Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<ApiSuccessResponse> resp = mediaSwicthToBargeInWithHttpInfo(mediatype, id, mediaSwicthToCoachData);
return resp.getData();
} | java | public ApiSuccessResponse mediaSwicthToBargeIn(String mediatype, String id, MediaSwicthToCoachData mediaSwicthToCoachData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = mediaSwicthToBargeInWithHttpInfo(mediatype, id, mediaSwicthToCoachData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"mediaSwicthToBargeIn",
"(",
"String",
"mediatype",
",",
"String",
"id",
",",
"MediaSwicthToCoachData",
"mediaSwicthToCoachData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"mediaSwicthToBargeInWithHttpInfo",
"(",
"mediatype",
",",
"id",
",",
"mediaSwicthToCoachData",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Switch to barge-in
Switch to the barge-in monitoring mode for the specified chat. Both the agent and the customer can see the supervisor's messages.
@param mediatype The media channel. (required)
@param id The ID of the chat interaction. (required)
@param mediaSwicthToCoachData Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Switch",
"to",
"barge",
"-",
"in",
"Switch",
"to",
"the",
"barge",
"-",
"in",
"monitoring",
"mode",
"for",
"the",
"specified",
"chat",
".",
"Both",
"the",
"agent",
"and",
"the",
"customer",
"can",
"see",
"the",
"supervisor'",
";",
"s",
"messages",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L2448-L2451 |
msteiger/jxmapviewer2 | jxmapviewer2/src/main/java/org/jxmapviewer/viewer/TileFactoryInfo.java | TileFactoryInfo.getTileUrl | public String getTileUrl(int x, int y, int zoom) {
"""
Returns the tile url for the specified tile at the specified zoom level. By default it will generate a tile url
using the base url and parameters specified in the constructor. Thus if <PRE><CODE>baseURl =
http://www.myserver.com/maps?version=0.1 xparam = x yparam = y zparam = z tilepoint = [1,2] zoom level = 3
</CODE> </PRE> then the resulting url would be:
<pre><code>http://www.myserver.com/maps?version=0.1&x=1&y=2&z=3</code></pre> Note that the URL can be
a <CODE>file:</CODE> url.
@param zoom the zoom level
@param x the x value, measured from left to right
@param y the y value, measured from top to bottom
@return a valid url to load the tile
"""
// System.out.println("getting tile at zoom: " + zoom);
// System.out.println("map width at zoom = " + getMapWidthInTilesAtZoom(zoom));
String ypart = "&" + yparam + "=" + y;
// System.out.println("ypart = " + ypart);
if (!yt2b)
{
int tilemax = getMapWidthInTilesAtZoom(zoom);
// int y = tilePoint.getY();
ypart = "&" + yparam + "=" + (tilemax / 2 - y - 1);
}
// System.out.println("new ypart = " + ypart);
String url = baseURL + "&" + xparam + "=" + x + ypart +
// "&" + yparam + "=" + tilePoint.getY() +
"&" + zparam + "=" + zoom;
return url;
} | java | public String getTileUrl(int x, int y, int zoom)
{
// System.out.println("getting tile at zoom: " + zoom);
// System.out.println("map width at zoom = " + getMapWidthInTilesAtZoom(zoom));
String ypart = "&" + yparam + "=" + y;
// System.out.println("ypart = " + ypart);
if (!yt2b)
{
int tilemax = getMapWidthInTilesAtZoom(zoom);
// int y = tilePoint.getY();
ypart = "&" + yparam + "=" + (tilemax / 2 - y - 1);
}
// System.out.println("new ypart = " + ypart);
String url = baseURL + "&" + xparam + "=" + x + ypart +
// "&" + yparam + "=" + tilePoint.getY() +
"&" + zparam + "=" + zoom;
return url;
} | [
"public",
"String",
"getTileUrl",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"zoom",
")",
"{",
"// System.out.println(\"getting tile at zoom: \" + zoom);",
"// System.out.println(\"map width at zoom = \" + getMapWidthInTilesAtZoom(zoom));",
"String",
"ypart",
"=",
"\"&\"",
"+",
"yparam",
"+",
"\"=\"",
"+",
"y",
";",
"// System.out.println(\"ypart = \" + ypart);",
"if",
"(",
"!",
"yt2b",
")",
"{",
"int",
"tilemax",
"=",
"getMapWidthInTilesAtZoom",
"(",
"zoom",
")",
";",
"// int y = tilePoint.getY();",
"ypart",
"=",
"\"&\"",
"+",
"yparam",
"+",
"\"=\"",
"+",
"(",
"tilemax",
"/",
"2",
"-",
"y",
"-",
"1",
")",
";",
"}",
"// System.out.println(\"new ypart = \" + ypart);",
"String",
"url",
"=",
"baseURL",
"+",
"\"&\"",
"+",
"xparam",
"+",
"\"=\"",
"+",
"x",
"+",
"ypart",
"+",
"// \"&\" + yparam + \"=\" + tilePoint.getY() +",
"\"&\"",
"+",
"zparam",
"+",
"\"=\"",
"+",
"zoom",
";",
"return",
"url",
";",
"}"
] | Returns the tile url for the specified tile at the specified zoom level. By default it will generate a tile url
using the base url and parameters specified in the constructor. Thus if <PRE><CODE>baseURl =
http://www.myserver.com/maps?version=0.1 xparam = x yparam = y zparam = z tilepoint = [1,2] zoom level = 3
</CODE> </PRE> then the resulting url would be:
<pre><code>http://www.myserver.com/maps?version=0.1&x=1&y=2&z=3</code></pre> Note that the URL can be
a <CODE>file:</CODE> url.
@param zoom the zoom level
@param x the x value, measured from left to right
@param y the y value, measured from top to bottom
@return a valid url to load the tile | [
"Returns",
"the",
"tile",
"url",
"for",
"the",
"specified",
"tile",
"at",
"the",
"specified",
"zoom",
"level",
".",
"By",
"default",
"it",
"will",
"generate",
"a",
"tile",
"url",
"using",
"the",
"base",
"url",
"and",
"parameters",
"specified",
"in",
"the",
"constructor",
".",
"Thus",
"if",
"<PRE",
">",
"<CODE",
">",
"baseURl",
"=",
"http",
":",
"//",
"www",
".",
"myserver",
".",
"com",
"/",
"maps?version",
"=",
"0",
".",
"1",
"xparam",
"=",
"x",
"yparam",
"=",
"y",
"zparam",
"=",
"z",
"tilepoint",
"=",
"[",
"1",
"2",
"]",
"zoom",
"level",
"=",
"3",
"<",
"/",
"CODE",
">",
"<",
"/",
"PRE",
">",
"then",
"the",
"resulting",
"url",
"would",
"be",
":",
"<pre",
">",
"<code",
">",
"http",
":",
"//",
"www",
".",
"myserver",
".",
"com",
"/",
"maps?version",
"=",
"0",
".",
"1&",
";",
"x",
"=",
"1&",
";",
"y",
"=",
"2&",
";",
"z",
"=",
"3<",
"/",
"code",
">",
"<",
"/",
"pre",
">",
"Note",
"that",
"the",
"URL",
"can",
"be",
"a",
"<CODE",
">",
"file",
":",
"<",
"/",
"CODE",
">",
"url",
"."
] | train | https://github.com/msteiger/jxmapviewer2/blob/82639273b0aac983b6026fb90aa925c0cf596410/jxmapviewer2/src/main/java/org/jxmapviewer/viewer/TileFactoryInfo.java#L211-L229 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/shipping/admin/profiles/ShippingInclusionRuleUrl.java | ShippingInclusionRuleUrl.getShippingInclusionRulesUrl | public static MozuUrl getShippingInclusionRulesUrl(String profilecode, String responseFields) {
"""
Get Resource Url for GetShippingInclusionRules
@param profilecode The unique, user-defined code of the profile with which the shipping inclusion rule is associated.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions?responseFields={responseFields}");
formatter.formatUrl("profilecode", profilecode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getShippingInclusionRulesUrl(String profilecode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions?responseFields={responseFields}");
formatter.formatUrl("profilecode", profilecode);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getShippingInclusionRulesUrl",
"(",
"String",
"profilecode",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions?responseFields={responseFields}\"",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"profilecode\"",
",",
"profilecode",
")",
";",
"formatter",
".",
"formatUrl",
"(",
"\"responseFields\"",
",",
"responseFields",
")",
";",
"return",
"new",
"MozuUrl",
"(",
"formatter",
".",
"getResourceUrl",
"(",
")",
",",
"MozuUrl",
".",
"UrlLocation",
".",
"TENANT_POD",
")",
";",
"}"
] | Get Resource Url for GetShippingInclusionRules
@param profilecode The unique, user-defined code of the profile with which the shipping inclusion rule is associated.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetShippingInclusionRules"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/shipping/admin/profiles/ShippingInclusionRuleUrl.java#L38-L44 |
jaxio/javaee-lab | javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/ByPatternUtil.java | ByPatternUtil.byPattern | @SuppressWarnings("unchecked")
public <T> Predicate byPattern(Root<T> root, CriteriaBuilder builder, SearchParameters sp, Class<T> type) {
"""
/*
Lookup entities having at least one String attribute matching the passed sp's pattern
"""
if (!sp.hasSearchPattern()) {
return null;
}
List<Predicate> predicates = newArrayList();
EntityType<T> entity = em.getMetamodel().entity(type);
String pattern = sp.getSearchPattern();
for (SingularAttribute<? super T, ?> attr : entity.getSingularAttributes()) {
if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
continue;
}
if (attr.getJavaType() == String.class) {
predicates.add(jpaUtil.stringPredicate((Expression<String>) root.get(jpaUtil.attribute(entity, attr)), pattern, sp, builder));
}
}
return jpaUtil.orPredicate(builder, predicates);
} | java | @SuppressWarnings("unchecked")
public <T> Predicate byPattern(Root<T> root, CriteriaBuilder builder, SearchParameters sp, Class<T> type) {
if (!sp.hasSearchPattern()) {
return null;
}
List<Predicate> predicates = newArrayList();
EntityType<T> entity = em.getMetamodel().entity(type);
String pattern = sp.getSearchPattern();
for (SingularAttribute<? super T, ?> attr : entity.getSingularAttributes()) {
if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
continue;
}
if (attr.getJavaType() == String.class) {
predicates.add(jpaUtil.stringPredicate((Expression<String>) root.get(jpaUtil.attribute(entity, attr)), pattern, sp, builder));
}
}
return jpaUtil.orPredicate(builder, predicates);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"Predicate",
"byPattern",
"(",
"Root",
"<",
"T",
">",
"root",
",",
"CriteriaBuilder",
"builder",
",",
"SearchParameters",
"sp",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"if",
"(",
"!",
"sp",
".",
"hasSearchPattern",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"List",
"<",
"Predicate",
">",
"predicates",
"=",
"newArrayList",
"(",
")",
";",
"EntityType",
"<",
"T",
">",
"entity",
"=",
"em",
".",
"getMetamodel",
"(",
")",
".",
"entity",
"(",
"type",
")",
";",
"String",
"pattern",
"=",
"sp",
".",
"getSearchPattern",
"(",
")",
";",
"for",
"(",
"SingularAttribute",
"<",
"?",
"super",
"T",
",",
"?",
">",
"attr",
":",
"entity",
".",
"getSingularAttributes",
"(",
")",
")",
"{",
"if",
"(",
"attr",
".",
"getPersistentAttributeType",
"(",
")",
"==",
"MANY_TO_ONE",
"||",
"attr",
".",
"getPersistentAttributeType",
"(",
")",
"==",
"ONE_TO_ONE",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"attr",
".",
"getJavaType",
"(",
")",
"==",
"String",
".",
"class",
")",
"{",
"predicates",
".",
"add",
"(",
"jpaUtil",
".",
"stringPredicate",
"(",
"(",
"Expression",
"<",
"String",
">",
")",
"root",
".",
"get",
"(",
"jpaUtil",
".",
"attribute",
"(",
"entity",
",",
"attr",
")",
")",
",",
"pattern",
",",
"sp",
",",
"builder",
")",
")",
";",
"}",
"}",
"return",
"jpaUtil",
".",
"orPredicate",
"(",
"builder",
",",
"predicates",
")",
";",
"}"
] | /*
Lookup entities having at least one String attribute matching the passed sp's pattern | [
"/",
"*",
"Lookup",
"entities",
"having",
"at",
"least",
"one",
"String",
"attribute",
"matching",
"the",
"passed",
"sp",
"s",
"pattern"
] | train | https://github.com/jaxio/javaee-lab/blob/61238b967952446d81cc68424a4e809093a77fcf/javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/ByPatternUtil.java#L45-L66 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/util/PropertyUtils.java | PropertyUtils.invokeMethod | private static Object invokeMethod(Method method, Object bean, Object[] values)
throws IllegalAccessException, InvocationTargetException {
"""
This utility method just catches and wraps IllegalArgumentException.
@param method
the method to call
@param bean
the bean
@param values
the values
@return the returned value of the method
@throws IllegalAccessException
if an exception occurs
@throws InvocationTargetException
if an exception occurs
"""
try {
return method.invoke(bean, values);
} catch (IllegalArgumentException e) {
LOGGER.error("Method invocation failed.", e);
throw new IllegalArgumentException("Cannot invoke " + method.getDeclaringClass().getName() + "."
+ method.getName() + " - " + e.getMessage());
}
} | java | private static Object invokeMethod(Method method, Object bean, Object[] values)
throws IllegalAccessException, InvocationTargetException {
try {
return method.invoke(bean, values);
} catch (IllegalArgumentException e) {
LOGGER.error("Method invocation failed.", e);
throw new IllegalArgumentException("Cannot invoke " + method.getDeclaringClass().getName() + "."
+ method.getName() + " - " + e.getMessage());
}
} | [
"private",
"static",
"Object",
"invokeMethod",
"(",
"Method",
"method",
",",
"Object",
"bean",
",",
"Object",
"[",
"]",
"values",
")",
"throws",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"try",
"{",
"return",
"method",
".",
"invoke",
"(",
"bean",
",",
"values",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Method invocation failed.\"",
",",
"e",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot invoke \"",
"+",
"method",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\".\"",
"+",
"method",
".",
"getName",
"(",
")",
"+",
"\" - \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | This utility method just catches and wraps IllegalArgumentException.
@param method
the method to call
@param bean
the bean
@param values
the values
@return the returned value of the method
@throws IllegalAccessException
if an exception occurs
@throws InvocationTargetException
if an exception occurs | [
"This",
"utility",
"method",
"just",
"catches",
"and",
"wraps",
"IllegalArgumentException",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/util/PropertyUtils.java#L234-L247 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/dynamic/output/OutputRegistry.java | OutputRegistry.getOutputComponentType | static OutputType getOutputComponentType(Class<? extends CommandOutput> commandOutputClass) {
"""
Retrieve {@link OutputType} for a {@link CommandOutput} type.
@param commandOutputClass
@return
"""
ClassTypeInformation<? extends CommandOutput> classTypeInformation = ClassTypeInformation.from(commandOutputClass);
TypeInformation<?> superTypeInformation = classTypeInformation.getSuperTypeInformation(CommandOutput.class);
if (superTypeInformation == null) {
return null;
}
List<TypeInformation<?>> typeArguments = superTypeInformation.getTypeArguments();
return new OutputType(commandOutputClass, typeArguments.get(2), false) {
@Override
public ResolvableType withCodec(RedisCodec<?, ?> codec) {
TypeInformation<?> typeInformation = ClassTypeInformation.from(codec.getClass());
ResolvableType resolvableType = ResolvableType.forType(commandOutputClass, new CodecVariableTypeResolver(
typeInformation));
while (!resolvableType.getRawClass().equals(CommandOutput.class)) {
resolvableType = resolvableType.getSuperType();
}
return resolvableType.getGeneric(2);
}
};
} | java | static OutputType getOutputComponentType(Class<? extends CommandOutput> commandOutputClass) {
ClassTypeInformation<? extends CommandOutput> classTypeInformation = ClassTypeInformation.from(commandOutputClass);
TypeInformation<?> superTypeInformation = classTypeInformation.getSuperTypeInformation(CommandOutput.class);
if (superTypeInformation == null) {
return null;
}
List<TypeInformation<?>> typeArguments = superTypeInformation.getTypeArguments();
return new OutputType(commandOutputClass, typeArguments.get(2), false) {
@Override
public ResolvableType withCodec(RedisCodec<?, ?> codec) {
TypeInformation<?> typeInformation = ClassTypeInformation.from(codec.getClass());
ResolvableType resolvableType = ResolvableType.forType(commandOutputClass, new CodecVariableTypeResolver(
typeInformation));
while (!resolvableType.getRawClass().equals(CommandOutput.class)) {
resolvableType = resolvableType.getSuperType();
}
return resolvableType.getGeneric(2);
}
};
} | [
"static",
"OutputType",
"getOutputComponentType",
"(",
"Class",
"<",
"?",
"extends",
"CommandOutput",
">",
"commandOutputClass",
")",
"{",
"ClassTypeInformation",
"<",
"?",
"extends",
"CommandOutput",
">",
"classTypeInformation",
"=",
"ClassTypeInformation",
".",
"from",
"(",
"commandOutputClass",
")",
";",
"TypeInformation",
"<",
"?",
">",
"superTypeInformation",
"=",
"classTypeInformation",
".",
"getSuperTypeInformation",
"(",
"CommandOutput",
".",
"class",
")",
";",
"if",
"(",
"superTypeInformation",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"List",
"<",
"TypeInformation",
"<",
"?",
">",
">",
"typeArguments",
"=",
"superTypeInformation",
".",
"getTypeArguments",
"(",
")",
";",
"return",
"new",
"OutputType",
"(",
"commandOutputClass",
",",
"typeArguments",
".",
"get",
"(",
"2",
")",
",",
"false",
")",
"{",
"@",
"Override",
"public",
"ResolvableType",
"withCodec",
"(",
"RedisCodec",
"<",
"?",
",",
"?",
">",
"codec",
")",
"{",
"TypeInformation",
"<",
"?",
">",
"typeInformation",
"=",
"ClassTypeInformation",
".",
"from",
"(",
"codec",
".",
"getClass",
"(",
")",
")",
";",
"ResolvableType",
"resolvableType",
"=",
"ResolvableType",
".",
"forType",
"(",
"commandOutputClass",
",",
"new",
"CodecVariableTypeResolver",
"(",
"typeInformation",
")",
")",
";",
"while",
"(",
"!",
"resolvableType",
".",
"getRawClass",
"(",
")",
".",
"equals",
"(",
"CommandOutput",
".",
"class",
")",
")",
"{",
"resolvableType",
"=",
"resolvableType",
".",
"getSuperType",
"(",
")",
";",
"}",
"return",
"resolvableType",
".",
"getGeneric",
"(",
"2",
")",
";",
"}",
"}",
";",
"}"
] | Retrieve {@link OutputType} for a {@link CommandOutput} type.
@param commandOutputClass
@return | [
"Retrieve",
"{",
"@link",
"OutputType",
"}",
"for",
"a",
"{",
"@link",
"CommandOutput",
"}",
"type",
"."
] | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/output/OutputRegistry.java#L199-L227 |
aws/aws-sdk-java | aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/emitters/CodeWriter.java | CodeWriter.flush | @Override
public void flush() {
"""
This method is expected to be called only once during the code generation process after the
template processing is done.
"""
PrintWriter out = null;
try {
try {
out = new PrintWriter(Utils.createFile(dir, file), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
String contents = getBuffer().toString();
out.write(processor.apply(contents));
} finally {
closeQuietly(out);
}
} | java | @Override
public void flush() {
PrintWriter out = null;
try {
try {
out = new PrintWriter(Utils.createFile(dir, file), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
String contents = getBuffer().toString();
out.write(processor.apply(contents));
} finally {
closeQuietly(out);
}
} | [
"@",
"Override",
"public",
"void",
"flush",
"(",
")",
"{",
"PrintWriter",
"out",
"=",
"null",
";",
"try",
"{",
"try",
"{",
"out",
"=",
"new",
"PrintWriter",
"(",
"Utils",
".",
"createFile",
"(",
"dir",
",",
"file",
")",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"String",
"contents",
"=",
"getBuffer",
"(",
")",
".",
"toString",
"(",
")",
";",
"out",
".",
"write",
"(",
"processor",
".",
"apply",
"(",
"contents",
")",
")",
";",
"}",
"finally",
"{",
"closeQuietly",
"(",
"out",
")",
";",
"}",
"}"
] | This method is expected to be called only once during the code generation process after the
template processing is done. | [
"This",
"method",
"is",
"expected",
"to",
"be",
"called",
"only",
"once",
"during",
"the",
"code",
"generation",
"process",
"after",
"the",
"template",
"processing",
"is",
"done",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/emitters/CodeWriter.java#L87-L102 |
landawn/AbacusUtil | src/com/landawn/abacus/util/StringUtil.java | StringUtil.removeStartIgnoreCase | public static String removeStartIgnoreCase(final String str, final String removeStr) {
"""
<p>
Case insensitive removal of a substring if it is at the beginning of a
source string, otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeStartIgnoreCase(null, *) = null
N.removeStartIgnoreCase("", *) = ""
N.removeStartIgnoreCase(*, null) = *
N.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
N.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
N.removeStartIgnoreCase("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for (case insensitive) and remove, may be
null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.4
"""
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (startsWithIgnoreCase(str, removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | java | public static String removeStartIgnoreCase(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (startsWithIgnoreCase(str, removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | [
"public",
"static",
"String",
"removeStartIgnoreCase",
"(",
"final",
"String",
"str",
",",
"final",
"String",
"removeStr",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"str",
")",
"||",
"N",
".",
"isNullOrEmpty",
"(",
"removeStr",
")",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"startsWithIgnoreCase",
"(",
"str",
",",
"removeStr",
")",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"removeStr",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"str",
";",
"}"
] | <p>
Case insensitive removal of a substring if it is at the beginning of a
source string, otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeStartIgnoreCase(null, *) = null
N.removeStartIgnoreCase("", *) = ""
N.removeStartIgnoreCase(*, null) = *
N.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
N.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
N.removeStartIgnoreCase("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for (case insensitive) and remove, may be
null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.4 | [
"<p",
">",
"Case",
"insensitive",
"removal",
"of",
"a",
"substring",
"if",
"it",
"is",
"at",
"the",
"beginning",
"of",
"a",
"source",
"string",
"otherwise",
"returns",
"the",
"source",
"string",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1191-L1201 |
tootedom/related | app/domain/src/main/java/org/greencheek/related/api/RelatedItemAdditionalProperties.java | RelatedItemAdditionalProperties.convertToStringArray | public String[][] convertToStringArray() {
"""
Returns a two dimensional array that is like that of a map:
[ key ],[ value ]
[ key ],[ value ]
[ key ],[ value ]
@return
"""
int numberOfProps = numberOfProperties;
String[][] props = new String[numberOfProps][2];
while(numberOfProps--!=0) {
RelatedItemAdditionalProperty prop = additionalProperties[numberOfProps];
props[numberOfProps][0] = new String(prop.name,0,prop.nameLength);
props[numberOfProps][1] = new String(prop.value,0,prop.valueLength);
}
return props;
} | java | public String[][] convertToStringArray() {
int numberOfProps = numberOfProperties;
String[][] props = new String[numberOfProps][2];
while(numberOfProps--!=0) {
RelatedItemAdditionalProperty prop = additionalProperties[numberOfProps];
props[numberOfProps][0] = new String(prop.name,0,prop.nameLength);
props[numberOfProps][1] = new String(prop.value,0,prop.valueLength);
}
return props;
} | [
"public",
"String",
"[",
"]",
"[",
"]",
"convertToStringArray",
"(",
")",
"{",
"int",
"numberOfProps",
"=",
"numberOfProperties",
";",
"String",
"[",
"]",
"[",
"]",
"props",
"=",
"new",
"String",
"[",
"numberOfProps",
"]",
"[",
"2",
"]",
";",
"while",
"(",
"numberOfProps",
"--",
"!=",
"0",
")",
"{",
"RelatedItemAdditionalProperty",
"prop",
"=",
"additionalProperties",
"[",
"numberOfProps",
"]",
";",
"props",
"[",
"numberOfProps",
"]",
"[",
"0",
"]",
"=",
"new",
"String",
"(",
"prop",
".",
"name",
",",
"0",
",",
"prop",
".",
"nameLength",
")",
";",
"props",
"[",
"numberOfProps",
"]",
"[",
"1",
"]",
"=",
"new",
"String",
"(",
"prop",
".",
"value",
",",
"0",
",",
"prop",
".",
"valueLength",
")",
";",
"}",
"return",
"props",
";",
"}"
] | Returns a two dimensional array that is like that of a map:
[ key ],[ value ]
[ key ],[ value ]
[ key ],[ value ]
@return | [
"Returns",
"a",
"two",
"dimensional",
"array",
"that",
"is",
"like",
"that",
"of",
"a",
"map",
":",
"[",
"key",
"]",
"[",
"value",
"]",
"[",
"key",
"]",
"[",
"value",
"]",
"[",
"key",
"]",
"[",
"value",
"]"
] | train | https://github.com/tootedom/related/blob/3782dd5a839bbcdc15661d598e8b895aae8aabb7/app/domain/src/main/java/org/greencheek/related/api/RelatedItemAdditionalProperties.java#L183-L192 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java | JobsInner.getAsync | public Observable<JobInner> getAsync(String resourceGroupName, String automationAccountName, UUID jobId) {
"""
Retrieve the job identified by job id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param jobId The job id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the JobInner object
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).map(new Func1<ServiceResponse<JobInner>, JobInner>() {
@Override
public JobInner call(ServiceResponse<JobInner> response) {
return response.body();
}
});
} | java | public Observable<JobInner> getAsync(String resourceGroupName, String automationAccountName, UUID jobId) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).map(new Func1<ServiceResponse<JobInner>, JobInner>() {
@Override
public JobInner call(ServiceResponse<JobInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"JobInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"UUID",
"jobId",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"jobId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"JobInner",
">",
",",
"JobInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"JobInner",
"call",
"(",
"ServiceResponse",
"<",
"JobInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Retrieve the job identified by job id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param jobId The job id.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the JobInner object | [
"Retrieve",
"the",
"job",
"identified",
"by",
"job",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java#L508-L515 |
jenkinsci/jenkins | core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java | WindowsInstallerLink.copy | private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name) throws ServletException, IOException {
"""
Copies a single resource into the target folder, by the given name, and handle errors gracefully.
"""
try {
FileUtils.copyURLToFile(src,new File(dir, name));
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to copy "+name,e);
sendError("Failed to copy "+name+": "+e.getMessage(),req,rsp);
throw new AbortException();
}
} | java | private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name) throws ServletException, IOException {
try {
FileUtils.copyURLToFile(src,new File(dir, name));
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to copy "+name,e);
sendError("Failed to copy "+name+": "+e.getMessage(),req,rsp);
throw new AbortException();
}
} | [
"private",
"void",
"copy",
"(",
"StaplerRequest",
"req",
",",
"StaplerResponse",
"rsp",
",",
"File",
"dir",
",",
"URL",
"src",
",",
"String",
"name",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"try",
"{",
"FileUtils",
".",
"copyURLToFile",
"(",
"src",
",",
"new",
"File",
"(",
"dir",
",",
"name",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to copy \"",
"+",
"name",
",",
"e",
")",
";",
"sendError",
"(",
"\"Failed to copy \"",
"+",
"name",
"+",
"\": \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"req",
",",
"rsp",
")",
";",
"throw",
"new",
"AbortException",
"(",
")",
";",
"}",
"}"
] | Copies a single resource into the target folder, by the given name, and handle errors gracefully. | [
"Copies",
"a",
"single",
"resource",
"into",
"the",
"target",
"folder",
"by",
"the",
"given",
"name",
"and",
"handle",
"errors",
"gracefully",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java#L164-L172 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_virtualMac_macAddress_virtualAddress_ipAddress_DELETE | public OvhTask serviceName_virtualMac_macAddress_virtualAddress_ipAddress_DELETE(String serviceName, String macAddress, String ipAddress) throws IOException {
"""
Remove this ip from virtual mac , if you remove the last linked Ip, virtualmac will be deleted
REST: DELETE /dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}
@param serviceName [required] The internal name of your dedicated server
@param macAddress [required] Virtual MAC address in 00:00:00:00:00:00 format
@param ipAddress [required] IP address
"""
String qPath = "/dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}";
StringBuilder sb = path(qPath, serviceName, macAddress, ipAddress);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_virtualMac_macAddress_virtualAddress_ipAddress_DELETE(String serviceName, String macAddress, String ipAddress) throws IOException {
String qPath = "/dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}";
StringBuilder sb = path(qPath, serviceName, macAddress, ipAddress);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_virtualMac_macAddress_virtualAddress_ipAddress_DELETE",
"(",
"String",
"serviceName",
",",
"String",
"macAddress",
",",
"String",
"ipAddress",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"macAddress",
",",
"ipAddress",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"DELETE\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhTask",
".",
"class",
")",
";",
"}"
] | Remove this ip from virtual mac , if you remove the last linked Ip, virtualmac will be deleted
REST: DELETE /dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}
@param serviceName [required] The internal name of your dedicated server
@param macAddress [required] Virtual MAC address in 00:00:00:00:00:00 format
@param ipAddress [required] IP address | [
"Remove",
"this",
"ip",
"from",
"virtual",
"mac",
"if",
"you",
"remove",
"the",
"last",
"linked",
"Ip",
"virtualmac",
"will",
"be",
"deleted"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L589-L594 |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/DeltaPlacement.java | DeltaPlacement.createTableDDL | private TableDDL createTableDDL(String tableName) {
"""
Both placement tables -- delta, and delta history -- follow the same DDL.
"""
TableMetadata tableMetadata = _keyspace.getKeyspaceMetadata().getTable(tableName);
String rowKeyColumnName = tableMetadata.getPrimaryKey().get(0).getName();
String timeSeriesColumnName = tableMetadata.getPrimaryKey().get(1).getName();
String valueColumnName = tableMetadata.getColumns().get(2).getName();
return new TableDDL(tableMetadata, rowKeyColumnName, timeSeriesColumnName, valueColumnName);
} | java | private TableDDL createTableDDL(String tableName) {
TableMetadata tableMetadata = _keyspace.getKeyspaceMetadata().getTable(tableName);
String rowKeyColumnName = tableMetadata.getPrimaryKey().get(0).getName();
String timeSeriesColumnName = tableMetadata.getPrimaryKey().get(1).getName();
String valueColumnName = tableMetadata.getColumns().get(2).getName();
return new TableDDL(tableMetadata, rowKeyColumnName, timeSeriesColumnName, valueColumnName);
} | [
"private",
"TableDDL",
"createTableDDL",
"(",
"String",
"tableName",
")",
"{",
"TableMetadata",
"tableMetadata",
"=",
"_keyspace",
".",
"getKeyspaceMetadata",
"(",
")",
".",
"getTable",
"(",
"tableName",
")",
";",
"String",
"rowKeyColumnName",
"=",
"tableMetadata",
".",
"getPrimaryKey",
"(",
")",
".",
"get",
"(",
"0",
")",
".",
"getName",
"(",
")",
";",
"String",
"timeSeriesColumnName",
"=",
"tableMetadata",
".",
"getPrimaryKey",
"(",
")",
".",
"get",
"(",
"1",
")",
".",
"getName",
"(",
")",
";",
"String",
"valueColumnName",
"=",
"tableMetadata",
".",
"getColumns",
"(",
")",
".",
"get",
"(",
"2",
")",
".",
"getName",
"(",
")",
";",
"return",
"new",
"TableDDL",
"(",
"tableMetadata",
",",
"rowKeyColumnName",
",",
"timeSeriesColumnName",
",",
"valueColumnName",
")",
";",
"}"
] | Both placement tables -- delta, and delta history -- follow the same DDL. | [
"Both",
"placement",
"tables",
"--",
"delta",
"and",
"delta",
"history",
"--",
"follow",
"the",
"same",
"DDL",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/DeltaPlacement.java#L45-L52 |
michaelliao/jsonstream | src/main/java/com/itranswarp/jsonstream/JsonBuilder.java | JsonBuilder.createReader | public JsonReader createReader(Reader reader) {
"""
Create a JsonReader by providing a Reader.
@param reader The Reader object.
@return JsonReader object.
"""
return new JsonReader(reader, jsonObjectFactory, jsonArrayFactory, objectMapper, typeAdapters);
} | java | public JsonReader createReader(Reader reader) {
return new JsonReader(reader, jsonObjectFactory, jsonArrayFactory, objectMapper, typeAdapters);
} | [
"public",
"JsonReader",
"createReader",
"(",
"Reader",
"reader",
")",
"{",
"return",
"new",
"JsonReader",
"(",
"reader",
",",
"jsonObjectFactory",
",",
"jsonArrayFactory",
",",
"objectMapper",
",",
"typeAdapters",
")",
";",
"}"
] | Create a JsonReader by providing a Reader.
@param reader The Reader object.
@return JsonReader object. | [
"Create",
"a",
"JsonReader",
"by",
"providing",
"a",
"Reader",
"."
] | train | https://github.com/michaelliao/jsonstream/blob/50adcff2e1293e655462eef5fc5f1b59277de514/src/main/java/com/itranswarp/jsonstream/JsonBuilder.java#L92-L94 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/rule/AbstractRule.java | AbstractRule.createViolation | protected Violation createViolation(HtmlElement htmlElement, Page page, String message) {
"""
Creates a new violation for that rule with the line number of the violating element in the given page and a
message that describes the violation in detail.
@param htmlElement the {@link com.gargoylesoftware.htmlunit.html.HtmlElement} where the violation occurs
@param page the page where the violation occurs
@param message description of the violation @return new violation to be added to the list of violations
@return Violation describing the error
"""
if (htmlElement == null)
htmlElement = page.findHtmlTag();
return new Violation(this, htmlElement, message);
} | java | protected Violation createViolation(HtmlElement htmlElement, Page page, String message) {
if (htmlElement == null)
htmlElement = page.findHtmlTag();
return new Violation(this, htmlElement, message);
} | [
"protected",
"Violation",
"createViolation",
"(",
"HtmlElement",
"htmlElement",
",",
"Page",
"page",
",",
"String",
"message",
")",
"{",
"if",
"(",
"htmlElement",
"==",
"null",
")",
"htmlElement",
"=",
"page",
".",
"findHtmlTag",
"(",
")",
";",
"return",
"new",
"Violation",
"(",
"this",
",",
"htmlElement",
",",
"message",
")",
";",
"}"
] | Creates a new violation for that rule with the line number of the violating element in the given page and a
message that describes the violation in detail.
@param htmlElement the {@link com.gargoylesoftware.htmlunit.html.HtmlElement} where the violation occurs
@param page the page where the violation occurs
@param message description of the violation @return new violation to be added to the list of violations
@return Violation describing the error | [
"Creates",
"a",
"new",
"violation",
"for",
"that",
"rule",
"with",
"the",
"line",
"number",
"of",
"the",
"violating",
"element",
"in",
"the",
"given",
"page",
"and",
"a",
"message",
"that",
"describes",
"the",
"violation",
"in",
"detail",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/rule/AbstractRule.java#L45-L49 |
mapsforge/mapsforge | mapsforge-core/src/main/java/org/mapsforge/core/util/LatLongUtils.java | LatLongUtils.sphericalDistance | public static double sphericalDistance(LatLong latLong1, LatLong latLong2) {
"""
Calculate the spherical distance between two LatLongs in meters using the Haversine
formula.
<p/>
This calculation is done using the assumption, that the earth is a sphere, it is not
though. If you need a higher precision and can afford a longer execution time you might
want to use vincentyDistance.
@param latLong1 first LatLong
@param latLong2 second LatLong
@return distance in meters as a double
"""
double dLat = Math.toRadians(latLong2.latitude - latLong1.latitude);
double dLon = Math.toRadians(latLong2.longitude - latLong1.longitude);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(latLong1.latitude))
* Math.cos(Math.toRadians(latLong2.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return c * LatLongUtils.EQUATORIAL_RADIUS;
} | java | public static double sphericalDistance(LatLong latLong1, LatLong latLong2) {
double dLat = Math.toRadians(latLong2.latitude - latLong1.latitude);
double dLon = Math.toRadians(latLong2.longitude - latLong1.longitude);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(latLong1.latitude))
* Math.cos(Math.toRadians(latLong2.latitude)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return c * LatLongUtils.EQUATORIAL_RADIUS;
} | [
"public",
"static",
"double",
"sphericalDistance",
"(",
"LatLong",
"latLong1",
",",
"LatLong",
"latLong2",
")",
"{",
"double",
"dLat",
"=",
"Math",
".",
"toRadians",
"(",
"latLong2",
".",
"latitude",
"-",
"latLong1",
".",
"latitude",
")",
";",
"double",
"dLon",
"=",
"Math",
".",
"toRadians",
"(",
"latLong2",
".",
"longitude",
"-",
"latLong1",
".",
"longitude",
")",
";",
"double",
"a",
"=",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"+",
"Math",
".",
"cos",
"(",
"Math",
".",
"toRadians",
"(",
"latLong1",
".",
"latitude",
")",
")",
"*",
"Math",
".",
"cos",
"(",
"Math",
".",
"toRadians",
"(",
"latLong2",
".",
"latitude",
")",
")",
"*",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
";",
"double",
"c",
"=",
"2",
"*",
"Math",
".",
"atan2",
"(",
"Math",
".",
"sqrt",
"(",
"a",
")",
",",
"Math",
".",
"sqrt",
"(",
"1",
"-",
"a",
")",
")",
";",
"return",
"c",
"*",
"LatLongUtils",
".",
"EQUATORIAL_RADIUS",
";",
"}"
] | Calculate the spherical distance between two LatLongs in meters using the Haversine
formula.
<p/>
This calculation is done using the assumption, that the earth is a sphere, it is not
though. If you need a higher precision and can afford a longer execution time you might
want to use vincentyDistance.
@param latLong1 first LatLong
@param latLong2 second LatLong
@return distance in meters as a double | [
"Calculate",
"the",
"spherical",
"distance",
"between",
"two",
"LatLongs",
"in",
"meters",
"using",
"the",
"Haversine",
"formula",
".",
"<p",
"/",
">",
"This",
"calculation",
"is",
"done",
"using",
"the",
"assumption",
"that",
"the",
"earth",
"is",
"a",
"sphere",
"it",
"is",
"not",
"though",
".",
"If",
"you",
"need",
"a",
"higher",
"precision",
"and",
"can",
"afford",
"a",
"longer",
"execution",
"time",
"you",
"might",
"want",
"to",
"use",
"vincentyDistance",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/LatLongUtils.java#L289-L296 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_config_diff.java | ns_config_diff.diff_table | public static ns_config_diff diff_table(nitro_service client, ns_config_diff resource) throws Exception {
"""
<pre>
Use this operation to get config diff between source and target configuration files in the tabular format.
</pre>
"""
return ((ns_config_diff[]) resource.perform_operation(client, "diff_table"))[0];
} | java | public static ns_config_diff diff_table(nitro_service client, ns_config_diff resource) throws Exception
{
return ((ns_config_diff[]) resource.perform_operation(client, "diff_table"))[0];
} | [
"public",
"static",
"ns_config_diff",
"diff_table",
"(",
"nitro_service",
"client",
",",
"ns_config_diff",
"resource",
")",
"throws",
"Exception",
"{",
"return",
"(",
"(",
"ns_config_diff",
"[",
"]",
")",
"resource",
".",
"perform_operation",
"(",
"client",
",",
"\"diff_table\"",
")",
")",
"[",
"0",
"]",
";",
"}"
] | <pre>
Use this operation to get config diff between source and target configuration files in the tabular format.
</pre> | [
"<pre",
">",
"Use",
"this",
"operation",
"to",
"get",
"config",
"diff",
"between",
"source",
"and",
"target",
"configuration",
"files",
"in",
"the",
"tabular",
"format",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_config_diff.java#L175-L178 |
alkacon/opencms-core | src/org/opencms/importexport/CmsExportHelper.java | CmsExportHelper.writeFile | public void writeFile(CmsFile file, String name) throws IOException {
"""
Writes a single OpenCms VFS file to the export.<p>
@param file the OpenCms VFS file to write
@param name the name of the file in the export
@throws IOException in case of file access issues
"""
if (m_isExportAsFiles) {
writeFile2Rfs(file, name);
} else {
writeFile2Zip(file, name);
}
} | java | public void writeFile(CmsFile file, String name) throws IOException {
if (m_isExportAsFiles) {
writeFile2Rfs(file, name);
} else {
writeFile2Zip(file, name);
}
} | [
"public",
"void",
"writeFile",
"(",
"CmsFile",
"file",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"if",
"(",
"m_isExportAsFiles",
")",
"{",
"writeFile2Rfs",
"(",
"file",
",",
"name",
")",
";",
"}",
"else",
"{",
"writeFile2Zip",
"(",
"file",
",",
"name",
")",
";",
"}",
"}"
] | Writes a single OpenCms VFS file to the export.<p>
@param file the OpenCms VFS file to write
@param name the name of the file in the export
@throws IOException in case of file access issues | [
"Writes",
"a",
"single",
"OpenCms",
"VFS",
"file",
"to",
"the",
"export",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExportHelper.java#L144-L151 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWvWMatchDetail | public void getWvWMatchDetail(String[] ids, Callback<List<WvWMatchDetail>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">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 match id(s)
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@throws GuildWars2Exception empty ID list
@see WvWMatchDetail WvW match detailed info
"""
isParamValid(new ParamChecker(ids));
gw2API.getWvWMatchInfoUsingID(processIds(ids)).enqueue(callback);
} | java | public void getWvWMatchDetail(String[] ids, Callback<List<WvWMatchDetail>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getWvWMatchInfoUsingID(processIds(ids)).enqueue(callback);
} | [
"public",
"void",
"getWvWMatchDetail",
"(",
"String",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"WvWMatchDetail",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getWvWMatchInfoUsingID",
"(",
"processIds",
"(",
"ids",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">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 match id(s)
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@throws GuildWars2Exception empty ID list
@see WvWMatchDetail WvW match detailed info | [
"For",
"more",
"info",
"on",
"WvW",
"matches",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"wvw",
"/",
"matches",
">",
"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#L2624-L2627 |
wisdom-framework/wisdom | core/wisdom-api/src/main/java/org/wisdom/api/router/RouteBuilder.java | RouteBuilder.to | public Route to(Controller controller, String method) {
"""
Sets the targeted action method of the resulting route.
@param controller the controller object, must not be {@literal null}.
@param method the method name, must not be {@literal null}.
@return the current route builder
"""
Preconditions.checkNotNull(controller);
Preconditions.checkNotNull(method);
this.controller = controller;
try {
this.controllerMethod = verifyThatControllerAndMethodExists(controller.getClass(),
method);
} catch (Exception e) {
throw new IllegalArgumentException(ERROR_CTRL + method + ERROR_IN + controller
.getClass() + "`, or the method is invalid", e);
}
return _build();
} | java | public Route to(Controller controller, String method) {
Preconditions.checkNotNull(controller);
Preconditions.checkNotNull(method);
this.controller = controller;
try {
this.controllerMethod = verifyThatControllerAndMethodExists(controller.getClass(),
method);
} catch (Exception e) {
throw new IllegalArgumentException(ERROR_CTRL + method + ERROR_IN + controller
.getClass() + "`, or the method is invalid", e);
}
return _build();
} | [
"public",
"Route",
"to",
"(",
"Controller",
"controller",
",",
"String",
"method",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"controller",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"method",
")",
";",
"this",
".",
"controller",
"=",
"controller",
";",
"try",
"{",
"this",
".",
"controllerMethod",
"=",
"verifyThatControllerAndMethodExists",
"(",
"controller",
".",
"getClass",
"(",
")",
",",
"method",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"ERROR_CTRL",
"+",
"method",
"+",
"ERROR_IN",
"+",
"controller",
".",
"getClass",
"(",
")",
"+",
"\"`, or the method is invalid\"",
",",
"e",
")",
";",
"}",
"return",
"_build",
"(",
")",
";",
"}"
] | Sets the targeted action method of the resulting route.
@param controller the controller object, must not be {@literal null}.
@param method the method name, must not be {@literal null}.
@return the current route builder | [
"Sets",
"the",
"targeted",
"action",
"method",
"of",
"the",
"resulting",
"route",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-api/src/main/java/org/wisdom/api/router/RouteBuilder.java#L84-L96 |
recommenders/rival | rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/GenericRecommenderBuilder.java | GenericRecommenderBuilder.buildRecommender | public Recommender buildRecommender(final DataModel dataModel, final String recType)
throws RecommenderException {
"""
CF recommender with default parameters.
@param dataModel the data model
@param recType the recommender type (as Mahout class)
@return the recommender
@throws RecommenderException see {@link #buildRecommender(org.apache.mahout.cf.taste.model.DataModel, java.lang.String, java.lang.String, int, int, int, java.lang.String)}
"""
return buildRecommender(dataModel, recType, null, DEFAULT_N, NOFACTORS, NOITER, null);
} | java | public Recommender buildRecommender(final DataModel dataModel, final String recType)
throws RecommenderException {
return buildRecommender(dataModel, recType, null, DEFAULT_N, NOFACTORS, NOITER, null);
} | [
"public",
"Recommender",
"buildRecommender",
"(",
"final",
"DataModel",
"dataModel",
",",
"final",
"String",
"recType",
")",
"throws",
"RecommenderException",
"{",
"return",
"buildRecommender",
"(",
"dataModel",
",",
"recType",
",",
"null",
",",
"DEFAULT_N",
",",
"NOFACTORS",
",",
"NOITER",
",",
"null",
")",
";",
"}"
] | CF recommender with default parameters.
@param dataModel the data model
@param recType the recommender type (as Mahout class)
@return the recommender
@throws RecommenderException see {@link #buildRecommender(org.apache.mahout.cf.taste.model.DataModel, java.lang.String, java.lang.String, int, int, int, java.lang.String)} | [
"CF",
"recommender",
"with",
"default",
"parameters",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/GenericRecommenderBuilder.java#L77-L80 |
ManfredTremmel/gwt-bean-validators | gwt-bean-validators/src/main/super/de/knightsoftnet/validators/supersource/java/net/URLConnection.java | URLConnection.getHeaderFieldDate | @SuppressWarnings("deprecation")
public long getHeaderFieldDate(final String name, final long pdefault) {
"""
Returns the value of the named field parsed as date. The result is the number of milliseconds
since January 1, 1970 GMT represented by the named field.
<p>
This form of {@code getHeaderField} exists because some connection types (e.g., {@code http-ng}
) have pre-parsed headers. Classes for that connection type can override this method and
short-circuit the parsing.
</p>
@param name the name of the header field.
@param pdefault a default value.
@return the value of the field, parsed as a date. The value of the {@code Default} argument is
returned if the field is missing or malformed.
"""
final String value = this.getHeaderField(name);
try {
return Date.parse(value);
} catch (final Exception e) { // NOPMD
}
return pdefault;
} | java | @SuppressWarnings("deprecation")
public long getHeaderFieldDate(final String name, final long pdefault) {
final String value = this.getHeaderField(name);
try {
return Date.parse(value);
} catch (final Exception e) { // NOPMD
}
return pdefault;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"long",
"getHeaderFieldDate",
"(",
"final",
"String",
"name",
",",
"final",
"long",
"pdefault",
")",
"{",
"final",
"String",
"value",
"=",
"this",
".",
"getHeaderField",
"(",
"name",
")",
";",
"try",
"{",
"return",
"Date",
".",
"parse",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"// NOPMD",
"}",
"return",
"pdefault",
";",
"}"
] | Returns the value of the named field parsed as date. The result is the number of milliseconds
since January 1, 1970 GMT represented by the named field.
<p>
This form of {@code getHeaderField} exists because some connection types (e.g., {@code http-ng}
) have pre-parsed headers. Classes for that connection type can override this method and
short-circuit the parsing.
</p>
@param name the name of the header field.
@param pdefault a default value.
@return the value of the field, parsed as a date. The value of the {@code Default} argument is
returned if the field is missing or malformed. | [
"Returns",
"the",
"value",
"of",
"the",
"named",
"field",
"parsed",
"as",
"date",
".",
"The",
"result",
"is",
"the",
"number",
"of",
"milliseconds",
"since",
"January",
"1",
"1970",
"GMT",
"represented",
"by",
"the",
"named",
"field",
".",
"<p",
">",
"This",
"form",
"of",
"{",
"@code",
"getHeaderField",
"}",
"exists",
"because",
"some",
"connection",
"types",
"(",
"e",
".",
"g",
".",
"{",
"@code",
"http",
"-",
"ng",
"}",
")",
"have",
"pre",
"-",
"parsed",
"headers",
".",
"Classes",
"for",
"that",
"connection",
"type",
"can",
"override",
"this",
"method",
"and",
"short",
"-",
"circuit",
"the",
"parsing",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwt-bean-validators/src/main/super/de/knightsoftnet/validators/supersource/java/net/URLConnection.java#L494-L502 |
weld/core | impl/src/main/java/org/jboss/weld/util/AnnotatedTypes.java | AnnotatedTypes.compareAnnotated | private static boolean compareAnnotated(Annotated a1, Annotated a2) {
"""
compares two annotated elements to see if they have the same annotations
@param a1
@param a2
@return
"""
return a1.getAnnotations().equals(a2.getAnnotations());
} | java | private static boolean compareAnnotated(Annotated a1, Annotated a2) {
return a1.getAnnotations().equals(a2.getAnnotations());
} | [
"private",
"static",
"boolean",
"compareAnnotated",
"(",
"Annotated",
"a1",
",",
"Annotated",
"a2",
")",
"{",
"return",
"a1",
".",
"getAnnotations",
"(",
")",
".",
"equals",
"(",
"a2",
".",
"getAnnotations",
"(",
")",
")",
";",
"}"
] | compares two annotated elements to see if they have the same annotations
@param a1
@param a2
@return | [
"compares",
"two",
"annotated",
"elements",
"to",
"see",
"if",
"they",
"have",
"the",
"same",
"annotations"
] | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/util/AnnotatedTypes.java#L428-L430 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/journal/xmlhelpers/AbstractXmlReader.java | AbstractXmlReader.isStartTagEvent | protected boolean isStartTagEvent(XMLEvent event, QName tagName) {
"""
Test an event to see whether it is an start tag with the expected name.
"""
return event.isStartElement()
&& event.asStartElement().getName().equals(tagName);
} | java | protected boolean isStartTagEvent(XMLEvent event, QName tagName) {
return event.isStartElement()
&& event.asStartElement().getName().equals(tagName);
} | [
"protected",
"boolean",
"isStartTagEvent",
"(",
"XMLEvent",
"event",
",",
"QName",
"tagName",
")",
"{",
"return",
"event",
".",
"isStartElement",
"(",
")",
"&&",
"event",
".",
"asStartElement",
"(",
")",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"tagName",
")",
";",
"}"
] | Test an event to see whether it is an start tag with the expected name. | [
"Test",
"an",
"event",
"to",
"see",
"whether",
"it",
"is",
"an",
"start",
"tag",
"with",
"the",
"expected",
"name",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/xmlhelpers/AbstractXmlReader.java#L56-L59 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java | JDBC4PreparedStatement.setString | @Override
public void setString(int parameterIndex, String x) throws SQLException {
"""
Sets the designated parameter to the given Java String value.
"""
checkParameterBounds(parameterIndex);
this.parameters[parameterIndex-1] = x == null ? VoltType.NULL_STRING_OR_VARBINARY : x;
} | java | @Override
public void setString(int parameterIndex, String x) throws SQLException
{
checkParameterBounds(parameterIndex);
this.parameters[parameterIndex-1] = x == null ? VoltType.NULL_STRING_OR_VARBINARY : x;
} | [
"@",
"Override",
"public",
"void",
"setString",
"(",
"int",
"parameterIndex",
",",
"String",
"x",
")",
"throws",
"SQLException",
"{",
"checkParameterBounds",
"(",
"parameterIndex",
")",
";",
"this",
".",
"parameters",
"[",
"parameterIndex",
"-",
"1",
"]",
"=",
"x",
"==",
"null",
"?",
"VoltType",
".",
"NULL_STRING_OR_VARBINARY",
":",
"x",
";",
"}"
] | Sets the designated parameter to the given Java String value. | [
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"Java",
"String",
"value",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java#L550-L555 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/classpath/ClasspathOrder.java | ClasspathOrder.addSystemClasspathEntry | boolean addSystemClasspathEntry(final String pathEntry, final ClassLoader classLoader) {
"""
Add a system classpath entry.
@param pathEntry
the system classpath entry -- the path string should already have been run through
FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, path
@param classLoader
the classloader
@return true, if added and unique
"""
if (classpathEntryUniqueResolvedPaths.add(pathEntry)) {
order.add(new SimpleEntry<>(pathEntry, classLoader));
return true;
}
return false;
} | java | boolean addSystemClasspathEntry(final String pathEntry, final ClassLoader classLoader) {
if (classpathEntryUniqueResolvedPaths.add(pathEntry)) {
order.add(new SimpleEntry<>(pathEntry, classLoader));
return true;
}
return false;
} | [
"boolean",
"addSystemClasspathEntry",
"(",
"final",
"String",
"pathEntry",
",",
"final",
"ClassLoader",
"classLoader",
")",
"{",
"if",
"(",
"classpathEntryUniqueResolvedPaths",
".",
"add",
"(",
"pathEntry",
")",
")",
"{",
"order",
".",
"add",
"(",
"new",
"SimpleEntry",
"<>",
"(",
"pathEntry",
",",
"classLoader",
")",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Add a system classpath entry.
@param pathEntry
the system classpath entry -- the path string should already have been run through
FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, path
@param classLoader
the classloader
@return true, if added and unique | [
"Add",
"a",
"system",
"classpath",
"entry",
"."
] | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/classpath/ClasspathOrder.java#L114-L120 |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.getIncludedProjectIdentifiers | private static Set<String> getIncludedProjectIdentifiers(final Project project) {
"""
Attempt to load the project identifiers (group:artifact) for projects that have been included. This method isn't
guaranteed to work all the time since there is no good API that we can use and need to rely on reflection for now.
@param project the project reference.
@return a collection of "included" project identifiers (a.k.a., composite projects).
"""
return getCachedReference(project, "thorntail_included_project_identifiers", () -> {
Set<String> identifiers = new HashSet<>();
// Check for included builds as well.
project.getGradle().getIncludedBuilds().forEach(build -> {
// Determine if the given reference has the following method definition,
// org.gradle.internal.build.IncludedBuildState#getAvailableModules()
try {
Method method = build.getClass().getMethod("getAvailableModules");
Class<?> retType = method.getReturnType();
if (Set.class.isAssignableFrom(retType)) {
// We have identified the right method. Get the values out of it.
Set availableModules = (Set) method.invoke(build);
for (Object entry : availableModules) {
Field field = entry.getClass().getField("left");
Object value = field.get(entry);
if (value instanceof ModuleVersionIdentifier) {
ModuleVersionIdentifier mv = (ModuleVersionIdentifier) value;
identifiers.add(String.format("%s:%s:%s", mv.getGroup(), mv.getName(), mv.getVersion()));
} else {
project.getLogger().debug("Unable to determine field type: {}", field);
}
}
} else {
project.getLogger().debug("Unable to determine method return type: {}", retType);
}
} catch (ReflectiveOperationException e) {
project.getLogger().debug("Unable to determine the included projects.", e);
}
});
return identifiers;
});
} | java | private static Set<String> getIncludedProjectIdentifiers(final Project project) {
return getCachedReference(project, "thorntail_included_project_identifiers", () -> {
Set<String> identifiers = new HashSet<>();
// Check for included builds as well.
project.getGradle().getIncludedBuilds().forEach(build -> {
// Determine if the given reference has the following method definition,
// org.gradle.internal.build.IncludedBuildState#getAvailableModules()
try {
Method method = build.getClass().getMethod("getAvailableModules");
Class<?> retType = method.getReturnType();
if (Set.class.isAssignableFrom(retType)) {
// We have identified the right method. Get the values out of it.
Set availableModules = (Set) method.invoke(build);
for (Object entry : availableModules) {
Field field = entry.getClass().getField("left");
Object value = field.get(entry);
if (value instanceof ModuleVersionIdentifier) {
ModuleVersionIdentifier mv = (ModuleVersionIdentifier) value;
identifiers.add(String.format("%s:%s:%s", mv.getGroup(), mv.getName(), mv.getVersion()));
} else {
project.getLogger().debug("Unable to determine field type: {}", field);
}
}
} else {
project.getLogger().debug("Unable to determine method return type: {}", retType);
}
} catch (ReflectiveOperationException e) {
project.getLogger().debug("Unable to determine the included projects.", e);
}
});
return identifiers;
});
} | [
"private",
"static",
"Set",
"<",
"String",
">",
"getIncludedProjectIdentifiers",
"(",
"final",
"Project",
"project",
")",
"{",
"return",
"getCachedReference",
"(",
"project",
",",
"\"thorntail_included_project_identifiers\"",
",",
"(",
")",
"->",
"{",
"Set",
"<",
"String",
">",
"identifiers",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"// Check for included builds as well.",
"project",
".",
"getGradle",
"(",
")",
".",
"getIncludedBuilds",
"(",
")",
".",
"forEach",
"(",
"build",
"->",
"{",
"// Determine if the given reference has the following method definition,",
"// org.gradle.internal.build.IncludedBuildState#getAvailableModules()",
"try",
"{",
"Method",
"method",
"=",
"build",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"\"getAvailableModules\"",
")",
";",
"Class",
"<",
"?",
">",
"retType",
"=",
"method",
".",
"getReturnType",
"(",
")",
";",
"if",
"(",
"Set",
".",
"class",
".",
"isAssignableFrom",
"(",
"retType",
")",
")",
"{",
"// We have identified the right method. Get the values out of it.",
"Set",
"availableModules",
"=",
"(",
"Set",
")",
"method",
".",
"invoke",
"(",
"build",
")",
";",
"for",
"(",
"Object",
"entry",
":",
"availableModules",
")",
"{",
"Field",
"field",
"=",
"entry",
".",
"getClass",
"(",
")",
".",
"getField",
"(",
"\"left\"",
")",
";",
"Object",
"value",
"=",
"field",
".",
"get",
"(",
"entry",
")",
";",
"if",
"(",
"value",
"instanceof",
"ModuleVersionIdentifier",
")",
"{",
"ModuleVersionIdentifier",
"mv",
"=",
"(",
"ModuleVersionIdentifier",
")",
"value",
";",
"identifiers",
".",
"add",
"(",
"String",
".",
"format",
"(",
"\"%s:%s:%s\"",
",",
"mv",
".",
"getGroup",
"(",
")",
",",
"mv",
".",
"getName",
"(",
")",
",",
"mv",
".",
"getVersion",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"project",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",
"\"Unable to determine field type: {}\"",
",",
"field",
")",
";",
"}",
"}",
"}",
"else",
"{",
"project",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",
"\"Unable to determine method return type: {}\"",
",",
"retType",
")",
";",
"}",
"}",
"catch",
"(",
"ReflectiveOperationException",
"e",
")",
"{",
"project",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",
"\"Unable to determine the included projects.\"",
",",
"e",
")",
";",
"}",
"}",
")",
";",
"return",
"identifiers",
";",
"}",
")",
";",
"}"
] | Attempt to load the project identifiers (group:artifact) for projects that have been included. This method isn't
guaranteed to work all the time since there is no good API that we can use and need to rely on reflection for now.
@param project the project reference.
@return a collection of "included" project identifiers (a.k.a., composite projects). | [
"Attempt",
"to",
"load",
"the",
"project",
"identifiers",
"(",
"group",
":",
"artifact",
")",
"for",
"projects",
"that",
"have",
"been",
"included",
".",
"This",
"method",
"isn",
"t",
"guaranteed",
"to",
"work",
"all",
"the",
"time",
"since",
"there",
"is",
"no",
"good",
"API",
"that",
"we",
"can",
"use",
"and",
"need",
"to",
"rely",
"on",
"reflection",
"for",
"now",
"."
] | train | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L338-L371 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/MonetizationApi.java | MonetizationApi.getPricingTiers | public DevicePricingTiersEnvelope getPricingTiers(String did, Boolean active) throws ApiException {
"""
Get a device's pricing tiers
Get a device's pricing tiers
@param did Device ID (required)
@param active Filter by active (optional)
@return DevicePricingTiersEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<DevicePricingTiersEnvelope> resp = getPricingTiersWithHttpInfo(did, active);
return resp.getData();
} | java | public DevicePricingTiersEnvelope getPricingTiers(String did, Boolean active) throws ApiException {
ApiResponse<DevicePricingTiersEnvelope> resp = getPricingTiersWithHttpInfo(did, active);
return resp.getData();
} | [
"public",
"DevicePricingTiersEnvelope",
"getPricingTiers",
"(",
"String",
"did",
",",
"Boolean",
"active",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"DevicePricingTiersEnvelope",
">",
"resp",
"=",
"getPricingTiersWithHttpInfo",
"(",
"did",
",",
"active",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Get a device's pricing tiers
Get a device's pricing tiers
@param did Device ID (required)
@param active Filter by active (optional)
@return DevicePricingTiersEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Get",
"a",
"device'",
";",
"s",
"pricing",
"tiers",
"Get",
"a",
"device'",
";",
"s",
"pricing",
"tiers"
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/MonetizationApi.java#L259-L262 |
j-easy/easy-random | easy-random-core/src/main/java/org/jeasy/random/EasyRandom.java | EasyRandom.nextObject | public <T> T nextObject(final Class<T> type) {
"""
Generate a random instance of the given type.
@param type the type for which an instance will be generated
@param <T> the actual type of the target object
@return a random instance of the given type
@throws ObjectCreationException when unable to create a new instance of the given type
"""
return doPopulateBean(type, new RandomizationContext(type, parameters));
} | java | public <T> T nextObject(final Class<T> type) {
return doPopulateBean(type, new RandomizationContext(type, parameters));
} | [
"public",
"<",
"T",
">",
"T",
"nextObject",
"(",
"final",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"doPopulateBean",
"(",
"type",
",",
"new",
"RandomizationContext",
"(",
"type",
",",
"parameters",
")",
")",
";",
"}"
] | Generate a random instance of the given type.
@param type the type for which an instance will be generated
@param <T> the actual type of the target object
@return a random instance of the given type
@throws ObjectCreationException when unable to create a new instance of the given type | [
"Generate",
"a",
"random",
"instance",
"of",
"the",
"given",
"type",
"."
] | train | https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/EasyRandom.java#L96-L98 |
Azure/azure-sdk-for-java | datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java | StorageAccountsInner.getStorageContainerAsync | public Observable<StorageContainerInner> getStorageContainerAsync(String resourceGroupName, String accountName, String storageAccountName, String containerName) {
"""
Gets the specified Azure Storage container associated with the given Data Lake Analytics and Azure Storage accounts.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@param storageAccountName The name of the Azure storage account from which to retrieve the blob container.
@param containerName The name of the Azure storage container to retrieve
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageContainerInner object
"""
return getStorageContainerWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName, containerName).map(new Func1<ServiceResponse<StorageContainerInner>, StorageContainerInner>() {
@Override
public StorageContainerInner call(ServiceResponse<StorageContainerInner> response) {
return response.body();
}
});
} | java | public Observable<StorageContainerInner> getStorageContainerAsync(String resourceGroupName, String accountName, String storageAccountName, String containerName) {
return getStorageContainerWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName, containerName).map(new Func1<ServiceResponse<StorageContainerInner>, StorageContainerInner>() {
@Override
public StorageContainerInner call(ServiceResponse<StorageContainerInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StorageContainerInner",
">",
"getStorageContainerAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"storageAccountName",
",",
"String",
"containerName",
")",
"{",
"return",
"getStorageContainerWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"storageAccountName",
",",
"containerName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"StorageContainerInner",
">",
",",
"StorageContainerInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"StorageContainerInner",
"call",
"(",
"ServiceResponse",
"<",
"StorageContainerInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the specified Azure Storage container associated with the given Data Lake Analytics and Azure Storage accounts.
@param resourceGroupName The name of the Azure resource group.
@param accountName The name of the Data Lake Analytics account.
@param storageAccountName The name of the Azure storage account from which to retrieve the blob container.
@param containerName The name of the Azure storage container to retrieve
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageContainerInner object | [
"Gets",
"the",
"specified",
"Azure",
"Storage",
"container",
"associated",
"with",
"the",
"given",
"Data",
"Lake",
"Analytics",
"and",
"Azure",
"Storage",
"accounts",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2016_11_01/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2016_11_01/implementation/StorageAccountsInner.java#L1029-L1036 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/style/sld/StyleHandler.java | StyleHandler.getStyle | public String getStyle(StyleType type, Color color, String colorName, String layerName) {
"""
Generates a style from a template using the provided substitutions.
@param type the template type, see {@link org.geoserver.catalog.StyleType}.
@param color java.aw.Color to use during substitution
@param colorName Human readable color name, for use generating comments
@param layerName Layer name, for use generating comments
@return The text content of the style template after performing substitutions
"""
throw new UnsupportedOperationException();
} | java | public String getStyle(StyleType type, Color color, String colorName, String layerName) {
throw new UnsupportedOperationException();
} | [
"public",
"String",
"getStyle",
"(",
"StyleType",
"type",
",",
"Color",
"color",
",",
"String",
"colorName",
",",
"String",
"layerName",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}"
] | Generates a style from a template using the provided substitutions.
@param type the template type, see {@link org.geoserver.catalog.StyleType}.
@param color java.aw.Color to use during substitution
@param colorName Human readable color name, for use generating comments
@param layerName Layer name, for use generating comments
@return The text content of the style template after performing substitutions | [
"Generates",
"a",
"style",
"from",
"a",
"template",
"using",
"the",
"provided",
"substitutions",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/sld/StyleHandler.java#L98-L100 |
apache/flink | flink-core/src/main/java/org/apache/flink/configuration/Configuration.java | Configuration.getDouble | @PublicEvolving
public double getDouble(ConfigOption<Double> configOption) {
"""
Returns the value associated with the given config option as a {@code double}.
@param configOption The configuration option
@return the (default) value associated with the given config option
"""
Object o = getValueOrDefaultFromOption(configOption);
return convertToDouble(o, configOption.defaultValue());
} | java | @PublicEvolving
public double getDouble(ConfigOption<Double> configOption) {
Object o = getValueOrDefaultFromOption(configOption);
return convertToDouble(o, configOption.defaultValue());
} | [
"@",
"PublicEvolving",
"public",
"double",
"getDouble",
"(",
"ConfigOption",
"<",
"Double",
">",
"configOption",
")",
"{",
"Object",
"o",
"=",
"getValueOrDefaultFromOption",
"(",
"configOption",
")",
";",
"return",
"convertToDouble",
"(",
"o",
",",
"configOption",
".",
"defaultValue",
"(",
")",
")",
";",
"}"
] | Returns the value associated with the given config option as a {@code double}.
@param configOption The configuration option
@return the (default) value associated with the given config option | [
"Returns",
"the",
"value",
"associated",
"with",
"the",
"given",
"config",
"option",
"as",
"a",
"{",
"@code",
"double",
"}",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L515-L519 |
boncey/Flickr4Java | src/main/java/com/flickr4java/flickr/photosets/PhotosetsInterface.java | PhotosetsInterface.editPhotos | public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {
"""
Edit which photos are in the photoset.
@param photosetId
The photoset ID
@param primaryPhotoId
The primary photo Id
@param photoIds
The photo IDs for the photos in the set
@throws FlickrException
"""
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_EDIT_PHOTOS);
parameters.put("photoset_id", photosetId);
parameters.put("primary_photo_id", primaryPhotoId);
parameters.put("photo_ids", StringUtilities.join(photoIds, ","));
Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
} | java | public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_EDIT_PHOTOS);
parameters.put("photoset_id", photosetId);
parameters.put("primary_photo_id", primaryPhotoId);
parameters.put("photo_ids", StringUtilities.join(photoIds, ","));
Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
} | [
"public",
"void",
"editPhotos",
"(",
"String",
"photosetId",
",",
"String",
"primaryPhotoId",
",",
"String",
"[",
"]",
"photoIds",
")",
"throws",
"FlickrException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"parameters",
".",
"put",
"(",
"\"method\"",
",",
"METHOD_EDIT_PHOTOS",
")",
";",
"parameters",
".",
"put",
"(",
"\"photoset_id\"",
",",
"photosetId",
")",
";",
"parameters",
".",
"put",
"(",
"\"primary_photo_id\"",
",",
"primaryPhotoId",
")",
";",
"parameters",
".",
"put",
"(",
"\"photo_ids\"",
",",
"StringUtilities",
".",
"join",
"(",
"photoIds",
",",
"\",\"",
")",
")",
";",
"Response",
"response",
"=",
"transportAPI",
".",
"post",
"(",
"transportAPI",
".",
"getPath",
"(",
")",
",",
"parameters",
",",
"apiKey",
",",
"sharedSecret",
")",
";",
"if",
"(",
"response",
".",
"isError",
"(",
")",
")",
"{",
"throw",
"new",
"FlickrException",
"(",
"response",
".",
"getErrorCode",
"(",
")",
",",
"response",
".",
"getErrorMessage",
"(",
")",
")",
";",
"}",
"}"
] | Edit which photos are in the photoset.
@param photosetId
The photoset ID
@param primaryPhotoId
The primary photo Id
@param photoIds
The photo IDs for the photos in the set
@throws FlickrException | [
"Edit",
"which",
"photos",
"are",
"in",
"the",
"photoset",
"."
] | train | https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photosets/PhotosetsInterface.java#L189-L201 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/GeoPoint.java | GeoPoint.destinationPoint | public GeoPoint destinationPoint(final double aDistanceInMeters, final double aBearingInDegrees) {
"""
Calculate a point that is the specified distance and bearing away from this point.
@see <a href="http://www.movable-type.co.uk/scripts/latlong.html">latlong.html</a>
@see <a href="http://www.movable-type.co.uk/scripts/latlon.js">latlon.js</a>
"""
// convert distance to angular distance
final double dist = aDistanceInMeters / RADIUS_EARTH_METERS;
// convert bearing to radians
final double brng = DEG2RAD * aBearingInDegrees;
// get current location in radians
final double lat1 = DEG2RAD * getLatitude();
final double lon1 = DEG2RAD * getLongitude();
final double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1)
* Math.sin(dist) * Math.cos(brng));
final double lon2 = lon1
+ Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist)
- Math.sin(lat1) * Math.sin(lat2));
final double lat2deg = lat2 / DEG2RAD;
final double lon2deg = lon2 / DEG2RAD;
return new GeoPoint(lat2deg, lon2deg);
} | java | public GeoPoint destinationPoint(final double aDistanceInMeters, final double aBearingInDegrees) {
// convert distance to angular distance
final double dist = aDistanceInMeters / RADIUS_EARTH_METERS;
// convert bearing to radians
final double brng = DEG2RAD * aBearingInDegrees;
// get current location in radians
final double lat1 = DEG2RAD * getLatitude();
final double lon1 = DEG2RAD * getLongitude();
final double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1)
* Math.sin(dist) * Math.cos(brng));
final double lon2 = lon1
+ Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist)
- Math.sin(lat1) * Math.sin(lat2));
final double lat2deg = lat2 / DEG2RAD;
final double lon2deg = lon2 / DEG2RAD;
return new GeoPoint(lat2deg, lon2deg);
} | [
"public",
"GeoPoint",
"destinationPoint",
"(",
"final",
"double",
"aDistanceInMeters",
",",
"final",
"double",
"aBearingInDegrees",
")",
"{",
"// convert distance to angular distance",
"final",
"double",
"dist",
"=",
"aDistanceInMeters",
"/",
"RADIUS_EARTH_METERS",
";",
"// convert bearing to radians",
"final",
"double",
"brng",
"=",
"DEG2RAD",
"*",
"aBearingInDegrees",
";",
"// get current location in radians",
"final",
"double",
"lat1",
"=",
"DEG2RAD",
"*",
"getLatitude",
"(",
")",
";",
"final",
"double",
"lon1",
"=",
"DEG2RAD",
"*",
"getLongitude",
"(",
")",
";",
"final",
"double",
"lat2",
"=",
"Math",
".",
"asin",
"(",
"Math",
".",
"sin",
"(",
"lat1",
")",
"*",
"Math",
".",
"cos",
"(",
"dist",
")",
"+",
"Math",
".",
"cos",
"(",
"lat1",
")",
"*",
"Math",
".",
"sin",
"(",
"dist",
")",
"*",
"Math",
".",
"cos",
"(",
"brng",
")",
")",
";",
"final",
"double",
"lon2",
"=",
"lon1",
"+",
"Math",
".",
"atan2",
"(",
"Math",
".",
"sin",
"(",
"brng",
")",
"*",
"Math",
".",
"sin",
"(",
"dist",
")",
"*",
"Math",
".",
"cos",
"(",
"lat1",
")",
",",
"Math",
".",
"cos",
"(",
"dist",
")",
"-",
"Math",
".",
"sin",
"(",
"lat1",
")",
"*",
"Math",
".",
"sin",
"(",
"lat2",
")",
")",
";",
"final",
"double",
"lat2deg",
"=",
"lat2",
"/",
"DEG2RAD",
";",
"final",
"double",
"lon2deg",
"=",
"lon2",
"/",
"DEG2RAD",
";",
"return",
"new",
"GeoPoint",
"(",
"lat2deg",
",",
"lon2deg",
")",
";",
"}"
] | Calculate a point that is the specified distance and bearing away from this point.
@see <a href="http://www.movable-type.co.uk/scripts/latlong.html">latlong.html</a>
@see <a href="http://www.movable-type.co.uk/scripts/latlon.js">latlon.js</a> | [
"Calculate",
"a",
"point",
"that",
"is",
"the",
"specified",
"distance",
"and",
"bearing",
"away",
"from",
"this",
"point",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/GeoPoint.java#L288-L310 |
plaid/plaid-java | src/main/java/com/plaid/client/internal/Util.java | Util.notEmpty | public static void notEmpty(Collection collection, String name) {
"""
Checks that a given collection is not null and not empty.
@param collection The collection to check
@param name The name of the collection to use when raising an error.
@throws IllegalArgumentException If the collection was null or empty.
"""
notNull(collection, name);
if (collection.isEmpty()) {
throw new IllegalArgumentException(name + " must not be empty");
}
} | java | public static void notEmpty(Collection collection, String name) {
notNull(collection, name);
if (collection.isEmpty()) {
throw new IllegalArgumentException(name + " must not be empty");
}
} | [
"public",
"static",
"void",
"notEmpty",
"(",
"Collection",
"collection",
",",
"String",
"name",
")",
"{",
"notNull",
"(",
"collection",
",",
"name",
")",
";",
"if",
"(",
"collection",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"name",
"+",
"\" must not be empty\"",
")",
";",
"}",
"}"
] | Checks that a given collection is not null and not empty.
@param collection The collection to check
@param name The name of the collection to use when raising an error.
@throws IllegalArgumentException If the collection was null or empty. | [
"Checks",
"that",
"a",
"given",
"collection",
"is",
"not",
"null",
"and",
"not",
"empty",
"."
] | train | https://github.com/plaid/plaid-java/blob/360f1f8a5178fa0c3c2c2e07a58f8ccec5f33117/src/main/java/com/plaid/client/internal/Util.java#L30-L36 |
jbundle/jbundle | app/program/db/src/main/java/org/jbundle/app/program/db/AnalysisLog.java | AnalysisLog.logRemoveRecord | public void logRemoveRecord(Rec record, int iSystemID) {
"""
Log that this record has been freed.
Call this from the end of record.free
@param record the record that is being added.
"""
try {
this.getTable().setProperty(DBParams.SUPRESSREMOTEDBMESSAGES, DBConstants.TRUE);
this.getTable().getDatabase().setProperty(DBParams.MESSAGES_TO_REMOTE, DBConstants.FALSE);
this.addNew();
this.getField(AnalysisLog.SYSTEM_ID).setValue(iSystemID);
this.getField(AnalysisLog.OBJECT_ID).setValue(Debug.getObjectID(record, true));
this.setKeyArea(AnalysisLog.OBJECT_ID_KEY);
if (this.seek(null))
{
this.edit();
((DateTimeField)this.getField(AnalysisLog.FREE_TIME)).setValue(DateTimeField.currentTime());
if (this.getField(AnalysisLog.RECORD_OWNER).isNull())
this.getField(AnalysisLog.RECORD_OWNER).setString(Debug.getClassName(((Record)record).getRecordOwner()));
this.set();
}
else
{
// Ignore for now System.exit(1);
}
} catch (DBException ex) {
ex.printStackTrace();
}
} | java | public void logRemoveRecord(Rec record, int iSystemID)
{
try {
this.getTable().setProperty(DBParams.SUPRESSREMOTEDBMESSAGES, DBConstants.TRUE);
this.getTable().getDatabase().setProperty(DBParams.MESSAGES_TO_REMOTE, DBConstants.FALSE);
this.addNew();
this.getField(AnalysisLog.SYSTEM_ID).setValue(iSystemID);
this.getField(AnalysisLog.OBJECT_ID).setValue(Debug.getObjectID(record, true));
this.setKeyArea(AnalysisLog.OBJECT_ID_KEY);
if (this.seek(null))
{
this.edit();
((DateTimeField)this.getField(AnalysisLog.FREE_TIME)).setValue(DateTimeField.currentTime());
if (this.getField(AnalysisLog.RECORD_OWNER).isNull())
this.getField(AnalysisLog.RECORD_OWNER).setString(Debug.getClassName(((Record)record).getRecordOwner()));
this.set();
}
else
{
// Ignore for now System.exit(1);
}
} catch (DBException ex) {
ex.printStackTrace();
}
} | [
"public",
"void",
"logRemoveRecord",
"(",
"Rec",
"record",
",",
"int",
"iSystemID",
")",
"{",
"try",
"{",
"this",
".",
"getTable",
"(",
")",
".",
"setProperty",
"(",
"DBParams",
".",
"SUPRESSREMOTEDBMESSAGES",
",",
"DBConstants",
".",
"TRUE",
")",
";",
"this",
".",
"getTable",
"(",
")",
".",
"getDatabase",
"(",
")",
".",
"setProperty",
"(",
"DBParams",
".",
"MESSAGES_TO_REMOTE",
",",
"DBConstants",
".",
"FALSE",
")",
";",
"this",
".",
"addNew",
"(",
")",
";",
"this",
".",
"getField",
"(",
"AnalysisLog",
".",
"SYSTEM_ID",
")",
".",
"setValue",
"(",
"iSystemID",
")",
";",
"this",
".",
"getField",
"(",
"AnalysisLog",
".",
"OBJECT_ID",
")",
".",
"setValue",
"(",
"Debug",
".",
"getObjectID",
"(",
"record",
",",
"true",
")",
")",
";",
"this",
".",
"setKeyArea",
"(",
"AnalysisLog",
".",
"OBJECT_ID_KEY",
")",
";",
"if",
"(",
"this",
".",
"seek",
"(",
"null",
")",
")",
"{",
"this",
".",
"edit",
"(",
")",
";",
"(",
"(",
"DateTimeField",
")",
"this",
".",
"getField",
"(",
"AnalysisLog",
".",
"FREE_TIME",
")",
")",
".",
"setValue",
"(",
"DateTimeField",
".",
"currentTime",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"getField",
"(",
"AnalysisLog",
".",
"RECORD_OWNER",
")",
".",
"isNull",
"(",
")",
")",
"this",
".",
"getField",
"(",
"AnalysisLog",
".",
"RECORD_OWNER",
")",
".",
"setString",
"(",
"Debug",
".",
"getClassName",
"(",
"(",
"(",
"Record",
")",
"record",
")",
".",
"getRecordOwner",
"(",
")",
")",
")",
";",
"this",
".",
"set",
"(",
")",
";",
"}",
"else",
"{",
"// Ignore for now System.exit(1);",
"}",
"}",
"catch",
"(",
"DBException",
"ex",
")",
"{",
"ex",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}"
] | Log that this record has been freed.
Call this from the end of record.free
@param record the record that is being added. | [
"Log",
"that",
"this",
"record",
"has",
"been",
"freed",
".",
"Call",
"this",
"from",
"the",
"end",
"of",
"record",
".",
"free"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/db/src/main/java/org/jbundle/app/program/db/AnalysisLog.java#L167-L192 |
febit/wit | wit-core/src/main/java/org/febit/wit_shaded/asm/MethodWriter.java | MethodWriter.addSuccessor | private void addSuccessor(final int stackSize, final Label successor) {
"""
Adds a successor to the {@link #currentBlock currentBlock} block.
@param stackSize the current (relative) stack size in the current block.
@param successor the successor block to be added to the current block.
"""
Edge b;
// creates a new Edge object or reuses one from the shared pool
synchronized (SIZE) {
if (pool == null) {
b = new Edge();
} else {
b = pool;
// removes b from the pool
pool = pool.poolNext;
}
}
// adds the previous Edge to the list of Edges used by this MethodWriter
if (tail == null) {
tail = b;
}
b.poolNext = head;
head = b;
// initializes the previous Edge object...
b.stackSize = stackSize;
b.successor = successor;
// ...and adds it to the successor list of the currentBlock block
b.next = currentBlock.successors;
currentBlock.successors = b;
} | java | private void addSuccessor(final int stackSize, final Label successor) {
Edge b;
// creates a new Edge object or reuses one from the shared pool
synchronized (SIZE) {
if (pool == null) {
b = new Edge();
} else {
b = pool;
// removes b from the pool
pool = pool.poolNext;
}
}
// adds the previous Edge to the list of Edges used by this MethodWriter
if (tail == null) {
tail = b;
}
b.poolNext = head;
head = b;
// initializes the previous Edge object...
b.stackSize = stackSize;
b.successor = successor;
// ...and adds it to the successor list of the currentBlock block
b.next = currentBlock.successors;
currentBlock.successors = b;
} | [
"private",
"void",
"addSuccessor",
"(",
"final",
"int",
"stackSize",
",",
"final",
"Label",
"successor",
")",
"{",
"Edge",
"b",
";",
"// creates a new Edge object or reuses one from the shared pool",
"synchronized",
"(",
"SIZE",
")",
"{",
"if",
"(",
"pool",
"==",
"null",
")",
"{",
"b",
"=",
"new",
"Edge",
"(",
")",
";",
"}",
"else",
"{",
"b",
"=",
"pool",
";",
"// removes b from the pool",
"pool",
"=",
"pool",
".",
"poolNext",
";",
"}",
"}",
"// adds the previous Edge to the list of Edges used by this MethodWriter",
"if",
"(",
"tail",
"==",
"null",
")",
"{",
"tail",
"=",
"b",
";",
"}",
"b",
".",
"poolNext",
"=",
"head",
";",
"head",
"=",
"b",
";",
"// initializes the previous Edge object...",
"b",
".",
"stackSize",
"=",
"stackSize",
";",
"b",
".",
"successor",
"=",
"successor",
";",
"// ...and adds it to the successor list of the currentBlock block",
"b",
".",
"next",
"=",
"currentBlock",
".",
"successors",
";",
"currentBlock",
".",
"successors",
"=",
"b",
";",
"}"
] | Adds a successor to the {@link #currentBlock currentBlock} block.
@param stackSize the current (relative) stack size in the current block.
@param successor the successor block to be added to the current block. | [
"Adds",
"a",
"successor",
"to",
"the",
"{",
"@link",
"#currentBlock",
"currentBlock",
"}",
"block",
"."
] | train | https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit_shaded/asm/MethodWriter.java#L955-L979 |
openengsb/openengsb | components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java | EngineeringObjectEnhancer.getReferenceBasedUpdates | private List<AdvancedModelWrapper> getReferenceBasedUpdates(AdvancedModelWrapper model,
Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) throws EKBException {
"""
Returns engineering objects to the commit, which are changed by a model which was committed in the EKBCommit
"""
List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>();
List<EDBObject> references = model.getModelsReferringToThisModel(edbService);
for (EDBObject reference : references) {
EDBModelObject modelReference = new EDBModelObject(reference, modelRegistry, edbConverter);
AdvancedModelWrapper ref = updateEOByUpdatedModel(modelReference, model, updated);
if (!updated.containsKey(ref.getCompleteModelOID())) {
updates.add(ref);
}
}
return updates;
} | java | private List<AdvancedModelWrapper> getReferenceBasedUpdates(AdvancedModelWrapper model,
Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) throws EKBException {
List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>();
List<EDBObject> references = model.getModelsReferringToThisModel(edbService);
for (EDBObject reference : references) {
EDBModelObject modelReference = new EDBModelObject(reference, modelRegistry, edbConverter);
AdvancedModelWrapper ref = updateEOByUpdatedModel(modelReference, model, updated);
if (!updated.containsKey(ref.getCompleteModelOID())) {
updates.add(ref);
}
}
return updates;
} | [
"private",
"List",
"<",
"AdvancedModelWrapper",
">",
"getReferenceBasedUpdates",
"(",
"AdvancedModelWrapper",
"model",
",",
"Map",
"<",
"Object",
",",
"AdvancedModelWrapper",
">",
"updated",
",",
"EKBCommit",
"commit",
")",
"throws",
"EKBException",
"{",
"List",
"<",
"AdvancedModelWrapper",
">",
"updates",
"=",
"new",
"ArrayList",
"<",
"AdvancedModelWrapper",
">",
"(",
")",
";",
"List",
"<",
"EDBObject",
">",
"references",
"=",
"model",
".",
"getModelsReferringToThisModel",
"(",
"edbService",
")",
";",
"for",
"(",
"EDBObject",
"reference",
":",
"references",
")",
"{",
"EDBModelObject",
"modelReference",
"=",
"new",
"EDBModelObject",
"(",
"reference",
",",
"modelRegistry",
",",
"edbConverter",
")",
";",
"AdvancedModelWrapper",
"ref",
"=",
"updateEOByUpdatedModel",
"(",
"modelReference",
",",
"model",
",",
"updated",
")",
";",
"if",
"(",
"!",
"updated",
".",
"containsKey",
"(",
"ref",
".",
"getCompleteModelOID",
"(",
")",
")",
")",
"{",
"updates",
".",
"add",
"(",
"ref",
")",
";",
"}",
"}",
"return",
"updates",
";",
"}"
] | Returns engineering objects to the commit, which are changed by a model which was committed in the EKBCommit | [
"Returns",
"engineering",
"objects",
"to",
"the",
"commit",
"which",
"are",
"changed",
"by",
"a",
"model",
"which",
"was",
"committed",
"in",
"the",
"EKBCommit"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java#L213-L225 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java | GaliosFieldTableOps.polyAdd | public void polyAdd(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) {
"""
Adds two polynomials together. output = polyA + polyB
<p>Coefficients for largest powers are first, e.g. 2*x**3 + 8*x**2+1 = [2,8,0,1]</p>
@param polyA (Input) First polynomial
@param polyB (Input) Second polynomial
@param output (Output) Results of addition
"""
output.resize(Math.max(polyA.size,polyB.size));
// compute offset that would align the smaller polynomial with the larger polynomial
int offsetA = Math.max(0,polyB.size-polyA.size);
int offsetB = Math.max(0,polyA.size-polyB.size);
int N = output.size;
for (int i = 0; i < offsetB; i++) {
output.data[i] = polyA.data[i];
}
for (int i = 0; i < offsetA; i++) {
output.data[i] = polyB.data[i];
}
for (int i = Math.max(offsetA,offsetB); i < N; i++) {
output.data[i] = (byte)((polyA.data[i-offsetA]&0xFF) ^ (polyB.data[i-offsetB]&0xFF));
}
} | java | public void polyAdd(GrowQueue_I8 polyA , GrowQueue_I8 polyB , GrowQueue_I8 output ) {
output.resize(Math.max(polyA.size,polyB.size));
// compute offset that would align the smaller polynomial with the larger polynomial
int offsetA = Math.max(0,polyB.size-polyA.size);
int offsetB = Math.max(0,polyA.size-polyB.size);
int N = output.size;
for (int i = 0; i < offsetB; i++) {
output.data[i] = polyA.data[i];
}
for (int i = 0; i < offsetA; i++) {
output.data[i] = polyB.data[i];
}
for (int i = Math.max(offsetA,offsetB); i < N; i++) {
output.data[i] = (byte)((polyA.data[i-offsetA]&0xFF) ^ (polyB.data[i-offsetB]&0xFF));
}
} | [
"public",
"void",
"polyAdd",
"(",
"GrowQueue_I8",
"polyA",
",",
"GrowQueue_I8",
"polyB",
",",
"GrowQueue_I8",
"output",
")",
"{",
"output",
".",
"resize",
"(",
"Math",
".",
"max",
"(",
"polyA",
".",
"size",
",",
"polyB",
".",
"size",
")",
")",
";",
"// compute offset that would align the smaller polynomial with the larger polynomial",
"int",
"offsetA",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"polyB",
".",
"size",
"-",
"polyA",
".",
"size",
")",
";",
"int",
"offsetB",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"polyA",
".",
"size",
"-",
"polyB",
".",
"size",
")",
";",
"int",
"N",
"=",
"output",
".",
"size",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"offsetB",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"polyA",
".",
"data",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"offsetA",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"polyB",
".",
"data",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"Math",
".",
"max",
"(",
"offsetA",
",",
"offsetB",
")",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"output",
".",
"data",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"polyA",
".",
"data",
"[",
"i",
"-",
"offsetA",
"]",
"&",
"0xFF",
")",
"^",
"(",
"polyB",
".",
"data",
"[",
"i",
"-",
"offsetB",
"]",
"&",
"0xFF",
")",
")",
";",
"}",
"}"
] | Adds two polynomials together. output = polyA + polyB
<p>Coefficients for largest powers are first, e.g. 2*x**3 + 8*x**2+1 = [2,8,0,1]</p>
@param polyA (Input) First polynomial
@param polyB (Input) Second polynomial
@param output (Output) Results of addition | [
"Adds",
"two",
"polynomials",
"together",
".",
"output",
"=",
"polyA",
"+",
"polyB"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/GaliosFieldTableOps.java#L147-L164 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java | StrSubstitutor.replaceIn | public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
"""
Replaces all the occurrences of variables within the given source
builder with their matching values from the resolver.
<p>
Only the specified portion of the builder will be processed.
The rest of the builder is not processed, but it is not deleted.
@param source the builder to replace in, null returns zero
@param offset the start offset within the array, must be valid
@param length the length within the builder to be processed, must be valid
@return true if altered
"""
if (source == null) {
return false;
}
return substitute(source, offset, length);
} | java | public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
if (source == null) {
return false;
}
return substitute(source, offset, length);
} | [
"public",
"boolean",
"replaceIn",
"(",
"final",
"StrBuilder",
"source",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"substitute",
"(",
"source",
",",
"offset",
",",
"length",
")",
";",
"}"
] | Replaces all the occurrences of variables within the given source
builder with their matching values from the resolver.
<p>
Only the specified portion of the builder will be processed.
The rest of the builder is not processed, but it is not deleted.
@param source the builder to replace in, null returns zero
@param offset the start offset within the array, must be valid
@param length the length within the builder to be processed, must be valid
@return true if altered | [
"Replaces",
"all",
"the",
"occurrences",
"of",
"variables",
"within",
"the",
"given",
"source",
"builder",
"with",
"their",
"matching",
"values",
"from",
"the",
"resolver",
".",
"<p",
">",
"Only",
"the",
"specified",
"portion",
"of",
"the",
"builder",
"will",
"be",
"processed",
".",
"The",
"rest",
"of",
"the",
"builder",
"is",
"not",
"processed",
"but",
"it",
"is",
"not",
"deleted",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java#L723-L728 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortablePositionNavigator.java | PortablePositionNavigator.createPositionForReadAccess | private static PortablePosition createPositionForReadAccess(
PortableNavigatorContext ctx, PortablePathCursor path, int index) throws IOException {
"""
Create an instance of the {@PortablePosition} for direct reading in the reader class.
The cursor and the path point to the leaf field, but there's still some adjustments to be made in certain cases.
<p>
- If it's a primitive array cell that is being accessed with the [number] quantifier the stream has to be
adjusted to point to the cell specified by the index.
<p>
- If it's a portable attribute that is being accessed the factoryId and classId have to be read and validated.
They are required for the portable read operation.
<p>
- If it's a portable array cell that is being accessed with the [number] quantifier the stream has to be
adjusted to point to the cell specified by the index. Also the factoryId and classId have to be read and
validated. They are required for the portable read operation.
<p>
If it's a whole portable array that is being accessed factoryId and classId have to be read and
validated. The length have to be read.
<p>
If it's a whole primitive array or a primitive field that is being accessed there's nothing to be adjusted.
"""
FieldType type = ctx.getCurrentFieldType();
if (type.isArrayType()) {
if (type == FieldType.PORTABLE_ARRAY) {
return createPositionForReadAccessInPortableArray(ctx, path, index);
} else {
return createPositionForReadAccessInPrimitiveArray(ctx, path, index);
}
} else {
validateNonArrayPosition(path, index);
return createPositionForReadAccessInFromAttribute(ctx, path, index, type);
}
} | java | private static PortablePosition createPositionForReadAccess(
PortableNavigatorContext ctx, PortablePathCursor path, int index) throws IOException {
FieldType type = ctx.getCurrentFieldType();
if (type.isArrayType()) {
if (type == FieldType.PORTABLE_ARRAY) {
return createPositionForReadAccessInPortableArray(ctx, path, index);
} else {
return createPositionForReadAccessInPrimitiveArray(ctx, path, index);
}
} else {
validateNonArrayPosition(path, index);
return createPositionForReadAccessInFromAttribute(ctx, path, index, type);
}
} | [
"private",
"static",
"PortablePosition",
"createPositionForReadAccess",
"(",
"PortableNavigatorContext",
"ctx",
",",
"PortablePathCursor",
"path",
",",
"int",
"index",
")",
"throws",
"IOException",
"{",
"FieldType",
"type",
"=",
"ctx",
".",
"getCurrentFieldType",
"(",
")",
";",
"if",
"(",
"type",
".",
"isArrayType",
"(",
")",
")",
"{",
"if",
"(",
"type",
"==",
"FieldType",
".",
"PORTABLE_ARRAY",
")",
"{",
"return",
"createPositionForReadAccessInPortableArray",
"(",
"ctx",
",",
"path",
",",
"index",
")",
";",
"}",
"else",
"{",
"return",
"createPositionForReadAccessInPrimitiveArray",
"(",
"ctx",
",",
"path",
",",
"index",
")",
";",
"}",
"}",
"else",
"{",
"validateNonArrayPosition",
"(",
"path",
",",
"index",
")",
";",
"return",
"createPositionForReadAccessInFromAttribute",
"(",
"ctx",
",",
"path",
",",
"index",
",",
"type",
")",
";",
"}",
"}"
] | Create an instance of the {@PortablePosition} for direct reading in the reader class.
The cursor and the path point to the leaf field, but there's still some adjustments to be made in certain cases.
<p>
- If it's a primitive array cell that is being accessed with the [number] quantifier the stream has to be
adjusted to point to the cell specified by the index.
<p>
- If it's a portable attribute that is being accessed the factoryId and classId have to be read and validated.
They are required for the portable read operation.
<p>
- If it's a portable array cell that is being accessed with the [number] quantifier the stream has to be
adjusted to point to the cell specified by the index. Also the factoryId and classId have to be read and
validated. They are required for the portable read operation.
<p>
If it's a whole portable array that is being accessed factoryId and classId have to be read and
validated. The length have to be read.
<p>
If it's a whole primitive array or a primitive field that is being accessed there's nothing to be adjusted. | [
"Create",
"an",
"instance",
"of",
"the",
"{"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortablePositionNavigator.java#L437-L450 |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeperMain.java | ZooKeeperMain.trimProcQuotas | private static boolean trimProcQuotas(ZooKeeper zk, String path)
throws KeeperException, IOException, InterruptedException {
"""
trim the quota tree to recover unwanted tree elements in the quota's tree
@param zk
the zookeeper client
@param path
the path to start from and go up and see if their is any
unwanted parent in the path.
@return true if sucessful
@throws KeeperException
@throws IOException
@throws InterruptedException
"""
if (Quotas.quotaZookeeper.equals(path)) {
return true;
}
List<String> children = zk.getChildren(path, false);
if (children.size() == 0) {
zk.delete(path, -1);
String parent = path.substring(0, path.lastIndexOf('/'));
return trimProcQuotas(zk, parent);
} else {
return true;
}
} | java | private static boolean trimProcQuotas(ZooKeeper zk, String path)
throws KeeperException, IOException, InterruptedException {
if (Quotas.quotaZookeeper.equals(path)) {
return true;
}
List<String> children = zk.getChildren(path, false);
if (children.size() == 0) {
zk.delete(path, -1);
String parent = path.substring(0, path.lastIndexOf('/'));
return trimProcQuotas(zk, parent);
} else {
return true;
}
} | [
"private",
"static",
"boolean",
"trimProcQuotas",
"(",
"ZooKeeper",
"zk",
",",
"String",
"path",
")",
"throws",
"KeeperException",
",",
"IOException",
",",
"InterruptedException",
"{",
"if",
"(",
"Quotas",
".",
"quotaZookeeper",
".",
"equals",
"(",
"path",
")",
")",
"{",
"return",
"true",
";",
"}",
"List",
"<",
"String",
">",
"children",
"=",
"zk",
".",
"getChildren",
"(",
"path",
",",
"false",
")",
";",
"if",
"(",
"children",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"zk",
".",
"delete",
"(",
"path",
",",
"-",
"1",
")",
";",
"String",
"parent",
"=",
"path",
".",
"substring",
"(",
"0",
",",
"path",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
";",
"return",
"trimProcQuotas",
"(",
"zk",
",",
"parent",
")",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] | trim the quota tree to recover unwanted tree elements in the quota's tree
@param zk
the zookeeper client
@param path
the path to start from and go up and see if their is any
unwanted parent in the path.
@return true if sucessful
@throws KeeperException
@throws IOException
@throws InterruptedException | [
"trim",
"the",
"quota",
"tree",
"to",
"recover",
"unwanted",
"tree",
"elements",
"in",
"the",
"quota",
"s",
"tree"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeperMain.java#L388-L401 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/metrics/spi/MetricsRecordImpl.java | MetricsRecordImpl.setTag | public void setTag(String tagName, byte tagValue) {
"""
Sets the named tag to the specified value.
@param tagName name of the tag
@param tagValue new value of the tag
@throws MetricsException if the tagName conflicts with the configuration
"""
tagTable.put(tagName, Byte.valueOf(tagValue));
} | java | public void setTag(String tagName, byte tagValue) {
tagTable.put(tagName, Byte.valueOf(tagValue));
} | [
"public",
"void",
"setTag",
"(",
"String",
"tagName",
",",
"byte",
"tagValue",
")",
"{",
"tagTable",
".",
"put",
"(",
"tagName",
",",
"Byte",
".",
"valueOf",
"(",
"tagValue",
")",
")",
";",
"}"
] | Sets the named tag to the specified value.
@param tagName name of the tag
@param tagValue new value of the tag
@throws MetricsException if the tagName conflicts with the configuration | [
"Sets",
"the",
"named",
"tag",
"to",
"the",
"specified",
"value",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/metrics/spi/MetricsRecordImpl.java#L112-L114 |
m-m-m/util | event/src/main/java/net/sf/mmm/util/event/base/AbstractEventBus.java | AbstractEventBus.getEventDispatcherRequired | @SuppressWarnings("unchecked")
protected <E> EventDispatcher<E> getEventDispatcherRequired(Class<E> eventType) {
"""
Gets or creates the {@link EventDispatcher} for the given {@code eventType}.
@param <E> is the generic type of {@code eventType}.
@param eventType is the {@link Class} reflecting the {@link net.sf.mmm.util.event.api.Event event}.
@return the {@link EventDispatcher} responsible for the given {@code eventType}.
"""
return getEventDispatcher(eventType, true);
} | java | @SuppressWarnings("unchecked")
protected <E> EventDispatcher<E> getEventDispatcherRequired(Class<E> eventType) {
return getEventDispatcher(eventType, true);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"<",
"E",
">",
"EventDispatcher",
"<",
"E",
">",
"getEventDispatcherRequired",
"(",
"Class",
"<",
"E",
">",
"eventType",
")",
"{",
"return",
"getEventDispatcher",
"(",
"eventType",
",",
"true",
")",
";",
"}"
] | Gets or creates the {@link EventDispatcher} for the given {@code eventType}.
@param <E> is the generic type of {@code eventType}.
@param eventType is the {@link Class} reflecting the {@link net.sf.mmm.util.event.api.Event event}.
@return the {@link EventDispatcher} responsible for the given {@code eventType}. | [
"Gets",
"or",
"creates",
"the",
"{",
"@link",
"EventDispatcher",
"}",
"for",
"the",
"given",
"{",
"@code",
"eventType",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/event/src/main/java/net/sf/mmm/util/event/base/AbstractEventBus.java#L179-L183 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java | CPOptionCategoryPersistenceImpl.fetchByUUID_G | @Override
public CPOptionCategory fetchByUUID_G(String uuid, long groupId) {
"""
Returns the cp option category where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp option category, or <code>null</code> if a matching cp option category could not be found
"""
return fetchByUUID_G(uuid, groupId, true);
} | java | @Override
public CPOptionCategory fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | [
"@",
"Override",
"public",
"CPOptionCategory",
"fetchByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"{",
"return",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
",",
"true",
")",
";",
"}"
] | Returns the cp option category where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp option category, or <code>null</code> if a matching cp option category could not be found | [
"Returns",
"the",
"cp",
"option",
"category",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
"finder",
"cache",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionCategoryPersistenceImpl.java#L702-L705 |
dadoonet/testcontainers-java-module-elasticsearch | src/main/java/fr/pilato/elasticsearch/containers/ElasticsearchContainer.java | ElasticsearchContainer.withSecureSetting | public ElasticsearchContainer withSecureSetting(String key, String value) {
"""
Define the elasticsearch docker registry base url
@param key Key
@param value Value
@return this
"""
securedKeys.put(key, value);
return this;
} | java | public ElasticsearchContainer withSecureSetting(String key, String value) {
securedKeys.put(key, value);
return this;
} | [
"public",
"ElasticsearchContainer",
"withSecureSetting",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"securedKeys",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Define the elasticsearch docker registry base url
@param key Key
@param value Value
@return this | [
"Define",
"the",
"elasticsearch",
"docker",
"registry",
"base",
"url"
] | train | https://github.com/dadoonet/testcontainers-java-module-elasticsearch/blob/780eec66c2999a1e4814f039b2a4559d6a5da408/src/main/java/fr/pilato/elasticsearch/containers/ElasticsearchContainer.java#L93-L96 |
OpenLiberty/open-liberty | dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java | SessionManager.modified | protected void modified(Map<?, ?> properties) {
"""
DS method for runtime updates to configuration without stopping and
restarting the component.
@param properties
"""
if (properties instanceof Dictionary) {
processConfig((Dictionary<?, ?>) properties);
} else {
Dictionary<?, ?> newconfig = new Hashtable<Object, Object>(properties);
processConfig(newconfig);
}
} | java | protected void modified(Map<?, ?> properties) {
if (properties instanceof Dictionary) {
processConfig((Dictionary<?, ?>) properties);
} else {
Dictionary<?, ?> newconfig = new Hashtable<Object, Object>(properties);
processConfig(newconfig);
}
} | [
"protected",
"void",
"modified",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"properties",
")",
"{",
"if",
"(",
"properties",
"instanceof",
"Dictionary",
")",
"{",
"processConfig",
"(",
"(",
"Dictionary",
"<",
"?",
",",
"?",
">",
")",
"properties",
")",
";",
"}",
"else",
"{",
"Dictionary",
"<",
"?",
",",
"?",
">",
"newconfig",
"=",
"new",
"Hashtable",
"<",
"Object",
",",
"Object",
">",
"(",
"properties",
")",
";",
"processConfig",
"(",
"newconfig",
")",
";",
"}",
"}"
] | DS method for runtime updates to configuration without stopping and
restarting the component.
@param properties | [
"DS",
"method",
"for",
"runtime",
"updates",
"to",
"configuration",
"without",
"stopping",
"and",
"restarting",
"the",
"component",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java#L97-L104 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/StringUtil.java | StringUtil.rtrim | public static String rtrim(String str, String defaultValue) {
"""
This function returns a string with whitespace stripped from the end of str
@param str String to clean
@return cleaned String
"""
if (str == null) return defaultValue;
int len = str.length();
while ((0 < len) && (str.charAt(len - 1) <= ' ')) {
len--;
}
return (len < str.length()) ? str.substring(0, len) : str;
} | java | public static String rtrim(String str, String defaultValue) {
if (str == null) return defaultValue;
int len = str.length();
while ((0 < len) && (str.charAt(len - 1) <= ' ')) {
len--;
}
return (len < str.length()) ? str.substring(0, len) : str;
} | [
"public",
"static",
"String",
"rtrim",
"(",
"String",
"str",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"return",
"defaultValue",
";",
"int",
"len",
"=",
"str",
".",
"length",
"(",
")",
";",
"while",
"(",
"(",
"0",
"<",
"len",
")",
"&&",
"(",
"str",
".",
"charAt",
"(",
"len",
"-",
"1",
")",
"<=",
"'",
"'",
")",
")",
"{",
"len",
"--",
";",
"}",
"return",
"(",
"len",
"<",
"str",
".",
"length",
"(",
")",
")",
"?",
"str",
".",
"substring",
"(",
"0",
",",
"len",
")",
":",
"str",
";",
"}"
] | This function returns a string with whitespace stripped from the end of str
@param str String to clean
@return cleaned String | [
"This",
"function",
"returns",
"a",
"string",
"with",
"whitespace",
"stripped",
"from",
"the",
"end",
"of",
"str"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L500-L508 |
OSSIndex/heuristic-version | src/main/java/net/ossindex/version/impl/SemanticVersion.java | SemanticVersion.getNextVersion | public SemanticVersion getNextVersion() {
"""
Get the next logical version in line. For example:
1.2.3 becomes 1.2.4
"""
int major = head.getMajorVersion();
int minor = head.getMinorVersion();
int patch = head.getPatchVersion();
return new SemanticVersion(major, minor, patch + 1);
} | java | public SemanticVersion getNextVersion() {
int major = head.getMajorVersion();
int minor = head.getMinorVersion();
int patch = head.getPatchVersion();
return new SemanticVersion(major, minor, patch + 1);
} | [
"public",
"SemanticVersion",
"getNextVersion",
"(",
")",
"{",
"int",
"major",
"=",
"head",
".",
"getMajorVersion",
"(",
")",
";",
"int",
"minor",
"=",
"head",
".",
"getMinorVersion",
"(",
")",
";",
"int",
"patch",
"=",
"head",
".",
"getPatchVersion",
"(",
")",
";",
"return",
"new",
"SemanticVersion",
"(",
"major",
",",
"minor",
",",
"patch",
"+",
"1",
")",
";",
"}"
] | Get the next logical version in line. For example:
1.2.3 becomes 1.2.4 | [
"Get",
"the",
"next",
"logical",
"version",
"in",
"line",
".",
"For",
"example",
":"
] | train | https://github.com/OSSIndex/heuristic-version/blob/9fe33a49d74acec54ddb91de9a3c3cd2f98fba40/src/main/java/net/ossindex/version/impl/SemanticVersion.java#L278-L283 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/AbstractVirtualHostBuilder.java | AbstractVirtualHostBuilder.accessLogger | public B accessLogger(Function<VirtualHost, Logger> mapper) {
"""
Sets the access logger mapper of this {@link VirtualHost}.
When {@link #build()} is called, this {@link VirtualHost} gets {@link Logger}
via the {@code mapper} for writing access logs.
"""
accessLoggerMapper = requireNonNull(mapper, "mapper");
return self();
} | java | public B accessLogger(Function<VirtualHost, Logger> mapper) {
accessLoggerMapper = requireNonNull(mapper, "mapper");
return self();
} | [
"public",
"B",
"accessLogger",
"(",
"Function",
"<",
"VirtualHost",
",",
"Logger",
">",
"mapper",
")",
"{",
"accessLoggerMapper",
"=",
"requireNonNull",
"(",
"mapper",
",",
"\"mapper\"",
")",
";",
"return",
"self",
"(",
")",
";",
"}"
] | Sets the access logger mapper of this {@link VirtualHost}.
When {@link #build()} is called, this {@link VirtualHost} gets {@link Logger}
via the {@code mapper} for writing access logs. | [
"Sets",
"the",
"access",
"logger",
"mapper",
"of",
"this",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/AbstractVirtualHostBuilder.java#L570-L573 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.listMultiRoleMetricsWithServiceResponseAsync | public Observable<ServiceResponse<Page<ResourceMetricInner>>> listMultiRoleMetricsWithServiceResponseAsync(final String resourceGroupName, final String name) {
"""
Get metrics for a multi-role pool of an App Service Environment.
Get metrics for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object
"""
return listMultiRoleMetricsSinglePageAsync(resourceGroupName, name)
.concatMap(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Observable<ServiceResponse<Page<ResourceMetricInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceMetricInner>>> call(ServiceResponse<Page<ResourceMetricInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMultiRoleMetricsNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<ResourceMetricInner>>> listMultiRoleMetricsWithServiceResponseAsync(final String resourceGroupName, final String name) {
return listMultiRoleMetricsSinglePageAsync(resourceGroupName, name)
.concatMap(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Observable<ServiceResponse<Page<ResourceMetricInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceMetricInner>>> call(ServiceResponse<Page<ResourceMetricInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMultiRoleMetricsNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
">",
"listMultiRoleMetricsWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
")",
"{",
"return",
"listMultiRoleMetricsSinglePageAsync",
"(",
"resourceGroupName",
",",
"name",
")",
".",
"concatMap",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
",",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
"page",
")",
"{",
"String",
"nextPageLink",
"=",
"page",
".",
"body",
"(",
")",
".",
"nextPageLink",
"(",
")",
";",
"if",
"(",
"nextPageLink",
"==",
"null",
")",
"{",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
";",
"}",
"return",
"Observable",
".",
"just",
"(",
"page",
")",
".",
"concatWith",
"(",
"listMultiRoleMetricsNextWithServiceResponseAsync",
"(",
"nextPageLink",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get metrics for a multi-role pool of an App Service Environment.
Get metrics for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object | [
"Get",
"metrics",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
".",
"Get",
"metrics",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L3152-L3164 |
alibaba/canal | client-adapter/elasticsearch/src/main/java/com/alibaba/otter/canal/client/adapter/es/support/ESTemplate.java | ESTemplate.delete | public void delete(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
"""
通过主键删除数据
@param mapping 配置对象
@param pkVal 主键值
@param esFieldData 数据Map
"""
if (mapping.get_id() != null) {
getBulk().add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString()));
commitBulk();
} else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(10000)
.get();
for (SearchHit hit : response.getHits()) {
getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.setDoc(esFieldData));
commitBulk();
}
}
} | java | public void delete(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
if (mapping.get_id() != null) {
getBulk().add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString()));
commitBulk();
} else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(10000)
.get();
for (SearchHit hit : response.getHits()) {
getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.setDoc(esFieldData));
commitBulk();
}
}
} | [
"public",
"void",
"delete",
"(",
"ESMapping",
"mapping",
",",
"Object",
"pkVal",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"esFieldData",
")",
"{",
"if",
"(",
"mapping",
".",
"get_id",
"(",
")",
"!=",
"null",
")",
"{",
"getBulk",
"(",
")",
".",
"add",
"(",
"transportClient",
".",
"prepareDelete",
"(",
"mapping",
".",
"get_index",
"(",
")",
",",
"mapping",
".",
"get_type",
"(",
")",
",",
"pkVal",
".",
"toString",
"(",
")",
")",
")",
";",
"commitBulk",
"(",
")",
";",
"}",
"else",
"{",
"SearchResponse",
"response",
"=",
"transportClient",
".",
"prepareSearch",
"(",
"mapping",
".",
"get_index",
"(",
")",
")",
".",
"setTypes",
"(",
"mapping",
".",
"get_type",
"(",
")",
")",
".",
"setQuery",
"(",
"QueryBuilders",
".",
"termQuery",
"(",
"mapping",
".",
"getPk",
"(",
")",
",",
"pkVal",
")",
")",
".",
"setSize",
"(",
"10000",
")",
".",
"get",
"(",
")",
";",
"for",
"(",
"SearchHit",
"hit",
":",
"response",
".",
"getHits",
"(",
")",
")",
"{",
"getBulk",
"(",
")",
".",
"add",
"(",
"transportClient",
".",
"prepareUpdate",
"(",
"mapping",
".",
"get_index",
"(",
")",
",",
"mapping",
".",
"get_type",
"(",
")",
",",
"hit",
".",
"getId",
"(",
")",
")",
".",
"setDoc",
"(",
"esFieldData",
")",
")",
";",
"commitBulk",
"(",
")",
";",
"}",
"}",
"}"
] | 通过主键删除数据
@param mapping 配置对象
@param pkVal 主键值
@param esFieldData 数据Map | [
"通过主键删除数据"
] | train | https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/client-adapter/elasticsearch/src/main/java/com/alibaba/otter/canal/client/adapter/es/support/ESTemplate.java#L175-L192 |
wildfly/wildfly-core | patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchContext.java | IdentityPatchContext.backupDirectory | static void backupDirectory(final File source, final File target) throws IOException {
"""
Backup all xml files in a given directory.
@param source the source directory
@param target the target directory
@throws IOException for any error
"""
if (!target.exists()) {
if (!target.mkdirs()) {
throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath());
}
}
final File[] files = source.listFiles(CONFIG_FILTER);
for (final File file : files) {
final File t = new File(target, file.getName());
IoUtils.copyFile(file, t);
}
} | java | static void backupDirectory(final File source, final File target) throws IOException {
if (!target.exists()) {
if (!target.mkdirs()) {
throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath());
}
}
final File[] files = source.listFiles(CONFIG_FILTER);
for (final File file : files) {
final File t = new File(target, file.getName());
IoUtils.copyFile(file, t);
}
} | [
"static",
"void",
"backupDirectory",
"(",
"final",
"File",
"source",
",",
"final",
"File",
"target",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"target",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"!",
"target",
".",
"mkdirs",
"(",
")",
")",
"{",
"throw",
"PatchLogger",
".",
"ROOT_LOGGER",
".",
"cannotCreateDirectory",
"(",
"target",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"final",
"File",
"[",
"]",
"files",
"=",
"source",
".",
"listFiles",
"(",
"CONFIG_FILTER",
")",
";",
"for",
"(",
"final",
"File",
"file",
":",
"files",
")",
"{",
"final",
"File",
"t",
"=",
"new",
"File",
"(",
"target",
",",
"file",
".",
"getName",
"(",
")",
")",
";",
"IoUtils",
".",
"copyFile",
"(",
"file",
",",
"t",
")",
";",
"}",
"}"
] | Backup all xml files in a given directory.
@param source the source directory
@param target the target directory
@throws IOException for any error | [
"Backup",
"all",
"xml",
"files",
"in",
"a",
"given",
"directory",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchContext.java#L1013-L1024 |
netty/netty | common/src/main/java/io/netty/util/internal/StringUtil.java | StringUtil.toHexString | public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
"""
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
"""
assert length >= 0;
if (length == 0) {
return dst;
}
final int end = offset + length;
final int endMinusOne = end - 1;
int i;
// Skip preceding zeroes.
for (i = offset; i < endMinusOne; i++) {
if (src[i] != 0) {
break;
}
}
byteToHexString(dst, src[i++]);
int remaining = end - i;
toHexStringPadded(dst, src, i, remaining);
return dst;
} | java | public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
assert length >= 0;
if (length == 0) {
return dst;
}
final int end = offset + length;
final int endMinusOne = end - 1;
int i;
// Skip preceding zeroes.
for (i = offset; i < endMinusOne; i++) {
if (src[i] != 0) {
break;
}
}
byteToHexString(dst, src[i++]);
int remaining = end - i;
toHexStringPadded(dst, src, i, remaining);
return dst;
} | [
"public",
"static",
"<",
"T",
"extends",
"Appendable",
">",
"T",
"toHexString",
"(",
"T",
"dst",
",",
"byte",
"[",
"]",
"src",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"assert",
"length",
">=",
"0",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"dst",
";",
"}",
"final",
"int",
"end",
"=",
"offset",
"+",
"length",
";",
"final",
"int",
"endMinusOne",
"=",
"end",
"-",
"1",
";",
"int",
"i",
";",
"// Skip preceding zeroes.",
"for",
"(",
"i",
"=",
"offset",
";",
"i",
"<",
"endMinusOne",
";",
"i",
"++",
")",
"{",
"if",
"(",
"src",
"[",
"i",
"]",
"!=",
"0",
")",
"{",
"break",
";",
"}",
"}",
"byteToHexString",
"(",
"dst",
",",
"src",
"[",
"i",
"++",
"]",
")",
";",
"int",
"remaining",
"=",
"end",
"-",
"i",
";",
"toHexStringPadded",
"(",
"dst",
",",
"src",
",",
"i",
",",
"remaining",
")",
";",
"return",
"dst",
";",
"}"
] | Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. | [
"Converts",
"the",
"specified",
"byte",
"array",
"into",
"a",
"hexadecimal",
"value",
"and",
"appends",
"it",
"to",
"the",
"specified",
"buffer",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/StringUtil.java#L181-L203 |
Azure/azure-sdk-for-java | notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NotificationHubsInner.java | NotificationHubsInner.checkAvailabilityAsync | public Observable<CheckAvailabilityResultInner> checkAvailabilityAsync(String resourceGroupName, String namespaceName, CheckAvailabilityParameters parameters) {
"""
Checks the availability of the given notificationHub in a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param parameters The notificationHub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CheckAvailabilityResultInner object
"""
return checkAvailabilityWithServiceResponseAsync(resourceGroupName, namespaceName, parameters).map(new Func1<ServiceResponse<CheckAvailabilityResultInner>, CheckAvailabilityResultInner>() {
@Override
public CheckAvailabilityResultInner call(ServiceResponse<CheckAvailabilityResultInner> response) {
return response.body();
}
});
} | java | public Observable<CheckAvailabilityResultInner> checkAvailabilityAsync(String resourceGroupName, String namespaceName, CheckAvailabilityParameters parameters) {
return checkAvailabilityWithServiceResponseAsync(resourceGroupName, namespaceName, parameters).map(new Func1<ServiceResponse<CheckAvailabilityResultInner>, CheckAvailabilityResultInner>() {
@Override
public CheckAvailabilityResultInner call(ServiceResponse<CheckAvailabilityResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"CheckAvailabilityResultInner",
">",
"checkAvailabilityAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"namespaceName",
",",
"CheckAvailabilityParameters",
"parameters",
")",
"{",
"return",
"checkAvailabilityWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"namespaceName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"CheckAvailabilityResultInner",
">",
",",
"CheckAvailabilityResultInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"CheckAvailabilityResultInner",
"call",
"(",
"ServiceResponse",
"<",
"CheckAvailabilityResultInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Checks the availability of the given notificationHub in a namespace.
@param resourceGroupName The name of the resource group.
@param namespaceName The namespace name.
@param parameters The notificationHub name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CheckAvailabilityResultInner object | [
"Checks",
"the",
"availability",
"of",
"the",
"given",
"notificationHub",
"in",
"a",
"namespace",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/notificationhubs/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/notificationhubs/v2016_03_01/implementation/NotificationHubsInner.java#L165-L172 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java | Character.offsetByCodePoints | public static int offsetByCodePoints(char[] a, int start, int count,
int index, int codePointOffset) {
"""
Returns the index within the given {@code char} subarray
that is offset from the given {@code index} by
{@code codePointOffset} code points. The
{@code start} and {@code count} arguments specify a
subarray of the {@code char} array. Unpaired surrogates
within the text range given by {@code index} and
{@code codePointOffset} count as one code point each.
@param a the {@code char} array
@param start the index of the first {@code char} of the
subarray
@param count the length of the subarray in {@code char}s
@param index the index to be offset
@param codePointOffset the offset in code points
@return the index within the subarray
@exception NullPointerException if {@code a} is null.
@exception IndexOutOfBoundsException
if {@code start} or {@code count} is negative,
or if {@code start + count} is larger than the length of
the given array,
or if {@code index} is less than {@code start} or
larger then {@code start + count},
or if {@code codePointOffset} is positive and the text range
starting with {@code index} and ending with {@code start + count - 1}
has fewer than {@code codePointOffset} code
points,
or if {@code codePointOffset} is negative and the text range
starting with {@code start} and ending with {@code index - 1}
has fewer than the absolute value of
{@code codePointOffset} code points.
@since 1.5
"""
if (count > a.length-start || start < 0 || count < 0
|| index < start || index > start+count) {
throw new IndexOutOfBoundsException();
}
return offsetByCodePointsImpl(a, start, count, index, codePointOffset);
} | java | public static int offsetByCodePoints(char[] a, int start, int count,
int index, int codePointOffset) {
if (count > a.length-start || start < 0 || count < 0
|| index < start || index > start+count) {
throw new IndexOutOfBoundsException();
}
return offsetByCodePointsImpl(a, start, count, index, codePointOffset);
} | [
"public",
"static",
"int",
"offsetByCodePoints",
"(",
"char",
"[",
"]",
"a",
",",
"int",
"start",
",",
"int",
"count",
",",
"int",
"index",
",",
"int",
"codePointOffset",
")",
"{",
"if",
"(",
"count",
">",
"a",
".",
"length",
"-",
"start",
"||",
"start",
"<",
"0",
"||",
"count",
"<",
"0",
"||",
"index",
"<",
"start",
"||",
"index",
">",
"start",
"+",
"count",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"return",
"offsetByCodePointsImpl",
"(",
"a",
",",
"start",
",",
"count",
",",
"index",
",",
"codePointOffset",
")",
";",
"}"
] | Returns the index within the given {@code char} subarray
that is offset from the given {@code index} by
{@code codePointOffset} code points. The
{@code start} and {@code count} arguments specify a
subarray of the {@code char} array. Unpaired surrogates
within the text range given by {@code index} and
{@code codePointOffset} count as one code point each.
@param a the {@code char} array
@param start the index of the first {@code char} of the
subarray
@param count the length of the subarray in {@code char}s
@param index the index to be offset
@param codePointOffset the offset in code points
@return the index within the subarray
@exception NullPointerException if {@code a} is null.
@exception IndexOutOfBoundsException
if {@code start} or {@code count} is negative,
or if {@code start + count} is larger than the length of
the given array,
or if {@code index} is less than {@code start} or
larger then {@code start + count},
or if {@code codePointOffset} is positive and the text range
starting with {@code index} and ending with {@code start + count - 1}
has fewer than {@code codePointOffset} code
points,
or if {@code codePointOffset} is negative and the text range
starting with {@code start} and ending with {@code index - 1}
has fewer than the absolute value of
{@code codePointOffset} code points.
@since 1.5 | [
"Returns",
"the",
"index",
"within",
"the",
"given",
"{",
"@code",
"char",
"}",
"subarray",
"that",
"is",
"offset",
"from",
"the",
"given",
"{",
"@code",
"index",
"}",
"by",
"{",
"@code",
"codePointOffset",
"}",
"code",
"points",
".",
"The",
"{",
"@code",
"start",
"}",
"and",
"{",
"@code",
"count",
"}",
"arguments",
"specify",
"a",
"subarray",
"of",
"the",
"{",
"@code",
"char",
"}",
"array",
".",
"Unpaired",
"surrogates",
"within",
"the",
"text",
"range",
"given",
"by",
"{",
"@code",
"index",
"}",
"and",
"{",
"@code",
"codePointOffset",
"}",
"count",
"as",
"one",
"code",
"point",
"each",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java#L5410-L5417 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.getErasedTypeTree | public static Tree getErasedTypeTree(Tree tree) {
"""
Returns the erasure of the given type tree, i.e. {@code List} for {@code List<Foo>}.
"""
return tree.accept(
new SimpleTreeVisitor<Tree, Void>() {
@Override
public Tree visitIdentifier(IdentifierTree tree, Void unused) {
return tree;
}
@Override
public Tree visitParameterizedType(ParameterizedTypeTree tree, Void unused) {
return tree.getType();
}
},
null);
} | java | public static Tree getErasedTypeTree(Tree tree) {
return tree.accept(
new SimpleTreeVisitor<Tree, Void>() {
@Override
public Tree visitIdentifier(IdentifierTree tree, Void unused) {
return tree;
}
@Override
public Tree visitParameterizedType(ParameterizedTypeTree tree, Void unused) {
return tree.getType();
}
},
null);
} | [
"public",
"static",
"Tree",
"getErasedTypeTree",
"(",
"Tree",
"tree",
")",
"{",
"return",
"tree",
".",
"accept",
"(",
"new",
"SimpleTreeVisitor",
"<",
"Tree",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Tree",
"visitIdentifier",
"(",
"IdentifierTree",
"tree",
",",
"Void",
"unused",
")",
"{",
"return",
"tree",
";",
"}",
"@",
"Override",
"public",
"Tree",
"visitParameterizedType",
"(",
"ParameterizedTypeTree",
"tree",
",",
"Void",
"unused",
")",
"{",
"return",
"tree",
".",
"getType",
"(",
")",
";",
"}",
"}",
",",
"null",
")",
";",
"}"
] | Returns the erasure of the given type tree, i.e. {@code List} for {@code List<Foo>}. | [
"Returns",
"the",
"erasure",
"of",
"the",
"given",
"type",
"tree",
"i",
".",
"e",
".",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L862-L876 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.removeByUUID_G | @Override
public CommerceCurrency removeByUUID_G(String uuid, long groupId)
throws NoSuchCurrencyException {
"""
Removes the commerce currency where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce currency that was removed
"""
CommerceCurrency commerceCurrency = findByUUID_G(uuid, groupId);
return remove(commerceCurrency);
} | java | @Override
public CommerceCurrency removeByUUID_G(String uuid, long groupId)
throws NoSuchCurrencyException {
CommerceCurrency commerceCurrency = findByUUID_G(uuid, groupId);
return remove(commerceCurrency);
} | [
"@",
"Override",
"public",
"CommerceCurrency",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCurrencyException",
"{",
"CommerceCurrency",
"commerceCurrency",
"=",
"findByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"return",
"remove",
"(",
"commerceCurrency",
")",
";",
"}"
] | Removes the commerce currency where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce currency that was removed | [
"Removes",
"the",
"commerce",
"currency",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L812-L818 |
mgm-tp/jfunk | jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ModuleArchiver.java | ModuleArchiver.addToArchive | public void addToArchive(final File relativeDir, final File fileOrDirToAdd) throws IOException {
"""
Adds a file or directory (recursively) to the archive directory if it is not already present
in the archive directory.
@param relativeDir
the directory relative to the archive root directory which the specified file or
directory is added to
@param fileOrDirToAdd
the file or directory to add
@throws IOException
if an IO error occurs during copying
"""
checkArgument(!relativeDir.isAbsolute(), "'relativeDir' must be a relative directory");
if (isArchivingDisabled()) {
return;
}
if (fileOrDirToAdd.getCanonicalPath().startsWith(moduleArchiveDir.getCanonicalPath())) {
// File already in archive dir
log.info("File '" + fileOrDirToAdd + "' already in archive directory. No copying necessary.");
return;
}
File archiveTargetDir = new File(moduleArchiveDir, relativeDir.getPath());
if (fileOrDirToAdd.isDirectory()) {
copyDirectory(fileOrDirToAdd, archiveTargetDir);
} else {
copyFileToDirectory(fileOrDirToAdd, archiveTargetDir);
}
} | java | public void addToArchive(final File relativeDir, final File fileOrDirToAdd) throws IOException {
checkArgument(!relativeDir.isAbsolute(), "'relativeDir' must be a relative directory");
if (isArchivingDisabled()) {
return;
}
if (fileOrDirToAdd.getCanonicalPath().startsWith(moduleArchiveDir.getCanonicalPath())) {
// File already in archive dir
log.info("File '" + fileOrDirToAdd + "' already in archive directory. No copying necessary.");
return;
}
File archiveTargetDir = new File(moduleArchiveDir, relativeDir.getPath());
if (fileOrDirToAdd.isDirectory()) {
copyDirectory(fileOrDirToAdd, archiveTargetDir);
} else {
copyFileToDirectory(fileOrDirToAdd, archiveTargetDir);
}
} | [
"public",
"void",
"addToArchive",
"(",
"final",
"File",
"relativeDir",
",",
"final",
"File",
"fileOrDirToAdd",
")",
"throws",
"IOException",
"{",
"checkArgument",
"(",
"!",
"relativeDir",
".",
"isAbsolute",
"(",
")",
",",
"\"'relativeDir' must be a relative directory\"",
")",
";",
"if",
"(",
"isArchivingDisabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"fileOrDirToAdd",
".",
"getCanonicalPath",
"(",
")",
".",
"startsWith",
"(",
"moduleArchiveDir",
".",
"getCanonicalPath",
"(",
")",
")",
")",
"{",
"// File already in archive dir",
"log",
".",
"info",
"(",
"\"File '\"",
"+",
"fileOrDirToAdd",
"+",
"\"' already in archive directory. No copying necessary.\"",
")",
";",
"return",
";",
"}",
"File",
"archiveTargetDir",
"=",
"new",
"File",
"(",
"moduleArchiveDir",
",",
"relativeDir",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"fileOrDirToAdd",
".",
"isDirectory",
"(",
")",
")",
"{",
"copyDirectory",
"(",
"fileOrDirToAdd",
",",
"archiveTargetDir",
")",
";",
"}",
"else",
"{",
"copyFileToDirectory",
"(",
"fileOrDirToAdd",
",",
"archiveTargetDir",
")",
";",
"}",
"}"
] | Adds a file or directory (recursively) to the archive directory if it is not already present
in the archive directory.
@param relativeDir
the directory relative to the archive root directory which the specified file or
directory is added to
@param fileOrDirToAdd
the file or directory to add
@throws IOException
if an IO error occurs during copying | [
"Adds",
"a",
"file",
"or",
"directory",
"(",
"recursively",
")",
"to",
"the",
"archive",
"directory",
"if",
"it",
"is",
"not",
"already",
"present",
"in",
"the",
"archive",
"directory",
"."
] | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ModuleArchiver.java#L250-L269 |
ixa-ehu/kaflib | src/main/java/ixa/kaflib/KAFDocument.java | KAFDocument.newDep | public Dep newDep(Term from, Term to, String rfunc) {
"""
Creates a new dependency. The Dep is added to the document object.
@param from the origin term of the dependency.
@param to the target term of the dependency.
@param rfunc relational function of the dependency.
@return a new dependency.
"""
Dep newDep = new Dep(from, to, rfunc);
annotationContainer.add(newDep, Layer.DEPS, AnnotationType.DEP);
return newDep;
} | java | public Dep newDep(Term from, Term to, String rfunc) {
Dep newDep = new Dep(from, to, rfunc);
annotationContainer.add(newDep, Layer.DEPS, AnnotationType.DEP);
return newDep;
} | [
"public",
"Dep",
"newDep",
"(",
"Term",
"from",
",",
"Term",
"to",
",",
"String",
"rfunc",
")",
"{",
"Dep",
"newDep",
"=",
"new",
"Dep",
"(",
"from",
",",
"to",
",",
"rfunc",
")",
";",
"annotationContainer",
".",
"add",
"(",
"newDep",
",",
"Layer",
".",
"DEPS",
",",
"AnnotationType",
".",
"DEP",
")",
";",
"return",
"newDep",
";",
"}"
] | Creates a new dependency. The Dep is added to the document object.
@param from the origin term of the dependency.
@param to the target term of the dependency.
@param rfunc relational function of the dependency.
@return a new dependency. | [
"Creates",
"a",
"new",
"dependency",
".",
"The",
"Dep",
"is",
"added",
"to",
"the",
"document",
"object",
"."
] | train | https://github.com/ixa-ehu/kaflib/blob/3921f55d9ae4621736a329418f6334fb721834b8/src/main/java/ixa/kaflib/KAFDocument.java#L691-L695 |
cdk/cdk | tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java | MmffAromaticTypeMapping.updateAromaticTypesInSixMemberRing | static void updateAromaticTypesInSixMemberRing(int[] cycle, String[] symbs) {
"""
Update aromatic atom types in a six member ring. The aromatic types here are hard coded from
the 'MMFFAROM.PAR' file.
@param cycle 6-member aromatic cycle / ring
@param symbs vector of symbolic types for the whole structure
"""
for (final int v : cycle) {
if (NCN_PLUS.equals(symbs[v]) || "N+=C".equals(symbs[v]) || "N=+C".equals(symbs[v]))
symbs[v] = "NPD+";
else if ("N2OX".equals(symbs[v]))
symbs[v] = "NPOX";
else if ("N=C".equals(symbs[v]) || "N=N".equals(symbs[v]))
symbs[v] = "NPYD";
else if (symbs[v].startsWith("C")) symbs[v] = "CB";
}
} | java | static void updateAromaticTypesInSixMemberRing(int[] cycle, String[] symbs) {
for (final int v : cycle) {
if (NCN_PLUS.equals(symbs[v]) || "N+=C".equals(symbs[v]) || "N=+C".equals(symbs[v]))
symbs[v] = "NPD+";
else if ("N2OX".equals(symbs[v]))
symbs[v] = "NPOX";
else if ("N=C".equals(symbs[v]) || "N=N".equals(symbs[v]))
symbs[v] = "NPYD";
else if (symbs[v].startsWith("C")) symbs[v] = "CB";
}
} | [
"static",
"void",
"updateAromaticTypesInSixMemberRing",
"(",
"int",
"[",
"]",
"cycle",
",",
"String",
"[",
"]",
"symbs",
")",
"{",
"for",
"(",
"final",
"int",
"v",
":",
"cycle",
")",
"{",
"if",
"(",
"NCN_PLUS",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
"||",
"\"N+=C\"",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
"||",
"\"N=+C\"",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
")",
"symbs",
"[",
"v",
"]",
"=",
"\"NPD+\"",
";",
"else",
"if",
"(",
"\"N2OX\"",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
")",
"symbs",
"[",
"v",
"]",
"=",
"\"NPOX\"",
";",
"else",
"if",
"(",
"\"N=C\"",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
"||",
"\"N=N\"",
".",
"equals",
"(",
"symbs",
"[",
"v",
"]",
")",
")",
"symbs",
"[",
"v",
"]",
"=",
"\"NPYD\"",
";",
"else",
"if",
"(",
"symbs",
"[",
"v",
"]",
".",
"startsWith",
"(",
"\"C\"",
")",
")",
"symbs",
"[",
"v",
"]",
"=",
"\"CB\"",
";",
"}",
"}"
] | Update aromatic atom types in a six member ring. The aromatic types here are hard coded from
the 'MMFFAROM.PAR' file.
@param cycle 6-member aromatic cycle / ring
@param symbs vector of symbolic types for the whole structure | [
"Update",
"aromatic",
"atom",
"types",
"in",
"a",
"six",
"member",
"ring",
".",
"The",
"aromatic",
"types",
"here",
"are",
"hard",
"coded",
"from",
"the",
"MMFFAROM",
".",
"PAR",
"file",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java#L225-L235 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaasqueue/src/main/java/net/minidev/ovh/api/ApiOvhDbaasqueue.java | ApiOvhDbaasqueue.serviceName_region_regionId_GET | public OvhRegion serviceName_region_regionId_GET(String serviceName, String regionId) throws IOException {
"""
Get one region
REST: GET /dbaas/queue/{serviceName}/region/{regionId}
@param serviceName [required] Application ID
@param regionId [required] Region ID
API beta
"""
String qPath = "/dbaas/queue/{serviceName}/region/{regionId}";
StringBuilder sb = path(qPath, serviceName, regionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRegion.class);
} | java | public OvhRegion serviceName_region_regionId_GET(String serviceName, String regionId) throws IOException {
String qPath = "/dbaas/queue/{serviceName}/region/{regionId}";
StringBuilder sb = path(qPath, serviceName, regionId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRegion.class);
} | [
"public",
"OvhRegion",
"serviceName_region_regionId_GET",
"(",
"String",
"serviceName",
",",
"String",
"regionId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dbaas/queue/{serviceName}/region/{regionId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"regionId",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhRegion",
".",
"class",
")",
";",
"}"
] | Get one region
REST: GET /dbaas/queue/{serviceName}/region/{regionId}
@param serviceName [required] Application ID
@param regionId [required] Region ID
API beta | [
"Get",
"one",
"region"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaasqueue/src/main/java/net/minidev/ovh/api/ApiOvhDbaasqueue.java#L303-L308 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/FileUtils.java | FileUtils.copyDir | public static void copyDir(File from, File to) throws FileNotFoundException, IOException {
"""
Recursively copy the files from one dir to the other.
@param from The directory to copy from, must exist.
@param to The directory to copy to, must exist, must be empty.
@throws IOException
@throws FileNotFoundException
"""
File[] files = from.listFiles();
if (files != null) {
for (File ff : files) {
File tf = new File(to, ff.getName());
if (ff.isDirectory()) {
if (tf.mkdir()) {
copyDir(ff, tf);
}
} else if (ff.isFile()) {
copyFile(tf, ff);
}
}
}
} | java | public static void copyDir(File from, File to) throws FileNotFoundException, IOException {
File[] files = from.listFiles();
if (files != null) {
for (File ff : files) {
File tf = new File(to, ff.getName());
if (ff.isDirectory()) {
if (tf.mkdir()) {
copyDir(ff, tf);
}
} else if (ff.isFile()) {
copyFile(tf, ff);
}
}
}
} | [
"public",
"static",
"void",
"copyDir",
"(",
"File",
"from",
",",
"File",
"to",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"File",
"[",
"]",
"files",
"=",
"from",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"files",
"!=",
"null",
")",
"{",
"for",
"(",
"File",
"ff",
":",
"files",
")",
"{",
"File",
"tf",
"=",
"new",
"File",
"(",
"to",
",",
"ff",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"ff",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"tf",
".",
"mkdir",
"(",
")",
")",
"{",
"copyDir",
"(",
"ff",
",",
"tf",
")",
";",
"}",
"}",
"else",
"if",
"(",
"ff",
".",
"isFile",
"(",
")",
")",
"{",
"copyFile",
"(",
"tf",
",",
"ff",
")",
";",
"}",
"}",
"}",
"}"
] | Recursively copy the files from one dir to the other.
@param from The directory to copy from, must exist.
@param to The directory to copy to, must exist, must be empty.
@throws IOException
@throws FileNotFoundException | [
"Recursively",
"copy",
"the",
"files",
"from",
"one",
"dir",
"to",
"the",
"other",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/FileUtils.java#L162-L177 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java | CacheManager.cleanAreaAsync | public CacheManagerTask cleanAreaAsync(final Context ctx, ArrayList<GeoPoint> geoPoints, int zoomMin, int zoomMax) {
"""
Remove all cached tiles covered by the GeoPoints list.
@param ctx
@param geoPoints
@param zoomMin
@param zoomMax
"""
BoundingBox extendedBounds = extendedBoundsFromGeoPoints(geoPoints,zoomMin);
return cleanAreaAsync(ctx, extendedBounds, zoomMin, zoomMax);
} | java | public CacheManagerTask cleanAreaAsync(final Context ctx, ArrayList<GeoPoint> geoPoints, int zoomMin, int zoomMax) {
BoundingBox extendedBounds = extendedBoundsFromGeoPoints(geoPoints,zoomMin);
return cleanAreaAsync(ctx, extendedBounds, zoomMin, zoomMax);
} | [
"public",
"CacheManagerTask",
"cleanAreaAsync",
"(",
"final",
"Context",
"ctx",
",",
"ArrayList",
"<",
"GeoPoint",
">",
"geoPoints",
",",
"int",
"zoomMin",
",",
"int",
"zoomMax",
")",
"{",
"BoundingBox",
"extendedBounds",
"=",
"extendedBoundsFromGeoPoints",
"(",
"geoPoints",
",",
"zoomMin",
")",
";",
"return",
"cleanAreaAsync",
"(",
"ctx",
",",
"extendedBounds",
",",
"zoomMin",
",",
"zoomMax",
")",
";",
"}"
] | Remove all cached tiles covered by the GeoPoints list.
@param ctx
@param geoPoints
@param zoomMin
@param zoomMax | [
"Remove",
"all",
"cached",
"tiles",
"covered",
"by",
"the",
"GeoPoints",
"list",
"."
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/cachemanager/CacheManager.java#L905-L908 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-classloader/xwiki-commons-classloader-api/src/main/java/org/xwiki/classloader/internal/ResourceLoader.java | ResourceLoader.getResource | public ResourceHandle getResource(URL source, String name) {
"""
Gets resource with given name at the given source URL. If the URL points to a directory, the name is the file
path relative to this directory. If the URL points to a JAR file, the name identifies an entry in that JAR file.
If the URL points to a JAR file, the resource is not found in that JAR file, and the JAR file has Class-Path
attribute, the JAR files identified in the Class-Path are also searched for the resource.
@param source the source URL
@param name the resource name
@return handle representing the resource, or null if not found
"""
return getResource(source, name, new HashSet<>(), null);
} | java | public ResourceHandle getResource(URL source, String name)
{
return getResource(source, name, new HashSet<>(), null);
} | [
"public",
"ResourceHandle",
"getResource",
"(",
"URL",
"source",
",",
"String",
"name",
")",
"{",
"return",
"getResource",
"(",
"source",
",",
"name",
",",
"new",
"HashSet",
"<>",
"(",
")",
",",
"null",
")",
";",
"}"
] | Gets resource with given name at the given source URL. If the URL points to a directory, the name is the file
path relative to this directory. If the URL points to a JAR file, the name identifies an entry in that JAR file.
If the URL points to a JAR file, the resource is not found in that JAR file, and the JAR file has Class-Path
attribute, the JAR files identified in the Class-Path are also searched for the resource.
@param source the source URL
@param name the resource name
@return handle representing the resource, or null if not found | [
"Gets",
"resource",
"with",
"given",
"name",
"at",
"the",
"given",
"source",
"URL",
".",
"If",
"the",
"URL",
"points",
"to",
"a",
"directory",
"the",
"name",
"is",
"the",
"file",
"path",
"relative",
"to",
"this",
"directory",
".",
"If",
"the",
"URL",
"points",
"to",
"a",
"JAR",
"file",
"the",
"name",
"identifies",
"an",
"entry",
"in",
"that",
"JAR",
"file",
".",
"If",
"the",
"URL",
"points",
"to",
"a",
"JAR",
"file",
"the",
"resource",
"is",
"not",
"found",
"in",
"that",
"JAR",
"file",
"and",
"the",
"JAR",
"file",
"has",
"Class",
"-",
"Path",
"attribute",
"the",
"JAR",
"files",
"identified",
"in",
"the",
"Class",
"-",
"Path",
"are",
"also",
"searched",
"for",
"the",
"resource",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-classloader/xwiki-commons-classloader-api/src/main/java/org/xwiki/classloader/internal/ResourceLoader.java#L115-L118 |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/LocalScanUploadMonitor.java | LocalScanUploadMonitor.resplitPartiallyCompleteTasks | private ScanStatus resplitPartiallyCompleteTasks(ScanStatus status) {
"""
Checks whether any completed tasks returned before scanning the entire range. If so then the unscanned
ranges are resplit and new tasks are created from them.
"""
boolean anyUpdated = false;
int nextTaskId = -1;
for (ScanRangeStatus complete : status.getCompleteScanRanges()) {
if (complete.getResplitRange().isPresent()) {
// This task only partially completed; there are still more data to scan.
if (nextTaskId == -1) {
nextTaskId = getNextTaskId(status);
}
ScanRange resplitRange = complete.getResplitRange().get();
// Resplit the un-scanned portion into new ranges
List<ScanRange> subRanges = resplit(complete.getPlacement(), resplitRange, status.getOptions().getRangeScanSplitSize());
// Create new tasks for each subrange that are immediately available for being queued.
List<ScanRangeStatus> resplitStatuses = Lists.newArrayListWithCapacity(subRanges.size());
for (ScanRange subRange : subRanges) {
resplitStatuses.add(
new ScanRangeStatus(nextTaskId++, complete.getPlacement(), subRange,
complete.getBatchId(), complete.getBlockedByBatchId(), complete.getConcurrencyId()));
}
_scanStatusDAO.resplitScanRangeTask(status.getScanId(), complete.getTaskId(), resplitStatuses);
anyUpdated = true;
}
}
if (!anyUpdated) {
return status;
}
// Slightly inefficient to reload but less risky than trying to keep the DAO and in-memory object in sync
return _scanStatusDAO.getScanStatus(status.getScanId());
} | java | private ScanStatus resplitPartiallyCompleteTasks(ScanStatus status) {
boolean anyUpdated = false;
int nextTaskId = -1;
for (ScanRangeStatus complete : status.getCompleteScanRanges()) {
if (complete.getResplitRange().isPresent()) {
// This task only partially completed; there are still more data to scan.
if (nextTaskId == -1) {
nextTaskId = getNextTaskId(status);
}
ScanRange resplitRange = complete.getResplitRange().get();
// Resplit the un-scanned portion into new ranges
List<ScanRange> subRanges = resplit(complete.getPlacement(), resplitRange, status.getOptions().getRangeScanSplitSize());
// Create new tasks for each subrange that are immediately available for being queued.
List<ScanRangeStatus> resplitStatuses = Lists.newArrayListWithCapacity(subRanges.size());
for (ScanRange subRange : subRanges) {
resplitStatuses.add(
new ScanRangeStatus(nextTaskId++, complete.getPlacement(), subRange,
complete.getBatchId(), complete.getBlockedByBatchId(), complete.getConcurrencyId()));
}
_scanStatusDAO.resplitScanRangeTask(status.getScanId(), complete.getTaskId(), resplitStatuses);
anyUpdated = true;
}
}
if (!anyUpdated) {
return status;
}
// Slightly inefficient to reload but less risky than trying to keep the DAO and in-memory object in sync
return _scanStatusDAO.getScanStatus(status.getScanId());
} | [
"private",
"ScanStatus",
"resplitPartiallyCompleteTasks",
"(",
"ScanStatus",
"status",
")",
"{",
"boolean",
"anyUpdated",
"=",
"false",
";",
"int",
"nextTaskId",
"=",
"-",
"1",
";",
"for",
"(",
"ScanRangeStatus",
"complete",
":",
"status",
".",
"getCompleteScanRanges",
"(",
")",
")",
"{",
"if",
"(",
"complete",
".",
"getResplitRange",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"// This task only partially completed; there are still more data to scan.",
"if",
"(",
"nextTaskId",
"==",
"-",
"1",
")",
"{",
"nextTaskId",
"=",
"getNextTaskId",
"(",
"status",
")",
";",
"}",
"ScanRange",
"resplitRange",
"=",
"complete",
".",
"getResplitRange",
"(",
")",
".",
"get",
"(",
")",
";",
"// Resplit the un-scanned portion into new ranges",
"List",
"<",
"ScanRange",
">",
"subRanges",
"=",
"resplit",
"(",
"complete",
".",
"getPlacement",
"(",
")",
",",
"resplitRange",
",",
"status",
".",
"getOptions",
"(",
")",
".",
"getRangeScanSplitSize",
"(",
")",
")",
";",
"// Create new tasks for each subrange that are immediately available for being queued.",
"List",
"<",
"ScanRangeStatus",
">",
"resplitStatuses",
"=",
"Lists",
".",
"newArrayListWithCapacity",
"(",
"subRanges",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"ScanRange",
"subRange",
":",
"subRanges",
")",
"{",
"resplitStatuses",
".",
"add",
"(",
"new",
"ScanRangeStatus",
"(",
"nextTaskId",
"++",
",",
"complete",
".",
"getPlacement",
"(",
")",
",",
"subRange",
",",
"complete",
".",
"getBatchId",
"(",
")",
",",
"complete",
".",
"getBlockedByBatchId",
"(",
")",
",",
"complete",
".",
"getConcurrencyId",
"(",
")",
")",
")",
";",
"}",
"_scanStatusDAO",
".",
"resplitScanRangeTask",
"(",
"status",
".",
"getScanId",
"(",
")",
",",
"complete",
".",
"getTaskId",
"(",
")",
",",
"resplitStatuses",
")",
";",
"anyUpdated",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"!",
"anyUpdated",
")",
"{",
"return",
"status",
";",
"}",
"// Slightly inefficient to reload but less risky than trying to keep the DAO and in-memory object in sync",
"return",
"_scanStatusDAO",
".",
"getScanStatus",
"(",
"status",
".",
"getScanId",
"(",
")",
")",
";",
"}"
] | Checks whether any completed tasks returned before scanning the entire range. If so then the unscanned
ranges are resplit and new tasks are created from them. | [
"Checks",
"whether",
"any",
"completed",
"tasks",
"returned",
"before",
"scanning",
"the",
"entire",
"range",
".",
"If",
"so",
"then",
"the",
"unscanned",
"ranges",
"are",
"resplit",
"and",
"new",
"tasks",
"are",
"created",
"from",
"them",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/LocalScanUploadMonitor.java#L282-L317 |
inferred/FreeBuilder | generated/main/java/org/inferred/freebuilder/processor/Datatype_Builder.java | Datatype_Builder.putStandardMethodUnderrides | public Datatype.Builder putStandardMethodUnderrides(StandardMethod key, UnderrideLevel value) {
"""
Associates {@code key} with {@code value} in the map to be returned from {@link
Datatype#getStandardMethodUnderrides()}. If the map previously contained a mapping for the key,
the old value is replaced by the specified value.
@return this {@code Builder} object
@throws NullPointerException if either {@code key} or {@code value} are null
"""
Objects.requireNonNull(key);
Objects.requireNonNull(value);
standardMethodUnderrides.put(key, value);
return (Datatype.Builder) this;
} | java | public Datatype.Builder putStandardMethodUnderrides(StandardMethod key, UnderrideLevel value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
standardMethodUnderrides.put(key, value);
return (Datatype.Builder) this;
} | [
"public",
"Datatype",
".",
"Builder",
"putStandardMethodUnderrides",
"(",
"StandardMethod",
"key",
",",
"UnderrideLevel",
"value",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"key",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"value",
")",
";",
"standardMethodUnderrides",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"(",
"Datatype",
".",
"Builder",
")",
"this",
";",
"}"
] | Associates {@code key} with {@code value} in the map to be returned from {@link
Datatype#getStandardMethodUnderrides()}. If the map previously contained a mapping for the key,
the old value is replaced by the specified value.
@return this {@code Builder} object
@throws NullPointerException if either {@code key} or {@code value} are null | [
"Associates",
"{",
"@code",
"key",
"}",
"with",
"{",
"@code",
"value",
"}",
"in",
"the",
"map",
"to",
"be",
"returned",
"from",
"{",
"@link",
"Datatype#getStandardMethodUnderrides",
"()",
"}",
".",
"If",
"the",
"map",
"previously",
"contained",
"a",
"mapping",
"for",
"the",
"key",
"the",
"old",
"value",
"is",
"replaced",
"by",
"the",
"specified",
"value",
"."
] | train | https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/generated/main/java/org/inferred/freebuilder/processor/Datatype_Builder.java#L522-L527 |
linkhub-sdk/popbill.sdk.java | src/main/java/com/popbill/api/message/MessageServiceImp.java | MessageServiceImp.sendMMS | @Override
public String sendMMS(String CorpNum, String sender, String receiver,
String receiverName, String subject, String content, File file,
Date reserveDT, String UserID) throws PopbillException {
"""
/*
(non-Javadoc)
@see com.popbill.api.MessageService#sendMMS(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.File, java.util.Date, java.lang.String)
"""
Message message = new Message();
message.setSender(sender);
message.setReceiver(receiver);
message.setReceiverName(receiverName);
message.setContent(content);
message.setSubject(subject);
return sendMMS(CorpNum, new Message[]{message}, file, reserveDT, UserID);
} | java | @Override
public String sendMMS(String CorpNum, String sender, String receiver,
String receiverName, String subject, String content, File file,
Date reserveDT, String UserID) throws PopbillException {
Message message = new Message();
message.setSender(sender);
message.setReceiver(receiver);
message.setReceiverName(receiverName);
message.setContent(content);
message.setSubject(subject);
return sendMMS(CorpNum, new Message[]{message}, file, reserveDT, UserID);
} | [
"@",
"Override",
"public",
"String",
"sendMMS",
"(",
"String",
"CorpNum",
",",
"String",
"sender",
",",
"String",
"receiver",
",",
"String",
"receiverName",
",",
"String",
"subject",
",",
"String",
"content",
",",
"File",
"file",
",",
"Date",
"reserveDT",
",",
"String",
"UserID",
")",
"throws",
"PopbillException",
"{",
"Message",
"message",
"=",
"new",
"Message",
"(",
")",
";",
"message",
".",
"setSender",
"(",
"sender",
")",
";",
"message",
".",
"setReceiver",
"(",
"receiver",
")",
";",
"message",
".",
"setReceiverName",
"(",
"receiverName",
")",
";",
"message",
".",
"setContent",
"(",
"content",
")",
";",
"message",
".",
"setSubject",
"(",
"subject",
")",
";",
"return",
"sendMMS",
"(",
"CorpNum",
",",
"new",
"Message",
"[",
"]",
"{",
"message",
"}",
",",
"file",
",",
"reserveDT",
",",
"UserID",
")",
";",
"}"
] | /*
(non-Javadoc)
@see com.popbill.api.MessageService#sendMMS(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.File, java.util.Date, java.lang.String) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/linkhub-sdk/popbill.sdk.java/blob/63a341fefe96d60a368776638f3d4c81888238b7/src/main/java/com/popbill/api/message/MessageServiceImp.java#L717-L731 |
emilsjolander/StickyListHeaders | library/src/se/emilsjolander/stickylistheaders/ExpandableStickyListHeadersListView.java | ExpandableStickyListHeadersListView.animateView | private void animateView(final View target, final int type) {
"""
Performs either COLLAPSE or EXPAND animation on the target view
@param target the view to animate
@param type the animation type, either ExpandCollapseAnimation.COLLAPSE
or ExpandCollapseAnimation.EXPAND
"""
if(ANIMATION_EXPAND==type&&target.getVisibility()==VISIBLE){
return;
}
if(ANIMATION_COLLAPSE==type&&target.getVisibility()!=VISIBLE){
return;
}
if(mDefaultAnimExecutor !=null){
mDefaultAnimExecutor.executeAnim(target,type);
}
} | java | private void animateView(final View target, final int type) {
if(ANIMATION_EXPAND==type&&target.getVisibility()==VISIBLE){
return;
}
if(ANIMATION_COLLAPSE==type&&target.getVisibility()!=VISIBLE){
return;
}
if(mDefaultAnimExecutor !=null){
mDefaultAnimExecutor.executeAnim(target,type);
}
} | [
"private",
"void",
"animateView",
"(",
"final",
"View",
"target",
",",
"final",
"int",
"type",
")",
"{",
"if",
"(",
"ANIMATION_EXPAND",
"==",
"type",
"&&",
"target",
".",
"getVisibility",
"(",
")",
"==",
"VISIBLE",
")",
"{",
"return",
";",
"}",
"if",
"(",
"ANIMATION_COLLAPSE",
"==",
"type",
"&&",
"target",
".",
"getVisibility",
"(",
")",
"!=",
"VISIBLE",
")",
"{",
"return",
";",
"}",
"if",
"(",
"mDefaultAnimExecutor",
"!=",
"null",
")",
"{",
"mDefaultAnimExecutor",
".",
"executeAnim",
"(",
"target",
",",
"type",
")",
";",
"}",
"}"
] | Performs either COLLAPSE or EXPAND animation on the target view
@param target the view to animate
@param type the animation type, either ExpandCollapseAnimation.COLLAPSE
or ExpandCollapseAnimation.EXPAND | [
"Performs",
"either",
"COLLAPSE",
"or",
"EXPAND",
"animation",
"on",
"the",
"target",
"view"
] | train | https://github.com/emilsjolander/StickyListHeaders/blob/cec8d6a6ddfc29c530df5864794a5a0a2d2f3675/library/src/se/emilsjolander/stickylistheaders/ExpandableStickyListHeadersListView.java#L113-L124 |
alkacon/opencms-core | src/org/opencms/loader/CmsDefaultFileNameGenerator.java | CmsDefaultFileNameGenerator.hasNumberMacro | private static boolean hasNumberMacro(String pattern, String macroStart, String macroEnd) {
"""
Checks the given pattern for the number macro.<p>
@param pattern the pattern to check
@param macroStart the macro start string
@param macroEnd the macro end string
@return <code>true</code> if the pattern contains the macro
"""
String macro = I_CmsFileNameGenerator.MACRO_NUMBER;
String macroPart = macroStart + macro + MACRO_NUMBER_DIGIT_SEPARATOR;
int prefixIndex = pattern.indexOf(macroPart);
if (prefixIndex >= 0) {
// this macro contains an individual digit setting
char n = pattern.charAt(prefixIndex + macroPart.length());
macro = macro + MACRO_NUMBER_DIGIT_SEPARATOR + n;
}
return pattern.contains(macroStart + macro + macroEnd);
} | java | private static boolean hasNumberMacro(String pattern, String macroStart, String macroEnd) {
String macro = I_CmsFileNameGenerator.MACRO_NUMBER;
String macroPart = macroStart + macro + MACRO_NUMBER_DIGIT_SEPARATOR;
int prefixIndex = pattern.indexOf(macroPart);
if (prefixIndex >= 0) {
// this macro contains an individual digit setting
char n = pattern.charAt(prefixIndex + macroPart.length());
macro = macro + MACRO_NUMBER_DIGIT_SEPARATOR + n;
}
return pattern.contains(macroStart + macro + macroEnd);
} | [
"private",
"static",
"boolean",
"hasNumberMacro",
"(",
"String",
"pattern",
",",
"String",
"macroStart",
",",
"String",
"macroEnd",
")",
"{",
"String",
"macro",
"=",
"I_CmsFileNameGenerator",
".",
"MACRO_NUMBER",
";",
"String",
"macroPart",
"=",
"macroStart",
"+",
"macro",
"+",
"MACRO_NUMBER_DIGIT_SEPARATOR",
";",
"int",
"prefixIndex",
"=",
"pattern",
".",
"indexOf",
"(",
"macroPart",
")",
";",
"if",
"(",
"prefixIndex",
">=",
"0",
")",
"{",
"// this macro contains an individual digit setting",
"char",
"n",
"=",
"pattern",
".",
"charAt",
"(",
"prefixIndex",
"+",
"macroPart",
".",
"length",
"(",
")",
")",
";",
"macro",
"=",
"macro",
"+",
"MACRO_NUMBER_DIGIT_SEPARATOR",
"+",
"n",
";",
"}",
"return",
"pattern",
".",
"contains",
"(",
"macroStart",
"+",
"macro",
"+",
"macroEnd",
")",
";",
"}"
] | Checks the given pattern for the number macro.<p>
@param pattern the pattern to check
@param macroStart the macro start string
@param macroEnd the macro end string
@return <code>true</code> if the pattern contains the macro | [
"Checks",
"the",
"given",
"pattern",
"for",
"the",
"number",
"macro",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsDefaultFileNameGenerator.java#L151-L162 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java | InterfaceEndpointsInner.beginDelete | public void beginDelete(String resourceGroupName, String interfaceEndpointName) {
"""
Deletes the specified interface endpoint.
@param resourceGroupName The name of the resource group.
@param interfaceEndpointName The name of the interface endpoint.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
beginDeleteWithServiceResponseAsync(resourceGroupName, interfaceEndpointName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String interfaceEndpointName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, interfaceEndpointName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"interfaceEndpointName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"interfaceEndpointName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Deletes the specified interface endpoint.
@param resourceGroupName The name of the resource group.
@param interfaceEndpointName The name of the interface endpoint.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Deletes",
"the",
"specified",
"interface",
"endpoint",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java#L180-L182 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/SplitMergeLineFitSegment.java | SplitMergeLineFitSegment.splitPixels | protected void splitPixels( int indexStart , int indexStop ) {
"""
Recursively splits pixels. Used in the initial segmentation. Only split points between
the two ends are added
"""
// too short to split
if( indexStart+1 >= indexStop )
return;
int indexSplit = selectSplitBetween(indexStart, indexStop);
if( indexSplit >= 0 ) {
splitPixels(indexStart, indexSplit);
splits.add(indexSplit);
splitPixels(indexSplit, indexStop);
}
} | java | protected void splitPixels( int indexStart , int indexStop ) {
// too short to split
if( indexStart+1 >= indexStop )
return;
int indexSplit = selectSplitBetween(indexStart, indexStop);
if( indexSplit >= 0 ) {
splitPixels(indexStart, indexSplit);
splits.add(indexSplit);
splitPixels(indexSplit, indexStop);
}
} | [
"protected",
"void",
"splitPixels",
"(",
"int",
"indexStart",
",",
"int",
"indexStop",
")",
"{",
"// too short to split",
"if",
"(",
"indexStart",
"+",
"1",
">=",
"indexStop",
")",
"return",
";",
"int",
"indexSplit",
"=",
"selectSplitBetween",
"(",
"indexStart",
",",
"indexStop",
")",
";",
"if",
"(",
"indexSplit",
">=",
"0",
")",
"{",
"splitPixels",
"(",
"indexStart",
",",
"indexSplit",
")",
";",
"splits",
".",
"add",
"(",
"indexSplit",
")",
";",
"splitPixels",
"(",
"indexSplit",
",",
"indexStop",
")",
";",
"}",
"}"
] | Recursively splits pixels. Used in the initial segmentation. Only split points between
the two ends are added | [
"Recursively",
"splits",
"pixels",
".",
"Used",
"in",
"the",
"initial",
"segmentation",
".",
"Only",
"split",
"points",
"between",
"the",
"two",
"ends",
"are",
"added"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/SplitMergeLineFitSegment.java#L70-L82 |
spotbugs/spotbugs | eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java | FindbugsPlugin.resetStore | private static void resetStore(IPreferenceStore store, String prefix) {
"""
Removes all consequent enumerated keys from given store staring with given prefix
"""
int start = 0;
// 99 is paranoia.
while(start < 99){
String name = prefix + start;
if(store.contains(name)){
store.setToDefault(name);
} else {
break;
}
start ++;
}
} | java | private static void resetStore(IPreferenceStore store, String prefix) {
int start = 0;
// 99 is paranoia.
while(start < 99){
String name = prefix + start;
if(store.contains(name)){
store.setToDefault(name);
} else {
break;
}
start ++;
}
} | [
"private",
"static",
"void",
"resetStore",
"(",
"IPreferenceStore",
"store",
",",
"String",
"prefix",
")",
"{",
"int",
"start",
"=",
"0",
";",
"// 99 is paranoia.",
"while",
"(",
"start",
"<",
"99",
")",
"{",
"String",
"name",
"=",
"prefix",
"+",
"start",
";",
"if",
"(",
"store",
".",
"contains",
"(",
"name",
")",
")",
"{",
"store",
".",
"setToDefault",
"(",
"name",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"start",
"++",
";",
"}",
"}"
] | Removes all consequent enumerated keys from given store staring with given prefix | [
"Removes",
"all",
"consequent",
"enumerated",
"keys",
"from",
"given",
"store",
"staring",
"with",
"given",
"prefix"
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/FindbugsPlugin.java#L1025-L1037 |
taimos/dvalin | jaxrs-jwtauth/src/main/java/de/taimos/dvalin/jaxrs/security/jwt/JWTAuth.java | JWTAuth.verifyToken | public SignedJWT verifyToken(String jwtString) throws ParseException {
"""
Check the given JWT
@param jwtString the JSON Web Token
@return the parsed and verified token or null if token is invalid
@throws ParseException if the token cannot be parsed
"""
try {
SignedJWT jwt = SignedJWT.parse(jwtString);
if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {
return jwt;
}
return null;
} catch (JOSEException e) {
throw new RuntimeException("Error verifying JSON Web Token", e);
}
} | java | public SignedJWT verifyToken(String jwtString) throws ParseException {
try {
SignedJWT jwt = SignedJWT.parse(jwtString);
if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) {
return jwt;
}
return null;
} catch (JOSEException e) {
throw new RuntimeException("Error verifying JSON Web Token", e);
}
} | [
"public",
"SignedJWT",
"verifyToken",
"(",
"String",
"jwtString",
")",
"throws",
"ParseException",
"{",
"try",
"{",
"SignedJWT",
"jwt",
"=",
"SignedJWT",
".",
"parse",
"(",
"jwtString",
")",
";",
"if",
"(",
"jwt",
".",
"verify",
"(",
"new",
"MACVerifier",
"(",
"this",
".",
"jwtSharedSecret",
")",
")",
")",
"{",
"return",
"jwt",
";",
"}",
"return",
"null",
";",
"}",
"catch",
"(",
"JOSEException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Error verifying JSON Web Token\"",
",",
"e",
")",
";",
"}",
"}"
] | Check the given JWT
@param jwtString the JSON Web Token
@return the parsed and verified token or null if token is invalid
@throws ParseException if the token cannot be parsed | [
"Check",
"the",
"given",
"JWT"
] | train | https://github.com/taimos/dvalin/blob/ff8f1bf594e43d7e8ca8de0b4da9f923b66a1a47/jaxrs-jwtauth/src/main/java/de/taimos/dvalin/jaxrs/security/jwt/JWTAuth.java#L97-L107 |
forge/core | maven/impl/src/main/java/org/jboss/forge/addon/maven/dependencies/MavenDependencyResolver.java | MavenDependencyResolver.getVersions | VersionRangeResult getVersions(DependencyQuery query) {
"""
Returns the versions of a specific artifact
@param query
@return
"""
Coordinate dep = query.getCoordinate();
try
{
String version = dep.getVersion();
if (version == null || version.isEmpty())
{
dep = CoordinateBuilder.create(dep).setVersion("[,)");
}
else if (!version.matches("(\\(|\\[).*?(\\)|\\])"))
{
dep = CoordinateBuilder.create(dep).setVersion("[" + version + "]");
}
RepositorySystem maven = container.getRepositorySystem();
Settings settings = container.getSettings();
DefaultRepositorySystemSession session = container.setupRepoSession(maven, settings);
Artifact artifact = MavenConvertUtils.coordinateToMavenArtifact(dep);
List<RemoteRepository> remoteRepos = MavenConvertUtils.convertToMavenRepos(query.getDependencyRepositories(),
settings);
remoteRepos.addAll(MavenRepositories.getRemoteRepositories(container, settings));
VersionRangeRequest rangeRequest = new VersionRangeRequest(artifact, remoteRepos, null);
VersionRangeResult rangeResult = maven.resolveVersionRange(session, rangeRequest);
return rangeResult;
}
catch (Exception e)
{
throw new RuntimeException("Failed to look up versions for [" + dep + "]", e);
}
} | java | VersionRangeResult getVersions(DependencyQuery query)
{
Coordinate dep = query.getCoordinate();
try
{
String version = dep.getVersion();
if (version == null || version.isEmpty())
{
dep = CoordinateBuilder.create(dep).setVersion("[,)");
}
else if (!version.matches("(\\(|\\[).*?(\\)|\\])"))
{
dep = CoordinateBuilder.create(dep).setVersion("[" + version + "]");
}
RepositorySystem maven = container.getRepositorySystem();
Settings settings = container.getSettings();
DefaultRepositorySystemSession session = container.setupRepoSession(maven, settings);
Artifact artifact = MavenConvertUtils.coordinateToMavenArtifact(dep);
List<RemoteRepository> remoteRepos = MavenConvertUtils.convertToMavenRepos(query.getDependencyRepositories(),
settings);
remoteRepos.addAll(MavenRepositories.getRemoteRepositories(container, settings));
VersionRangeRequest rangeRequest = new VersionRangeRequest(artifact, remoteRepos, null);
VersionRangeResult rangeResult = maven.resolveVersionRange(session, rangeRequest);
return rangeResult;
}
catch (Exception e)
{
throw new RuntimeException("Failed to look up versions for [" + dep + "]", e);
}
} | [
"VersionRangeResult",
"getVersions",
"(",
"DependencyQuery",
"query",
")",
"{",
"Coordinate",
"dep",
"=",
"query",
".",
"getCoordinate",
"(",
")",
";",
"try",
"{",
"String",
"version",
"=",
"dep",
".",
"getVersion",
"(",
")",
";",
"if",
"(",
"version",
"==",
"null",
"||",
"version",
".",
"isEmpty",
"(",
")",
")",
"{",
"dep",
"=",
"CoordinateBuilder",
".",
"create",
"(",
"dep",
")",
".",
"setVersion",
"(",
"\"[,)\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"version",
".",
"matches",
"(",
"\"(\\\\(|\\\\[).*?(\\\\)|\\\\])\"",
")",
")",
"{",
"dep",
"=",
"CoordinateBuilder",
".",
"create",
"(",
"dep",
")",
".",
"setVersion",
"(",
"\"[\"",
"+",
"version",
"+",
"\"]\"",
")",
";",
"}",
"RepositorySystem",
"maven",
"=",
"container",
".",
"getRepositorySystem",
"(",
")",
";",
"Settings",
"settings",
"=",
"container",
".",
"getSettings",
"(",
")",
";",
"DefaultRepositorySystemSession",
"session",
"=",
"container",
".",
"setupRepoSession",
"(",
"maven",
",",
"settings",
")",
";",
"Artifact",
"artifact",
"=",
"MavenConvertUtils",
".",
"coordinateToMavenArtifact",
"(",
"dep",
")",
";",
"List",
"<",
"RemoteRepository",
">",
"remoteRepos",
"=",
"MavenConvertUtils",
".",
"convertToMavenRepos",
"(",
"query",
".",
"getDependencyRepositories",
"(",
")",
",",
"settings",
")",
";",
"remoteRepos",
".",
"addAll",
"(",
"MavenRepositories",
".",
"getRemoteRepositories",
"(",
"container",
",",
"settings",
")",
")",
";",
"VersionRangeRequest",
"rangeRequest",
"=",
"new",
"VersionRangeRequest",
"(",
"artifact",
",",
"remoteRepos",
",",
"null",
")",
";",
"VersionRangeResult",
"rangeResult",
"=",
"maven",
".",
"resolveVersionRange",
"(",
"session",
",",
"rangeRequest",
")",
";",
"return",
"rangeResult",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to look up versions for [\"",
"+",
"dep",
"+",
"\"]\"",
",",
"e",
")",
";",
"}",
"}"
] | Returns the versions of a specific artifact
@param query
@return | [
"Returns",
"the",
"versions",
"of",
"a",
"specific",
"artifact"
] | train | https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/maven/impl/src/main/java/org/jboss/forge/addon/maven/dependencies/MavenDependencyResolver.java#L141-L174 |
alkacon/opencms-core | src/org/opencms/file/CmsRequestContext.java | CmsRequestContext.setAttribute | public void setAttribute(String key, Object value) {
"""
Sets an attribute in the request context.<p>
@param key the attribute name
@param value the attribute value
"""
if (m_attributeMap == null) {
// hash table is still the most efficient form of a synchronized Map
m_attributeMap = new Hashtable<String, Object>();
}
m_attributeMap.put(key, value);
} | java | public void setAttribute(String key, Object value) {
if (m_attributeMap == null) {
// hash table is still the most efficient form of a synchronized Map
m_attributeMap = new Hashtable<String, Object>();
}
m_attributeMap.put(key, value);
} | [
"public",
"void",
"setAttribute",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"m_attributeMap",
"==",
"null",
")",
"{",
"// hash table is still the most efficient form of a synchronized Map",
"m_attributeMap",
"=",
"new",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"}",
"m_attributeMap",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Sets an attribute in the request context.<p>
@param key the attribute name
@param value the attribute value | [
"Sets",
"an",
"attribute",
"in",
"the",
"request",
"context",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsRequestContext.java#L550-L557 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/json/JsonReader.java | JsonReader.decodeLiteral | private JsonToken decodeLiteral() throws IOException {
"""
Assigns {@code nextToken} based on the value of {@code nextValue}.
"""
if (valuePos == -1) {
// it was too long to fit in the buffer so it can only be a string
return JsonToken.STRING;
} else if (valueLength == 4
&& ('n' == buffer[valuePos] || 'N' == buffer[valuePos])
&& ('u' == buffer[valuePos + 1] || 'U' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('l' == buffer[valuePos + 3] || 'L' == buffer[valuePos + 3])) {
value = "null";
return JsonToken.NULL;
} else if (valueLength == 4
&& ('t' == buffer[valuePos] || 'T' == buffer[valuePos])
&& ('r' == buffer[valuePos + 1] || 'R' == buffer[valuePos + 1])
&& ('u' == buffer[valuePos + 2] || 'U' == buffer[valuePos + 2])
&& ('e' == buffer[valuePos + 3] || 'E' == buffer[valuePos + 3])) {
value = TRUE;
return JsonToken.BOOLEAN;
} else if (valueLength == 5
&& ('f' == buffer[valuePos] || 'F' == buffer[valuePos])
&& ('a' == buffer[valuePos + 1] || 'A' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('s' == buffer[valuePos + 3] || 'S' == buffer[valuePos + 3])
&& ('e' == buffer[valuePos + 4] || 'E' == buffer[valuePos + 4])) {
value = FALSE;
return JsonToken.BOOLEAN;
} else {
value = stringPool.get(buffer, valuePos, valueLength);
return decodeNumber(buffer, valuePos, valueLength);
}
} | java | private JsonToken decodeLiteral() throws IOException {
if (valuePos == -1) {
// it was too long to fit in the buffer so it can only be a string
return JsonToken.STRING;
} else if (valueLength == 4
&& ('n' == buffer[valuePos] || 'N' == buffer[valuePos])
&& ('u' == buffer[valuePos + 1] || 'U' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('l' == buffer[valuePos + 3] || 'L' == buffer[valuePos + 3])) {
value = "null";
return JsonToken.NULL;
} else if (valueLength == 4
&& ('t' == buffer[valuePos] || 'T' == buffer[valuePos])
&& ('r' == buffer[valuePos + 1] || 'R' == buffer[valuePos + 1])
&& ('u' == buffer[valuePos + 2] || 'U' == buffer[valuePos + 2])
&& ('e' == buffer[valuePos + 3] || 'E' == buffer[valuePos + 3])) {
value = TRUE;
return JsonToken.BOOLEAN;
} else if (valueLength == 5
&& ('f' == buffer[valuePos] || 'F' == buffer[valuePos])
&& ('a' == buffer[valuePos + 1] || 'A' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('s' == buffer[valuePos + 3] || 'S' == buffer[valuePos + 3])
&& ('e' == buffer[valuePos + 4] || 'E' == buffer[valuePos + 4])) {
value = FALSE;
return JsonToken.BOOLEAN;
} else {
value = stringPool.get(buffer, valuePos, valueLength);
return decodeNumber(buffer, valuePos, valueLength);
}
} | [
"private",
"JsonToken",
"decodeLiteral",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"valuePos",
"==",
"-",
"1",
")",
"{",
"// it was too long to fit in the buffer so it can only be a string",
"return",
"JsonToken",
".",
"STRING",
";",
"}",
"else",
"if",
"(",
"valueLength",
"==",
"4",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
")",
")",
"{",
"value",
"=",
"\"null\"",
";",
"return",
"JsonToken",
".",
"NULL",
";",
"}",
"else",
"if",
"(",
"valueLength",
"==",
"4",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
")",
")",
"{",
"value",
"=",
"TRUE",
";",
"return",
"JsonToken",
".",
"BOOLEAN",
";",
"}",
"else",
"if",
"(",
"valueLength",
"==",
"5",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"1",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"2",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"3",
"]",
")",
"&&",
"(",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"4",
"]",
"||",
"'",
"'",
"==",
"buffer",
"[",
"valuePos",
"+",
"4",
"]",
")",
")",
"{",
"value",
"=",
"FALSE",
";",
"return",
"JsonToken",
".",
"BOOLEAN",
";",
"}",
"else",
"{",
"value",
"=",
"stringPool",
".",
"get",
"(",
"buffer",
",",
"valuePos",
",",
"valueLength",
")",
";",
"return",
"decodeNumber",
"(",
"buffer",
",",
"valuePos",
",",
"valueLength",
")",
";",
"}",
"}"
] | Assigns {@code nextToken} based on the value of {@code nextValue}. | [
"Assigns",
"{"
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L857-L887 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapFileSystemProvider.java | ShrinkWrapFileSystemProvider.copy | private void copy(final InputStream in, final SeekableByteChannel out) throws IOException {
"""
Writes the contents of the {@link InputStream} to the {@link SeekableByteChannel}
@param in
@param out
@throws IOException
"""
assert in != null : "InStream must be specified";
assert out != null : "Channel must be specified";
final byte[] backingBuffer = new byte[1024 * 4];
final ByteBuffer byteBuffer = ByteBuffer.wrap(backingBuffer);
int bytesRead = 0;
while ((bytesRead = in.read(backingBuffer, 0, backingBuffer.length)) > -1) {
// Limit to the amount we've actually read in, so we don't overflow into old data blocks
byteBuffer.limit(bytesRead);
out.write(byteBuffer);
// Position back to 0
byteBuffer.clear();
}
} | java | private void copy(final InputStream in, final SeekableByteChannel out) throws IOException {
assert in != null : "InStream must be specified";
assert out != null : "Channel must be specified";
final byte[] backingBuffer = new byte[1024 * 4];
final ByteBuffer byteBuffer = ByteBuffer.wrap(backingBuffer);
int bytesRead = 0;
while ((bytesRead = in.read(backingBuffer, 0, backingBuffer.length)) > -1) {
// Limit to the amount we've actually read in, so we don't overflow into old data blocks
byteBuffer.limit(bytesRead);
out.write(byteBuffer);
// Position back to 0
byteBuffer.clear();
}
} | [
"private",
"void",
"copy",
"(",
"final",
"InputStream",
"in",
",",
"final",
"SeekableByteChannel",
"out",
")",
"throws",
"IOException",
"{",
"assert",
"in",
"!=",
"null",
":",
"\"InStream must be specified\"",
";",
"assert",
"out",
"!=",
"null",
":",
"\"Channel must be specified\"",
";",
"final",
"byte",
"[",
"]",
"backingBuffer",
"=",
"new",
"byte",
"[",
"1024",
"*",
"4",
"]",
";",
"final",
"ByteBuffer",
"byteBuffer",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"backingBuffer",
")",
";",
"int",
"bytesRead",
"=",
"0",
";",
"while",
"(",
"(",
"bytesRead",
"=",
"in",
".",
"read",
"(",
"backingBuffer",
",",
"0",
",",
"backingBuffer",
".",
"length",
")",
")",
">",
"-",
"1",
")",
"{",
"// Limit to the amount we've actually read in, so we don't overflow into old data blocks",
"byteBuffer",
".",
"limit",
"(",
"bytesRead",
")",
";",
"out",
".",
"write",
"(",
"byteBuffer",
")",
";",
"// Position back to 0",
"byteBuffer",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | Writes the contents of the {@link InputStream} to the {@link SeekableByteChannel}
@param in
@param out
@throws IOException | [
"Writes",
"the",
"contents",
"of",
"the",
"{",
"@link",
"InputStream",
"}",
"to",
"the",
"{",
"@link",
"SeekableByteChannel",
"}"
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapFileSystemProvider.java#L626-L640 |
lessthanoptimal/ejml | main/ejml-core/src/org/ejml/data/DMatrixSparseCSC.java | DMatrixSparseCSC.nz_index | public int nz_index( int row , int col ) {
"""
Returns the index in nz_rows for the element at (row,col) if it already exists in the matrix. If not then -1
is returned.
@param row row coordinate
@param col column coordinate
@return nz_row index or -1 if the element does not exist
"""
int col0 = col_idx[col];
int col1 = col_idx[col+1];
for (int i = col0; i < col1; i++) {
if( nz_rows[i] == row ) {
return i;
}
}
return -1;
} | java | public int nz_index( int row , int col ) {
int col0 = col_idx[col];
int col1 = col_idx[col+1];
for (int i = col0; i < col1; i++) {
if( nz_rows[i] == row ) {
return i;
}
}
return -1;
} | [
"public",
"int",
"nz_index",
"(",
"int",
"row",
",",
"int",
"col",
")",
"{",
"int",
"col0",
"=",
"col_idx",
"[",
"col",
"]",
";",
"int",
"col1",
"=",
"col_idx",
"[",
"col",
"+",
"1",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"col0",
";",
"i",
"<",
"col1",
";",
"i",
"++",
")",
"{",
"if",
"(",
"nz_rows",
"[",
"i",
"]",
"==",
"row",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Returns the index in nz_rows for the element at (row,col) if it already exists in the matrix. If not then -1
is returned.
@param row row coordinate
@param col column coordinate
@return nz_row index or -1 if the element does not exist | [
"Returns",
"the",
"index",
"in",
"nz_rows",
"for",
"the",
"element",
"at",
"(",
"row",
"col",
")",
"if",
"it",
"already",
"exists",
"in",
"the",
"matrix",
".",
"If",
"not",
"then",
"-",
"1",
"is",
"returned",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/data/DMatrixSparseCSC.java#L195-L205 |
elvishew/xLog | library/src/main/java/com/elvishew/xlog/flattener/PatternFlattener.java | PatternFlattener.parseMessageParameter | static MessageFiller parseMessageParameter(String wrappedParameter, String trimmedParameter) {
"""
Try to create a message filler if the given parameter is a message parameter.
@return created message filler, or null if the given parameter is not a message parameter
"""
if (trimmedParameter.equals(PARAMETER_MESSAGE)) {
return new MessageFiller(wrappedParameter, trimmedParameter);
}
return null;
} | java | static MessageFiller parseMessageParameter(String wrappedParameter, String trimmedParameter) {
if (trimmedParameter.equals(PARAMETER_MESSAGE)) {
return new MessageFiller(wrappedParameter, trimmedParameter);
}
return null;
} | [
"static",
"MessageFiller",
"parseMessageParameter",
"(",
"String",
"wrappedParameter",
",",
"String",
"trimmedParameter",
")",
"{",
"if",
"(",
"trimmedParameter",
".",
"equals",
"(",
"PARAMETER_MESSAGE",
")",
")",
"{",
"return",
"new",
"MessageFiller",
"(",
"wrappedParameter",
",",
"trimmedParameter",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Try to create a message filler if the given parameter is a message parameter.
@return created message filler, or null if the given parameter is not a message parameter | [
"Try",
"to",
"create",
"a",
"message",
"filler",
"if",
"the",
"given",
"parameter",
"is",
"a",
"message",
"parameter",
"."
] | train | https://github.com/elvishew/xLog/blob/c6fb95555ce619d3e527f5ba6c45d4d247c5a838/library/src/main/java/com/elvishew/xlog/flattener/PatternFlattener.java#L233-L238 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGSimpleLinearAxis.java | SVGSimpleLinearAxis.setupCSSClasses | private static void setupCSSClasses(Object owner, CSSClassManager manager, StyleLibrary style) throws CSSNamingConflict {
"""
Register CSS classes with a {@link CSSClassManager}
@param owner Owner of the CSS classes
@param manager Manager to register the classes with
@throws CSSNamingConflict when a name clash occurs
"""
if(!manager.contains(CSS_AXIS)) {
CSSClass axis = new CSSClass(owner, CSS_AXIS);
axis.setStatement(SVGConstants.CSS_STROKE_PROPERTY, style.getColor(StyleLibrary.AXIS));
axis.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, style.getLineWidth(StyleLibrary.AXIS));
manager.addClass(axis);
}
if(!manager.contains(CSS_AXIS_TICK)) {
CSSClass tick = new CSSClass(owner, CSS_AXIS_TICK);
tick.setStatement(SVGConstants.CSS_STROKE_PROPERTY, style.getColor(StyleLibrary.AXIS_TICK));
tick.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, style.getLineWidth(StyleLibrary.AXIS_TICK));
manager.addClass(tick);
}
if(!manager.contains(CSS_AXIS_LABEL)) {
CSSClass label = new CSSClass(owner, CSS_AXIS_LABEL);
label.setStatement(SVGConstants.CSS_FILL_PROPERTY, style.getTextColor(StyleLibrary.AXIS_LABEL));
label.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, style.getFontFamily(StyleLibrary.AXIS_LABEL));
label.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, style.getTextSize(StyleLibrary.AXIS_LABEL));
manager.addClass(label);
}
} | java | private static void setupCSSClasses(Object owner, CSSClassManager manager, StyleLibrary style) throws CSSNamingConflict {
if(!manager.contains(CSS_AXIS)) {
CSSClass axis = new CSSClass(owner, CSS_AXIS);
axis.setStatement(SVGConstants.CSS_STROKE_PROPERTY, style.getColor(StyleLibrary.AXIS));
axis.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, style.getLineWidth(StyleLibrary.AXIS));
manager.addClass(axis);
}
if(!manager.contains(CSS_AXIS_TICK)) {
CSSClass tick = new CSSClass(owner, CSS_AXIS_TICK);
tick.setStatement(SVGConstants.CSS_STROKE_PROPERTY, style.getColor(StyleLibrary.AXIS_TICK));
tick.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, style.getLineWidth(StyleLibrary.AXIS_TICK));
manager.addClass(tick);
}
if(!manager.contains(CSS_AXIS_LABEL)) {
CSSClass label = new CSSClass(owner, CSS_AXIS_LABEL);
label.setStatement(SVGConstants.CSS_FILL_PROPERTY, style.getTextColor(StyleLibrary.AXIS_LABEL));
label.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, style.getFontFamily(StyleLibrary.AXIS_LABEL));
label.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, style.getTextSize(StyleLibrary.AXIS_LABEL));
manager.addClass(label);
}
} | [
"private",
"static",
"void",
"setupCSSClasses",
"(",
"Object",
"owner",
",",
"CSSClassManager",
"manager",
",",
"StyleLibrary",
"style",
")",
"throws",
"CSSNamingConflict",
"{",
"if",
"(",
"!",
"manager",
".",
"contains",
"(",
"CSS_AXIS",
")",
")",
"{",
"CSSClass",
"axis",
"=",
"new",
"CSSClass",
"(",
"owner",
",",
"CSS_AXIS",
")",
";",
"axis",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_STROKE_PROPERTY",
",",
"style",
".",
"getColor",
"(",
"StyleLibrary",
".",
"AXIS",
")",
")",
";",
"axis",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_STROKE_WIDTH_PROPERTY",
",",
"style",
".",
"getLineWidth",
"(",
"StyleLibrary",
".",
"AXIS",
")",
")",
";",
"manager",
".",
"addClass",
"(",
"axis",
")",
";",
"}",
"if",
"(",
"!",
"manager",
".",
"contains",
"(",
"CSS_AXIS_TICK",
")",
")",
"{",
"CSSClass",
"tick",
"=",
"new",
"CSSClass",
"(",
"owner",
",",
"CSS_AXIS_TICK",
")",
";",
"tick",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_STROKE_PROPERTY",
",",
"style",
".",
"getColor",
"(",
"StyleLibrary",
".",
"AXIS_TICK",
")",
")",
";",
"tick",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_STROKE_WIDTH_PROPERTY",
",",
"style",
".",
"getLineWidth",
"(",
"StyleLibrary",
".",
"AXIS_TICK",
")",
")",
";",
"manager",
".",
"addClass",
"(",
"tick",
")",
";",
"}",
"if",
"(",
"!",
"manager",
".",
"contains",
"(",
"CSS_AXIS_LABEL",
")",
")",
"{",
"CSSClass",
"label",
"=",
"new",
"CSSClass",
"(",
"owner",
",",
"CSS_AXIS_LABEL",
")",
";",
"label",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_FILL_PROPERTY",
",",
"style",
".",
"getTextColor",
"(",
"StyleLibrary",
".",
"AXIS_LABEL",
")",
")",
";",
"label",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_FONT_FAMILY_PROPERTY",
",",
"style",
".",
"getFontFamily",
"(",
"StyleLibrary",
".",
"AXIS_LABEL",
")",
")",
";",
"label",
".",
"setStatement",
"(",
"SVGConstants",
".",
"CSS_FONT_SIZE_PROPERTY",
",",
"style",
".",
"getTextSize",
"(",
"StyleLibrary",
".",
"AXIS_LABEL",
")",
")",
";",
"manager",
".",
"addClass",
"(",
"label",
")",
";",
"}",
"}"
] | Register CSS classes with a {@link CSSClassManager}
@param owner Owner of the CSS classes
@param manager Manager to register the classes with
@throws CSSNamingConflict when a name clash occurs | [
"Register",
"CSS",
"classes",
"with",
"a",
"{",
"@link",
"CSSClassManager",
"}"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGSimpleLinearAxis.java#L92-L112 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/introspection/MethodArgumentsUberspector.java | MethodArgumentsUberspector.convertArguments | private Object[] convertArguments(Object obj, String methodName, Object[] args) {
"""
Converts the given arguments to match a method with the specified name and the same number of formal parameters
as the number of arguments.
@param obj the object the method is invoked on, used to retrieve the list of available methods
@param methodName the method we're looking for
@param args the method arguments
@return a new array of arguments where some values have been converted to match the formal method parameter
types, {@code null} if no such method is found
"""
for (Method method : obj.getClass().getMethods()) {
if (method.getName().equalsIgnoreCase(methodName)
&& (method.getGenericParameterTypes().length == args.length || method.isVarArgs())) {
try {
return convertArguments(args, method.getGenericParameterTypes(), method.isVarArgs());
} catch (Exception e) {
// Ignore and try the next method.
}
}
}
return null;
} | java | private Object[] convertArguments(Object obj, String methodName, Object[] args)
{
for (Method method : obj.getClass().getMethods()) {
if (method.getName().equalsIgnoreCase(methodName)
&& (method.getGenericParameterTypes().length == args.length || method.isVarArgs())) {
try {
return convertArguments(args, method.getGenericParameterTypes(), method.isVarArgs());
} catch (Exception e) {
// Ignore and try the next method.
}
}
}
return null;
} | [
"private",
"Object",
"[",
"]",
"convertArguments",
"(",
"Object",
"obj",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"for",
"(",
"Method",
"method",
":",
"obj",
".",
"getClass",
"(",
")",
".",
"getMethods",
"(",
")",
")",
"{",
"if",
"(",
"method",
".",
"getName",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"methodName",
")",
"&&",
"(",
"method",
".",
"getGenericParameterTypes",
"(",
")",
".",
"length",
"==",
"args",
".",
"length",
"||",
"method",
".",
"isVarArgs",
"(",
")",
")",
")",
"{",
"try",
"{",
"return",
"convertArguments",
"(",
"args",
",",
"method",
".",
"getGenericParameterTypes",
"(",
")",
",",
"method",
".",
"isVarArgs",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Ignore and try the next method.",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Converts the given arguments to match a method with the specified name and the same number of formal parameters
as the number of arguments.
@param obj the object the method is invoked on, used to retrieve the list of available methods
@param methodName the method we're looking for
@param args the method arguments
@return a new array of arguments where some values have been converted to match the formal method parameter
types, {@code null} if no such method is found | [
"Converts",
"the",
"given",
"arguments",
"to",
"match",
"a",
"method",
"with",
"the",
"specified",
"name",
"and",
"the",
"same",
"number",
"of",
"formal",
"parameters",
"as",
"the",
"number",
"of",
"arguments",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/introspection/MethodArgumentsUberspector.java#L144-L158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.