repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
belaban/JGroups | src/org/jgroups/View.java | View.sameMembers | public static boolean sameMembers(View v1, View v2) {
"""
Checks if two views have the same members regardless of order. E.g. {A,B,C} and {B,A,C} returns true
"""
if(v1 == v2)
return true;
if(v1.size() != v2.size())
return false;
Address[][] diff=diff(v1, v2);
return diff[0].length == 0 && diff[1].length == 0;
} | java | public static boolean sameMembers(View v1, View v2) {
if(v1 == v2)
return true;
if(v1.size() != v2.size())
return false;
Address[][] diff=diff(v1, v2);
return diff[0].length == 0 && diff[1].length == 0;
} | [
"public",
"static",
"boolean",
"sameMembers",
"(",
"View",
"v1",
",",
"View",
"v2",
")",
"{",
"if",
"(",
"v1",
"==",
"v2",
")",
"return",
"true",
";",
"if",
"(",
"v1",
".",
"size",
"(",
")",
"!=",
"v2",
".",
"size",
"(",
")",
")",
"return",
"fa... | Checks if two views have the same members regardless of order. E.g. {A,B,C} and {B,A,C} returns true | [
"Checks",
"if",
"two",
"views",
"have",
"the",
"same",
"members",
"regardless",
"of",
"order",
".",
"E",
".",
"g",
".",
"{",
"A",
"B",
"C",
"}",
"and",
"{",
"B",
"A",
"C",
"}",
"returns",
"true"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/View.java#L300-L307 |
kiegroup/drools | drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseFactory.java | KnowledgeBaseFactory.newKnowledgeBase | public static InternalKnowledgeBase newKnowledgeBase(String kbaseId,
KieBaseConfiguration conf) {
"""
Create a new KnowledgeBase using the given KnowledgeBaseConfiguration and
the given KnowledgeBase ID.
@param kbaseId
A string Identifier for the knowledge base. Specially useful when enabling
JMX monitoring and management, as that ID will be used to compose the
JMX ObjectName for all related MBeans. The application must ensure all kbase
IDs are unique.
@return
The KnowledgeBase
"""
return new KnowledgeBaseImpl( kbaseId, (RuleBaseConfiguration) conf);
} | java | public static InternalKnowledgeBase newKnowledgeBase(String kbaseId,
KieBaseConfiguration conf) {
return new KnowledgeBaseImpl( kbaseId, (RuleBaseConfiguration) conf);
} | [
"public",
"static",
"InternalKnowledgeBase",
"newKnowledgeBase",
"(",
"String",
"kbaseId",
",",
"KieBaseConfiguration",
"conf",
")",
"{",
"return",
"new",
"KnowledgeBaseImpl",
"(",
"kbaseId",
",",
"(",
"RuleBaseConfiguration",
")",
"conf",
")",
";",
"}"
] | Create a new KnowledgeBase using the given KnowledgeBaseConfiguration and
the given KnowledgeBase ID.
@param kbaseId
A string Identifier for the knowledge base. Specially useful when enabling
JMX monitoring and management, as that ID will be used to compose the
JMX ObjectName for all related MBeans. The application must ensure all kbase
IDs are unique.
@return
The KnowledgeBase | [
"Create",
"a",
"new",
"KnowledgeBase",
"using",
"the",
"given",
"KnowledgeBaseConfiguration",
"and",
"the",
"given",
"KnowledgeBase",
"ID",
"."
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/impl/KnowledgeBaseFactory.java#L104-L107 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.executeObject | @Override
public <T> T executeObject(String name, T object) throws CpoException {
"""
Executes an Object whose metadata will call an executable within the datasource. It is assumed that the executable
object exists in the metadatasource. If the executable does not exist, an exception will be thrown.
<p/>
<pre>Example:
<code>
<p/>
class SomeObject so = new SomeObject();
class CpoAdapter cpo = null;
<p/>
try {
cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false));
} catch (CpoException ce) {
// Handle the error
cpo = null;
}
<p/>
if (cpo!=null) {
so.setId(1);
so.setName("SomeName");
try{
cpo.executeObject("execNotifyProc",so);
} catch (CpoException ce) {
// Handle the error
}
}
</code>
</pre>
@param name The filter name which tells the datasource which objects should be returned. The name also signifies
what data in the object will be populated.
@param object This is an object that has been defined within the metadata of the datasource. If the class is not
defined an exception will be thrown. If the object does not exist in the datasource, an exception will be thrown.
This object is used to populate the IN arguments used to retrieve the collection of objects. This object defines
the object type that will be returned in the collection and contain the result set data or the OUT Parameters.
@return A result object populate with the OUT arguments
@throws CpoException if there are errors accessing the datasource
"""
throw new UnsupportedOperationException("Execute Functions not supported in Cassandra");
} | java | @Override
public <T> T executeObject(String name, T object) throws CpoException {
throw new UnsupportedOperationException("Execute Functions not supported in Cassandra");
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"T",
"executeObject",
"(",
"String",
"name",
",",
"T",
"object",
")",
"throws",
"CpoException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Execute Functions not supported in Cassandra\"",
")",
";",
"}"
] | Executes an Object whose metadata will call an executable within the datasource. It is assumed that the executable
object exists in the metadatasource. If the executable does not exist, an exception will be thrown.
<p/>
<pre>Example:
<code>
<p/>
class SomeObject so = new SomeObject();
class CpoAdapter cpo = null;
<p/>
try {
cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false));
} catch (CpoException ce) {
// Handle the error
cpo = null;
}
<p/>
if (cpo!=null) {
so.setId(1);
so.setName("SomeName");
try{
cpo.executeObject("execNotifyProc",so);
} catch (CpoException ce) {
// Handle the error
}
}
</code>
</pre>
@param name The filter name which tells the datasource which objects should be returned. The name also signifies
what data in the object will be populated.
@param object This is an object that has been defined within the metadata of the datasource. If the class is not
defined an exception will be thrown. If the object does not exist in the datasource, an exception will be thrown.
This object is used to populate the IN arguments used to retrieve the collection of objects. This object defines
the object type that will be returned in the collection and contain the result set data or the OUT Parameters.
@return A result object populate with the OUT arguments
@throws CpoException if there are errors accessing the datasource | [
"Executes",
"an",
"Object",
"whose",
"metadata",
"will",
"call",
"an",
"executable",
"within",
"the",
"datasource",
".",
"It",
"is",
"assumed",
"that",
"the",
"executable",
"object",
"exists",
"in",
"the",
"metadatasource",
".",
"If",
"the",
"executable",
"doe... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L765-L768 |
dequelabs/axe-selenium-java | src/main/java/com/deque/axe/AXE.java | AXE.writeResults | public static void writeResults(final String name, final Object output) {
"""
Writes a raw object out to a JSON file with the specified name.
@param name Desired filename, sans extension
@param output Object to write. Most useful if you pass in either the Builder.analyze() response or the
violations array it contains.
"""
Writer writer = null;
try {
writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(name + ".json"), "utf-8"));
writer.write(output.toString());
} catch (IOException ignored) {
} finally {
try {writer.close();}
catch (Exception ignored) {}
}
} | java | public static void writeResults(final String name, final Object output) {
Writer writer = null;
try {
writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(name + ".json"), "utf-8"));
writer.write(output.toString());
} catch (IOException ignored) {
} finally {
try {writer.close();}
catch (Exception ignored) {}
}
} | [
"public",
"static",
"void",
"writeResults",
"(",
"final",
"String",
"name",
",",
"final",
"Object",
"output",
")",
"{",
"Writer",
"writer",
"=",
"null",
";",
"try",
"{",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
... | Writes a raw object out to a JSON file with the specified name.
@param name Desired filename, sans extension
@param output Object to write. Most useful if you pass in either the Builder.analyze() response or the
violations array it contains. | [
"Writes",
"a",
"raw",
"object",
"out",
"to",
"a",
"JSON",
"file",
"with",
"the",
"specified",
"name",
"."
] | train | https://github.com/dequelabs/axe-selenium-java/blob/68b35ff46c59111b0e9a9f573380c3d250bcfd65/src/main/java/com/deque/axe/AXE.java#L212-L226 |
gresrun/jesque | src/main/java/net/greghaines/jesque/worker/MapBasedJobFactory.java | MapBasedJobFactory.checkJobTypes | protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {
"""
Verify the given job types are all valid.
@param jobTypes the given job types
@throws IllegalArgumentException if any of the job types are invalid
@see #checkJobType(String, Class)
"""
if (jobTypes == null) {
throw new IllegalArgumentException("jobTypes must not be null");
}
for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {
try {
checkJobType(entry.getKey(), entry.getValue());
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("jobTypes contained invalid value", iae);
}
}
} | java | protected void checkJobTypes(final Map<String, ? extends Class<?>> jobTypes) {
if (jobTypes == null) {
throw new IllegalArgumentException("jobTypes must not be null");
}
for (final Entry<String, ? extends Class<?>> entry : jobTypes.entrySet()) {
try {
checkJobType(entry.getKey(), entry.getValue());
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("jobTypes contained invalid value", iae);
}
}
} | [
"protected",
"void",
"checkJobTypes",
"(",
"final",
"Map",
"<",
"String",
",",
"?",
"extends",
"Class",
"<",
"?",
">",
">",
"jobTypes",
")",
"{",
"if",
"(",
"jobTypes",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"jobTypes mu... | Verify the given job types are all valid.
@param jobTypes the given job types
@throws IllegalArgumentException if any of the job types are invalid
@see #checkJobType(String, Class) | [
"Verify",
"the",
"given",
"job",
"types",
"are",
"all",
"valid",
"."
] | train | https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/worker/MapBasedJobFactory.java#L109-L120 |
apereo/cas | support/cas-server-support-consent-core/src/main/java/org/apereo/cas/consent/AttributeConsentReportEndpoint.java | AttributeConsentReportEndpoint.revokeConsents | @DeleteOperation
public boolean revokeConsents(@Selector final String principal, @Selector final long decisionId) {
"""
Revoke consents.
@param principal the principal
@param decisionId the decision id
@return the boolean
"""
LOGGER.debug("Deleting consent decisions for principal [{}].", principal);
return this.consentRepository.deleteConsentDecision(decisionId, principal);
} | java | @DeleteOperation
public boolean revokeConsents(@Selector final String principal, @Selector final long decisionId) {
LOGGER.debug("Deleting consent decisions for principal [{}].", principal);
return this.consentRepository.deleteConsentDecision(decisionId, principal);
} | [
"@",
"DeleteOperation",
"public",
"boolean",
"revokeConsents",
"(",
"@",
"Selector",
"final",
"String",
"principal",
",",
"@",
"Selector",
"final",
"long",
"decisionId",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Deleting consent decisions for principal [{}].\"",
",",
... | Revoke consents.
@param principal the principal
@param decisionId the decision id
@return the boolean | [
"Revoke",
"consents",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-consent-core/src/main/java/org/apereo/cas/consent/AttributeConsentReportEndpoint.java#L68-L72 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/scanner/AbstractPlugin.java | AbstractPlugin.stripOff | protected String stripOff(String body, String pattern) {
"""
Replace body by stripping of pattern string. The URLencoded and
URLdecoded pattern will also be stripped off. This is mainly used for
stripping off a testing string in HTTP response for comparison against
the original response. Reference: TestInjectionSQL
@param body the body that will be used
@param pattern the pattern used for the removals
@return the body without the pattern
"""
String urlEncodePattern = getURLEncode(pattern);
String urlDecodePattern = getURLDecode(pattern);
String htmlEncodePattern1 = getHTMLEncode(pattern);
String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern);
String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern);
String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", "");
result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", "");
return result;
} | java | protected String stripOff(String body, String pattern) {
String urlEncodePattern = getURLEncode(pattern);
String urlDecodePattern = getURLDecode(pattern);
String htmlEncodePattern1 = getHTMLEncode(pattern);
String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern);
String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern);
String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", "");
result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", "");
return result;
} | [
"protected",
"String",
"stripOff",
"(",
"String",
"body",
",",
"String",
"pattern",
")",
"{",
"String",
"urlEncodePattern",
"=",
"getURLEncode",
"(",
"pattern",
")",
";",
"String",
"urlDecodePattern",
"=",
"getURLDecode",
"(",
"pattern",
")",
";",
"String",
"h... | Replace body by stripping of pattern string. The URLencoded and
URLdecoded pattern will also be stripped off. This is mainly used for
stripping off a testing string in HTTP response for comparison against
the original response. Reference: TestInjectionSQL
@param body the body that will be used
@param pattern the pattern used for the removals
@return the body without the pattern | [
"Replace",
"body",
"by",
"stripping",
"of",
"pattern",
"string",
".",
"The",
"URLencoded",
"and",
"URLdecoded",
"pattern",
"will",
"also",
"be",
"stripped",
"off",
".",
"This",
"is",
"mainly",
"used",
"for",
"stripping",
"off",
"a",
"testing",
"string",
"in"... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/AbstractPlugin.java#L771-L780 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/admin/instance/v1/InstanceAdminClient.java | InstanceAdminClient.setIamPolicy | public final Policy setIamPolicy(String resource, Policy policy) {
"""
Sets the access control policy on an instance resource. Replaces any existing policy.
<p>Authorization requires `spanner.instances.setIamPolicy` on
[resource][google.iam.v1.SetIamPolicyRequest.resource].
<p>Sample code:
<pre><code>
try (InstanceAdminClient instanceAdminClient = InstanceAdminClient.create()) {
String formattedResource = InstanceName.format("[PROJECT]", "[INSTANCE]");
Policy policy = Policy.newBuilder().build();
Policy response = instanceAdminClient.setIamPolicy(formattedResource, policy);
}
</code></pre>
@param resource REQUIRED: The resource for which the policy is being specified. `resource` is
usually specified as a path. For example, a Project resource is specified as
`projects/{project}`.
@param policy REQUIRED: The complete policy to be applied to the `resource`. The size of the
policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud
Platform services (such as Projects) might reject them.
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder().setResource(resource).setPolicy(policy).build();
return setIamPolicy(request);
} | java | public final Policy setIamPolicy(String resource, Policy policy) {
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder().setResource(resource).setPolicy(policy).build();
return setIamPolicy(request);
} | [
"public",
"final",
"Policy",
"setIamPolicy",
"(",
"String",
"resource",
",",
"Policy",
"policy",
")",
"{",
"SetIamPolicyRequest",
"request",
"=",
"SetIamPolicyRequest",
".",
"newBuilder",
"(",
")",
".",
"setResource",
"(",
"resource",
")",
".",
"setPolicy",
"(",... | Sets the access control policy on an instance resource. Replaces any existing policy.
<p>Authorization requires `spanner.instances.setIamPolicy` on
[resource][google.iam.v1.SetIamPolicyRequest.resource].
<p>Sample code:
<pre><code>
try (InstanceAdminClient instanceAdminClient = InstanceAdminClient.create()) {
String formattedResource = InstanceName.format("[PROJECT]", "[INSTANCE]");
Policy policy = Policy.newBuilder().build();
Policy response = instanceAdminClient.setIamPolicy(formattedResource, policy);
}
</code></pre>
@param resource REQUIRED: The resource for which the policy is being specified. `resource` is
usually specified as a path. For example, a Project resource is specified as
`projects/{project}`.
@param policy REQUIRED: The complete policy to be applied to the `resource`. The size of the
policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud
Platform services (such as Projects) might reject them.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Sets",
"the",
"access",
"control",
"policy",
"on",
"an",
"instance",
"resource",
".",
"Replaces",
"any",
"existing",
"policy",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/admin/instance/v1/InstanceAdminClient.java#L1356-L1361 |
javamelody/javamelody | javamelody-swing/src/main/java/net/bull/javamelody/swing/table/MListTableModel.java | MListTableModel.isCellEditable | @Override
public boolean isCellEditable(final int row, final int column) {
"""
Retourne un booléen suivant que la cellule est éditable (false par défaut). <br/>
Ici, l'implémentation est faite selon que la propriété cellEditor de la TableColumn correspondante est nulle ou non.
@return boolean
@param row
int
@param column
int
"""
final int index = table.convertColumnIndexToView(column);
return table.isEnabled() && table.getColumnModel().getColumn(index).getCellEditor() != null;
} | java | @Override
public boolean isCellEditable(final int row, final int column) {
final int index = table.convertColumnIndexToView(column);
return table.isEnabled() && table.getColumnModel().getColumn(index).getCellEditor() != null;
} | [
"@",
"Override",
"public",
"boolean",
"isCellEditable",
"(",
"final",
"int",
"row",
",",
"final",
"int",
"column",
")",
"{",
"final",
"int",
"index",
"=",
"table",
".",
"convertColumnIndexToView",
"(",
"column",
")",
";",
"return",
"table",
".",
"isEnabled",... | Retourne un booléen suivant que la cellule est éditable (false par défaut). <br/>
Ici, l'implémentation est faite selon que la propriété cellEditor de la TableColumn correspondante est nulle ou non.
@return boolean
@param row
int
@param column
int | [
"Retourne",
"un",
"booléen",
"suivant",
"que",
"la",
"cellule",
"est",
"éditable",
"(",
"false",
"par",
"défaut",
")",
".",
"<br",
"/",
">",
"Ici",
"l",
"implémentation",
"est",
"faite",
"selon",
"que",
"la",
"propriété",
"cellEditor",
"de",
"la",
"TableCo... | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/table/MListTableModel.java#L167-L171 |
apereo/cas | core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/ticket/BaseTicketCatalogConfigurer.java | BaseTicketCatalogConfigurer.buildTicketDefinition | protected TicketDefinition buildTicketDefinition(final TicketCatalog plan, final String prefix, final Class impl, final int order) {
"""
Build ticket ticket definition.
@param plan the plan
@param prefix the prefix
@param impl the
@param order the order
@return the ticket definition
"""
if (plan.contains(prefix)) {
return plan.find(prefix);
}
return new DefaultTicketDefinition(impl, prefix, order);
} | java | protected TicketDefinition buildTicketDefinition(final TicketCatalog plan, final String prefix, final Class impl, final int order) {
if (plan.contains(prefix)) {
return plan.find(prefix);
}
return new DefaultTicketDefinition(impl, prefix, order);
} | [
"protected",
"TicketDefinition",
"buildTicketDefinition",
"(",
"final",
"TicketCatalog",
"plan",
",",
"final",
"String",
"prefix",
",",
"final",
"Class",
"impl",
",",
"final",
"int",
"order",
")",
"{",
"if",
"(",
"plan",
".",
"contains",
"(",
"prefix",
")",
... | Build ticket ticket definition.
@param plan the plan
@param prefix the prefix
@param impl the
@param order the order
@return the ticket definition | [
"Build",
"ticket",
"ticket",
"definition",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-tickets-api/src/main/java/org/apereo/cas/ticket/BaseTicketCatalogConfigurer.java#L21-L26 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/JMProgressiveManager.java | JMProgressiveManager.registerPercentChangeListener | public JMProgressiveManager<T, R> registerPercentChangeListener(
Consumer<Number> percentChangeListener) {
"""
Register percent change listener jm progressive manager.
@param percentChangeListener the percent change listener
@return the jm progressive manager
"""
return registerListener(progressivePercent, percentChangeListener);
} | java | public JMProgressiveManager<T, R> registerPercentChangeListener(
Consumer<Number> percentChangeListener) {
return registerListener(progressivePercent, percentChangeListener);
} | [
"public",
"JMProgressiveManager",
"<",
"T",
",",
"R",
">",
"registerPercentChangeListener",
"(",
"Consumer",
"<",
"Number",
">",
"percentChangeListener",
")",
"{",
"return",
"registerListener",
"(",
"progressivePercent",
",",
"percentChangeListener",
")",
";",
"}"
] | Register percent change listener jm progressive manager.
@param percentChangeListener the percent change listener
@return the jm progressive manager | [
"Register",
"percent",
"change",
"listener",
"jm",
"progressive",
"manager",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/JMProgressiveManager.java#L276-L279 |
hdbeukel/james-extensions | src/main/java/org/jamesframework/ext/analysis/AnalysisResults.java | AnalysisResults.writeJSON | public void writeJSON(String filePath, JsonConverter<SolutionType> solutionJsonConverter) throws IOException {
"""
Write the results to a JSON file that can be loaded into R to be inspected and visualized using
the james-analysis R package. If the specified file already exists, it is overwritten. This method
stores the evaluation values, the update times and the actual best found solution for each search
run. The solutions are converted to a JSON representation using the given converter. If the latter
is <code>null</code>, the actual solutions are not stored in the output file.
@param filePath path of the file to which the JSON output is written
@param solutionJsonConverter converts solutions to a JSON representation
@throws IOException if an I/O error occurs when writing to the file
"""
/**************************************************/
/* STEP 1: Convert results to JSON representation */
/**************************************************/
Json resultsJson = Json.object();
// register problems
results.forEach((problemID, searches) -> {
Json problemJson = Json.object();
searches.forEach((searchID, runs) -> {
Json searchJson = Json.array();
// register search runs
runs.forEach(run -> {
Json runJson = Json.object();
// register update times and values
Json times = Json.array(run.getTimes().toArray());
Json values = Json.array(run.getValues().toArray());
runJson.set("times", times);
runJson.set("values", values);
// register best found solution, if a JSON converter is given
if(solutionJsonConverter != null){
runJson.set("best.solution", solutionJsonConverter.toJson(run.getBestSolution()));
}
searchJson.add(runJson);
});
problemJson.set(searchID, searchJson);
});
resultsJson.set(problemID, problemJson);
});
/*************************************/
/* STEP 2: Write JSON string to file */
/*************************************/
Files.write(Paths.get(filePath), Collections.singleton(resultsJson.toString()));
} | java | public void writeJSON(String filePath, JsonConverter<SolutionType> solutionJsonConverter) throws IOException{
/**************************************************/
/* STEP 1: Convert results to JSON representation */
/**************************************************/
Json resultsJson = Json.object();
// register problems
results.forEach((problemID, searches) -> {
Json problemJson = Json.object();
searches.forEach((searchID, runs) -> {
Json searchJson = Json.array();
// register search runs
runs.forEach(run -> {
Json runJson = Json.object();
// register update times and values
Json times = Json.array(run.getTimes().toArray());
Json values = Json.array(run.getValues().toArray());
runJson.set("times", times);
runJson.set("values", values);
// register best found solution, if a JSON converter is given
if(solutionJsonConverter != null){
runJson.set("best.solution", solutionJsonConverter.toJson(run.getBestSolution()));
}
searchJson.add(runJson);
});
problemJson.set(searchID, searchJson);
});
resultsJson.set(problemID, problemJson);
});
/*************************************/
/* STEP 2: Write JSON string to file */
/*************************************/
Files.write(Paths.get(filePath), Collections.singleton(resultsJson.toString()));
} | [
"public",
"void",
"writeJSON",
"(",
"String",
"filePath",
",",
"JsonConverter",
"<",
"SolutionType",
">",
"solutionJsonConverter",
")",
"throws",
"IOException",
"{",
"/**************************************************/",
"/* STEP 1: Convert results to JSON representation */",
"/... | Write the results to a JSON file that can be loaded into R to be inspected and visualized using
the james-analysis R package. If the specified file already exists, it is overwritten. This method
stores the evaluation values, the update times and the actual best found solution for each search
run. The solutions are converted to a JSON representation using the given converter. If the latter
is <code>null</code>, the actual solutions are not stored in the output file.
@param filePath path of the file to which the JSON output is written
@param solutionJsonConverter converts solutions to a JSON representation
@throws IOException if an I/O error occurs when writing to the file | [
"Write",
"the",
"results",
"to",
"a",
"JSON",
"file",
"that",
"can",
"be",
"loaded",
"into",
"R",
"to",
"be",
"inspected",
"and",
"visualized",
"using",
"the",
"james",
"-",
"analysis",
"R",
"package",
".",
"If",
"the",
"specified",
"file",
"already",
"e... | train | https://github.com/hdbeukel/james-extensions/blob/37a43aa6ac4d67575cabc7aed25fd96c91d4c7b2/src/main/java/org/jamesframework/ext/analysis/AnalysisResults.java#L201-L252 |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/AbstractEngineFactory.java | AbstractEngineFactory.createEngine | @Override
public final IEngine createEngine() {
"""
Call this to create a new engine. This method uses the engine
config singleton to create the engine.
"""
IPluginRegistry pluginRegistry = createPluginRegistry();
IDataEncrypter encrypter = createDataEncrypter(pluginRegistry);
CurrentDataEncrypter.instance = encrypter;
IRegistry registry = createRegistry(pluginRegistry, encrypter);
IComponentRegistry componentRegistry = createComponentRegistry(pluginRegistry);
IConnectorFactory cfactory = createConnectorFactory(pluginRegistry);
IPolicyFactory pfactory = createPolicyFactory(pluginRegistry);
IMetrics metrics = createMetrics(pluginRegistry);
IDelegateFactory logFactory = createLoggerFactory(pluginRegistry);
IApiRequestPathParser pathParser = createRequestPathParser(pluginRegistry);
List<IGatewayInitializer> initializers = createInitializers(pluginRegistry);
for (IGatewayInitializer initializer : initializers) {
initializer.initialize();
}
complete();
return new EngineImpl(registry, pluginRegistry, componentRegistry, cfactory, pfactory, metrics, logFactory, pathParser);
} | java | @Override
public final IEngine createEngine() {
IPluginRegistry pluginRegistry = createPluginRegistry();
IDataEncrypter encrypter = createDataEncrypter(pluginRegistry);
CurrentDataEncrypter.instance = encrypter;
IRegistry registry = createRegistry(pluginRegistry, encrypter);
IComponentRegistry componentRegistry = createComponentRegistry(pluginRegistry);
IConnectorFactory cfactory = createConnectorFactory(pluginRegistry);
IPolicyFactory pfactory = createPolicyFactory(pluginRegistry);
IMetrics metrics = createMetrics(pluginRegistry);
IDelegateFactory logFactory = createLoggerFactory(pluginRegistry);
IApiRequestPathParser pathParser = createRequestPathParser(pluginRegistry);
List<IGatewayInitializer> initializers = createInitializers(pluginRegistry);
for (IGatewayInitializer initializer : initializers) {
initializer.initialize();
}
complete();
return new EngineImpl(registry, pluginRegistry, componentRegistry, cfactory, pfactory, metrics, logFactory, pathParser);
} | [
"@",
"Override",
"public",
"final",
"IEngine",
"createEngine",
"(",
")",
"{",
"IPluginRegistry",
"pluginRegistry",
"=",
"createPluginRegistry",
"(",
")",
";",
"IDataEncrypter",
"encrypter",
"=",
"createDataEncrypter",
"(",
"pluginRegistry",
")",
";",
"CurrentDataEncry... | Call this to create a new engine. This method uses the engine
config singleton to create the engine. | [
"Call",
"this",
"to",
"create",
"a",
"new",
"engine",
".",
"This",
"method",
"uses",
"the",
"engine",
"config",
"singleton",
"to",
"create",
"the",
"engine",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/AbstractEngineFactory.java#L51-L71 |
RestComm/Restcomm-Connect | restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/JBossConnectorDiscover.java | JBossConnectorDiscover.findConnectors | @Override
public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException,
InstanceNotFoundException, MBeanException, ReflectionException {
"""
A list of connectors. Not bound connectors will be discarded.
@return
@throws MalformedObjectNameException
@throws NullPointerException
@throws UnknownHostException
@throws AttributeNotFoundException
@throws InstanceNotFoundException
@throws MBeanException
@throws ReflectionException
"""
LOG.info("Searching JBoss HTTP connectors.");
HttpConnectorList httpConnectorList = null;
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> jbossObjs = mbs.queryNames(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http*"), null);
LOG.info("JBoss Mbean found.");
ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>();
if (jbossObjs != null && jbossObjs.size() > 0) {
LOG.info("JBoss Connectors found:" + jbossObjs.size());
for (ObjectName obj : jbossObjs) {
Boolean bound = (Boolean) mbs.getAttribute(obj, "bound");
if (bound) {
String scheme = mbs.getAttribute(obj, "name").toString().replaceAll("\"", "");
Integer port = (Integer) mbs.getAttribute(obj, "boundPort");
String address = ((String) mbs.getAttribute(obj, "boundAddress")).replaceAll("\"", "");
if (LOG.isInfoEnabled()) {
LOG.info("Jboss Http Connector: " + scheme + "://" + address + ":" + port);
}
HttpConnector httpConnector = new HttpConnector(scheme, address, port, scheme.equalsIgnoreCase("https"));
endPoints.add(httpConnector);
} else {
LOG.info("JBoss Connector not bound,discarding.");
}
}
}
if (endPoints.isEmpty()) {
LOG.warn("Coundn't discover any Http Interfaces.");
}
httpConnectorList = new HttpConnectorList(endPoints);
return httpConnectorList;
} | java | @Override
public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException,
InstanceNotFoundException, MBeanException, ReflectionException {
LOG.info("Searching JBoss HTTP connectors.");
HttpConnectorList httpConnectorList = null;
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> jbossObjs = mbs.queryNames(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http*"), null);
LOG.info("JBoss Mbean found.");
ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>();
if (jbossObjs != null && jbossObjs.size() > 0) {
LOG.info("JBoss Connectors found:" + jbossObjs.size());
for (ObjectName obj : jbossObjs) {
Boolean bound = (Boolean) mbs.getAttribute(obj, "bound");
if (bound) {
String scheme = mbs.getAttribute(obj, "name").toString().replaceAll("\"", "");
Integer port = (Integer) mbs.getAttribute(obj, "boundPort");
String address = ((String) mbs.getAttribute(obj, "boundAddress")).replaceAll("\"", "");
if (LOG.isInfoEnabled()) {
LOG.info("Jboss Http Connector: " + scheme + "://" + address + ":" + port);
}
HttpConnector httpConnector = new HttpConnector(scheme, address, port, scheme.equalsIgnoreCase("https"));
endPoints.add(httpConnector);
} else {
LOG.info("JBoss Connector not bound,discarding.");
}
}
}
if (endPoints.isEmpty()) {
LOG.warn("Coundn't discover any Http Interfaces.");
}
httpConnectorList = new HttpConnectorList(endPoints);
return httpConnectorList;
} | [
"@",
"Override",
"public",
"HttpConnectorList",
"findConnectors",
"(",
")",
"throws",
"MalformedObjectNameException",
",",
"NullPointerException",
",",
"UnknownHostException",
",",
"AttributeNotFoundException",
",",
"InstanceNotFoundException",
",",
"MBeanException",
",",
"Re... | A list of connectors. Not bound connectors will be discarded.
@return
@throws MalformedObjectNameException
@throws NullPointerException
@throws UnknownHostException
@throws AttributeNotFoundException
@throws InstanceNotFoundException
@throws MBeanException
@throws ReflectionException | [
"A",
"list",
"of",
"connectors",
".",
"Not",
"bound",
"connectors",
"will",
"be",
"discarded",
"."
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/JBossConnectorDiscover.java#L53-L86 |
OpenTSDB/opentsdb | src/core/Tags.java | Tags.getTags | static Map<String, String> getTags(final TSDB tsdb,
final byte[] row) throws NoSuchUniqueId {
"""
Returns the tags stored in the given row key.
@param tsdb The TSDB instance to use for Unique ID lookups.
@param row The row key from which to extract the tags.
@return A map of tag names (keys), tag values (values).
@throws NoSuchUniqueId if the row key contained an invalid ID (unlikely).
"""
try {
return getTagsAsync(tsdb, row).joinUninterruptibly();
} catch (DeferredGroupException e) {
final Throwable ex = Exceptions.getCause(e);
if (ex instanceof NoSuchUniqueId) {
throw (NoSuchUniqueId)ex;
}
throw new RuntimeException("Should never be here", e);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Should never be here", e);
}
} | java | static Map<String, String> getTags(final TSDB tsdb,
final byte[] row) throws NoSuchUniqueId {
try {
return getTagsAsync(tsdb, row).joinUninterruptibly();
} catch (DeferredGroupException e) {
final Throwable ex = Exceptions.getCause(e);
if (ex instanceof NoSuchUniqueId) {
throw (NoSuchUniqueId)ex;
}
throw new RuntimeException("Should never be here", e);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Should never be here", e);
}
} | [
"static",
"Map",
"<",
"String",
",",
"String",
">",
"getTags",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"byte",
"[",
"]",
"row",
")",
"throws",
"NoSuchUniqueId",
"{",
"try",
"{",
"return",
"getTagsAsync",
"(",
"tsdb",
",",
"row",
")",
".",
"joinUnin... | Returns the tags stored in the given row key.
@param tsdb The TSDB instance to use for Unique ID lookups.
@param row The row key from which to extract the tags.
@return A map of tag names (keys), tag values (values).
@throws NoSuchUniqueId if the row key contained an invalid ID (unlikely). | [
"Returns",
"the",
"tags",
"stored",
"in",
"the",
"given",
"row",
"key",
"."
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/Tags.java#L405-L421 |
padrig64/ValidationFramework | validationframework-core/src/main/java/com/google/code/validationframework/base/validator/generalvalidator/GeneralValidator.java | GeneralValidator.processEachRuleWithEachResultHandler | @SuppressWarnings("unchecked") // NOSONAR (Avoid Duplicate Literals)
private void processEachRuleWithEachResultHandler(RI ruleInput) {
"""
Processes the specified rule input with each rule, and processes the results of each rule one by one with each
result handler.
@param ruleInput Rule input to be validated.
"""
// For each rule
for (Rule<RI, RO> rule : rules) {
// Validate the data and get the rule output
Object ruleOutput = rule.validate(ruleInput);
// Transform the rule output
if (ruleOutputTransformers != null) {
for (Transformer transformer : ruleOutputTransformers) {
ruleOutput = transformer.transform(ruleOutput);
}
}
// Transform the transformed rule output to result handler input
if (resultHandlerInputTransformers != null) {
for (Transformer transformer : resultHandlerInputTransformers) {
ruleOutput = transformer.transform(ruleOutput);
}
}
RHI resultHandlerInput = (RHI) ruleOutput;
// Process the result handler input with the result handlers
processResultHandlers(resultHandlerInput);
}
} | java | @SuppressWarnings("unchecked") // NOSONAR (Avoid Duplicate Literals)
private void processEachRuleWithEachResultHandler(RI ruleInput) {
// For each rule
for (Rule<RI, RO> rule : rules) {
// Validate the data and get the rule output
Object ruleOutput = rule.validate(ruleInput);
// Transform the rule output
if (ruleOutputTransformers != null) {
for (Transformer transformer : ruleOutputTransformers) {
ruleOutput = transformer.transform(ruleOutput);
}
}
// Transform the transformed rule output to result handler input
if (resultHandlerInputTransformers != null) {
for (Transformer transformer : resultHandlerInputTransformers) {
ruleOutput = transformer.transform(ruleOutput);
}
}
RHI resultHandlerInput = (RHI) ruleOutput;
// Process the result handler input with the result handlers
processResultHandlers(resultHandlerInput);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// NOSONAR (Avoid Duplicate Literals)",
"private",
"void",
"processEachRuleWithEachResultHandler",
"(",
"RI",
"ruleInput",
")",
"{",
"// For each rule",
"for",
"(",
"Rule",
"<",
"RI",
",",
"RO",
">",
"rule",
":",
... | Processes the specified rule input with each rule, and processes the results of each rule one by one with each
result handler.
@param ruleInput Rule input to be validated. | [
"Processes",
"the",
"specified",
"rule",
"input",
"with",
"each",
"rule",
"and",
"processes",
"the",
"results",
"of",
"each",
"rule",
"one",
"by",
"one",
"with",
"each",
"result",
"handler",
"."
] | train | https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-core/src/main/java/com/google/code/validationframework/base/validator/generalvalidator/GeneralValidator.java#L454-L479 |
ZieIony/Carbon | carbon/src/main/java/carbon/drawable/ripple/RippleDrawableICS.java | RippleDrawableICS.tryRippleEnter | private void tryRippleEnter() {
"""
Attempts to start an enter animation for the active hotspot. Fails if there are too many
animating ripples.
"""
if (mExitingRipplesCount >= MAX_RIPPLES) {
// This should never happen unless the user is tapping like a maniac
// or there is a bug that's preventing ripples from being removed.
return;
}
if (mRipple == null) {
final float x;
final float y;
if (mHasPending) {
mHasPending = false;
x = mPendingX;
y = mPendingY;
} else {
x = mHotspotBounds.exactCenterX();
y = mHotspotBounds.exactCenterY();
}
final boolean isBounded = isBounded();
mRipple = new RippleForeground(this, mHotspotBounds, x, y, isBounded);
}
mRipple.setup(mState.mMaxRadius, mDensity);
mRipple.enter(false);
} | java | private void tryRippleEnter() {
if (mExitingRipplesCount >= MAX_RIPPLES) {
// This should never happen unless the user is tapping like a maniac
// or there is a bug that's preventing ripples from being removed.
return;
}
if (mRipple == null) {
final float x;
final float y;
if (mHasPending) {
mHasPending = false;
x = mPendingX;
y = mPendingY;
} else {
x = mHotspotBounds.exactCenterX();
y = mHotspotBounds.exactCenterY();
}
final boolean isBounded = isBounded();
mRipple = new RippleForeground(this, mHotspotBounds, x, y, isBounded);
}
mRipple.setup(mState.mMaxRadius, mDensity);
mRipple.enter(false);
} | [
"private",
"void",
"tryRippleEnter",
"(",
")",
"{",
"if",
"(",
"mExitingRipplesCount",
">=",
"MAX_RIPPLES",
")",
"{",
"// This should never happen unless the user is tapping like a maniac",
"// or there is a bug that's preventing ripples from being removed.",
"return",
";",
"}",
... | Attempts to start an enter animation for the active hotspot. Fails if there are too many
animating ripples. | [
"Attempts",
"to",
"start",
"an",
"enter",
"animation",
"for",
"the",
"active",
"hotspot",
".",
"Fails",
"if",
"there",
"are",
"too",
"many",
"animating",
"ripples",
"."
] | train | https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/drawable/ripple/RippleDrawableICS.java#L567-L592 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/apache/logging/log4j/Level.java | Level.forName | public static Level forName(final String name, final int intValue) {
"""
Retrieves an existing Level or creates on if it didn't previously exist.
@param name The name of the level.
@param intValue The integer value for the Level. If the level was previously created this value is ignored.
@return The Level.
@throws java.lang.IllegalArgumentException if the name is null or intValue is less than zero.
"""
final Level level = LEVELS.get(name);
if (level != null) {
return level;
}
try {
return new Level(name, intValue);
} catch (final IllegalStateException ex) {
// The level was added by something else so just return that one.
return LEVELS.get(name);
}
} | java | public static Level forName(final String name, final int intValue) {
final Level level = LEVELS.get(name);
if (level != null) {
return level;
}
try {
return new Level(name, intValue);
} catch (final IllegalStateException ex) {
// The level was added by something else so just return that one.
return LEVELS.get(name);
}
} | [
"public",
"static",
"Level",
"forName",
"(",
"final",
"String",
"name",
",",
"final",
"int",
"intValue",
")",
"{",
"final",
"Level",
"level",
"=",
"LEVELS",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"level",
"!=",
"null",
")",
"{",
"return",
"lev... | Retrieves an existing Level or creates on if it didn't previously exist.
@param name The name of the level.
@param intValue The integer value for the Level. If the level was previously created this value is ignored.
@return The Level.
@throws java.lang.IllegalArgumentException if the name is null or intValue is less than zero. | [
"Retrieves",
"an",
"existing",
"Level",
"or",
"creates",
"on",
"if",
"it",
"didn",
"t",
"previously",
"exist",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/Level.java#L241-L252 |
romannurik/muzei | muzei-api/src/main/java/com/google/android/apps/muzei/api/Artwork.java | Artwork.setComponentName | public void setComponentName(Context context, Class<? extends MuzeiArtSource> source) {
"""
Sets the {@link ComponentName} of the {@link MuzeiArtSource} providing this artwork.
This will automatically be set for you by Muzei.
@param context context to use to construct the {@link ComponentName}.
@param source the {@link MuzeiArtSource} providing this artwork.
"""
mComponentName = new ComponentName(context, source);
} | java | public void setComponentName(Context context, Class<? extends MuzeiArtSource> source) {
mComponentName = new ComponentName(context, source);
} | [
"public",
"void",
"setComponentName",
"(",
"Context",
"context",
",",
"Class",
"<",
"?",
"extends",
"MuzeiArtSource",
">",
"source",
")",
"{",
"mComponentName",
"=",
"new",
"ComponentName",
"(",
"context",
",",
"source",
")",
";",
"}"
] | Sets the {@link ComponentName} of the {@link MuzeiArtSource} providing this artwork.
This will automatically be set for you by Muzei.
@param context context to use to construct the {@link ComponentName}.
@param source the {@link MuzeiArtSource} providing this artwork. | [
"Sets",
"the",
"{",
"@link",
"ComponentName",
"}",
"of",
"the",
"{",
"@link",
"MuzeiArtSource",
"}",
"providing",
"this",
"artwork",
".",
"This",
"will",
"automatically",
"be",
"set",
"for",
"you",
"by",
"Muzei",
"."
] | train | https://github.com/romannurik/muzei/blob/d00777a5fc59f34471be338c814ea85ddcbde304/muzei-api/src/main/java/com/google/android/apps/muzei/api/Artwork.java#L200-L202 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/Validate.java | Validate.noNullElements | @GwtIncompatible("incompatible method")
public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
"""
<p>Validate that the specified argument iterable is neither
{@code null} nor contains any elements that are {@code null};
otherwise throwing an exception with the specified message.
<pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre>
<p>If the iterable is {@code null}, then the message in the exception
is "The validated object is null".</p>
<p>If the iterable has a {@code null} element, then the iteration
index of the invalid element is appended to the {@code values}
argument.</p>
@param <T> the iterable type
@param iterable the iterable to check, validated not null by this method
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@return the validated iterable (never {@code null} method for chaining)
@throws NullPointerException if the array is {@code null}
@throws IllegalArgumentException if an element is {@code null}
@see #noNullElements(Iterable)
"""
Validate.notNull(iterable);
int i = 0;
for (final Iterator<?> it = iterable.iterator(); it.hasNext(); i++) {
if (it.next() == null) {
final Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i));
throw new IllegalArgumentException(StringUtils.simpleFormat(message, values2));
}
}
return iterable;
} | java | @GwtIncompatible("incompatible method")
public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) {
Validate.notNull(iterable);
int i = 0;
for (final Iterator<?> it = iterable.iterator(); it.hasNext(); i++) {
if (it.next() == null) {
final Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i));
throw new IllegalArgumentException(StringUtils.simpleFormat(message, values2));
}
}
return iterable;
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"public",
"static",
"<",
"T",
"extends",
"Iterable",
"<",
"?",
">",
">",
"T",
"noNullElements",
"(",
"final",
"T",
"iterable",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"val... | <p>Validate that the specified argument iterable is neither
{@code null} nor contains any elements that are {@code null};
otherwise throwing an exception with the specified message.
<pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre>
<p>If the iterable is {@code null}, then the message in the exception
is "The validated object is null".</p>
<p>If the iterable has a {@code null} element, then the iteration
index of the invalid element is appended to the {@code values}
argument.</p>
@param <T> the iterable type
@param iterable the iterable to check, validated not null by this method
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@return the validated iterable (never {@code null} method for chaining)
@throws NullPointerException if the array is {@code null}
@throws IllegalArgumentException if an element is {@code null}
@see #noNullElements(Iterable) | [
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"iterable",
"is",
"neither",
"{",
"@code",
"null",
"}",
"nor",
"contains",
"any",
"elements",
"that",
"are",
"{",
"@code",
"null",
"}",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L574-L585 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/SipCall.java | SipCall.initiateOutgoingMessage | public boolean initiateOutgoingMessage(String toUri, String viaNonProxyRoute) {
"""
This basic method is used to initiate an outgoing MESSAGE.
<p>
This method returns when the request message has been sent out. Your calling program must
subsequently call the waitOutgoingMessageResponse() method (one or more times) to get the
result(s).
<p>
If a DIALOG exists the method will use it to send the MESSAGE
@param toUri The URI (sip:bob@nist.gov) to which the message should be directed
@param viaNonProxyRoute Indicates whether to route the MESSAGE via Proxy or some other route.
If null, route the call to the Proxy that was specified when the SipPhone object was
created (SipStack.createSipPhone()). Else route it to the given node, which is specified
as "hostaddress:port;parms/transport" i.e. 129.1.22.333:5060;lr/UDP.
@return true if the message was successfully sent, false otherwise.
"""
return initiateOutgoingMessage(null, toUri, viaNonProxyRoute, null, null, null);
} | java | public boolean initiateOutgoingMessage(String toUri, String viaNonProxyRoute) {
return initiateOutgoingMessage(null, toUri, viaNonProxyRoute, null, null, null);
} | [
"public",
"boolean",
"initiateOutgoingMessage",
"(",
"String",
"toUri",
",",
"String",
"viaNonProxyRoute",
")",
"{",
"return",
"initiateOutgoingMessage",
"(",
"null",
",",
"toUri",
",",
"viaNonProxyRoute",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}"
] | This basic method is used to initiate an outgoing MESSAGE.
<p>
This method returns when the request message has been sent out. Your calling program must
subsequently call the waitOutgoingMessageResponse() method (one or more times) to get the
result(s).
<p>
If a DIALOG exists the method will use it to send the MESSAGE
@param toUri The URI (sip:bob@nist.gov) to which the message should be directed
@param viaNonProxyRoute Indicates whether to route the MESSAGE via Proxy or some other route.
If null, route the call to the Proxy that was specified when the SipPhone object was
created (SipStack.createSipPhone()). Else route it to the given node, which is specified
as "hostaddress:port;parms/transport" i.e. 129.1.22.333:5060;lr/UDP.
@return true if the message was successfully sent, false otherwise. | [
"This",
"basic",
"method",
"is",
"used",
"to",
"initiate",
"an",
"outgoing",
"MESSAGE",
"."
] | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipCall.java#L746-L748 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.1/src/com/ibm/ws/microprofile/config/converters/UserConverter.java | UserConverter.newInstance | @Trivial
public static <K> UserConverter<K> newInstance(Type type, Converter<K> converter) {
"""
Construct a new PriorityConverter using discovered or default priority
@param converter
"""
return newInstance(type, getPriority(converter), converter);
} | java | @Trivial
public static <K> UserConverter<K> newInstance(Type type, Converter<K> converter) {
return newInstance(type, getPriority(converter), converter);
} | [
"@",
"Trivial",
"public",
"static",
"<",
"K",
">",
"UserConverter",
"<",
"K",
">",
"newInstance",
"(",
"Type",
"type",
",",
"Converter",
"<",
"K",
">",
"converter",
")",
"{",
"return",
"newInstance",
"(",
"type",
",",
"getPriority",
"(",
"converter",
")"... | Construct a new PriorityConverter using discovered or default priority
@param converter | [
"Construct",
"a",
"new",
"PriorityConverter",
"using",
"discovered",
"or",
"default",
"priority"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.1/src/com/ibm/ws/microprofile/config/converters/UserConverter.java#L50-L53 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java | CheckBoxMenuItemPainter.paintCheckIconEnabledAndSelected | private void paintCheckIconEnabledAndSelected(Graphics2D g, int width, int height) {
"""
Paint the check mark in enabled state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height.
"""
Shape s = shapeGenerator.createCheckMark(0, 0, width, height);
g.setPaint(iconEnabledSelected);
g.fill(s);
} | java | private void paintCheckIconEnabledAndSelected(Graphics2D g, int width, int height) {
Shape s = shapeGenerator.createCheckMark(0, 0, width, height);
g.setPaint(iconEnabledSelected);
g.fill(s);
} | [
"private",
"void",
"paintCheckIconEnabledAndSelected",
"(",
"Graphics2D",
"g",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Shape",
"s",
"=",
"shapeGenerator",
".",
"createCheckMark",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"g",... | Paint the check mark in enabled state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height. | [
"Paint",
"the",
"check",
"mark",
"in",
"enabled",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java#L147-L151 |
trellis-ldp-archive/trellis-http | src/main/java/org/trellisldp/http/domain/Digest.java | Digest.valueOf | public static Digest valueOf(final String value) {
"""
Get a Digest object from a string-based header value
@param value the header value
@return a Digest object or null if the value is invalid
"""
final String[] parts = value.split("=", 2);
if (parts.length == 2) {
return new Digest(parts[0], parts[1]);
}
return null;
} | java | public static Digest valueOf(final String value) {
final String[] parts = value.split("=", 2);
if (parts.length == 2) {
return new Digest(parts[0], parts[1]);
}
return null;
} | [
"public",
"static",
"Digest",
"valueOf",
"(",
"final",
"String",
"value",
")",
"{",
"final",
"String",
"[",
"]",
"parts",
"=",
"value",
".",
"split",
"(",
"\"=\"",
",",
"2",
")",
";",
"if",
"(",
"parts",
".",
"length",
"==",
"2",
")",
"{",
"return"... | Get a Digest object from a string-based header value
@param value the header value
@return a Digest object or null if the value is invalid | [
"Get",
"a",
"Digest",
"object",
"from",
"a",
"string",
"-",
"based",
"header",
"value"
] | train | https://github.com/trellis-ldp-archive/trellis-http/blob/bc762f88602c49c2b137a7adf68d576666e55fff/src/main/java/org/trellisldp/http/domain/Digest.java#L60-L66 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/SipCall.java | SipCall.waitForCancelResponse | public boolean waitForCancelResponse(SipTransaction siptrans, long timeout) {
"""
The waitForCancelResponse() method waits for a response to be received from the network for a
sent CANCEL. Call this method after calling sendCancel().
<p>
This method blocks until one of the following occurs: 1) A response message has been received.
In this case, a value of true is returned. Call the getLastReceivedResponse() method to get the
response details. 2) A timeout occurs. A false value is returned in this case. 3) An error
occurs. False is returned in this case.
<p>
Regardless of the outcome, getReturnCode() can be called after this method returns to get the
status code: IE, the SIP response code received from the network (defined in SipResponse, along
with the corresponding textual equivalent) or a SipUnit internal status/error code (defined in
SipSession, along with the corresponding textual equivalent). SipUnit internal codes are in a
specially designated range (SipSession.SIPUNIT_INTERNAL_RETURNCODE_MIN and upward).
<p>
@param siptrans This is the object that was returned by method sendCancel(). It identifies a
specific Cancel transaction.
@param timeout The maximum amount of time to wait, in milliseconds. Use a value of 0 to wait
indefinitely.
@return true if a response was received - in that case, call getReturnCode() to get the status
code that was contained in the received response, and/or call getLastReceivedResponse()
to see the response details. Returns false if timeout or error.
"""
initErrorInfo();
if (siptrans == null) {
returnCode = SipSession.INVALID_OPERATION;
errorMessage = (String) SipSession.statusCodeDescription.get(new Integer(returnCode))
+ " - no RE-INVITE transaction object given";
return false;
}
EventObject response_event = parent.waitResponse(siptrans, timeout);
if (response_event == null) {
setErrorMessage(parent.getErrorMessage());
setException(parent.getException());
setReturnCode(parent.getReturnCode());
return false;
}
if (response_event instanceof TimeoutEvent) {
setReturnCode(SipPhone.TIMEOUT_OCCURRED);
setErrorMessage("A Timeout Event was received");
return false;
}
Response resp = ((ResponseEvent) response_event).getResponse();
receivedResponses.add(new SipResponse((ResponseEvent) response_event));
LOG.info("CANCEL response received: {}", resp.toString());
setReturnCode(resp.getStatusCode());
return true;
} | java | public boolean waitForCancelResponse(SipTransaction siptrans, long timeout) {
initErrorInfo();
if (siptrans == null) {
returnCode = SipSession.INVALID_OPERATION;
errorMessage = (String) SipSession.statusCodeDescription.get(new Integer(returnCode))
+ " - no RE-INVITE transaction object given";
return false;
}
EventObject response_event = parent.waitResponse(siptrans, timeout);
if (response_event == null) {
setErrorMessage(parent.getErrorMessage());
setException(parent.getException());
setReturnCode(parent.getReturnCode());
return false;
}
if (response_event instanceof TimeoutEvent) {
setReturnCode(SipPhone.TIMEOUT_OCCURRED);
setErrorMessage("A Timeout Event was received");
return false;
}
Response resp = ((ResponseEvent) response_event).getResponse();
receivedResponses.add(new SipResponse((ResponseEvent) response_event));
LOG.info("CANCEL response received: {}", resp.toString());
setReturnCode(resp.getStatusCode());
return true;
} | [
"public",
"boolean",
"waitForCancelResponse",
"(",
"SipTransaction",
"siptrans",
",",
"long",
"timeout",
")",
"{",
"initErrorInfo",
"(",
")",
";",
"if",
"(",
"siptrans",
"==",
"null",
")",
"{",
"returnCode",
"=",
"SipSession",
".",
"INVALID_OPERATION",
";",
"e... | The waitForCancelResponse() method waits for a response to be received from the network for a
sent CANCEL. Call this method after calling sendCancel().
<p>
This method blocks until one of the following occurs: 1) A response message has been received.
In this case, a value of true is returned. Call the getLastReceivedResponse() method to get the
response details. 2) A timeout occurs. A false value is returned in this case. 3) An error
occurs. False is returned in this case.
<p>
Regardless of the outcome, getReturnCode() can be called after this method returns to get the
status code: IE, the SIP response code received from the network (defined in SipResponse, along
with the corresponding textual equivalent) or a SipUnit internal status/error code (defined in
SipSession, along with the corresponding textual equivalent). SipUnit internal codes are in a
specially designated range (SipSession.SIPUNIT_INTERNAL_RETURNCODE_MIN and upward).
<p>
@param siptrans This is the object that was returned by method sendCancel(). It identifies a
specific Cancel transaction.
@param timeout The maximum amount of time to wait, in milliseconds. Use a value of 0 to wait
indefinitely.
@return true if a response was received - in that case, call getReturnCode() to get the status
code that was contained in the received response, and/or call getLastReceivedResponse()
to see the response details. Returns false if timeout or error. | [
"The",
"waitForCancelResponse",
"()",
"method",
"waits",
"for",
"a",
"response",
"to",
"be",
"received",
"from",
"the",
"network",
"for",
"a",
"sent",
"CANCEL",
".",
"Call",
"this",
"method",
"after",
"calling",
"sendCancel",
"()",
".",
"<p",
">",
"This",
... | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipCall.java#L3388-L3420 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java | Trigger.setInertia | public void setInertia(Long inertiaMillis) {
"""
Sets the inertia associated with the trigger in milliseconds.
@param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative.
"""
if (this.alert == null) { // Only during deserialization.
this.inertia = inertiaMillis;
} else {
requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative.");
Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression());
if (inertiaMillis > longestIntervalLength)
throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength));
this.inertia = inertiaMillis;
}
} | java | public void setInertia(Long inertiaMillis) {
if (this.alert == null) { // Only during deserialization.
this.inertia = inertiaMillis;
} else {
requireArgument(inertiaMillis != null && inertiaMillis >= 0, "Inertia cannot be negative.");
Long longestIntervalLength = AlertUtils.getMaximumIntervalLength(this.alert.getExpression());
if (inertiaMillis > longestIntervalLength)
throw new IllegalArgumentException(String.format("Inertia %d cannot be more than width of the longest interval %d.", inertiaMillis, longestIntervalLength));
this.inertia = inertiaMillis;
}
} | [
"public",
"void",
"setInertia",
"(",
"Long",
"inertiaMillis",
")",
"{",
"if",
"(",
"this",
".",
"alert",
"==",
"null",
")",
"{",
"// Only during deserialization.",
"this",
".",
"inertia",
"=",
"inertiaMillis",
";",
"}",
"else",
"{",
"requireArgument",
"(",
"... | Sets the inertia associated with the trigger in milliseconds.
@param inertiaMillis The inertia associated with the trigger in milliseconds. Cannot be null or negative. | [
"Sets",
"the",
"inertia",
"associated",
"with",
"the",
"trigger",
"in",
"milliseconds",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java#L364-L374 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Getter.java | Getter.getView | public <T extends View> T getView(Class<T> classToFilterBy, int index) {
"""
Returns a {@code View} with a certain index, from the list of current {@code View}s of the specified type.
@param classToFilterBy which {@code View}s to choose from
@param index choose among all instances of this type, e.g. {@code Button.class} or {@code EditText.class}
@return a {@code View} with a certain index, from the list of current {@code View}s of the specified type
"""
return waiter.waitForAndGetView(index, classToFilterBy);
} | java | public <T extends View> T getView(Class<T> classToFilterBy, int index) {
return waiter.waitForAndGetView(index, classToFilterBy);
} | [
"public",
"<",
"T",
"extends",
"View",
">",
"T",
"getView",
"(",
"Class",
"<",
"T",
">",
"classToFilterBy",
",",
"int",
"index",
")",
"{",
"return",
"waiter",
".",
"waitForAndGetView",
"(",
"index",
",",
"classToFilterBy",
")",
";",
"}"
] | Returns a {@code View} with a certain index, from the list of current {@code View}s of the specified type.
@param classToFilterBy which {@code View}s to choose from
@param index choose among all instances of this type, e.g. {@code Button.class} or {@code EditText.class}
@return a {@code View} with a certain index, from the list of current {@code View}s of the specified type | [
"Returns",
"a",
"{",
"@code",
"View",
"}",
"with",
"a",
"certain",
"index",
"from",
"the",
"list",
"of",
"current",
"{",
"@code",
"View",
"}",
"s",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Getter.java#L50-L52 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java | TextModerationsImpl.detectLanguageAsync | public Observable<DetectedLanguage> detectLanguageAsync(String textContentType, byte[] textContent) {
"""
This operation will detect the language of given input content. Returns the <a href="http://www-01.sil.org/iso639-3/codes.asp">ISO 639-3 code</a> for the predominant language comprising the submitted text. Over 110 languages supported.
@param textContentType The content type. Possible values include: 'text/plain', 'text/html', 'text/xml', 'text/markdown'
@param textContent Content to screen.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DetectedLanguage object
"""
return detectLanguageWithServiceResponseAsync(textContentType, textContent).map(new Func1<ServiceResponse<DetectedLanguage>, DetectedLanguage>() {
@Override
public DetectedLanguage call(ServiceResponse<DetectedLanguage> response) {
return response.body();
}
});
} | java | public Observable<DetectedLanguage> detectLanguageAsync(String textContentType, byte[] textContent) {
return detectLanguageWithServiceResponseAsync(textContentType, textContent).map(new Func1<ServiceResponse<DetectedLanguage>, DetectedLanguage>() {
@Override
public DetectedLanguage call(ServiceResponse<DetectedLanguage> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DetectedLanguage",
">",
"detectLanguageAsync",
"(",
"String",
"textContentType",
",",
"byte",
"[",
"]",
"textContent",
")",
"{",
"return",
"detectLanguageWithServiceResponseAsync",
"(",
"textContentType",
",",
"textContent",
")",
".",
"ma... | This operation will detect the language of given input content. Returns the <a href="http://www-01.sil.org/iso639-3/codes.asp">ISO 639-3 code</a> for the predominant language comprising the submitted text. Over 110 languages supported.
@param textContentType The content type. Possible values include: 'text/plain', 'text/html', 'text/xml', 'text/markdown'
@param textContent Content to screen.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DetectedLanguage object | [
"This",
"operation",
"will",
"detect",
"the",
"language",
"of",
"given",
"input",
"content",
".",
"Returns",
"the",
"<",
";",
"a",
"href",
"=",
"http",
":",
"//",
"www",
"-",
"01",
".",
"sil",
".",
"org",
"/",
"iso639",
"-",
"3",
"/",
"codes",
".... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java#L317-L324 |
alibaba/Tangram-Android | tangram/src/main/java/com/tmall/wireless/tangram3/BaseTangramEngine.java | BaseTangramEngine.replaceData | @Deprecated
public void replaceData(int position, @Nullable List<Card> data) {
"""
Replace original data to Tangram at target position. It cause full screen item's rebinding, be careful.
@param position Target replace position.
@param data Parsed data list.
"""
Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first");
this.mGroupBasicAdapter.replaceGroup(position, data);
} | java | @Deprecated
public void replaceData(int position, @Nullable List<Card> data) {
Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first");
this.mGroupBasicAdapter.replaceGroup(position, data);
} | [
"@",
"Deprecated",
"public",
"void",
"replaceData",
"(",
"int",
"position",
",",
"@",
"Nullable",
"List",
"<",
"Card",
">",
"data",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"mGroupBasicAdapter",
"!=",
"null",
",",
"\"Must call bindView() first\"",
")",... | Replace original data to Tangram at target position. It cause full screen item's rebinding, be careful.
@param position Target replace position.
@param data Parsed data list. | [
"Replace",
"original",
"data",
"to",
"Tangram",
"at",
"target",
"position",
".",
"It",
"cause",
"full",
"screen",
"item",
"s",
"rebinding",
"be",
"careful",
"."
] | train | https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/BaseTangramEngine.java#L349-L353 |
petergeneric/stdlib | util/carbon-client/src/main/java/com/peterphi/carbon/type/XMLWrapper.java | XMLWrapper.getElement | protected Element getElement(String name, int index) {
"""
Helper method to retrieve a child element with a particular name and index
@param name
the name of the element
@param index
the index (where 0 is the first element with that name)
@return an Element (or null if none could be found by that name or with that index)
"""
List<Element> children = getElement().getChildren(name);
if (children.size() > index)
return children.get(index);
else
return null;
} | java | protected Element getElement(String name, int index)
{
List<Element> children = getElement().getChildren(name);
if (children.size() > index)
return children.get(index);
else
return null;
} | [
"protected",
"Element",
"getElement",
"(",
"String",
"name",
",",
"int",
"index",
")",
"{",
"List",
"<",
"Element",
">",
"children",
"=",
"getElement",
"(",
")",
".",
"getChildren",
"(",
"name",
")",
";",
"if",
"(",
"children",
".",
"size",
"(",
")",
... | Helper method to retrieve a child element with a particular name and index
@param name
the name of the element
@param index
the index (where 0 is the first element with that name)
@return an Element (or null if none could be found by that name or with that index) | [
"Helper",
"method",
"to",
"retrieve",
"a",
"child",
"element",
"with",
"a",
"particular",
"name",
"and",
"index"
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/util/carbon-client/src/main/java/com/peterphi/carbon/type/XMLWrapper.java#L72-L80 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java | KeyValueHandler.handleNoopRequest | private static BinaryMemcacheRequest handleNoopRequest(final ChannelHandlerContext ctx, final NoopRequest msg) {
"""
Encodes a {@link NoopRequest} into its lower level representation.
@param ctx the {@link ChannelHandlerContext} to use for allocation and others.
@param msg the incoming message.
@return a ready {@link BinaryMemcacheRequest}.
"""
BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest();
request.setOpcode(OP_NOOP);
return request;
} | java | private static BinaryMemcacheRequest handleNoopRequest(final ChannelHandlerContext ctx, final NoopRequest msg) {
BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest();
request.setOpcode(OP_NOOP);
return request;
} | [
"private",
"static",
"BinaryMemcacheRequest",
"handleNoopRequest",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"NoopRequest",
"msg",
")",
"{",
"BinaryMemcacheRequest",
"request",
"=",
"new",
"DefaultBinaryMemcacheRequest",
"(",
")",
";",
"request",
".",
... | Encodes a {@link NoopRequest} into its lower level representation.
@param ctx the {@link ChannelHandlerContext} to use for allocation and others.
@param msg the incoming message.
@return a ready {@link BinaryMemcacheRequest}. | [
"Encodes",
"a",
"{",
"@link",
"NoopRequest",
"}",
"into",
"its",
"lower",
"level",
"representation",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L471-L475 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/predicate/FullText.java | FullText.fullTextMatch | public static P<String> fullTextMatch(String configuration,final String value) {
"""
Build full text matching predicate (use in has(column,...))
@param configuration the full text configuration to use
@param value the value to search for
@return the predicate
"""
return fullTextMatch(configuration,false, value);
} | java | public static P<String> fullTextMatch(String configuration,final String value){
return fullTextMatch(configuration,false, value);
} | [
"public",
"static",
"P",
"<",
"String",
">",
"fullTextMatch",
"(",
"String",
"configuration",
",",
"final",
"String",
"value",
")",
"{",
"return",
"fullTextMatch",
"(",
"configuration",
",",
"false",
",",
"value",
")",
";",
"}"
] | Build full text matching predicate (use in has(column,...))
@param configuration the full text configuration to use
@param value the value to search for
@return the predicate | [
"Build",
"full",
"text",
"matching",
"predicate",
"(",
"use",
"in",
"has",
"(",
"column",
"...",
"))"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/predicate/FullText.java#L42-L44 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcSketch.java | CpcSketch.updateHIP | private static void updateHIP(final CpcSketch sketch, final int rowCol) {
"""
Call this whenever a new coupon has been collected.
@param sketch the given sketch
@param rowCol the given row / column
"""
final int k = 1 << sketch.lgK;
final int col = rowCol & 63;
final double oneOverP = k / sketch.kxp;
sketch.hipEstAccum += oneOverP;
sketch.kxp -= invPow2(col + 1); // notice the "+1"
} | java | private static void updateHIP(final CpcSketch sketch, final int rowCol) {
final int k = 1 << sketch.lgK;
final int col = rowCol & 63;
final double oneOverP = k / sketch.kxp;
sketch.hipEstAccum += oneOverP;
sketch.kxp -= invPow2(col + 1); // notice the "+1"
} | [
"private",
"static",
"void",
"updateHIP",
"(",
"final",
"CpcSketch",
"sketch",
",",
"final",
"int",
"rowCol",
")",
"{",
"final",
"int",
"k",
"=",
"1",
"<<",
"sketch",
".",
"lgK",
";",
"final",
"int",
"col",
"=",
"rowCol",
"&",
"63",
";",
"final",
"do... | Call this whenever a new coupon has been collected.
@param sketch the given sketch
@param rowCol the given row / column | [
"Call",
"this",
"whenever",
"a",
"new",
"coupon",
"has",
"been",
"collected",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcSketch.java#L559-L565 |
javabits/pojo-mbean | pojo-mbean-impl/src/main/java/org/softee/util/Preconditions.java | Preconditions.notNull | public static <E> E notNull(E obj, String msg) {
"""
An assertion method that makes null validation more fluent
@param <E> The type of elements
@param obj an Object
@param msg a message that is reported in the exception
@return {@code obj}
@throws NullPointerException if {@code obj} is null
"""
if (obj == null) {
throw (msg == null) ? new NullPointerException() : new NullPointerException(msg);
}
return obj;
} | java | public static <E> E notNull(E obj, String msg) {
if (obj == null) {
throw (msg == null) ? new NullPointerException() : new NullPointerException(msg);
}
return obj;
} | [
"public",
"static",
"<",
"E",
">",
"E",
"notNull",
"(",
"E",
"obj",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"(",
"msg",
"==",
"null",
")",
"?",
"new",
"NullPointerException",
"(",
")",
":",
"new",
"NullP... | An assertion method that makes null validation more fluent
@param <E> The type of elements
@param obj an Object
@param msg a message that is reported in the exception
@return {@code obj}
@throws NullPointerException if {@code obj} is null | [
"An",
"assertion",
"method",
"that",
"makes",
"null",
"validation",
"more",
"fluent"
] | train | https://github.com/javabits/pojo-mbean/blob/9aa7fb065e560ec1e3e63373b28cd95ad438b26a/pojo-mbean-impl/src/main/java/org/softee/util/Preconditions.java#L27-L32 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getDeletedCertificateAsync | public Observable<DeletedCertificateBundle> getDeletedCertificateAsync(String vaultBaseUrl, String certificateName) {
"""
Retrieves information about the specified deleted certificate.
The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires the certificates/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DeletedCertificateBundle object
"""
return getDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<DeletedCertificateBundle>, DeletedCertificateBundle>() {
@Override
public DeletedCertificateBundle call(ServiceResponse<DeletedCertificateBundle> response) {
return response.body();
}
});
} | java | public Observable<DeletedCertificateBundle> getDeletedCertificateAsync(String vaultBaseUrl, String certificateName) {
return getDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<DeletedCertificateBundle>, DeletedCertificateBundle>() {
@Override
public DeletedCertificateBundle call(ServiceResponse<DeletedCertificateBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DeletedCertificateBundle",
">",
"getDeletedCertificateAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"getDeletedCertificateWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",
... | Retrieves information about the specified deleted certificate.
The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires the certificates/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DeletedCertificateBundle object | [
"Retrieves",
"information",
"about",
"the",
"specified",
"deleted",
"certificate",
".",
"The",
"GetDeletedCertificate",
"operation",
"retrieves",
"the",
"deleted",
"certificate",
"information",
"plus",
"its",
"attributes",
"such",
"as",
"retention",
"interval",
"schedul... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L8561-L8568 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/xml/XmlConfiguration.java | XmlConfiguration.refObj | private Object refObj(Object obj, XmlParser.Node node) throws NoSuchMethodException,
ClassNotFoundException, InvocationTargetException, IllegalAccessException {
"""
/*
Reference an id value object.
@param obj @param node @return @exception NoSuchMethodException @exception
ClassNotFoundException @exception InvocationTargetException
"""
String id = node.getAttribute("id");
obj = _idMap.get(id);
if (obj == null) throw new IllegalStateException("No object for id=" + id);
configure(obj, node, 0);
return obj;
} | java | private Object refObj(Object obj, XmlParser.Node node) throws NoSuchMethodException,
ClassNotFoundException, InvocationTargetException, IllegalAccessException
{
String id = node.getAttribute("id");
obj = _idMap.get(id);
if (obj == null) throw new IllegalStateException("No object for id=" + id);
configure(obj, node, 0);
return obj;
} | [
"private",
"Object",
"refObj",
"(",
"Object",
"obj",
",",
"XmlParser",
".",
"Node",
"node",
")",
"throws",
"NoSuchMethodException",
",",
"ClassNotFoundException",
",",
"InvocationTargetException",
",",
"IllegalAccessException",
"{",
"String",
"id",
"=",
"node",
".",... | /*
Reference an id value object.
@param obj @param node @return @exception NoSuchMethodException @exception
ClassNotFoundException @exception InvocationTargetException | [
"/",
"*",
"Reference",
"an",
"id",
"value",
"object",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/xml/XmlConfiguration.java#L632-L640 |
aws/aws-cloudtrail-processing-library | src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/CloudTrailSourceSerializer.java | CloudTrailSourceSerializer.addCloudTrailLogsAndMessageAttributes | private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, List<CloudTrailLog> cloudTrailLogs, JsonNode messageNode) throws IOException {
"""
As long as there is at least one CloudTrail log object:
<p>
<li>Add the CloudTrail log object key to the list.</li>
<li>Add <code>accountId</code> extracted from log object key to <code>sqsMessage</code>.</li>
<li>Add {@link SourceType#CloudTrailLog} to the <code>sqsMessage</code>.</li>
</p>
If there is no CloudTrail log object and it is a valid CloudTrail message, CPL adds only {@link SourceType#Other}
to the <code>sqsMessage</code>.
"""
SourceType sourceType = SourceType.Other;
String bucketName = messageNode.get(S3_BUCKET_NAME).textValue();
List<String> objectKeys = mapper.readValue(messageNode.get(S3_OBJECT_KEY).traverse(), new TypeReference<List<String>>() {});
for (String objectKey: objectKeys) {
SourceType currSourceType = sourceIdentifier.identify(objectKey);
if (currSourceType == SourceType.CloudTrailLog) {
cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey));
sourceType = currSourceType;
LibraryUtils.setMessageAccountId(sqsMessage, objectKey);
}
}
sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name());
} | java | private void addCloudTrailLogsAndMessageAttributes(Message sqsMessage, List<CloudTrailLog> cloudTrailLogs, JsonNode messageNode) throws IOException {
SourceType sourceType = SourceType.Other;
String bucketName = messageNode.get(S3_BUCKET_NAME).textValue();
List<String> objectKeys = mapper.readValue(messageNode.get(S3_OBJECT_KEY).traverse(), new TypeReference<List<String>>() {});
for (String objectKey: objectKeys) {
SourceType currSourceType = sourceIdentifier.identify(objectKey);
if (currSourceType == SourceType.CloudTrailLog) {
cloudTrailLogs.add(new CloudTrailLog(bucketName, objectKey));
sourceType = currSourceType;
LibraryUtils.setMessageAccountId(sqsMessage, objectKey);
}
}
sqsMessage.addAttributesEntry(SourceAttributeKeys.SOURCE_TYPE.getAttributeKey(), sourceType.name());
} | [
"private",
"void",
"addCloudTrailLogsAndMessageAttributes",
"(",
"Message",
"sqsMessage",
",",
"List",
"<",
"CloudTrailLog",
">",
"cloudTrailLogs",
",",
"JsonNode",
"messageNode",
")",
"throws",
"IOException",
"{",
"SourceType",
"sourceType",
"=",
"SourceType",
".",
"... | As long as there is at least one CloudTrail log object:
<p>
<li>Add the CloudTrail log object key to the list.</li>
<li>Add <code>accountId</code> extracted from log object key to <code>sqsMessage</code>.</li>
<li>Add {@link SourceType#CloudTrailLog} to the <code>sqsMessage</code>.</li>
</p>
If there is no CloudTrail log object and it is a valid CloudTrail message, CPL adds only {@link SourceType#Other}
to the <code>sqsMessage</code>. | [
"As",
"long",
"as",
"there",
"is",
"at",
"least",
"one",
"CloudTrail",
"log",
"object",
":",
"<p",
">",
"<li",
">",
"Add",
"the",
"CloudTrail",
"log",
"object",
"key",
"to",
"the",
"list",
".",
"<",
"/",
"li",
">",
"<li",
">",
"Add",
"<code",
">",
... | train | https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/CloudTrailSourceSerializer.java#L79-L95 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java | DateTimeUtils.addSeconds | public static Calendar addSeconds(Calendar origin, int value) {
"""
Add/Subtract the specified amount of seconds to the given {@link Calendar}.
<p>
The returned {@link Calendar} has its fields synced.
</p>
@param origin
@param value
@return
@since 0.9.2
"""
Calendar cal = sync((Calendar) origin.clone());
cal.add(Calendar.SECOND, value);
return sync(cal);
} | java | public static Calendar addSeconds(Calendar origin, int value) {
Calendar cal = sync((Calendar) origin.clone());
cal.add(Calendar.SECOND, value);
return sync(cal);
} | [
"public",
"static",
"Calendar",
"addSeconds",
"(",
"Calendar",
"origin",
",",
"int",
"value",
")",
"{",
"Calendar",
"cal",
"=",
"sync",
"(",
"(",
"Calendar",
")",
"origin",
".",
"clone",
"(",
")",
")",
";",
"cal",
".",
"add",
"(",
"Calendar",
".",
"S... | Add/Subtract the specified amount of seconds to the given {@link Calendar}.
<p>
The returned {@link Calendar} has its fields synced.
</p>
@param origin
@param value
@return
@since 0.9.2 | [
"Add",
"/",
"Subtract",
"the",
"specified",
"amount",
"of",
"seconds",
"to",
"the",
"given",
"{",
"@link",
"Calendar",
"}",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java#L192-L196 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ObjectExtensions.java | ObjectExtensions.operator_elvis | @Pure
public static <T> T operator_elvis(T first, T second) {
"""
The elvis operator <code>?:</code> is a short hand notation for
providing default value in case an expression evaluates to <code>null</code>.
Not that the Xtend compiler will inline calls to this not call this method with a short-circuit semantic.
That is the second argument is only evaluated if the first one evaluates to <code>null</code>.
Example:
<code>person.name?:'Hans'</code>
@param first
an {@link Object}. Might be <code>null</code>.
@param second
an {@link Object}. Might be <code>null</code>.
@return a reference to <code>first</code> if <code>first != null </code>, <code>second<code> otherwise,
@since 2.3
"""
if (first != null)
return first;
return second;
} | java | @Pure
public static <T> T operator_elvis(T first, T second) {
if (first != null)
return first;
return second;
} | [
"@",
"Pure",
"public",
"static",
"<",
"T",
">",
"T",
"operator_elvis",
"(",
"T",
"first",
",",
"T",
"second",
")",
"{",
"if",
"(",
"first",
"!=",
"null",
")",
"return",
"first",
";",
"return",
"second",
";",
"}"
] | The elvis operator <code>?:</code> is a short hand notation for
providing default value in case an expression evaluates to <code>null</code>.
Not that the Xtend compiler will inline calls to this not call this method with a short-circuit semantic.
That is the second argument is only evaluated if the first one evaluates to <code>null</code>.
Example:
<code>person.name?:'Hans'</code>
@param first
an {@link Object}. Might be <code>null</code>.
@param second
an {@link Object}. Might be <code>null</code>.
@return a reference to <code>first</code> if <code>first != null </code>, <code>second<code> otherwise,
@since 2.3 | [
"The",
"elvis",
"operator",
"<code",
">",
"?",
":",
"<",
"/",
"code",
">",
"is",
"a",
"short",
"hand",
"notation",
"for",
"providing",
"default",
"value",
"in",
"case",
"an",
"expression",
"evaluates",
"to",
"<code",
">",
"null<",
"/",
"code",
">",
"."... | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ObjectExtensions.java#L177-L182 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-cache/xwiki-commons-cache-api/src/main/java/org/xwiki/cache/internal/DefaultCacheManager.java | DefaultCacheManager.createNewCache | public <T> Cache<T> createNewCache(CacheConfiguration config, String cacheHint) throws CacheException {
"""
Lookup the cache component with provided hint and create a new cache.
@param <T> the class of the data stored in the cache.
@param config the cache configuration.
@param cacheHint the role hint to lookup.
@return a new {@link Cache}.
@throws CacheException error when creating the cache.
"""
CacheFactory cacheFactory;
try {
cacheFactory = this.componentManager.getInstance(CacheFactory.class, cacheHint);
} catch (ComponentLookupException e) {
throw new CacheException("Failed to get cache factory for role hint [" + cacheHint + "]", e);
}
return cacheFactory.newCache(config);
} | java | public <T> Cache<T> createNewCache(CacheConfiguration config, String cacheHint) throws CacheException
{
CacheFactory cacheFactory;
try {
cacheFactory = this.componentManager.getInstance(CacheFactory.class, cacheHint);
} catch (ComponentLookupException e) {
throw new CacheException("Failed to get cache factory for role hint [" + cacheHint + "]", e);
}
return cacheFactory.newCache(config);
} | [
"public",
"<",
"T",
">",
"Cache",
"<",
"T",
">",
"createNewCache",
"(",
"CacheConfiguration",
"config",
",",
"String",
"cacheHint",
")",
"throws",
"CacheException",
"{",
"CacheFactory",
"cacheFactory",
";",
"try",
"{",
"cacheFactory",
"=",
"this",
".",
"compon... | Lookup the cache component with provided hint and create a new cache.
@param <T> the class of the data stored in the cache.
@param config the cache configuration.
@param cacheHint the role hint to lookup.
@return a new {@link Cache}.
@throws CacheException error when creating the cache. | [
"Lookup",
"the",
"cache",
"component",
"with",
"provided",
"hint",
"and",
"create",
"a",
"new",
"cache",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-cache/xwiki-commons-cache-api/src/main/java/org/xwiki/cache/internal/DefaultCacheManager.java#L103-L113 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java | PoolsImpl.stopResizeAsync | public Observable<Void> stopResizeAsync(String poolId) {
"""
Stops an ongoing resize operation on the pool.
This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created.
@param poolId The ID of the pool whose resizing you want to stop.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful.
"""
return stopResizeWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolStopResizeHeaders> response) {
return response.body();
}
});
} | java | public Observable<Void> stopResizeAsync(String poolId) {
return stopResizeWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolStopResizeHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"stopResizeAsync",
"(",
"String",
"poolId",
")",
"{",
"return",
"stopResizeWithServiceResponseAsync",
"(",
"poolId",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponseWithHeaders",
"<",
"Void",
",",
"PoolStopResiz... | Stops an ongoing resize operation on the pool.
This does not restore the pool to its previous state before the resize operation: it only stops any further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this API can also be used to halt the initial sizing of the pool when it is created.
@param poolId The ID of the pool whose resizing you want to stop.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful. | [
"Stops",
"an",
"ongoing",
"resize",
"operation",
"on",
"the",
"pool",
".",
"This",
"does",
"not",
"restore",
"the",
"pool",
"to",
"its",
"previous",
"state",
"before",
"the",
"resize",
"operation",
":",
"it",
"only",
"stops",
"any",
"further",
"changes",
"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L2990-L2997 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/Document.java | Document.putExistingRevision | @InterfaceAudience.Public
public boolean putExistingRevision(Map<String, Object> properties,
Map<String, Object> attachments,
List<String> revIDs,
URL sourceURL)
throws CouchbaseLiteException {
"""
Adds an existing revision copied from another database. Unlike a normal insertion, this does
not assign a new revision ID; instead the revision's ID must be given. The revision's history
(ancestry) must be given, which can put it anywhere in the revision tree. It's not an error if
the revision already exists locally; it will just be ignored.
This is not an operation that clients normally perform; it's used by the replicator.
You might want to use it if you're pre-loading a database with canned content, or if you're
implementing some new kind of replicator that transfers revisions from another database.
@param properties The properties of the revision (_id and _rev will be ignored, but _deleted
and _attachments are recognized.)
@param attachments A dictionary providing attachment bodies. The keys are the attachment
names (matching the keys in the properties' `_attachments` dictionary) and
the values are the attachment bodies as NSData or NSURL.
@param revIDs The revision history in the form of an array of revision-ID strings, in
reverse chronological order. The first item must be the new revision's ID.
Following items are its parent's ID, etc.
@param sourceURL The URL of the database this revision came from, if any. (This value shows
up in the CBLDatabaseChange triggered by this insertion, and can help clients
decide whether the change is local or not.)
@return true on success, false on failure.
@throws CouchbaseLiteException Error information will be thrown if the insertion fails.
"""
assert (revIDs != null && revIDs.size() > 0);
boolean deleted = false;
if (properties != null)
deleted = properties.get("_deleted") != null &&
((Boolean) properties.get("_deleted")).booleanValue();
RevisionInternal rev = new RevisionInternal(documentId, revIDs.get(0), deleted);
rev.setProperties(propertiesToInsert(properties));
Status status = new Status();
if (!database.registerAttachmentBodies(attachments, rev, status))
return false;
database.forceInsert(rev, revIDs, sourceURL);
return true;
} | java | @InterfaceAudience.Public
public boolean putExistingRevision(Map<String, Object> properties,
Map<String, Object> attachments,
List<String> revIDs,
URL sourceURL)
throws CouchbaseLiteException {
assert (revIDs != null && revIDs.size() > 0);
boolean deleted = false;
if (properties != null)
deleted = properties.get("_deleted") != null &&
((Boolean) properties.get("_deleted")).booleanValue();
RevisionInternal rev = new RevisionInternal(documentId, revIDs.get(0), deleted);
rev.setProperties(propertiesToInsert(properties));
Status status = new Status();
if (!database.registerAttachmentBodies(attachments, rev, status))
return false;
database.forceInsert(rev, revIDs, sourceURL);
return true;
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"boolean",
"putExistingRevision",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"attachments",
",",
"List",
"<",
"String",
">",
"revIDs",
",",
... | Adds an existing revision copied from another database. Unlike a normal insertion, this does
not assign a new revision ID; instead the revision's ID must be given. The revision's history
(ancestry) must be given, which can put it anywhere in the revision tree. It's not an error if
the revision already exists locally; it will just be ignored.
This is not an operation that clients normally perform; it's used by the replicator.
You might want to use it if you're pre-loading a database with canned content, or if you're
implementing some new kind of replicator that transfers revisions from another database.
@param properties The properties of the revision (_id and _rev will be ignored, but _deleted
and _attachments are recognized.)
@param attachments A dictionary providing attachment bodies. The keys are the attachment
names (matching the keys in the properties' `_attachments` dictionary) and
the values are the attachment bodies as NSData or NSURL.
@param revIDs The revision history in the form of an array of revision-ID strings, in
reverse chronological order. The first item must be the new revision's ID.
Following items are its parent's ID, etc.
@param sourceURL The URL of the database this revision came from, if any. (This value shows
up in the CBLDatabaseChange triggered by this insertion, and can help clients
decide whether the change is local or not.)
@return true on success, false on failure.
@throws CouchbaseLiteException Error information will be thrown if the insertion fails. | [
"Adds",
"an",
"existing",
"revision",
"copied",
"from",
"another",
"database",
".",
"Unlike",
"a",
"normal",
"insertion",
"this",
"does",
"not",
"assign",
"a",
"new",
"revision",
"ID",
";",
"instead",
"the",
"revision",
"s",
"ID",
"must",
"be",
"given",
".... | train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Document.java#L417-L437 |
j256/ormlite-core | src/main/java/com/j256/ormlite/support/BaseConnectionSource.java | BaseConnectionSource.clearSpecial | protected boolean clearSpecial(DatabaseConnection connection, Logger logger) {
"""
Clear the connection that was previously saved.
@return True if the connection argument had been saved.
"""
NestedConnection currentSaved = specialConnection.get();
boolean cleared = false;
if (connection == null) {
// ignored
} else if (currentSaved == null) {
logger.error("no connection has been saved when clear() called");
} else if (currentSaved.connection == connection) {
if (currentSaved.decrementAndGet() == 0) {
// we only clear the connection if nested counter is 0
specialConnection.set(null);
}
cleared = true;
} else {
logger.error("connection saved {} is not the one being cleared {}", currentSaved.connection, connection);
}
// release should then be called after clear
return cleared;
} | java | protected boolean clearSpecial(DatabaseConnection connection, Logger logger) {
NestedConnection currentSaved = specialConnection.get();
boolean cleared = false;
if (connection == null) {
// ignored
} else if (currentSaved == null) {
logger.error("no connection has been saved when clear() called");
} else if (currentSaved.connection == connection) {
if (currentSaved.decrementAndGet() == 0) {
// we only clear the connection if nested counter is 0
specialConnection.set(null);
}
cleared = true;
} else {
logger.error("connection saved {} is not the one being cleared {}", currentSaved.connection, connection);
}
// release should then be called after clear
return cleared;
} | [
"protected",
"boolean",
"clearSpecial",
"(",
"DatabaseConnection",
"connection",
",",
"Logger",
"logger",
")",
"{",
"NestedConnection",
"currentSaved",
"=",
"specialConnection",
".",
"get",
"(",
")",
";",
"boolean",
"cleared",
"=",
"false",
";",
"if",
"(",
"conn... | Clear the connection that was previously saved.
@return True if the connection argument had been saved. | [
"Clear",
"the",
"connection",
"that",
"was",
"previously",
"saved",
"."
] | train | https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/support/BaseConnectionSource.java#L80-L98 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/backend/MBeanServers.java | MBeanServers.lookupJolokiaMBeanServer | private MBeanServer lookupJolokiaMBeanServer() {
"""
Check, whether the Jolokia MBean Server is available and return it.
"""
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
(MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
null;
} catch (JMException e) {
throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
}
} | java | private MBeanServer lookupJolokiaMBeanServer() {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
(MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
null;
} catch (JMException e) {
throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
}
} | [
"private",
"MBeanServer",
"lookupJolokiaMBeanServer",
"(",
")",
"{",
"MBeanServer",
"server",
"=",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
";",
"try",
"{",
"return",
"server",
".",
"isRegistered",
"(",
"JOLOKIA_MBEAN_SERVER_ONAME",
")",
"?",
"(... | Check, whether the Jolokia MBean Server is available and return it. | [
"Check",
"whether",
"the",
"Jolokia",
"MBean",
"Server",
"is",
"available",
"and",
"return",
"it",
"."
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/backend/MBeanServers.java#L133-L142 |
Azure/azure-sdk-for-java | recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/ProtectionContainersInner.java | ProtectionContainersInner.inquireAsync | public Observable<Void> inquireAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, String filter) {
"""
Inquires all the protectable item in the given container that can be protected.
Inquires all the protectable items that are protectable under the given container.
@param vaultName The name of the recovery services vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param fabricName Fabric Name associated with the container.
@param containerName Name of the container in which inquiry needs to be triggered.
@param filter OData filter options.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return inquireWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName, filter).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> inquireAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, String filter) {
return inquireWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName, filter).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"inquireAsync",
"(",
"String",
"vaultName",
",",
"String",
"resourceGroupName",
",",
"String",
"fabricName",
",",
"String",
"containerName",
",",
"String",
"filter",
")",
"{",
"return",
"inquireWithServiceResponseAsync",
"("... | Inquires all the protectable item in the given container that can be protected.
Inquires all the protectable items that are protectable under the given container.
@param vaultName The name of the recovery services vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param fabricName Fabric Name associated with the container.
@param containerName Name of the container in which inquiry needs to be triggered.
@param filter OData filter options.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Inquires",
"all",
"the",
"protectable",
"item",
"in",
"the",
"given",
"container",
"that",
"can",
"be",
"protected",
".",
"Inquires",
"all",
"the",
"protectable",
"items",
"that",
"are",
"protectable",
"under",
"the",
"given",
"container",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_12_01/implementation/ProtectionContainersInner.java#L541-L548 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java | AvatarNode.initializeGenericKeys | public static void initializeGenericKeys(Configuration conf, String serviceKey) {
"""
In federation configuration is set for a set of
avartanodes, namenodes etc, which are
grouped under a logical nameservice ID. The configuration keys specific
to them have suffix set to configured nameserviceId.
This method copies the value from specific key of format key.nameserviceId
to key, to set up the generic configuration. Once this is done, only
generic version of the configuration is read in rest of the code, for
backward compatibility and simpler code changes.
@param conf
Configuration object to lookup specific key and to set the value
to the key passed. Note the conf object is modified
@see DFSUtil#setGenericConf(Configuration, String, String...)
"""
if ((serviceKey == null) || serviceKey.isEmpty()) {
return;
}
NameNode.initializeGenericKeys(conf, serviceKey);
DFSUtil.setGenericConf(conf, serviceKey, AVATARSERVICE_SPECIFIC_KEYS);
// adjust meta directory names for this service
adjustMetaDirectoryNames(conf, serviceKey);
} | java | public static void initializeGenericKeys(Configuration conf, String serviceKey) {
if ((serviceKey == null) || serviceKey.isEmpty()) {
return;
}
NameNode.initializeGenericKeys(conf, serviceKey);
DFSUtil.setGenericConf(conf, serviceKey, AVATARSERVICE_SPECIFIC_KEYS);
// adjust meta directory names for this service
adjustMetaDirectoryNames(conf, serviceKey);
} | [
"public",
"static",
"void",
"initializeGenericKeys",
"(",
"Configuration",
"conf",
",",
"String",
"serviceKey",
")",
"{",
"if",
"(",
"(",
"serviceKey",
"==",
"null",
")",
"||",
"serviceKey",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"NameNode... | In federation configuration is set for a set of
avartanodes, namenodes etc, which are
grouped under a logical nameservice ID. The configuration keys specific
to them have suffix set to configured nameserviceId.
This method copies the value from specific key of format key.nameserviceId
to key, to set up the generic configuration. Once this is done, only
generic version of the configuration is read in rest of the code, for
backward compatibility and simpler code changes.
@param conf
Configuration object to lookup specific key and to set the value
to the key passed. Note the conf object is modified
@see DFSUtil#setGenericConf(Configuration, String, String...) | [
"In",
"federation",
"configuration",
"is",
"set",
"for",
"a",
"set",
"of",
"avartanodes",
"namenodes",
"etc",
"which",
"are",
"grouped",
"under",
"a",
"logical",
"nameservice",
"ID",
".",
"The",
"configuration",
"keys",
"specific",
"to",
"them",
"have",
"suffi... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/AvatarNode.java#L1581-L1591 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.deleteBuildVariable | public void deleteBuildVariable(Integer projectId, String key)
throws IOException {
"""
Deletes an existing variable.
@param projectId The ID of the project containing the variable.
@param key The key of the variable to delete.
@throws IOException on gitlab api call error
"""
String tailUrl = GitlabProject.URL + "/" +
projectId +
GitlabBuildVariable.URL + "/" +
key;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | java | public void deleteBuildVariable(Integer projectId, String key)
throws IOException {
String tailUrl = GitlabProject.URL + "/" +
projectId +
GitlabBuildVariable.URL + "/" +
key;
retrieve().method(DELETE).to(tailUrl, Void.class);
} | [
"public",
"void",
"deleteBuildVariable",
"(",
"Integer",
"projectId",
",",
"String",
"key",
")",
"throws",
"IOException",
"{",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"\"/\"",
"+",
"projectId",
"+",
"GitlabBuildVariable",
".",
"URL",
"+",
"... | Deletes an existing variable.
@param projectId The ID of the project containing the variable.
@param key The key of the variable to delete.
@throws IOException on gitlab api call error | [
"Deletes",
"an",
"existing",
"variable",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3706-L3713 |
PureSolTechnologies/parsers | parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java | PackratParser.processIgnoredTokens | MemoEntry processIgnoredTokens(ParseTreeNode node, int position, int line) throws TreeException, ParserException {
"""
<p>
This class reads all hidden and ignored tokens from the text and puts them
into the node as children.
</p>
<p>
This is the recursive part of the procedure.
</p>
<p>
Attention: This method is package private for testing purposes!
</p>
<p>
@param node
@param position
@return
@throws TreeException
@throws ParserException
"""
MemoEntry progress = MemoEntry.success(0, 0, node);
MemoEntry newProgress = MemoEntry.success(0, 0, null);
do {
for (TokenDefinition tokenDefinition : hiddenAndIgnoredTokens) {
newProgress = processTokenDefinition(node, tokenDefinition, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if (!newProgress.getAnswer().equals(Status.FAILED)) {
progress.add(newProgress);
break;
}
}
} while (newProgress.getDeltaPosition() > 0);
return progress;
} | java | MemoEntry processIgnoredTokens(ParseTreeNode node, int position, int line) throws TreeException, ParserException {
MemoEntry progress = MemoEntry.success(0, 0, node);
MemoEntry newProgress = MemoEntry.success(0, 0, null);
do {
for (TokenDefinition tokenDefinition : hiddenAndIgnoredTokens) {
newProgress = processTokenDefinition(node, tokenDefinition, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if (!newProgress.getAnswer().equals(Status.FAILED)) {
progress.add(newProgress);
break;
}
}
} while (newProgress.getDeltaPosition() > 0);
return progress;
} | [
"MemoEntry",
"processIgnoredTokens",
"(",
"ParseTreeNode",
"node",
",",
"int",
"position",
",",
"int",
"line",
")",
"throws",
"TreeException",
",",
"ParserException",
"{",
"MemoEntry",
"progress",
"=",
"MemoEntry",
".",
"success",
"(",
"0",
",",
"0",
",",
"nod... | <p>
This class reads all hidden and ignored tokens from the text and puts them
into the node as children.
</p>
<p>
This is the recursive part of the procedure.
</p>
<p>
Attention: This method is package private for testing purposes!
</p>
<p>
@param node
@param position
@return
@throws TreeException
@throws ParserException | [
"<p",
">",
"This",
"class",
"reads",
"all",
"hidden",
"and",
"ignored",
"tokens",
"from",
"the",
"text",
"and",
"puts",
"them",
"into",
"the",
"node",
"as",
"children",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"is",
"the",
"recursive",
"part",
"of... | train | https://github.com/PureSolTechnologies/parsers/blob/61077223b90d3768ff9445ae13036343c98b63cd/parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java#L663-L677 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.bodyContainsIllegalCode | public static void bodyContainsIllegalCode(Method method, Exception additionalInformation) {
"""
Thrown when the code contained in the body method is illegal.
@param method method to adjust
@param additionalInformation additional information relative to the byteCode library exception
"""
Class<?> clazz = method.getClazz();
if(isNull(clazz)) clazz = JMapper.class;
String originalName = method.getOriginalName();
if(isNull(originalName)) originalName = method.getName();
String message = clazz != JMapper.class ? MSG.INSTANCE.message(conversionBodyIllegalCode,clazz.getSimpleName(),originalName,""+additionalInformation.getMessage())
: MSG.INSTANCE.message(conversionBodyIllegalCode2,""+additionalInformation.getMessage());
throw new ConversionBodyIllegalCodeException(message);
} | java | public static void bodyContainsIllegalCode(Method method, Exception additionalInformation){
Class<?> clazz = method.getClazz();
if(isNull(clazz)) clazz = JMapper.class;
String originalName = method.getOriginalName();
if(isNull(originalName)) originalName = method.getName();
String message = clazz != JMapper.class ? MSG.INSTANCE.message(conversionBodyIllegalCode,clazz.getSimpleName(),originalName,""+additionalInformation.getMessage())
: MSG.INSTANCE.message(conversionBodyIllegalCode2,""+additionalInformation.getMessage());
throw new ConversionBodyIllegalCodeException(message);
} | [
"public",
"static",
"void",
"bodyContainsIllegalCode",
"(",
"Method",
"method",
",",
"Exception",
"additionalInformation",
")",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"method",
".",
"getClazz",
"(",
")",
";",
"if",
"(",
"isNull",
"(",
"clazz",
")",
")"... | Thrown when the code contained in the body method is illegal.
@param method method to adjust
@param additionalInformation additional information relative to the byteCode library exception | [
"Thrown",
"when",
"the",
"code",
"contained",
"in",
"the",
"body",
"method",
"is",
"illegal",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L176-L187 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java | Trie.getRawOffset | protected final int getRawOffset(int offset, char ch) {
"""
Gets the offset to the data which the index ch after variable offset
points to.
Note for locating a non-supplementary character data offset, calling
<p>
getRawOffset(0, ch);
</p>
will do. Otherwise if it is a supplementary character formed by
surrogates lead and trail. Then we would have to call getRawOffset()
with getFoldingIndexOffset(). See getSurrogateOffset().
@param offset index offset which ch is to start from
@param ch index to be used after offset
@return offset to the data
"""
return (m_index_[offset + (ch >> INDEX_STAGE_1_SHIFT_)]
<< INDEX_STAGE_2_SHIFT_)
+ (ch & INDEX_STAGE_3_MASK_);
} | java | protected final int getRawOffset(int offset, char ch)
{
return (m_index_[offset + (ch >> INDEX_STAGE_1_SHIFT_)]
<< INDEX_STAGE_2_SHIFT_)
+ (ch & INDEX_STAGE_3_MASK_);
} | [
"protected",
"final",
"int",
"getRawOffset",
"(",
"int",
"offset",
",",
"char",
"ch",
")",
"{",
"return",
"(",
"m_index_",
"[",
"offset",
"+",
"(",
"ch",
">>",
"INDEX_STAGE_1_SHIFT_",
")",
"]",
"<<",
"INDEX_STAGE_2_SHIFT_",
")",
"+",
"(",
"ch",
"&",
"IND... | Gets the offset to the data which the index ch after variable offset
points to.
Note for locating a non-supplementary character data offset, calling
<p>
getRawOffset(0, ch);
</p>
will do. Otherwise if it is a supplementary character formed by
surrogates lead and trail. Then we would have to call getRawOffset()
with getFoldingIndexOffset(). See getSurrogateOffset().
@param offset index offset which ch is to start from
@param ch index to be used after offset
@return offset to the data | [
"Gets",
"the",
"offset",
"to",
"the",
"data",
"which",
"the",
"index",
"ch",
"after",
"variable",
"offset",
"points",
"to",
".",
"Note",
"for",
"locating",
"a",
"non",
"-",
"supplementary",
"character",
"data",
"offset",
"calling",
"<p",
">",
"getRawOffset",... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java#L297-L302 |
icode/ameba | src/main/java/ameba/container/server/Connector.java | Connector.createDefault | public static Connector createDefault(Map<String, String> properties) {
"""
<p>createDefault.</p>
@param properties a {@link java.util.Map} object.
@return a {@link ameba.container.server.Connector} object.
"""
Connector.Builder builder = Connector.Builder.create()
.rawProperties(properties)
.secureEnabled(Boolean.parseBoolean(properties.get("ssl.enabled")))
.sslProtocol(properties.get("ssl.protocol"))
.sslClientMode(Boolean.parseBoolean(properties.get("ssl.clientMode")))
.sslNeedClientAuth(Boolean.parseBoolean(properties.get("ssl.needClientAuth")))
.sslWantClientAuth(Boolean.parseBoolean(properties.get("ssl.wantClientAuth")))
.sslKeyManagerFactoryAlgorithm(properties.get("ssl.key.manager.factory.algorithm"))
.sslKeyPassword(properties.get("ssl.key.password"))
.sslKeyStoreProvider(properties.get("ssl.key.store.provider"))
.sslKeyStoreType(properties.get("ssl.key.store.type"))
.sslKeyStorePassword(properties.get("ssl.key.store.password"))
.sslTrustManagerFactoryAlgorithm(properties.get("ssl.trust.manager.factory.algorithm"))
.sslTrustPassword(properties.get("ssl.trust.password"))
.sslTrustStoreProvider(properties.get("ssl.trust.store.provider"))
.sslTrustStoreType(properties.get("ssl.trust.store.type"))
.sslTrustStorePassword(properties.get("ssl.trust.store.password"))
.ajpEnabled(Boolean.parseBoolean(properties.get("ajp.enabled")))
.host(StringUtils.defaultIfBlank(properties.get("host"), "0.0.0.0"))
.port(Integer.valueOf(StringUtils.defaultIfBlank(properties.get("port"), "80")))
.name(properties.get("name"));
String keyStoreFile = properties.get("ssl.key.store.file");
if (StringUtils.isNotBlank(keyStoreFile))
try {
builder.sslKeyStoreFile(readByteArrayFromResource(keyStoreFile));
} catch (IOException e) {
logger.error("读取sslKeyStoreFile出错", e);
}
String trustStoreFile = properties.get("ssl.trust.store.file");
if (StringUtils.isNotBlank(trustStoreFile))
try {
builder.sslTrustStoreFile(readByteArrayFromResource(trustStoreFile));
} catch (IOException e) {
logger.error("读取sslTrustStoreFile出错", e);
}
return builder.build();
} | java | public static Connector createDefault(Map<String, String> properties) {
Connector.Builder builder = Connector.Builder.create()
.rawProperties(properties)
.secureEnabled(Boolean.parseBoolean(properties.get("ssl.enabled")))
.sslProtocol(properties.get("ssl.protocol"))
.sslClientMode(Boolean.parseBoolean(properties.get("ssl.clientMode")))
.sslNeedClientAuth(Boolean.parseBoolean(properties.get("ssl.needClientAuth")))
.sslWantClientAuth(Boolean.parseBoolean(properties.get("ssl.wantClientAuth")))
.sslKeyManagerFactoryAlgorithm(properties.get("ssl.key.manager.factory.algorithm"))
.sslKeyPassword(properties.get("ssl.key.password"))
.sslKeyStoreProvider(properties.get("ssl.key.store.provider"))
.sslKeyStoreType(properties.get("ssl.key.store.type"))
.sslKeyStorePassword(properties.get("ssl.key.store.password"))
.sslTrustManagerFactoryAlgorithm(properties.get("ssl.trust.manager.factory.algorithm"))
.sslTrustPassword(properties.get("ssl.trust.password"))
.sslTrustStoreProvider(properties.get("ssl.trust.store.provider"))
.sslTrustStoreType(properties.get("ssl.trust.store.type"))
.sslTrustStorePassword(properties.get("ssl.trust.store.password"))
.ajpEnabled(Boolean.parseBoolean(properties.get("ajp.enabled")))
.host(StringUtils.defaultIfBlank(properties.get("host"), "0.0.0.0"))
.port(Integer.valueOf(StringUtils.defaultIfBlank(properties.get("port"), "80")))
.name(properties.get("name"));
String keyStoreFile = properties.get("ssl.key.store.file");
if (StringUtils.isNotBlank(keyStoreFile))
try {
builder.sslKeyStoreFile(readByteArrayFromResource(keyStoreFile));
} catch (IOException e) {
logger.error("读取sslKeyStoreFile出错", e);
}
String trustStoreFile = properties.get("ssl.trust.store.file");
if (StringUtils.isNotBlank(trustStoreFile))
try {
builder.sslTrustStoreFile(readByteArrayFromResource(trustStoreFile));
} catch (IOException e) {
logger.error("读取sslTrustStoreFile出错", e);
}
return builder.build();
} | [
"public",
"static",
"Connector",
"createDefault",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
")",
"{",
"Connector",
".",
"Builder",
"builder",
"=",
"Connector",
".",
"Builder",
".",
"create",
"(",
")",
".",
"rawProperties",
"(",
"properties... | <p>createDefault.</p>
@param properties a {@link java.util.Map} object.
@return a {@link ameba.container.server.Connector} object. | [
"<p",
">",
"createDefault",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/container/server/Connector.java#L73-L113 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.checkIfParameterTypesAreSame | public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
"""
Check if parameter types are same.
@param isVarArgs Whether or not the method or constructor contains var args.
@param expectedParameterTypes the expected parameter types
@param actualParameterTypes the actual parameter types
@return if all actual parameter types are assignable from the expected
parameter types, otherwise.
"""
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
} | java | public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
} | [
"public",
"static",
"boolean",
"checkIfParameterTypesAreSame",
"(",
"boolean",
"isVarArgs",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"expectedParameterTypes",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"actualParameterTypes",
")",
"{",
"return",
"new",
"ParameterTypes... | Check if parameter types are same.
@param isVarArgs Whether or not the method or constructor contains var args.
@param expectedParameterTypes the expected parameter types
@param actualParameterTypes the actual parameter types
@return if all actual parameter types are assignable from the expected
parameter types, otherwise. | [
"Check",
"if",
"parameter",
"types",
"are",
"same",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2242-L2245 |
google/truth | extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java | MapWithProtoValuesSubject.containsExactly | @CanIgnoreReturnValue
public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) {
"""
Fails if the map does not contain exactly the given set of key/value pairs.
<p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of
key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
"""
return delegate().containsExactly(k0, v0, rest);
} | java | @CanIgnoreReturnValue
public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) {
return delegate().containsExactly(k0, v0, rest);
} | [
"@",
"CanIgnoreReturnValue",
"public",
"Ordered",
"containsExactly",
"(",
"@",
"NullableDecl",
"Object",
"k0",
",",
"@",
"NullableDecl",
"Object",
"v0",
",",
"Object",
"...",
"rest",
")",
"{",
"return",
"delegate",
"(",
")",
".",
"containsExactly",
"(",
"k0",
... | Fails if the map does not contain exactly the given set of key/value pairs.
<p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of
key/value pairs at compile time. Please make sure you provide varargs in key/value pairs! | [
"Fails",
"if",
"the",
"map",
"does",
"not",
"contain",
"exactly",
"the",
"given",
"set",
"of",
"key",
"/",
"value",
"pairs",
"."
] | train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java#L163-L166 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/ByteIOUtils.java | ByteIOUtils.readInt | public static int readInt(ByteBuffer buf, int pos) {
"""
Reads a specific integer byte value (4 bytes) from the input byte buffer at the given offset.
@param buf input byte buffer
@param pos offset into the byte buffer to read
@return the int value read
"""
return (((buf.get(pos) & 0xff) << 24) | ((buf.get(pos + 1) & 0xff) << 16)
| ((buf.get(pos + 2) & 0xff) << 8) | (buf.get(pos + 3) & 0xff));
} | java | public static int readInt(ByteBuffer buf, int pos) {
return (((buf.get(pos) & 0xff) << 24) | ((buf.get(pos + 1) & 0xff) << 16)
| ((buf.get(pos + 2) & 0xff) << 8) | (buf.get(pos + 3) & 0xff));
} | [
"public",
"static",
"int",
"readInt",
"(",
"ByteBuffer",
"buf",
",",
"int",
"pos",
")",
"{",
"return",
"(",
"(",
"(",
"buf",
".",
"get",
"(",
"pos",
")",
"&",
"0xff",
")",
"<<",
"24",
")",
"|",
"(",
"(",
"buf",
".",
"get",
"(",
"pos",
"+",
"1... | Reads a specific integer byte value (4 bytes) from the input byte buffer at the given offset.
@param buf input byte buffer
@param pos offset into the byte buffer to read
@return the int value read | [
"Reads",
"a",
"specific",
"integer",
"byte",
"value",
"(",
"4",
"bytes",
")",
"from",
"the",
"input",
"byte",
"buffer",
"at",
"the",
"given",
"offset",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/ByteIOUtils.java#L83-L86 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/document/json/JsonObject.java | JsonObject.getAndDecryptBigInteger | public BigInteger getAndDecryptBigInteger(String name, String providerName) throws Exception {
"""
Retrieves the decrypted value from the field name and casts it to {@link BigInteger}.
Note: Use of the Field Level Encryption functionality provided in the
com.couchbase.client.encryption namespace provided by Couchbase is
subject to the Couchbase Inc. Enterprise Subscription License Agreement
at https://www.couchbase.com/ESLA-11132015.
@param name the name of the field.
@param providerName crypto provider name for decryption.
@return the result or null if it does not exist.
"""
return (BigInteger) getAndDecrypt(name, providerName);
} | java | public BigInteger getAndDecryptBigInteger(String name, String providerName) throws Exception {
return (BigInteger) getAndDecrypt(name, providerName);
} | [
"public",
"BigInteger",
"getAndDecryptBigInteger",
"(",
"String",
"name",
",",
"String",
"providerName",
")",
"throws",
"Exception",
"{",
"return",
"(",
"BigInteger",
")",
"getAndDecrypt",
"(",
"name",
",",
"providerName",
")",
";",
"}"
] | Retrieves the decrypted value from the field name and casts it to {@link BigInteger}.
Note: Use of the Field Level Encryption functionality provided in the
com.couchbase.client.encryption namespace provided by Couchbase is
subject to the Couchbase Inc. Enterprise Subscription License Agreement
at https://www.couchbase.com/ESLA-11132015.
@param name the name of the field.
@param providerName crypto provider name for decryption.
@return the result or null if it does not exist. | [
"Retrieves",
"the",
"decrypted",
"value",
"from",
"the",
"field",
"name",
"and",
"casts",
"it",
"to",
"{",
"@link",
"BigInteger",
"}",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L912-L914 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayPrependAll | public <T> MutateInBuilder arrayPrependAll(String path, T... values) {
"""
Prepend multiple values at once in an existing array, pushing all values to the front/start of the array.
This is provided as a convenience alternative to {@link #arrayPrependAll(String, Collection, boolean)}.
Note that parent nodes are not created when using this method (ie. createPath = false).
First value becomes the first element of the array, second value the second, etc... All existing values
are shifted right in the array, by the number of inserted elements.
Each item in the collection is inserted as an individual element of the array, but a bit of overhead
is saved compared to individual {@link #arrayPrepend(String, Object, boolean)} (String, Object)} by grouping
mutations in a single packet.
For example given an array [ A, B, C ], prepending the values X and Y yields [ X, Y, A, B, C ]
and not [ [ X, Y ], A, B, C ].
@param path the path of the array.
@param values the values to insert at the front of the array as individual elements.
@param <T> the type of data in the collection (must be JSON serializable).
@see #arrayPrependAll(String, Collection, boolean) if you need to create missing intermediary nodes.
"""
asyncBuilder.arrayPrependAll(path, values);
return this;
} | java | public <T> MutateInBuilder arrayPrependAll(String path, T... values) {
asyncBuilder.arrayPrependAll(path, values);
return this;
} | [
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayPrependAll",
"(",
"String",
"path",
",",
"T",
"...",
"values",
")",
"{",
"asyncBuilder",
".",
"arrayPrependAll",
"(",
"path",
",",
"values",
")",
";",
"return",
"this",
";",
"}"
] | Prepend multiple values at once in an existing array, pushing all values to the front/start of the array.
This is provided as a convenience alternative to {@link #arrayPrependAll(String, Collection, boolean)}.
Note that parent nodes are not created when using this method (ie. createPath = false).
First value becomes the first element of the array, second value the second, etc... All existing values
are shifted right in the array, by the number of inserted elements.
Each item in the collection is inserted as an individual element of the array, but a bit of overhead
is saved compared to individual {@link #arrayPrepend(String, Object, boolean)} (String, Object)} by grouping
mutations in a single packet.
For example given an array [ A, B, C ], prepending the values X and Y yields [ X, Y, A, B, C ]
and not [ [ X, Y ], A, B, C ].
@param path the path of the array.
@param values the values to insert at the front of the array as individual elements.
@param <T> the type of data in the collection (must be JSON serializable).
@see #arrayPrependAll(String, Collection, boolean) if you need to create missing intermediary nodes. | [
"Prepend",
"multiple",
"values",
"at",
"once",
"in",
"an",
"existing",
"array",
"pushing",
"all",
"values",
"to",
"the",
"front",
"/",
"start",
"of",
"the",
"array",
".",
"This",
"is",
"provided",
"as",
"a",
"convenience",
"alternative",
"to",
"{",
"@link"... | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L795-L798 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/InternalDocumentRevision.java | InternalDocumentRevision.setAttachmentsInternal | protected void setAttachmentsInternal(Map<String, ? extends Attachment> attachments) {
"""
/*
Helper used by sub-classes to convert between list and map representation of attachments
"""
if (attachments != null) {
// this awkward looking way of doing things is to avoid marking the map as being
// modified
HashMap<String, Attachment> m = new HashMap<String, Attachment>();
for (Map.Entry<String, ? extends Attachment> att : attachments.entrySet()) {
m.put(att.getKey(), att.getValue());
}
this.attachments = SimpleChangeNotifyingMap.wrap(m);
}
} | java | protected void setAttachmentsInternal(Map<String, ? extends Attachment> attachments) {
if (attachments != null) {
// this awkward looking way of doing things is to avoid marking the map as being
// modified
HashMap<String, Attachment> m = new HashMap<String, Attachment>();
for (Map.Entry<String, ? extends Attachment> att : attachments.entrySet()) {
m.put(att.getKey(), att.getValue());
}
this.attachments = SimpleChangeNotifyingMap.wrap(m);
}
} | [
"protected",
"void",
"setAttachmentsInternal",
"(",
"Map",
"<",
"String",
",",
"?",
"extends",
"Attachment",
">",
"attachments",
")",
"{",
"if",
"(",
"attachments",
"!=",
"null",
")",
"{",
"// this awkward looking way of doing things is to avoid marking the map as being",... | /*
Helper used by sub-classes to convert between list and map representation of attachments | [
"/",
"*",
"Helper",
"used",
"by",
"sub",
"-",
"classes",
"to",
"convert",
"between",
"list",
"and",
"map",
"representation",
"of",
"attachments"
] | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/InternalDocumentRevision.java#L127-L137 |
ben-manes/caffeine | simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/Synthetic.java | Synthetic.scrambledZipfian | public static LongStream scrambledZipfian(int items, double constant, int events) {
"""
Returns a sequence of events where some items are more popular than others, according to a
zipfian distribution. Unlike {@link #zipfian}, the generated sequence scatters the "popular"
items across the item space. Use if you don't want the head of the distribution (the popular
items) clustered together.
@param items the number of items in the distribution
@param constant the skew factor for the distribution
@param events the number of events in the distribution
"""
return generate(new ScrambledZipfianGenerator(0, items - 1, constant), events);
} | java | public static LongStream scrambledZipfian(int items, double constant, int events) {
return generate(new ScrambledZipfianGenerator(0, items - 1, constant), events);
} | [
"public",
"static",
"LongStream",
"scrambledZipfian",
"(",
"int",
"items",
",",
"double",
"constant",
",",
"int",
"events",
")",
"{",
"return",
"generate",
"(",
"new",
"ScrambledZipfianGenerator",
"(",
"0",
",",
"items",
"-",
"1",
",",
"constant",
")",
",",
... | Returns a sequence of events where some items are more popular than others, according to a
zipfian distribution. Unlike {@link #zipfian}, the generated sequence scatters the "popular"
items across the item space. Use if you don't want the head of the distribution (the popular
items) clustered together.
@param items the number of items in the distribution
@param constant the skew factor for the distribution
@param events the number of events in the distribution | [
"Returns",
"a",
"sequence",
"of",
"events",
"where",
"some",
"items",
"are",
"more",
"popular",
"than",
"others",
"according",
"to",
"a",
"zipfian",
"distribution",
".",
"Unlike",
"{",
"@link",
"#zipfian",
"}",
"the",
"generated",
"sequence",
"scatters",
"the"... | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/Synthetic.java#L121-L123 |
google/closure-compiler | src/com/google/javascript/jscomp/Es6RewriteDestructuring.java | Es6RewriteDestructuring.replacePatternParamWithTempVar | private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
"""
Replace a destructuring pattern parameter with a a temporary parameter name and add a new
local variable declaration to the function assigning the temporary parameter to the pattern.
<p> Note: Rewrites of variable declaration destructuring will happen later to rewrite
this declaration as non-destructured code.
@param function
@param insertSpot The local variable declaration will be inserted after this statement.
@param patternParam
@param tempVarName the name to use for the temporary variable
@return the declaration statement that was generated for the local variable
"""
// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`
JSType paramType = patternParam.getJSType();
Node newParam = astFactory.createName(tempVarName, paramType);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, astFactory.createName(tempVarName, paramType));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
} | java | private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`
JSType paramType = patternParam.getJSType();
Node newParam = astFactory.createName(tempVarName, paramType);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, astFactory.createName(tempVarName, paramType));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
} | [
"private",
"Node",
"replacePatternParamWithTempVar",
"(",
"Node",
"function",
",",
"Node",
"insertSpot",
",",
"Node",
"patternParam",
",",
"String",
"tempVarName",
")",
"{",
"// Convert `function f([a, b]) {}` to `function f(tempVar) { var [a, b] = tempVar; }`",
"JSType",
"para... | Replace a destructuring pattern parameter with a a temporary parameter name and add a new
local variable declaration to the function assigning the temporary parameter to the pattern.
<p> Note: Rewrites of variable declaration destructuring will happen later to rewrite
this declaration as non-destructured code.
@param function
@param insertSpot The local variable declaration will be inserted after this statement.
@param patternParam
@param tempVarName the name to use for the temporary variable
@return the declaration statement that was generated for the local variable | [
"Replace",
"a",
"destructuring",
"pattern",
"parameter",
"with",
"a",
"a",
"temporary",
"parameter",
"name",
"and",
"add",
"a",
"new",
"local",
"variable",
"declaration",
"to",
"the",
"function",
"assigning",
"the",
"temporary",
"parameter",
"to",
"the",
"patter... | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Es6RewriteDestructuring.java#L303-L313 |
alkacon/opencms-core | src-gwt/org/opencms/acacia/client/ui/CmsAttributeValueView.java | CmsAttributeValueView.setValueEntity | public void setValueEntity(I_CmsEntityRenderer renderer, CmsEntity value) {
"""
Sets the value entity.<p>
@param renderer the entity renderer
@param value the value entity
"""
if (m_hasValue) {
throw new RuntimeException("Value has already been set");
}
m_hasValue = true;
m_isSimpleValue = false;
FlowPanel entityPanel = new FlowPanel();
m_widgetHolder.add(entityPanel);
int index = getValueIndex();
m_handler.ensureHandlers(index);
renderer.renderForm(value, entityPanel, m_handler, index);
removeStyleName(formCss().emptyValue());
} | java | public void setValueEntity(I_CmsEntityRenderer renderer, CmsEntity value) {
if (m_hasValue) {
throw new RuntimeException("Value has already been set");
}
m_hasValue = true;
m_isSimpleValue = false;
FlowPanel entityPanel = new FlowPanel();
m_widgetHolder.add(entityPanel);
int index = getValueIndex();
m_handler.ensureHandlers(index);
renderer.renderForm(value, entityPanel, m_handler, index);
removeStyleName(formCss().emptyValue());
} | [
"public",
"void",
"setValueEntity",
"(",
"I_CmsEntityRenderer",
"renderer",
",",
"CmsEntity",
"value",
")",
"{",
"if",
"(",
"m_hasValue",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Value has already been set\"",
")",
";",
"}",
"m_hasValue",
"=",
"true",... | Sets the value entity.<p>
@param renderer the entity renderer
@param value the value entity | [
"Sets",
"the",
"value",
"entity",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/ui/CmsAttributeValueView.java#L737-L750 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataTiffImage.java | CoverageDataTiffImage.getPixel | public float getPixel(int x, int y) {
"""
Get the pixel at the coordinate
@param x
x coordinate
@param y
y coordinate
@return pixel value
"""
float pixel = -1;
if (rasters == null) {
readPixels();
}
if (rasters != null) {
pixel = rasters.getFirstPixelSample(x, y).floatValue();
} else {
throw new GeoPackageException("Could not retrieve pixel value");
}
return pixel;
} | java | public float getPixel(int x, int y) {
float pixel = -1;
if (rasters == null) {
readPixels();
}
if (rasters != null) {
pixel = rasters.getFirstPixelSample(x, y).floatValue();
} else {
throw new GeoPackageException("Could not retrieve pixel value");
}
return pixel;
} | [
"public",
"float",
"getPixel",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"float",
"pixel",
"=",
"-",
"1",
";",
"if",
"(",
"rasters",
"==",
"null",
")",
"{",
"readPixels",
"(",
")",
";",
"}",
"if",
"(",
"rasters",
"!=",
"null",
")",
"{",
"pixe... | Get the pixel at the coordinate
@param x
x coordinate
@param y
y coordinate
@return pixel value | [
"Get",
"the",
"pixel",
"at",
"the",
"coordinate"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataTiffImage.java#L147-L158 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.getPermissions | public CmsPermissionSetCustom getPermissions(CmsDbContext dbc, CmsResource resource, CmsUser user)
throws CmsException {
"""
Returns the set of permissions of the current user for a given resource.<p>
@param dbc the current database context
@param resource the resource
@param user the user
@return bit set with allowed permissions
@throws CmsException if something goes wrong
"""
CmsAccessControlList acList = getAccessControlList(dbc, resource, false);
return acList.getPermissions(user, getGroupsOfUser(dbc, user.getName(), false), getRolesForUser(dbc, user));
} | java | public CmsPermissionSetCustom getPermissions(CmsDbContext dbc, CmsResource resource, CmsUser user)
throws CmsException {
CmsAccessControlList acList = getAccessControlList(dbc, resource, false);
return acList.getPermissions(user, getGroupsOfUser(dbc, user.getName(), false), getRolesForUser(dbc, user));
} | [
"public",
"CmsPermissionSetCustom",
"getPermissions",
"(",
"CmsDbContext",
"dbc",
",",
"CmsResource",
"resource",
",",
"CmsUser",
"user",
")",
"throws",
"CmsException",
"{",
"CmsAccessControlList",
"acList",
"=",
"getAccessControlList",
"(",
"dbc",
",",
"resource",
",... | Returns the set of permissions of the current user for a given resource.<p>
@param dbc the current database context
@param resource the resource
@param user the user
@return bit set with allowed permissions
@throws CmsException if something goes wrong | [
"Returns",
"the",
"set",
"of",
"permissions",
"of",
"the",
"current",
"user",
"for",
"a",
"given",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L4281-L4286 |
kejunxia/AndroidMvc | extension/service-mediastore/src/main/java/com/shipdream/lib/android/mvc/service/internal/MediaStoreServiceImpl.java | MediaStoreServiceImpl.extractOneVideoFromCursor | protected VideoDTO extractOneVideoFromCursor(Cursor cursor) {
"""
Extract one videoDTO from the given cursor from its current position
@param cursor
@return
"""
if(videoIdCol == -1) {
videoIdCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
videoTitleCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
videoDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoDescriptionCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DESCRIPTION);
videoBucketIdCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID);
videoBucketDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
videoDataCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoMimeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
videoResolutionCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION);
videoSizeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoDateAddedCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED);
videoDateTakenCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN);
videoDateModifyCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED);
videoLatitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LATITUDE);
videoLongitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LONGITUDE);
videoAlbumCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM);
videoArtistCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST);
}
VideoDTO video = new VideoDTO();
video.setId(cursor.getLong(videoIdCol));
video.setTitle(cursor.getString(videoTitleCol));
video.setDisplayName(cursor.getString(videoDisplayNameCol));
video.setDescription(cursor.getString(videoDescriptionCol));
video.setBucketId(cursor.getString(videoBucketIdCol));
video.setBucketDisplayName(cursor.getString(videoBucketDisplayNameCol));
video.setUri(cursor.getString(videoDataCol));
video.setMimeType(cursor.getString(videoMimeCol));
video.setSize(cursor.getLong(videoSizeCol));
video.setAddedDate(new Date(cursor.getLong(videoDateAddedCol)));
video.setTakenDate(new Date(cursor.getLong(videoDateTakenCol)));
video.setModifyDate(new Date(cursor.getLong(videoDateModifyCol)));
video.setLatitude(cursor.getDouble(videoLatitudeCol));
video.setLongitude(cursor.getDouble(videoLongitudeCol));
video.setAlbum(cursor.getString(videoAlbumCol));
video.setArtist(cursor.getString(videoArtistCol));
String resolution = cursor.getString(videoResolutionCol);
if (resolution != null) {
try {
String[] res = resolution.split("x");
int width = Integer.parseInt(res[0]);
int height = Integer.parseInt(res[1]);
video.setWidth(width);
video.setHeight(height);
} catch (Exception e) {
Log.w(TAG, String.format("Failed to parse resolution of video(id=%d, title=%s, displayName=%s)",
video.getId(), video.getTitle(), video.getDisplayName()), e);
}
}
return video;
} | java | protected VideoDTO extractOneVideoFromCursor(Cursor cursor) {
if(videoIdCol == -1) {
videoIdCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
videoTitleCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
videoDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoDescriptionCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DESCRIPTION);
videoBucketIdCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID);
videoBucketDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
videoDataCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoMimeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
videoResolutionCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION);
videoSizeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoDateAddedCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED);
videoDateTakenCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN);
videoDateModifyCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED);
videoLatitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LATITUDE);
videoLongitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.LONGITUDE);
videoAlbumCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ALBUM);
videoArtistCol = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST);
}
VideoDTO video = new VideoDTO();
video.setId(cursor.getLong(videoIdCol));
video.setTitle(cursor.getString(videoTitleCol));
video.setDisplayName(cursor.getString(videoDisplayNameCol));
video.setDescription(cursor.getString(videoDescriptionCol));
video.setBucketId(cursor.getString(videoBucketIdCol));
video.setBucketDisplayName(cursor.getString(videoBucketDisplayNameCol));
video.setUri(cursor.getString(videoDataCol));
video.setMimeType(cursor.getString(videoMimeCol));
video.setSize(cursor.getLong(videoSizeCol));
video.setAddedDate(new Date(cursor.getLong(videoDateAddedCol)));
video.setTakenDate(new Date(cursor.getLong(videoDateTakenCol)));
video.setModifyDate(new Date(cursor.getLong(videoDateModifyCol)));
video.setLatitude(cursor.getDouble(videoLatitudeCol));
video.setLongitude(cursor.getDouble(videoLongitudeCol));
video.setAlbum(cursor.getString(videoAlbumCol));
video.setArtist(cursor.getString(videoArtistCol));
String resolution = cursor.getString(videoResolutionCol);
if (resolution != null) {
try {
String[] res = resolution.split("x");
int width = Integer.parseInt(res[0]);
int height = Integer.parseInt(res[1]);
video.setWidth(width);
video.setHeight(height);
} catch (Exception e) {
Log.w(TAG, String.format("Failed to parse resolution of video(id=%d, title=%s, displayName=%s)",
video.getId(), video.getTitle(), video.getDisplayName()), e);
}
}
return video;
} | [
"protected",
"VideoDTO",
"extractOneVideoFromCursor",
"(",
"Cursor",
"cursor",
")",
"{",
"if",
"(",
"videoIdCol",
"==",
"-",
"1",
")",
"{",
"videoIdCol",
"=",
"cursor",
".",
"getColumnIndexOrThrow",
"(",
"MediaStore",
".",
"Video",
".",
"Media",
".",
"_ID",
... | Extract one videoDTO from the given cursor from its current position
@param cursor
@return | [
"Extract",
"one",
"videoDTO",
"from",
"the",
"given",
"cursor",
"from",
"its",
"current",
"position"
] | train | https://github.com/kejunxia/AndroidMvc/blob/c7893f0a13119d64297b9eb2988f7323b7da5bbc/extension/service-mediastore/src/main/java/com/shipdream/lib/android/mvc/service/internal/MediaStoreServiceImpl.java#L464-L517 |
ontop/ontop | mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/LegacyMappingDatatypeFiller.java | LegacyMappingDatatypeFiller.inferMissingDatatypes | @Override
public MappingWithProvenance inferMissingDatatypes(MappingWithProvenance mapping, DBMetadata dbMetadata) throws UnknownDatatypeException {
"""
*
Infers missing data types.
For each rule, gets the type from the rule head, and if absent, retrieves the type from the metadata.
The behavior of type retrieval is the following for each rule:
. build a "termOccurrenceIndex", which is a map from variables to body atoms + position.
For ex, consider the rule: C(x, y) <- A(x, y) \wedge B(y)
The "termOccurrenceIndex" map is {
x \mapsTo [<A(x, y), 1>],
y \mapsTo [<A(x, y), 2>, <B(y), 1>]
}
. then take the first occurrence each variable (e.g. take <A(x, y), 2> for variable y),
and assign to the variable the corresponding column type in the DB
(e.g. for y, the type of column 1 of table A).
. then inductively infer the types of functions (e.g. concat, ...) from the variable types.
Only the outermost expression is assigned a type.
Assumptions:
.rule body atoms are extensional
.the corresponding column types are compatible (e.g the types for column 1 of A and column 1 of B)
"""
MappingDataTypeCompletion typeCompletion = new MappingDataTypeCompletion(dbMetadata,
settings.isDefaultDatatypeInferred(), relation2Predicate, termFactory, typeFactory, termTypeInferenceTools, immutabilityTools);
ImmutableMap<CQIE, PPMappingAssertionProvenance> ruleMap = mapping2DatalogConverter.convert(mapping);
//CQIEs are mutable
for(CQIE rule : ruleMap.keySet()){
typeCompletion.insertDataTyping(rule);
}
return datalog2MappingConverter.convertMappingRules(ruleMap, mapping.getMetadata());
} | java | @Override
public MappingWithProvenance inferMissingDatatypes(MappingWithProvenance mapping, DBMetadata dbMetadata) throws UnknownDatatypeException {
MappingDataTypeCompletion typeCompletion = new MappingDataTypeCompletion(dbMetadata,
settings.isDefaultDatatypeInferred(), relation2Predicate, termFactory, typeFactory, termTypeInferenceTools, immutabilityTools);
ImmutableMap<CQIE, PPMappingAssertionProvenance> ruleMap = mapping2DatalogConverter.convert(mapping);
//CQIEs are mutable
for(CQIE rule : ruleMap.keySet()){
typeCompletion.insertDataTyping(rule);
}
return datalog2MappingConverter.convertMappingRules(ruleMap, mapping.getMetadata());
} | [
"@",
"Override",
"public",
"MappingWithProvenance",
"inferMissingDatatypes",
"(",
"MappingWithProvenance",
"mapping",
",",
"DBMetadata",
"dbMetadata",
")",
"throws",
"UnknownDatatypeException",
"{",
"MappingDataTypeCompletion",
"typeCompletion",
"=",
"new",
"MappingDataTypeComp... | *
Infers missing data types.
For each rule, gets the type from the rule head, and if absent, retrieves the type from the metadata.
The behavior of type retrieval is the following for each rule:
. build a "termOccurrenceIndex", which is a map from variables to body atoms + position.
For ex, consider the rule: C(x, y) <- A(x, y) \wedge B(y)
The "termOccurrenceIndex" map is {
x \mapsTo [<A(x, y), 1>],
y \mapsTo [<A(x, y), 2>, <B(y), 1>]
}
. then take the first occurrence each variable (e.g. take <A(x, y), 2> for variable y),
and assign to the variable the corresponding column type in the DB
(e.g. for y, the type of column 1 of table A).
. then inductively infer the types of functions (e.g. concat, ...) from the variable types.
Only the outermost expression is assigned a type.
Assumptions:
.rule body atoms are extensional
.the corresponding column types are compatible (e.g the types for column 1 of A and column 1 of B) | [
"*",
"Infers",
"missing",
"data",
"types",
".",
"For",
"each",
"rule",
"gets",
"the",
"type",
"from",
"the",
"rule",
"head",
"and",
"if",
"absent",
"retrieves",
"the",
"type",
"from",
"the",
"metadata",
"."
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/LegacyMappingDatatypeFiller.java#L74-L85 |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.makeStringResponse | public static void makeStringResponse(HttpResponse response, String s) {
"""
Sets a string as the response
@param response The response object
@param s The response body
"""
StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
entity.setContentEncoding("utf-8");
response.setEntity(entity);
} | java | public static void makeStringResponse(HttpResponse response, String s) {
StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
entity.setContentEncoding("utf-8");
response.setEntity(entity);
} | [
"public",
"static",
"void",
"makeStringResponse",
"(",
"HttpResponse",
"response",
",",
"String",
"s",
")",
"{",
"StringEntity",
"entity",
"=",
"new",
"StringEntity",
"(",
"s",
",",
"ContentType",
".",
"TEXT_PLAIN",
")",
";",
"entity",
".",
"setContentEncoding",... | Sets a string as the response
@param response The response object
@param s The response body | [
"Sets",
"a",
"string",
"as",
"the",
"response"
] | train | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L148-L152 |
citrusframework/citrus | modules/citrus-model/model-core/src/main/java/com/consol/citrus/model/config/core/SchemaRepositoryModelBuilder.java | SchemaRepositoryModelBuilder.addSchema | public SchemaRepositoryModelBuilder addSchema(String id, String location) {
"""
Adds new schema by id and location.
@param id
@param location
@return
"""
SchemaModel schema = new SchemaModel();
schema.setId(id);
schema.setLocation(location);
if (model.getSchemas() == null) {
model.setSchemas(new SchemaRepositoryModel.Schemas());
}
model.getSchemas().getSchemas().add(schema);
return this;
} | java | public SchemaRepositoryModelBuilder addSchema(String id, String location) {
SchemaModel schema = new SchemaModel();
schema.setId(id);
schema.setLocation(location);
if (model.getSchemas() == null) {
model.setSchemas(new SchemaRepositoryModel.Schemas());
}
model.getSchemas().getSchemas().add(schema);
return this;
} | [
"public",
"SchemaRepositoryModelBuilder",
"addSchema",
"(",
"String",
"id",
",",
"String",
"location",
")",
"{",
"SchemaModel",
"schema",
"=",
"new",
"SchemaModel",
"(",
")",
";",
"schema",
".",
"setId",
"(",
"id",
")",
";",
"schema",
".",
"setLocation",
"("... | Adds new schema by id and location.
@param id
@param location
@return | [
"Adds",
"new",
"schema",
"by",
"id",
"and",
"location",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-model/model-core/src/main/java/com/consol/citrus/model/config/core/SchemaRepositoryModelBuilder.java#L52-L63 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/MediaApi.java | MediaApi.createOpenMedia | public ApiSuccessResponse createOpenMedia(String mediatype, CreateData1 createData) throws ApiException {
"""
Create open media interaction
Create a new open media interaction
@param mediatype The media channel. (required)
@param createData Request parameters. (required)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<ApiSuccessResponse> resp = createOpenMediaWithHttpInfo(mediatype, createData);
return resp.getData();
} | java | public ApiSuccessResponse createOpenMedia(String mediatype, CreateData1 createData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = createOpenMediaWithHttpInfo(mediatype, createData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"createOpenMedia",
"(",
"String",
"mediatype",
",",
"CreateData1",
"createData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"createOpenMediaWithHttpInfo",
"(",
"mediatype",
",",
"create... | Create open media interaction
Create a new open media interaction
@param mediatype The media channel. (required)
@param createData Request parameters. (required)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Create",
"open",
"media",
"interaction",
"Create",
"a",
"new",
"open",
"media",
"interaction"
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L1429-L1432 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java | DatabasesInner.getByElasticPoolAsync | public Observable<DatabaseInner> getByElasticPoolAsync(String resourceGroupName, String serverName, String elasticPoolName, String databaseName) {
"""
Gets a database inside of an elastic pool.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param elasticPoolName The name of the elastic pool to be retrieved.
@param databaseName The name of the database to be retrieved.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseInner object
"""
return getByElasticPoolWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName, databaseName).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() {
@Override
public DatabaseInner call(ServiceResponse<DatabaseInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseInner> getByElasticPoolAsync(String resourceGroupName, String serverName, String elasticPoolName, String databaseName) {
return getByElasticPoolWithServiceResponseAsync(resourceGroupName, serverName, elasticPoolName, databaseName).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() {
@Override
public DatabaseInner call(ServiceResponse<DatabaseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseInner",
">",
"getByElasticPoolAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"elasticPoolName",
",",
"String",
"databaseName",
")",
"{",
"return",
"getByElasticPoolWithServiceResponseAsync",
"(... | Gets a database inside of an elastic pool.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param elasticPoolName The name of the elastic pool to be retrieved.
@param databaseName The name of the database to be retrieved.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseInner object | [
"Gets",
"a",
"database",
"inside",
"of",
"an",
"elastic",
"pool",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1371-L1378 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/las/databases/LasLevelsTable.java | LasLevelsTable.hasLevel | public static boolean hasLevel( ASpatialDb db, int levelNum ) throws Exception {
"""
Checks if the given level table exists.
@param db the database.
@param levelNum the level number to check.
@return <code>true</code> if the level table exists.
@throws Exception
"""
String tablename = TABLENAME + levelNum;
return db.hasTable(tablename);
} | java | public static boolean hasLevel( ASpatialDb db, int levelNum ) throws Exception {
String tablename = TABLENAME + levelNum;
return db.hasTable(tablename);
} | [
"public",
"static",
"boolean",
"hasLevel",
"(",
"ASpatialDb",
"db",
",",
"int",
"levelNum",
")",
"throws",
"Exception",
"{",
"String",
"tablename",
"=",
"TABLENAME",
"+",
"levelNum",
";",
"return",
"db",
".",
"hasTable",
"(",
"tablename",
")",
";",
"}"
] | Checks if the given level table exists.
@param db the database.
@param levelNum the level number to check.
@return <code>true</code> if the level table exists.
@throws Exception | [
"Checks",
"if",
"the",
"given",
"level",
"table",
"exists",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/las/databases/LasLevelsTable.java#L61-L64 |
webmetrics/browsermob-proxy | src/main/java/org/browsermob/proxy/jetty/html/TableForm.java | TableForm.addReset | public void addReset(String label) {
"""
Add a reset button.
@param label The label for the element in the table.
"""
if (buttons==null)
buttonsAtBottom();
Element e = new Input(Input.Reset,"Reset",label);
if (extendRow)
addField(null,e);
else
buttons.add(e);
} | java | public void addReset(String label)
{
if (buttons==null)
buttonsAtBottom();
Element e = new Input(Input.Reset,"Reset",label);
if (extendRow)
addField(null,e);
else
buttons.add(e);
} | [
"public",
"void",
"addReset",
"(",
"String",
"label",
")",
"{",
"if",
"(",
"buttons",
"==",
"null",
")",
"buttonsAtBottom",
"(",
")",
";",
"Element",
"e",
"=",
"new",
"Input",
"(",
"Input",
".",
"Reset",
",",
"\"Reset\"",
",",
"label",
")",
";",
"if"... | Add a reset button.
@param label The label for the element in the table. | [
"Add",
"a",
"reset",
"button",
"."
] | train | https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/html/TableForm.java#L281-L290 |
icode/ameba | src/main/java/ameba/mvc/template/internal/ResolvingViewableContext.java | ResolvingViewableContext.resolveAbsoluteViewable | @SuppressWarnings("unchecked")
private ResolvedViewable resolveAbsoluteViewable(final Viewable viewable, Class<?> resourceClass,
final MediaType mediaType,
final TemplateProcessor templateProcessor) {
"""
Resolve given {@link Viewable viewable} with absolute template name using {@link MediaType media type} and
{@link TemplateProcessor template processor}.
@param viewable viewable to be resolved.
@param mediaType media type of te output.
@param resourceClass resource class.
@param templateProcessor template processor to be used.
@return resolved viewable or {@code null} if the viewable cannot be resolved.
"""
final Object resolvedTemplateObject = templateProcessor.resolve(viewable.getTemplateName(), mediaType);
if (resolvedTemplateObject != null) {
return new ResolvedViewable(templateProcessor, resolvedTemplateObject, viewable, resourceClass, mediaType);
}
return null;
} | java | @SuppressWarnings("unchecked")
private ResolvedViewable resolveAbsoluteViewable(final Viewable viewable, Class<?> resourceClass,
final MediaType mediaType,
final TemplateProcessor templateProcessor) {
final Object resolvedTemplateObject = templateProcessor.resolve(viewable.getTemplateName(), mediaType);
if (resolvedTemplateObject != null) {
return new ResolvedViewable(templateProcessor, resolvedTemplateObject, viewable, resourceClass, mediaType);
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"ResolvedViewable",
"resolveAbsoluteViewable",
"(",
"final",
"Viewable",
"viewable",
",",
"Class",
"<",
"?",
">",
"resourceClass",
",",
"final",
"MediaType",
"mediaType",
",",
"final",
"TemplateProcessor",... | Resolve given {@link Viewable viewable} with absolute template name using {@link MediaType media type} and
{@link TemplateProcessor template processor}.
@param viewable viewable to be resolved.
@param mediaType media type of te output.
@param resourceClass resource class.
@param templateProcessor template processor to be used.
@return resolved viewable or {@code null} if the viewable cannot be resolved. | [
"Resolve",
"given",
"{",
"@link",
"Viewable",
"viewable",
"}",
"with",
"absolute",
"template",
"name",
"using",
"{",
"@link",
"MediaType",
"media",
"type",
"}",
"and",
"{",
"@link",
"TemplateProcessor",
"template",
"processor",
"}",
"."
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/mvc/template/internal/ResolvingViewableContext.java#L62-L73 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/gm/model/VarConfig.java | VarConfig.put | public void put(Var var, String stateName) {
"""
Sets the state value to stateName for the given variable, adding it if necessary.
"""
int state = var.getState(stateName);
if (state == -1) {
throw new IllegalArgumentException("Unknown state name " + stateName + " for var " + var);
}
put(var, state);
} | java | public void put(Var var, String stateName) {
int state = var.getState(stateName);
if (state == -1) {
throw new IllegalArgumentException("Unknown state name " + stateName + " for var " + var);
}
put(var, state);
} | [
"public",
"void",
"put",
"(",
"Var",
"var",
",",
"String",
"stateName",
")",
"{",
"int",
"state",
"=",
"var",
".",
"getState",
"(",
"stateName",
")",
";",
"if",
"(",
"state",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
... | Sets the state value to stateName for the given variable, adding it if necessary. | [
"Sets",
"the",
"state",
"value",
"to",
"stateName",
"for",
"the",
"given",
"variable",
"adding",
"it",
"if",
"necessary",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/model/VarConfig.java#L82-L88 |
line/armeria | core/src/main/java/com/linecorp/armeria/client/endpoint/healthcheck/HttpHealthCheckedEndpointGroup.java | HttpHealthCheckedEndpointGroup.of | @Deprecated
public static HttpHealthCheckedEndpointGroup of(EndpointGroup delegate,
String healthCheckPath,
Duration healthCheckRetryInterval) {
"""
Creates a new {@link HttpHealthCheckedEndpointGroup} instance.
@deprecated Use {@link HttpHealthCheckedEndpointGroupBuilder}.
"""
return of(ClientFactory.DEFAULT, delegate, healthCheckPath, healthCheckRetryInterval);
} | java | @Deprecated
public static HttpHealthCheckedEndpointGroup of(EndpointGroup delegate,
String healthCheckPath,
Duration healthCheckRetryInterval) {
return of(ClientFactory.DEFAULT, delegate, healthCheckPath, healthCheckRetryInterval);
} | [
"@",
"Deprecated",
"public",
"static",
"HttpHealthCheckedEndpointGroup",
"of",
"(",
"EndpointGroup",
"delegate",
",",
"String",
"healthCheckPath",
",",
"Duration",
"healthCheckRetryInterval",
")",
"{",
"return",
"of",
"(",
"ClientFactory",
".",
"DEFAULT",
",",
"delega... | Creates a new {@link HttpHealthCheckedEndpointGroup} instance.
@deprecated Use {@link HttpHealthCheckedEndpointGroupBuilder}. | [
"Creates",
"a",
"new",
"{",
"@link",
"HttpHealthCheckedEndpointGroup",
"}",
"instance",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/client/endpoint/healthcheck/HttpHealthCheckedEndpointGroup.java#L53-L58 |
samskivert/pythagoras | src/main/java/pythagoras/f/Vectors.java | Vectors.epsilonEquals | public static boolean epsilonEquals (IVector v1, IVector v2, float epsilon) {
"""
Returns true if the supplied vectors' x and y components are equal to one another within
{@code epsilon}.
"""
return Math.abs(v1.x() - v2.x()) <= epsilon && Math.abs(v1.y() - v2.y()) <= epsilon;
} | java | public static boolean epsilonEquals (IVector v1, IVector v2, float epsilon) {
return Math.abs(v1.x() - v2.x()) <= epsilon && Math.abs(v1.y() - v2.y()) <= epsilon;
} | [
"public",
"static",
"boolean",
"epsilonEquals",
"(",
"IVector",
"v1",
",",
"IVector",
"v2",
",",
"float",
"epsilon",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"v1",
".",
"x",
"(",
")",
"-",
"v2",
".",
"x",
"(",
")",
")",
"<=",
"epsilon",
"&&",
... | Returns true if the supplied vectors' x and y components are equal to one another within
{@code epsilon}. | [
"Returns",
"true",
"if",
"the",
"supplied",
"vectors",
"x",
"and",
"y",
"components",
"are",
"equal",
"to",
"one",
"another",
"within",
"{"
] | train | https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Vectors.java#L91-L93 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java | PatternBox.controlsExpressionWithConversion | public static Pattern controlsExpressionWithConversion() {
"""
Finds the cases where transcription relation is shown using a Conversion instead of a
TemplateReaction.
@return the pattern
"""
Pattern p = new Pattern(SequenceEntityReference.class, "TF ER");
p.add(linkedER(true), "TF ER", "TF generic ER");
p.add(erToPE(), "TF generic ER", "TF SPE");
p.add(linkToComplex(), "TF SPE", "TF PE");
p.add(peToControl(), "TF PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
p.add(new Size(right(), 1, Size.Type.EQUAL), "Conversion");
p.add(new OR(new MappedConst(new Empty(left()), 0), new MappedConst(new ConstraintAdapter(1)
{
@Override
public boolean satisfies(Match match, int... ind)
{
Conversion cnv = (Conversion) match.get(ind[0]);
Set<PhysicalEntity> left = cnv.getLeft();
if (left.size() > 1) return false;
if (left.isEmpty()) return true;
PhysicalEntity pe = left.iterator().next();
if (pe instanceof NucleicAcid)
{
PhysicalEntity rPE = cnv.getRight().iterator().next();
return rPE instanceof Protein;
}
return false;
}
}, 0)), "Conversion");
p.add(right(), "Conversion", "right PE");
p.add(linkToSpecific(), "right PE", "right SPE");
p.add(new Type(SequenceEntity.class), "right SPE");
p.add(peToER(), "right SPE", "product generic ER");
p.add(linkedER(false), "product generic ER", "product ER");
p.add(equal(false), "TF ER", "product ER");
return p;
} | java | public static Pattern controlsExpressionWithConversion()
{
Pattern p = new Pattern(SequenceEntityReference.class, "TF ER");
p.add(linkedER(true), "TF ER", "TF generic ER");
p.add(erToPE(), "TF generic ER", "TF SPE");
p.add(linkToComplex(), "TF SPE", "TF PE");
p.add(peToControl(), "TF PE", "Control");
p.add(controlToConv(), "Control", "Conversion");
p.add(new Size(right(), 1, Size.Type.EQUAL), "Conversion");
p.add(new OR(new MappedConst(new Empty(left()), 0), new MappedConst(new ConstraintAdapter(1)
{
@Override
public boolean satisfies(Match match, int... ind)
{
Conversion cnv = (Conversion) match.get(ind[0]);
Set<PhysicalEntity> left = cnv.getLeft();
if (left.size() > 1) return false;
if (left.isEmpty()) return true;
PhysicalEntity pe = left.iterator().next();
if (pe instanceof NucleicAcid)
{
PhysicalEntity rPE = cnv.getRight().iterator().next();
return rPE instanceof Protein;
}
return false;
}
}, 0)), "Conversion");
p.add(right(), "Conversion", "right PE");
p.add(linkToSpecific(), "right PE", "right SPE");
p.add(new Type(SequenceEntity.class), "right SPE");
p.add(peToER(), "right SPE", "product generic ER");
p.add(linkedER(false), "product generic ER", "product ER");
p.add(equal(false), "TF ER", "product ER");
return p;
} | [
"public",
"static",
"Pattern",
"controlsExpressionWithConversion",
"(",
")",
"{",
"Pattern",
"p",
"=",
"new",
"Pattern",
"(",
"SequenceEntityReference",
".",
"class",
",",
"\"TF ER\"",
")",
";",
"p",
".",
"add",
"(",
"linkedER",
"(",
"true",
")",
",",
"\"TF ... | Finds the cases where transcription relation is shown using a Conversion instead of a
TemplateReaction.
@return the pattern | [
"Finds",
"the",
"cases",
"where",
"transcription",
"relation",
"is",
"shown",
"using",
"a",
"Conversion",
"instead",
"of",
"a",
"TemplateReaction",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L441-L475 |
prestodb/presto | presto-main/src/main/java/com/facebook/presto/sql/gen/VarArgsToMapAdapterGenerator.java | VarArgsToMapAdapterGenerator.generateVarArgsToMapAdapter | public static MethodHandle generateVarArgsToMapAdapter(Class<?> returnType, List<Class<?>> javaTypes, List<String> names, Function<Map<String, Object>, Object> function) {
"""
Generate byte code that
<p><ul>
<li>takes a specified number of variables as arguments (types of the arguments are provided in {@code javaTypes})
<li>put the variables in a map (keys of the map are provided in {@code names})
<li>invoke the provided {@code function} with the map
<li>return with the result of the function call (type must match {@code returnType})
</ul></p>
"""
checkCondition(javaTypes.size() <= 254, NOT_SUPPORTED, "Too many arguments for vararg function");
CallSiteBinder callSiteBinder = new CallSiteBinder();
ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName("VarArgsToMapAdapter"), type(Object.class));
ImmutableList.Builder<Parameter> parameterListBuilder = ImmutableList.builder();
for (int i = 0; i < javaTypes.size(); i++) {
Class<?> javaType = javaTypes.get(i);
parameterListBuilder.add(arg("input_" + i, javaType));
}
ImmutableList<Parameter> parameterList = parameterListBuilder.build();
MethodDefinition methodDefinition = classDefinition.declareMethod(a(PUBLIC, STATIC), "varArgsToMap", type(returnType), parameterList);
BytecodeBlock body = methodDefinition.getBody();
// ImmutableMap.Builder can not be used here because it doesn't allow nulls.
Variable map = methodDefinition.getScope().declareVariable(
"map",
methodDefinition.getBody(),
invokeStatic(Maps.class, "newHashMapWithExpectedSize", HashMap.class, constantInt(javaTypes.size())));
for (int i = 0; i < javaTypes.size(); i++) {
body.append(map.invoke("put", Object.class, constantString(names.get(i)).cast(Object.class), parameterList.get(i).cast(Object.class)));
}
body.append(
loadConstant(callSiteBinder, function, Function.class)
.invoke("apply", Object.class, map.cast(Object.class))
.cast(returnType)
.ret());
Class<?> generatedClass = defineClass(classDefinition, Object.class, callSiteBinder.getBindings(), new DynamicClassLoader(VarArgsToMapAdapterGenerator.class.getClassLoader()));
return Reflection.methodHandle(generatedClass, "varArgsToMap", javaTypes.toArray(new Class<?>[javaTypes.size()]));
} | java | public static MethodHandle generateVarArgsToMapAdapter(Class<?> returnType, List<Class<?>> javaTypes, List<String> names, Function<Map<String, Object>, Object> function)
{
checkCondition(javaTypes.size() <= 254, NOT_SUPPORTED, "Too many arguments for vararg function");
CallSiteBinder callSiteBinder = new CallSiteBinder();
ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL), makeClassName("VarArgsToMapAdapter"), type(Object.class));
ImmutableList.Builder<Parameter> parameterListBuilder = ImmutableList.builder();
for (int i = 0; i < javaTypes.size(); i++) {
Class<?> javaType = javaTypes.get(i);
parameterListBuilder.add(arg("input_" + i, javaType));
}
ImmutableList<Parameter> parameterList = parameterListBuilder.build();
MethodDefinition methodDefinition = classDefinition.declareMethod(a(PUBLIC, STATIC), "varArgsToMap", type(returnType), parameterList);
BytecodeBlock body = methodDefinition.getBody();
// ImmutableMap.Builder can not be used here because it doesn't allow nulls.
Variable map = methodDefinition.getScope().declareVariable(
"map",
methodDefinition.getBody(),
invokeStatic(Maps.class, "newHashMapWithExpectedSize", HashMap.class, constantInt(javaTypes.size())));
for (int i = 0; i < javaTypes.size(); i++) {
body.append(map.invoke("put", Object.class, constantString(names.get(i)).cast(Object.class), parameterList.get(i).cast(Object.class)));
}
body.append(
loadConstant(callSiteBinder, function, Function.class)
.invoke("apply", Object.class, map.cast(Object.class))
.cast(returnType)
.ret());
Class<?> generatedClass = defineClass(classDefinition, Object.class, callSiteBinder.getBindings(), new DynamicClassLoader(VarArgsToMapAdapterGenerator.class.getClassLoader()));
return Reflection.methodHandle(generatedClass, "varArgsToMap", javaTypes.toArray(new Class<?>[javaTypes.size()]));
} | [
"public",
"static",
"MethodHandle",
"generateVarArgsToMapAdapter",
"(",
"Class",
"<",
"?",
">",
"returnType",
",",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"javaTypes",
",",
"List",
"<",
"String",
">",
"names",
",",
"Function",
"<",
"Map",
"<",
"String",
... | Generate byte code that
<p><ul>
<li>takes a specified number of variables as arguments (types of the arguments are provided in {@code javaTypes})
<li>put the variables in a map (keys of the map are provided in {@code names})
<li>invoke the provided {@code function} with the map
<li>return with the result of the function call (type must match {@code returnType})
</ul></p> | [
"Generate",
"byte",
"code",
"that",
"<p",
">",
"<ul",
">",
"<li",
">",
"takes",
"a",
"specified",
"number",
"of",
"variables",
"as",
"arguments",
"(",
"types",
"of",
"the",
"arguments",
"are",
"provided",
"in",
"{"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/sql/gen/VarArgsToMapAdapterGenerator.java#L62-L95 |
cojen/Cojen | src/main/java/org/cojen/util/ClassInjector.java | ClassInjector.createExplicit | public static ClassInjector createExplicit(String name, ClassLoader parent) {
"""
Create a ClassInjector for defining one class with an explicit name. If
the parent ClassLoader is not specified, it will default to the
ClassLoader of the ClassInjector class.
<p>
If the parent loader was used for loading injected classes, the new
class will be loaded by it. This allows auto-generated classes access to
package accessible members, as long as they are defined in the same
package.
@param name required class name
@param parent optional parent ClassLoader
@throws IllegalArgumentException if name is null
"""
if (name == null) {
throw new IllegalArgumentException("Explicit class name not provided");
}
return create(name, parent, true);
} | java | public static ClassInjector createExplicit(String name, ClassLoader parent) {
if (name == null) {
throw new IllegalArgumentException("Explicit class name not provided");
}
return create(name, parent, true);
} | [
"public",
"static",
"ClassInjector",
"createExplicit",
"(",
"String",
"name",
",",
"ClassLoader",
"parent",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Explicit class name not provided\"",
")",
";",
"}",... | Create a ClassInjector for defining one class with an explicit name. If
the parent ClassLoader is not specified, it will default to the
ClassLoader of the ClassInjector class.
<p>
If the parent loader was used for loading injected classes, the new
class will be loaded by it. This allows auto-generated classes access to
package accessible members, as long as they are defined in the same
package.
@param name required class name
@param parent optional parent ClassLoader
@throws IllegalArgumentException if name is null | [
"Create",
"a",
"ClassInjector",
"for",
"defining",
"one",
"class",
"with",
"an",
"explicit",
"name",
".",
"If",
"the",
"parent",
"ClassLoader",
"is",
"not",
"specified",
"it",
"will",
"default",
"to",
"the",
"ClassLoader",
"of",
"the",
"ClassInjector",
"class"... | train | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ClassInjector.java#L107-L112 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceInfoMap.java | SourceInfoMap.addFieldLine | public void addFieldLine(String className, String fieldName, SourceLineRange range) {
"""
Add a line number entry for a field.
@param className
name of class containing the field
@param fieldName
name of field
@param range
the line number(s) of the field
"""
fieldLineMap.put(new FieldDescriptor(className, fieldName), range);
} | java | public void addFieldLine(String className, String fieldName, SourceLineRange range) {
fieldLineMap.put(new FieldDescriptor(className, fieldName), range);
} | [
"public",
"void",
"addFieldLine",
"(",
"String",
"className",
",",
"String",
"fieldName",
",",
"SourceLineRange",
"range",
")",
"{",
"fieldLineMap",
".",
"put",
"(",
"new",
"FieldDescriptor",
"(",
"className",
",",
"fieldName",
")",
",",
"range",
")",
";",
"... | Add a line number entry for a field.
@param className
name of class containing the field
@param fieldName
name of field
@param range
the line number(s) of the field | [
"Add",
"a",
"line",
"number",
"entry",
"for",
"a",
"field",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/SourceInfoMap.java#L251-L253 |
i-net-software/jlessc | src/com/inet/lib/less/CssFormatter.java | CssFormatter.removeGuardParameters | void removeGuardParameters( Map<String, Expression> parameters ) {
"""
remove the parameters of a guard
@param parameters the parameters
"""
if( parameters != null ) {
removeMixin();
}
isGuard = false;
} | java | void removeGuardParameters( Map<String, Expression> parameters ) {
if( parameters != null ) {
removeMixin();
}
isGuard = false;
} | [
"void",
"removeGuardParameters",
"(",
"Map",
"<",
"String",
",",
"Expression",
">",
"parameters",
")",
"{",
"if",
"(",
"parameters",
"!=",
"null",
")",
"{",
"removeMixin",
"(",
")",
";",
"}",
"isGuard",
"=",
"false",
";",
"}"
] | remove the parameters of a guard
@param parameters the parameters | [
"remove",
"the",
"parameters",
"of",
"a",
"guard"
] | train | https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/CssFormatter.java#L491-L496 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.read | public static String read(InputStream in, String charsetName) throws IORuntimeException {
"""
从流中读取内容
@param in 输入流
@param charsetName 字符集
@return 内容
@throws IORuntimeException IO异常
"""
FastByteArrayOutputStream out = read(in);
return StrUtil.isBlank(charsetName) ? out.toString() : out.toString(charsetName);
} | java | public static String read(InputStream in, String charsetName) throws IORuntimeException {
FastByteArrayOutputStream out = read(in);
return StrUtil.isBlank(charsetName) ? out.toString() : out.toString(charsetName);
} | [
"public",
"static",
"String",
"read",
"(",
"InputStream",
"in",
",",
"String",
"charsetName",
")",
"throws",
"IORuntimeException",
"{",
"FastByteArrayOutputStream",
"out",
"=",
"read",
"(",
"in",
")",
";",
"return",
"StrUtil",
".",
"isBlank",
"(",
"charsetName",... | 从流中读取内容
@param in 输入流
@param charsetName 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"从流中读取内容"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L396-L399 |
mgormley/pacaya | src/main/java/edu/jhu/pacaya/autodiff/Toposort.java | Toposort.checkAreDescendentsOf | public static <T> void checkAreDescendentsOf(Set<T> inputSet, T root, Deps<T> deps) {
"""
Checks that the given inputSet consists of only descendents of the root.
"""
// Check that all modules in the input set are descendents of the output module.
HashSet<T> visited = new HashSet<T>();
dfs(root, visited, deps);
if (!visited.containsAll(inputSet)) {
throw new IllegalStateException("Input set contains modules which are not descendents of the output module: " + inputSet);
}
} | java | public static <T> void checkAreDescendentsOf(Set<T> inputSet, T root, Deps<T> deps) {
// Check that all modules in the input set are descendents of the output module.
HashSet<T> visited = new HashSet<T>();
dfs(root, visited, deps);
if (!visited.containsAll(inputSet)) {
throw new IllegalStateException("Input set contains modules which are not descendents of the output module: " + inputSet);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"checkAreDescendentsOf",
"(",
"Set",
"<",
"T",
">",
"inputSet",
",",
"T",
"root",
",",
"Deps",
"<",
"T",
">",
"deps",
")",
"{",
"// Check that all modules in the input set are descendents of the output module.",
"HashSet",
... | Checks that the given inputSet consists of only descendents of the root. | [
"Checks",
"that",
"the",
"given",
"inputSet",
"consists",
"of",
"only",
"descendents",
"of",
"the",
"root",
"."
] | train | https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/autodiff/Toposort.java#L115-L122 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java | LOF.computeLOFScore | protected double computeLOFScore(KNNQuery<O> knnq, DBIDRef cur, DoubleDataStore lrds) {
"""
Compute a single LOF score.
@param knnq kNN query
@param cur Current object
@param lrds Stored reachability densities
@return LOF score.
"""
final double lrdp = lrds.doubleValue(cur);
if(Double.isInfinite(lrdp)) {
return 1.0;
}
double sum = 0.;
int count = 0;
final KNNList neighbors = knnq.getKNNForDBID(cur, k);
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(cur, neighbor)) {
continue;
}
sum += lrds.doubleValue(neighbor);
++count;
}
return sum / (lrdp * count);
} | java | protected double computeLOFScore(KNNQuery<O> knnq, DBIDRef cur, DoubleDataStore lrds) {
final double lrdp = lrds.doubleValue(cur);
if(Double.isInfinite(lrdp)) {
return 1.0;
}
double sum = 0.;
int count = 0;
final KNNList neighbors = knnq.getKNNForDBID(cur, k);
for(DBIDIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) {
// skip the point itself
if(DBIDUtil.equal(cur, neighbor)) {
continue;
}
sum += lrds.doubleValue(neighbor);
++count;
}
return sum / (lrdp * count);
} | [
"protected",
"double",
"computeLOFScore",
"(",
"KNNQuery",
"<",
"O",
">",
"knnq",
",",
"DBIDRef",
"cur",
",",
"DoubleDataStore",
"lrds",
")",
"{",
"final",
"double",
"lrdp",
"=",
"lrds",
".",
"doubleValue",
"(",
"cur",
")",
";",
"if",
"(",
"Double",
".",... | Compute a single LOF score.
@param knnq kNN query
@param cur Current object
@param lrds Stored reachability densities
@return LOF score. | [
"Compute",
"a",
"single",
"LOF",
"score",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java#L223-L240 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/BeatFinder.java | BeatFinder.deliverMasterYieldResponse | private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {
"""
Send a master handoff yield response to all registered listeners.
@param fromPlayer the device number that is responding to our request that it yield the tempo master role to us
@param yielded will be {@code true} if we should now be the tempo master
"""
for (final MasterHandoffListener listener : getMasterHandoffListeners()) {
try {
listener.yieldResponse(fromPlayer, yielded);
} catch (Throwable t) {
logger.warn("Problem delivering master yield response to listener", t);
}
}
} | java | private void deliverMasterYieldResponse(int fromPlayer, boolean yielded) {
for (final MasterHandoffListener listener : getMasterHandoffListeners()) {
try {
listener.yieldResponse(fromPlayer, yielded);
} catch (Throwable t) {
logger.warn("Problem delivering master yield response to listener", t);
}
}
} | [
"private",
"void",
"deliverMasterYieldResponse",
"(",
"int",
"fromPlayer",
",",
"boolean",
"yielded",
")",
"{",
"for",
"(",
"final",
"MasterHandoffListener",
"listener",
":",
"getMasterHandoffListeners",
"(",
")",
")",
"{",
"try",
"{",
"listener",
".",
"yieldRespo... | Send a master handoff yield response to all registered listeners.
@param fromPlayer the device number that is responding to our request that it yield the tempo master role to us
@param yielded will be {@code true} if we should now be the tempo master | [
"Send",
"a",
"master",
"handoff",
"yield",
"response",
"to",
"all",
"registered",
"listeners",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/BeatFinder.java#L439-L447 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.existsResource | public boolean existsResource(CmsRequestContext context, CmsUUID structureId, CmsResourceFilter filter) {
"""
Checks the availability of a resource in the VFS,
using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p>
A resource may be of type <code>{@link CmsFile}</code> or
<code>{@link CmsFolder}</code>.<p>
The specified filter controls what kind of resources should be "found"
during the read operation. This will depend on the application. For example,
using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently
"valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code>
will ignore the date release / date expired information of the resource.<p>
This method also takes into account the user permissions, so if
the given resource exists, but the current user has not the required
permissions, then this method will return <code>false</code>.<p>
@param context the current request context
@param structureId the structure id of the resource to check
@param filter the resource filter to use while reading
@return <code>true</code> if the resource is available
@see CmsObject#existsResource(CmsUUID, CmsResourceFilter)
@see CmsObject#existsResource(CmsUUID)
"""
boolean result = false;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
readResource(dbc, structureId, filter);
result = true;
} catch (Exception e) {
result = false;
} finally {
dbc.clear();
}
return result;
} | java | public boolean existsResource(CmsRequestContext context, CmsUUID structureId, CmsResourceFilter filter) {
boolean result = false;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
readResource(dbc, structureId, filter);
result = true;
} catch (Exception e) {
result = false;
} finally {
dbc.clear();
}
return result;
} | [
"public",
"boolean",
"existsResource",
"(",
"CmsRequestContext",
"context",
",",
"CmsUUID",
"structureId",
",",
"CmsResourceFilter",
"filter",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(... | Checks the availability of a resource in the VFS,
using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p>
A resource may be of type <code>{@link CmsFile}</code> or
<code>{@link CmsFolder}</code>.<p>
The specified filter controls what kind of resources should be "found"
during the read operation. This will depend on the application. For example,
using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently
"valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code>
will ignore the date release / date expired information of the resource.<p>
This method also takes into account the user permissions, so if
the given resource exists, but the current user has not the required
permissions, then this method will return <code>false</code>.<p>
@param context the current request context
@param structureId the structure id of the resource to check
@param filter the resource filter to use while reading
@return <code>true</code> if the resource is available
@see CmsObject#existsResource(CmsUUID, CmsResourceFilter)
@see CmsObject#existsResource(CmsUUID) | [
"Checks",
"the",
"availability",
"of",
"a",
"resource",
"in",
"the",
"VFS",
"using",
"the",
"<code",
">",
"{",
"@link",
"CmsResourceFilter#DEFAULT",
"}",
"<",
"/",
"code",
">",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L1767-L1780 |
abel533/Mapper | core/src/main/java/tk/mybatis/mapper/mapperhelper/EntityHelper.java | EntityHelper.setKeyProperties | public static void setKeyProperties(Set<EntityColumn> pkColumns, MappedStatement ms) {
"""
通过反射设置MappedStatement的keyProperties字段值
@param pkColumns 所有的主键字段
@param ms MappedStatement
"""
if (pkColumns == null || pkColumns.isEmpty()) {
return;
}
List<String> keyProperties = new ArrayList<String>(pkColumns.size());
for (EntityColumn column : pkColumns) {
keyProperties.add(column.getProperty());
}
MetaObjectUtil.forObject(ms).setValue("keyProperties", keyProperties.toArray(new String[]{}));
} | java | public static void setKeyProperties(Set<EntityColumn> pkColumns, MappedStatement ms) {
if (pkColumns == null || pkColumns.isEmpty()) {
return;
}
List<String> keyProperties = new ArrayList<String>(pkColumns.size());
for (EntityColumn column : pkColumns) {
keyProperties.add(column.getProperty());
}
MetaObjectUtil.forObject(ms).setValue("keyProperties", keyProperties.toArray(new String[]{}));
} | [
"public",
"static",
"void",
"setKeyProperties",
"(",
"Set",
"<",
"EntityColumn",
">",
"pkColumns",
",",
"MappedStatement",
"ms",
")",
"{",
"if",
"(",
"pkColumns",
"==",
"null",
"||",
"pkColumns",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"L... | 通过反射设置MappedStatement的keyProperties字段值
@param pkColumns 所有的主键字段
@param ms MappedStatement | [
"通过反射设置MappedStatement的keyProperties字段值"
] | train | https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/EntityHelper.java#L192-L203 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java | JobExecutionsInner.createOrUpdate | public JobExecutionInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId) {
"""
Creates or updatess a job execution.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@param jobExecutionId The job execution id to create the job execution under.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobExecutionInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId).toBlocking().last().body();
} | java | public JobExecutionInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, UUID jobExecutionId) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId).toBlocking().last().body();
} | [
"public",
"JobExecutionInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"jobAgentName",
",",
"String",
"jobName",
",",
"UUID",
"jobExecutionId",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"... | Creates or updatess a job execution.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param jobAgentName The name of the job agent.
@param jobName The name of the job to get.
@param jobExecutionId The job execution id to create the job execution under.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the JobExecutionInner object if successful. | [
"Creates",
"or",
"updatess",
"a",
"job",
"execution",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L1126-L1128 |
xiancloud/xian | xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/pool/PoolFactory.java | PoolFactory.getPool | public static IPool getPool(String host, Integer port, String database, String... userPwd) {
"""
根据指定的域名端口和数据库名获取连接池,如果之前已经初始化过该连接池那么直接返回已存在的那个连接池
@param host MySQL主机ip或域名
@param port MySQL端口
@param database 数据库名
@return 数据库连接池
"""
//暂未启用
throw new RuntimeException("未找到指定的数据库连接池");
} | java | public static IPool getPool(String host, Integer port, String database, String... userPwd) {
//暂未启用
throw new RuntimeException("未找到指定的数据库连接池");
} | [
"public",
"static",
"IPool",
"getPool",
"(",
"String",
"host",
",",
"Integer",
"port",
",",
"String",
"database",
",",
"String",
"...",
"userPwd",
")",
"{",
"//暂未启用",
"throw",
"new",
"RuntimeException",
"(",
"\"未找到指定的数据库连接池\");",
"",
"",
"}"
] | 根据指定的域名端口和数据库名获取连接池,如果之前已经初始化过该连接池那么直接返回已存在的那个连接池
@param host MySQL主机ip或域名
@param port MySQL端口
@param database 数据库名
@return 数据库连接池 | [
"根据指定的域名端口和数据库名获取连接池",
"如果之前已经初始化过该连接池那么直接返回已存在的那个连接池"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/pool/PoolFactory.java#L44-L47 |
aws/aws-sdk-java | aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateRobotResult.java | CreateRobotResult.withTags | public CreateRobotResult withTags(java.util.Map<String, String> tags) {
"""
<p>
The list of all tags added to the robot.
</p>
@param tags
The list of all tags added to the robot.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public CreateRobotResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateRobotResult",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The list of all tags added to the robot.
</p>
@param tags
The list of all tags added to the robot.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"list",
"of",
"all",
"tags",
"added",
"to",
"the",
"robot",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateRobotResult.java#L317-L320 |
pravega/pravega | client/src/main/java/io/pravega/client/admin/impl/StreamCutHelper.java | StreamCutHelper.fetchTailStreamCut | public CompletableFuture<StreamCut> fetchTailStreamCut(final Stream stream) {
"""
Obtain the {@link StreamCut} pointing to the current TAIL of the Stream.
@param stream The Stream.
@return {@link StreamCut} pointing to the TAIL of the Stream.
"""
return controller.getCurrentSegments(stream.getScope(), stream.getStreamName())
.thenApply(s -> {
latestDelegationToken.set(s.getDelegationToken());
Map<Segment, Long> pos =
s.getSegments().stream().map(this::segmentToInfo)
.collect(Collectors.toMap(SegmentInfo::getSegment, SegmentInfo::getWriteOffset));
return new StreamCutImpl(stream, pos);
});
} | java | public CompletableFuture<StreamCut> fetchTailStreamCut(final Stream stream) {
return controller.getCurrentSegments(stream.getScope(), stream.getStreamName())
.thenApply(s -> {
latestDelegationToken.set(s.getDelegationToken());
Map<Segment, Long> pos =
s.getSegments().stream().map(this::segmentToInfo)
.collect(Collectors.toMap(SegmentInfo::getSegment, SegmentInfo::getWriteOffset));
return new StreamCutImpl(stream, pos);
});
} | [
"public",
"CompletableFuture",
"<",
"StreamCut",
">",
"fetchTailStreamCut",
"(",
"final",
"Stream",
"stream",
")",
"{",
"return",
"controller",
".",
"getCurrentSegments",
"(",
"stream",
".",
"getScope",
"(",
")",
",",
"stream",
".",
"getStreamName",
"(",
")",
... | Obtain the {@link StreamCut} pointing to the current TAIL of the Stream.
@param stream The Stream.
@return {@link StreamCut} pointing to the TAIL of the Stream. | [
"Obtain",
"the",
"{"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/admin/impl/StreamCutHelper.java#L62-L71 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.notEmpty | @CodingStyleguideUnaware
public static <T extends Collection <?>> T notEmpty (final T aValue, @Nonnull final Supplier <? extends String> aName) {
"""
Check that the passed {@link Collection} is neither <code>null</code> nor
empty.
@param <T>
Type to be checked and returned
@param aValue
The String to check.
@param aName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is empty
"""
notNull (aValue, aName);
if (isEnabled ())
if (aValue.isEmpty ())
throw new IllegalArgumentException ("The value of the collection '" + aName.get () + "' may not be empty!");
return aValue;
} | java | @CodingStyleguideUnaware
public static <T extends Collection <?>> T notEmpty (final T aValue, @Nonnull final Supplier <? extends String> aName)
{
notNull (aValue, aName);
if (isEnabled ())
if (aValue.isEmpty ())
throw new IllegalArgumentException ("The value of the collection '" + aName.get () + "' may not be empty!");
return aValue;
} | [
"@",
"CodingStyleguideUnaware",
"public",
"static",
"<",
"T",
"extends",
"Collection",
"<",
"?",
">",
">",
"T",
"notEmpty",
"(",
"final",
"T",
"aValue",
",",
"@",
"Nonnull",
"final",
"Supplier",
"<",
"?",
"extends",
"String",
">",
"aName",
")",
"{",
"not... | Check that the passed {@link Collection} is neither <code>null</code> nor
empty.
@param <T>
Type to be checked and returned
@param aValue
The String to check.
@param aName
The name of the value (e.g. the parameter name)
@return The passed value.
@throws IllegalArgumentException
if the passed value is empty | [
"Check",
"that",
"the",
"passed",
"{",
"@link",
"Collection",
"}",
"is",
"neither",
"<code",
">",
"null<",
"/",
"code",
">",
"nor",
"empty",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L757-L765 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java | ByteConverter.int8 | public static void int8(byte[] target, int idx, long value) {
"""
Encodes a long value to the byte array.
@param target The byte array to encode to.
@param idx The starting index in the byte array.
@param value The value to encode.
"""
target[idx + 0] = (byte) (value >>> 56);
target[idx + 1] = (byte) (value >>> 48);
target[idx + 2] = (byte) (value >>> 40);
target[idx + 3] = (byte) (value >>> 32);
target[idx + 4] = (byte) (value >>> 24);
target[idx + 5] = (byte) (value >>> 16);
target[idx + 6] = (byte) (value >>> 8);
target[idx + 7] = (byte) value;
} | java | public static void int8(byte[] target, int idx, long value) {
target[idx + 0] = (byte) (value >>> 56);
target[idx + 1] = (byte) (value >>> 48);
target[idx + 2] = (byte) (value >>> 40);
target[idx + 3] = (byte) (value >>> 32);
target[idx + 4] = (byte) (value >>> 24);
target[idx + 5] = (byte) (value >>> 16);
target[idx + 6] = (byte) (value >>> 8);
target[idx + 7] = (byte) value;
} | [
"public",
"static",
"void",
"int8",
"(",
"byte",
"[",
"]",
"target",
",",
"int",
"idx",
",",
"long",
"value",
")",
"{",
"target",
"[",
"idx",
"+",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"value",
">>>",
"56",
")",
";",
"target",
"[",
"idx",
"+",
... | Encodes a long value to the byte array.
@param target The byte array to encode to.
@param idx The starting index in the byte array.
@param value The value to encode. | [
"Encodes",
"a",
"long",
"value",
"to",
"the",
"byte",
"array",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java#L106-L115 |
softindex/datakernel | core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBuf.java | ByteBuf.drainTo | public int drainTo(@NotNull ByteBuf buf, int length) {
"""
Drains bytes to a given {@code ByteBuf}.
@see #drainTo(byte[], int, int)
"""
assert !buf.isRecycled();
assert buf.tail + length <= buf.array.length;
drainTo(buf.array, buf.tail, length);
buf.tail += length;
return length;
} | java | public int drainTo(@NotNull ByteBuf buf, int length) {
assert !buf.isRecycled();
assert buf.tail + length <= buf.array.length;
drainTo(buf.array, buf.tail, length);
buf.tail += length;
return length;
} | [
"public",
"int",
"drainTo",
"(",
"@",
"NotNull",
"ByteBuf",
"buf",
",",
"int",
"length",
")",
"{",
"assert",
"!",
"buf",
".",
"isRecycled",
"(",
")",
";",
"assert",
"buf",
".",
"tail",
"+",
"length",
"<=",
"buf",
".",
"array",
".",
"length",
";",
"... | Drains bytes to a given {@code ByteBuf}.
@see #drainTo(byte[], int, int) | [
"Drains",
"bytes",
"to",
"a",
"given",
"{",
"@code",
"ByteBuf",
"}",
"."
] | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-bytebuf/src/main/java/io/datakernel/bytebuf/ByteBuf.java#L590-L596 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java | JsonUtil.getFloat | public static float getFloat(JsonObject object, String field) {
"""
Returns a field in a Json object as a float.
Throws IllegalArgumentException if the field value is null.
@param object the Json Object
@param field the field in the Json object to return
@return the Json field value as a float
"""
final JsonValue value = object.get(field);
throwExceptionIfNull(value, field);
return value.asFloat();
} | java | public static float getFloat(JsonObject object, String field) {
final JsonValue value = object.get(field);
throwExceptionIfNull(value, field);
return value.asFloat();
} | [
"public",
"static",
"float",
"getFloat",
"(",
"JsonObject",
"object",
",",
"String",
"field",
")",
"{",
"final",
"JsonValue",
"value",
"=",
"object",
".",
"get",
"(",
"field",
")",
";",
"throwExceptionIfNull",
"(",
"value",
",",
"field",
")",
";",
"return"... | Returns a field in a Json object as a float.
Throws IllegalArgumentException if the field value is null.
@param object the Json Object
@param field the field in the Json object to return
@return the Json field value as a float | [
"Returns",
"a",
"field",
"in",
"a",
"Json",
"object",
"as",
"a",
"float",
".",
"Throws",
"IllegalArgumentException",
"if",
"the",
"field",
"value",
"is",
"null",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java#L137-L141 |
allengeorge/libraft | libraft-samples/kayvee/src/main/java/io/libraft/kayvee/mappers/KayVeeLoggingExceptionMapper.java | KayVeeLoggingExceptionMapper.newResponse | protected final Response newResponse(ExceptionType exception, Response.Status status) {
"""
Generate an HTTP error response.
<p/>
This response includes:
<ul>
<li>A unique id for this exception event.</li>
<li>The response code (specified by subclasses).</li>
<li>The exception stack trace.</li>
</ul>
@param exception exception instance thrown while processing {@link KayVeeLoggingExceptionMapper#request}
@param status HTTP status code of the response (ex. 400, 404, etc.)
@return a valid {@code Response} instance with a fully-populated error message and HTTP response code set that can be sent to the client
"""
final StringWriter writer = new StringWriter(4096);
try {
final long id = randomId();
logException(id, exception);
errorHandler.writeErrorPage(request,
writer,
status.getStatusCode(),
formatResponseEntity(id, exception),
false);
} catch (IOException e) {
LOGGER.warn("Unable to generate error page", e);
}
return Response
.status(status)
.type(MediaType.TEXT_HTML_TYPE)
.entity(writer.toString())
.build();
} | java | protected final Response newResponse(ExceptionType exception, Response.Status status) {
final StringWriter writer = new StringWriter(4096);
try {
final long id = randomId();
logException(id, exception);
errorHandler.writeErrorPage(request,
writer,
status.getStatusCode(),
formatResponseEntity(id, exception),
false);
} catch (IOException e) {
LOGGER.warn("Unable to generate error page", e);
}
return Response
.status(status)
.type(MediaType.TEXT_HTML_TYPE)
.entity(writer.toString())
.build();
} | [
"protected",
"final",
"Response",
"newResponse",
"(",
"ExceptionType",
"exception",
",",
"Response",
".",
"Status",
"status",
")",
"{",
"final",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
"4096",
")",
";",
"try",
"{",
"final",
"long",
"id",
"... | Generate an HTTP error response.
<p/>
This response includes:
<ul>
<li>A unique id for this exception event.</li>
<li>The response code (specified by subclasses).</li>
<li>The exception stack trace.</li>
</ul>
@param exception exception instance thrown while processing {@link KayVeeLoggingExceptionMapper#request}
@param status HTTP status code of the response (ex. 400, 404, etc.)
@return a valid {@code Response} instance with a fully-populated error message and HTTP response code set that can be sent to the client | [
"Generate",
"an",
"HTTP",
"error",
"response",
".",
"<p",
"/",
">",
"This",
"response",
"includes",
":",
"<ul",
">",
"<li",
">",
"A",
"unique",
"id",
"for",
"this",
"exception",
"event",
".",
"<",
"/",
"li",
">",
"<li",
">",
"The",
"response",
"code"... | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-samples/kayvee/src/main/java/io/libraft/kayvee/mappers/KayVeeLoggingExceptionMapper.java#L89-L108 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/inverse/InvertMatrix.java | InvertMatrix.pLeftInvert | public static INDArray pLeftInvert(INDArray arr, boolean inPlace) {
"""
Compute the left pseudo inverse. Input matrix must have full column rank.
See also: <a href="https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Definition">Moore–Penrose inverse</a>
@param arr Input matrix
@param inPlace Whether to store the result in {@code arr}
@return Left pseudo inverse of {@code arr}
@exception IllegalArgumentException Input matrix {@code arr} did not have full column rank.
"""
try {
final INDArray inv = invert(arr.transpose().mmul(arr), inPlace).mmul(arr.transpose());
if (inPlace) arr.assign(inv);
return inv;
} catch (SingularMatrixException e) {
throw new IllegalArgumentException(
"Full column rank condition for left pseudo inverse was not met.");
}
} | java | public static INDArray pLeftInvert(INDArray arr, boolean inPlace) {
try {
final INDArray inv = invert(arr.transpose().mmul(arr), inPlace).mmul(arr.transpose());
if (inPlace) arr.assign(inv);
return inv;
} catch (SingularMatrixException e) {
throw new IllegalArgumentException(
"Full column rank condition for left pseudo inverse was not met.");
}
} | [
"public",
"static",
"INDArray",
"pLeftInvert",
"(",
"INDArray",
"arr",
",",
"boolean",
"inPlace",
")",
"{",
"try",
"{",
"final",
"INDArray",
"inv",
"=",
"invert",
"(",
"arr",
".",
"transpose",
"(",
")",
".",
"mmul",
"(",
"arr",
")",
",",
"inPlace",
")"... | Compute the left pseudo inverse. Input matrix must have full column rank.
See also: <a href="https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Definition">Moore–Penrose inverse</a>
@param arr Input matrix
@param inPlace Whether to store the result in {@code arr}
@return Left pseudo inverse of {@code arr}
@exception IllegalArgumentException Input matrix {@code arr} did not have full column rank. | [
"Compute",
"the",
"left",
"pseudo",
"inverse",
".",
"Input",
"matrix",
"must",
"have",
"full",
"column",
"rank",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/inverse/InvertMatrix.java#L108-L117 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java | ClassDocImpl.findMethod | public MethodDocImpl findMethod(String methodName, String[] paramTypes) {
"""
Find a method in this class scope.
Search order: this class, interfaces, superclasses, outerclasses.
Note that this is not necessarily what the compiler would do!
@param methodName the unqualified name to search for.
@param paramTypes the array of Strings for method parameter types.
@return the first MethodDocImpl which matches, null if not found.
"""
// Use hash table 'searched' to avoid searching same class twice.
//### It is not clear how this could happen.
return searchMethod(methodName, paramTypes, new HashSet<ClassDocImpl>());
} | java | public MethodDocImpl findMethod(String methodName, String[] paramTypes) {
// Use hash table 'searched' to avoid searching same class twice.
//### It is not clear how this could happen.
return searchMethod(methodName, paramTypes, new HashSet<ClassDocImpl>());
} | [
"public",
"MethodDocImpl",
"findMethod",
"(",
"String",
"methodName",
",",
"String",
"[",
"]",
"paramTypes",
")",
"{",
"// Use hash table 'searched' to avoid searching same class twice.",
"//### It is not clear how this could happen.",
"return",
"searchMethod",
"(",
"methodName",... | Find a method in this class scope.
Search order: this class, interfaces, superclasses, outerclasses.
Note that this is not necessarily what the compiler would do!
@param methodName the unqualified name to search for.
@param paramTypes the array of Strings for method parameter types.
@return the first MethodDocImpl which matches, null if not found. | [
"Find",
"a",
"method",
"in",
"this",
"class",
"scope",
".",
"Search",
"order",
":",
"this",
"class",
"interfaces",
"superclasses",
"outerclasses",
".",
"Note",
"that",
"this",
"is",
"not",
"necessarily",
"what",
"the",
"compiler",
"would",
"do!"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java#L874-L878 |
apiman/apiman | gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java | ConnectorFactory.createConnector | @Override
public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
"""
In the future we can switch to different back-end implementations here!
"""
return (request, resultHandler) -> {
// Apply options from config as our base case
ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config)
.setHasDataPolicy(hasDataPolicy)
.setRequiredAuthType(authType)
.setTlsOptions(tlsOptions)
.setUri(parseApiEndpoint(api))
.setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$
// If API has endpoint properties indicating timeouts, then override config.
setAttributesFromApiEndpointProperties(api, httpOptions);
// Get from cache
HttpClient client = clientFromCache(httpOptions);
return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect();
};
} | java | @Override
public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
return (request, resultHandler) -> {
// Apply options from config as our base case
ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config)
.setHasDataPolicy(hasDataPolicy)
.setRequiredAuthType(authType)
.setTlsOptions(tlsOptions)
.setUri(parseApiEndpoint(api))
.setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$
// If API has endpoint properties indicating timeouts, then override config.
setAttributesFromApiEndpointProperties(api, httpOptions);
// Get from cache
HttpClient client = clientFromCache(httpOptions);
return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect();
};
} | [
"@",
"Override",
"public",
"IApiConnector",
"createConnector",
"(",
"ApiRequest",
"req",
",",
"Api",
"api",
",",
"RequiredAuthType",
"authType",
",",
"boolean",
"hasDataPolicy",
",",
"IConnectorConfig",
"connectorConfig",
")",
"{",
"return",
"(",
"request",
",",
"... | In the future we can switch to different back-end implementations here! | [
"In",
"the",
"future",
"we",
"can",
"switch",
"to",
"different",
"back",
"-",
"end",
"implementations",
"here!"
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java#L87-L103 |
audit4j/audit4j-db | src/main/java/org/audit4j/handler/db/Utils.java | Utils.checkNotEmpty | public static String checkNotEmpty(String str, String message) {
"""
Throws a IllegalArgumentException if given String is empty
@param str the parameter to check
@param message the parameter to check
@return the provided parameter
"""
if (checkNotNull(str).isEmpty()) {
throw new IllegalArgumentException(message);
}
return str;
} | java | public static String checkNotEmpty(String str, String message) {
if (checkNotNull(str).isEmpty()) {
throw new IllegalArgumentException(message);
}
return str;
} | [
"public",
"static",
"String",
"checkNotEmpty",
"(",
"String",
"str",
",",
"String",
"message",
")",
"{",
"if",
"(",
"checkNotNull",
"(",
"str",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
";",
... | Throws a IllegalArgumentException if given String is empty
@param str the parameter to check
@param message the parameter to check
@return the provided parameter | [
"Throws",
"a",
"IllegalArgumentException",
"if",
"given",
"String",
"is",
"empty"
] | train | https://github.com/audit4j/audit4j-db/blob/bba822a5722533e6f465a9784f2353ae2e5bc01d/src/main/java/org/audit4j/handler/db/Utils.java#L81-L86 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.incrementCounter | public int incrementCounter(CmsDbContext dbc, String name) throws CmsException {
"""
Increments a counter and returns its value before incrementing.<p>
@param dbc the current database context
@param name the name of the counter which should be incremented
@return the value of the counter
@throws CmsException if something goes wrong
"""
return getVfsDriver(dbc).incrementCounter(dbc, name);
} | java | public int incrementCounter(CmsDbContext dbc, String name) throws CmsException {
return getVfsDriver(dbc).incrementCounter(dbc, name);
} | [
"public",
"int",
"incrementCounter",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"name",
")",
"throws",
"CmsException",
"{",
"return",
"getVfsDriver",
"(",
"dbc",
")",
".",
"incrementCounter",
"(",
"dbc",
",",
"name",
")",
";",
"}"
] | Increments a counter and returns its value before incrementing.<p>
@param dbc the current database context
@param name the name of the counter which should be incremented
@return the value of the counter
@throws CmsException if something goes wrong | [
"Increments",
"a",
"counter",
"and",
"returns",
"its",
"value",
"before",
"incrementing",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L5132-L5135 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java | CPDefinitionOptionRelPersistenceImpl.findByUUID_G | @Override
public CPDefinitionOptionRel findByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionOptionRelException {
"""
Returns the cp definition option rel where uuid = ? and groupId = ? or throws a {@link NoSuchCPDefinitionOptionRelException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching cp definition option rel
@throws NoSuchCPDefinitionOptionRelException if a matching cp definition option rel could not be found
"""
CPDefinitionOptionRel cpDefinitionOptionRel = fetchByUUID_G(uuid,
groupId);
if (cpDefinitionOptionRel == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPDefinitionOptionRelException(msg.toString());
}
return cpDefinitionOptionRel;
} | java | @Override
public CPDefinitionOptionRel findByUUID_G(String uuid, long groupId)
throws NoSuchCPDefinitionOptionRelException {
CPDefinitionOptionRel cpDefinitionOptionRel = fetchByUUID_G(uuid,
groupId);
if (cpDefinitionOptionRel == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPDefinitionOptionRelException(msg.toString());
}
return cpDefinitionOptionRel;
} | [
"@",
"Override",
"public",
"CPDefinitionOptionRel",
"findByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCPDefinitionOptionRelException",
"{",
"CPDefinitionOptionRel",
"cpDefinitionOptionRel",
"=",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupI... | Returns the cp definition option rel where uuid = ? and groupId = ? or throws a {@link NoSuchCPDefinitionOptionRelException} if it could not be found.
@param uuid the uuid
@param groupId the group ID
@return the matching cp definition option rel
@throws NoSuchCPDefinitionOptionRelException if a matching cp definition option rel could not be found | [
"Returns",
"the",
"cp",
"definition",
"option",
"rel",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"throws",
"a",
"{",
"@link",
"NoSuchCPDefinitionOptionRelException",
"}",
"if",
"it",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java#L670-L697 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.