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 |
|---|---|---|---|---|---|---|---|---|---|---|
tango-controls/JTango | server/src/main/java/org/tango/server/servant/ORBUtils.java | ORBUtils.exportDeviceWithDatabase | private static void exportDeviceWithDatabase(final DeviceImpl dev, final String hostName, final String pid)
throws DevFailed {
"""
description : This method exports a device to the outside world. This is done by sending its CORBA network
parameter (mainly the IOR) to the Tango database
@param dev
@throws DevFailed
"""
XLOGGER.entry(dev.getName());
final ORB orb = ORBManager.getOrb();
// Activate the CORBA object incarnated by the Java object
final Device_5 d = dev._this(orb);
// Get the object id and store it
final POA poa = ORBManager.getPoa();
try {
dev.setObjId(poa.reference_to_id(d));
} catch (final WrongAdapter e) {
throw DevFailedUtils.newDevFailed(e);
} catch (final WrongPolicy e) {
throw DevFailedUtils.newDevFailed(e);
}
final DeviceExportInfo info = new DeviceExportInfo(dev.getName(), orb.object_to_string(d), hostName,
Integer.toString(DeviceImpl.SERVER_VERSION), pid, dev.getClassName());
DatabaseFactory.getDatabase().exportDevice(info);
XLOGGER.exit();
} | java | private static void exportDeviceWithDatabase(final DeviceImpl dev, final String hostName, final String pid)
throws DevFailed {
XLOGGER.entry(dev.getName());
final ORB orb = ORBManager.getOrb();
// Activate the CORBA object incarnated by the Java object
final Device_5 d = dev._this(orb);
// Get the object id and store it
final POA poa = ORBManager.getPoa();
try {
dev.setObjId(poa.reference_to_id(d));
} catch (final WrongAdapter e) {
throw DevFailedUtils.newDevFailed(e);
} catch (final WrongPolicy e) {
throw DevFailedUtils.newDevFailed(e);
}
final DeviceExportInfo info = new DeviceExportInfo(dev.getName(), orb.object_to_string(d), hostName,
Integer.toString(DeviceImpl.SERVER_VERSION), pid, dev.getClassName());
DatabaseFactory.getDatabase().exportDevice(info);
XLOGGER.exit();
} | [
"private",
"static",
"void",
"exportDeviceWithDatabase",
"(",
"final",
"DeviceImpl",
"dev",
",",
"final",
"String",
"hostName",
",",
"final",
"String",
"pid",
")",
"throws",
"DevFailed",
"{",
"XLOGGER",
".",
"entry",
"(",
"dev",
".",
"getName",
"(",
")",
")"... | description : This method exports a device to the outside world. This is done by sending its CORBA network
parameter (mainly the IOR) to the Tango database
@param dev
@throws DevFailed | [
"description",
":",
"This",
"method",
"exports",
"a",
"device",
"to",
"the",
"outside",
"world",
".",
"This",
"is",
"done",
"by",
"sending",
"its",
"CORBA",
"network",
"parameter",
"(",
"mainly",
"the",
"IOR",
")",
"to",
"the",
"Tango",
"database"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/ORBUtils.java#L73-L98 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/sjavac/JavacState.java | JavacState.taintPackagesDependingOnChangedPackages | public void taintPackagesDependingOnChangedPackages(Set<String> pkgs, Set<String> recentlyCompiled) {
"""
Propagate recompilation through the dependency chains.
Avoid re-tainting packages that have already been compiled.
"""
for (Package pkg : prev.packages().values()) {
for (String dep : pkg.dependencies()) {
if (pkgs.contains(dep) && !recentlyCompiled.contains(pkg.name())) {
taintPackage(pkg.name(), " its depending on "+dep);
}
}
}
} | java | public void taintPackagesDependingOnChangedPackages(Set<String> pkgs, Set<String> recentlyCompiled) {
for (Package pkg : prev.packages().values()) {
for (String dep : pkg.dependencies()) {
if (pkgs.contains(dep) && !recentlyCompiled.contains(pkg.name())) {
taintPackage(pkg.name(), " its depending on "+dep);
}
}
}
} | [
"public",
"void",
"taintPackagesDependingOnChangedPackages",
"(",
"Set",
"<",
"String",
">",
"pkgs",
",",
"Set",
"<",
"String",
">",
"recentlyCompiled",
")",
"{",
"for",
"(",
"Package",
"pkg",
":",
"prev",
".",
"packages",
"(",
")",
".",
"values",
"(",
")"... | Propagate recompilation through the dependency chains.
Avoid re-tainting packages that have already been compiled. | [
"Propagate",
"recompilation",
"through",
"the",
"dependency",
"chains",
".",
"Avoid",
"re",
"-",
"tainting",
"packages",
"that",
"have",
"already",
"been",
"compiled",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/JavacState.java#L497-L505 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/Environment.java | Environment.doHead | public void doHead(String url, HttpResponse response, Map<String, Object> headers) {
"""
HEADs content from URL.
@param url url to get from.
@param response response to store url and response value in.
@param headers http headers to add.
"""
response.setRequest(url);
httpClient.head(url, response, headers);
} | java | public void doHead(String url, HttpResponse response, Map<String, Object> headers) {
response.setRequest(url);
httpClient.head(url, response, headers);
} | [
"public",
"void",
"doHead",
"(",
"String",
"url",
",",
"HttpResponse",
"response",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"headers",
")",
"{",
"response",
".",
"setRequest",
"(",
"url",
")",
";",
"httpClient",
".",
"head",
"(",
"url",
",",
"res... | HEADs content from URL.
@param url url to get from.
@param response response to store url and response value in.
@param headers http headers to add. | [
"HEADs",
"content",
"from",
"URL",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L416-L419 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/preview/CmsPreviewUtil.java | CmsPreviewUtil.setImageLink | public static void setImageLink(String path, Map<String, String> attributes, String linkPath, String target) {
"""
Sets the image link within the rich text editor (FCKEditor, CKEditor, ...).<p>
@param path the image path
@param attributes the image tag attributes
@param linkPath the link path
@param target the link target attribute
"""
CmsJSONMap attributesJS = CmsJSONMap.createJSONMap();
for (Entry<String, String> entry : attributes.entrySet()) {
attributesJS.put(entry.getKey(), entry.getValue());
}
nativeSetImageLink(path, attributesJS, linkPath, target);
} | java | public static void setImageLink(String path, Map<String, String> attributes, String linkPath, String target) {
CmsJSONMap attributesJS = CmsJSONMap.createJSONMap();
for (Entry<String, String> entry : attributes.entrySet()) {
attributesJS.put(entry.getKey(), entry.getValue());
}
nativeSetImageLink(path, attributesJS, linkPath, target);
} | [
"public",
"static",
"void",
"setImageLink",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
",",
"String",
"linkPath",
",",
"String",
"target",
")",
"{",
"CmsJSONMap",
"attributesJS",
"=",
"CmsJSONMap",
".",
"createJSONMap",... | Sets the image link within the rich text editor (FCKEditor, CKEditor, ...).<p>
@param path the image path
@param attributes the image tag attributes
@param linkPath the link path
@param target the link target attribute | [
"Sets",
"the",
"image",
"link",
"within",
"the",
"rich",
"text",
"editor",
"(",
"FCKEditor",
"CKEditor",
"...",
")",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/preview/CmsPreviewUtil.java#L239-L246 |
ontop/ontop | mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpressionAttributes.java | RAExpressionAttributes.crossJoin | public static RAExpressionAttributes crossJoin(RAExpressionAttributes re1, RAExpressionAttributes re2) throws IllegalJoinException {
"""
CROSS JOIN (also denoted by , in SQL)
@param re1 a {@link RAExpressionAttributes}
@param re2 a {@link RAExpressionAttributes}
@return a {@link RAExpressionAttributes}
@throws IllegalJoinException if the same alias occurs in both arguments
"""
checkRelationAliasesConsistency(re1, re2);
ImmutableMap<QualifiedAttributeID, Term> attributes = merge(
re1.selectAttributes(id ->
(id.getRelation() != null) || re2.isAbsent(id.getAttribute())),
re2.selectAttributes(id ->
(id.getRelation() != null) || re1.isAbsent(id.getAttribute())));
return new RAExpressionAttributes(attributes,
getAttributeOccurrences(re1, re2, id -> attributeOccurrencesUnion(id, re1, re2)));
} | java | public static RAExpressionAttributes crossJoin(RAExpressionAttributes re1, RAExpressionAttributes re2) throws IllegalJoinException {
checkRelationAliasesConsistency(re1, re2);
ImmutableMap<QualifiedAttributeID, Term> attributes = merge(
re1.selectAttributes(id ->
(id.getRelation() != null) || re2.isAbsent(id.getAttribute())),
re2.selectAttributes(id ->
(id.getRelation() != null) || re1.isAbsent(id.getAttribute())));
return new RAExpressionAttributes(attributes,
getAttributeOccurrences(re1, re2, id -> attributeOccurrencesUnion(id, re1, re2)));
} | [
"public",
"static",
"RAExpressionAttributes",
"crossJoin",
"(",
"RAExpressionAttributes",
"re1",
",",
"RAExpressionAttributes",
"re2",
")",
"throws",
"IllegalJoinException",
"{",
"checkRelationAliasesConsistency",
"(",
"re1",
",",
"re2",
")",
";",
"ImmutableMap",
"<",
"... | CROSS JOIN (also denoted by , in SQL)
@param re1 a {@link RAExpressionAttributes}
@param re2 a {@link RAExpressionAttributes}
@return a {@link RAExpressionAttributes}
@throws IllegalJoinException if the same alias occurs in both arguments | [
"CROSS",
"JOIN",
"(",
"also",
"denoted",
"by",
"in",
"SQL",
")"
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/sql/core/src/main/java/it/unibz/inf/ontop/spec/mapping/parser/impl/RAExpressionAttributes.java#L72-L85 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.createNicePartialMock | public static synchronized <T> T createNicePartialMock(Class<T> type, Class<? super T> where, String... methodNames) {
"""
A utility method that may be used to nicely mock several methods in an
easy way (by just passing in the method names of the method you wish to
mock). Note that you cannot uniquely specify a method to mock using this
method if there are several methods with the same name in
{@code type}. This method will mock ALL methods that match the
supplied name regardless of parameter types and signature. If this is the
case you should fall-back on using the
{@link #createMock(Class, Method...)} method instead.
<p/>
With this method you can specify where the class hierarchy the methods
are located. This is useful in, for example, situations where class A
extends B and both have a method called "mockMe" (A overrides B's mockMe
method) and you like to specify the only the "mockMe" method in B should
be mocked. "mockMe" in A should be left intact. In this case you should
do:
<p/>
<pre>
A tested = createPartialMockNice(A.class, B.class, "mockMe");
</pre>
@param <T> The type of the mock.
@param type The type that'll be used to create a mock instance.
@param where Where in the class hierarchy the methods resides.
@param methodNames The names of the methods that should be mocked. If
{@code null}, then this method will have the same effect
as just calling {@link #createMock(Class, Method...)} with the
second parameter as {@code new Method[0]} (i.e. all
methods in that class will be mocked).
@return A mock object of type <T>.
"""
return createNiceMock(type, Whitebox.getMethods(where, methodNames));
} | java | public static synchronized <T> T createNicePartialMock(Class<T> type, Class<? super T> where, String... methodNames) {
return createNiceMock(type, Whitebox.getMethods(where, methodNames));
} | [
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"createNicePartialMock",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"Class",
"<",
"?",
"super",
"T",
">",
"where",
",",
"String",
"...",
"methodNames",
")",
"{",
"return",
"createNiceMock",
"(",
"typ... | A utility method that may be used to nicely mock several methods in an
easy way (by just passing in the method names of the method you wish to
mock). Note that you cannot uniquely specify a method to mock using this
method if there are several methods with the same name in
{@code type}. This method will mock ALL methods that match the
supplied name regardless of parameter types and signature. If this is the
case you should fall-back on using the
{@link #createMock(Class, Method...)} method instead.
<p/>
With this method you can specify where the class hierarchy the methods
are located. This is useful in, for example, situations where class A
extends B and both have a method called "mockMe" (A overrides B's mockMe
method) and you like to specify the only the "mockMe" method in B should
be mocked. "mockMe" in A should be left intact. In this case you should
do:
<p/>
<pre>
A tested = createPartialMockNice(A.class, B.class, "mockMe");
</pre>
@param <T> The type of the mock.
@param type The type that'll be used to create a mock instance.
@param where Where in the class hierarchy the methods resides.
@param methodNames The names of the methods that should be mocked. If
{@code null}, then this method will have the same effect
as just calling {@link #createMock(Class, Method...)} with the
second parameter as {@code new Method[0]} (i.e. all
methods in that class will be mocked).
@return A mock object of type <T>. | [
"A",
"utility",
"method",
"that",
"may",
"be",
"used",
"to",
"nicely",
"mock",
"several",
"methods",
"in",
"an",
"easy",
"way",
"(",
"by",
"just",
"passing",
"in",
"the",
"method",
"names",
"of",
"the",
"method",
"you",
"wish",
"to",
"mock",
")",
".",
... | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L819-L821 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java | FSNamesystem.isGoodReplica | private boolean isGoodReplica(DatanodeDescriptor node, Block block) {
"""
Decide if a replica is valid
@param node datanode the block is located
@param block a block
@return true if a replica is valid
"""
Collection<Block> excessBlocks =
excessReplicateMap.get(node.getStorageID());
Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(block);
return (nodesCorrupt == null || !nodesCorrupt.contains(node)) // not corrupt
// not over scheduling for replication
&& (node.getNumberOfBlocksToBeReplicated() < maxReplicationStreams)
// not alredy scheduled for removal
&& (excessBlocks == null || !excessBlocks.contains(block))
&& !node.isDecommissioned(); // not decommissioned
} | java | private boolean isGoodReplica(DatanodeDescriptor node, Block block) {
Collection<Block> excessBlocks =
excessReplicateMap.get(node.getStorageID());
Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(block);
return (nodesCorrupt == null || !nodesCorrupt.contains(node)) // not corrupt
// not over scheduling for replication
&& (node.getNumberOfBlocksToBeReplicated() < maxReplicationStreams)
// not alredy scheduled for removal
&& (excessBlocks == null || !excessBlocks.contains(block))
&& !node.isDecommissioned(); // not decommissioned
} | [
"private",
"boolean",
"isGoodReplica",
"(",
"DatanodeDescriptor",
"node",
",",
"Block",
"block",
")",
"{",
"Collection",
"<",
"Block",
">",
"excessBlocks",
"=",
"excessReplicateMap",
".",
"get",
"(",
"node",
".",
"getStorageID",
"(",
")",
")",
";",
"Collection... | Decide if a replica is valid
@param node datanode the block is located
@param block a block
@return true if a replica is valid | [
"Decide",
"if",
"a",
"replica",
"is",
"valid"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java#L5697-L5707 |
stackify/stackify-api-java | src/main/java/com/stackify/api/common/ApiConfigurations.java | ApiConfigurations.fromPropertiesWithOverrides | public static ApiConfiguration fromPropertiesWithOverrides(final String apiUrl, final String apiKey, final String application, final String environment, final String allowComDotStackify) {
"""
Explicitly configure the API
@param apiUrl API URL
@param apiKey API Key
@param application Configured application name
@param environment Configured environment name
@param allowComDotStackify Configured allow com.stackify.* logging
@return ApiConfiguration
"""
ApiConfiguration props = ApiConfigurations.fromProperties();
String mergedApiUrl = ((apiUrl != null) && (0 < apiUrl.length())) ? apiUrl : props.getApiUrl();
String mergedApiKey = ((apiKey != null) && (0 < apiKey.length())) ? apiKey : props.getApiKey();
String mergedApplication = ((application != null) && (0 < application.length())) ? application : props.getApplication();
String mergedEnvironment = ((environment != null) && (0 < environment.length())) ? environment : props.getEnvironment();
ApiConfiguration.Builder builder = ApiConfiguration.newBuilder();
builder.apiUrl(mergedApiUrl);
builder.apiKey(mergedApiKey);
builder.application(mergedApplication);
builder.environment(mergedEnvironment);
builder.envDetail(EnvironmentDetails.getEnvironmentDetail(mergedApplication, mergedEnvironment));
builder.allowComDotStackify(Boolean.valueOf(allowComDotStackify));
return builder.build();
} | java | public static ApiConfiguration fromPropertiesWithOverrides(final String apiUrl, final String apiKey, final String application, final String environment, final String allowComDotStackify) {
ApiConfiguration props = ApiConfigurations.fromProperties();
String mergedApiUrl = ((apiUrl != null) && (0 < apiUrl.length())) ? apiUrl : props.getApiUrl();
String mergedApiKey = ((apiKey != null) && (0 < apiKey.length())) ? apiKey : props.getApiKey();
String mergedApplication = ((application != null) && (0 < application.length())) ? application : props.getApplication();
String mergedEnvironment = ((environment != null) && (0 < environment.length())) ? environment : props.getEnvironment();
ApiConfiguration.Builder builder = ApiConfiguration.newBuilder();
builder.apiUrl(mergedApiUrl);
builder.apiKey(mergedApiKey);
builder.application(mergedApplication);
builder.environment(mergedEnvironment);
builder.envDetail(EnvironmentDetails.getEnvironmentDetail(mergedApplication, mergedEnvironment));
builder.allowComDotStackify(Boolean.valueOf(allowComDotStackify));
return builder.build();
} | [
"public",
"static",
"ApiConfiguration",
"fromPropertiesWithOverrides",
"(",
"final",
"String",
"apiUrl",
",",
"final",
"String",
"apiKey",
",",
"final",
"String",
"application",
",",
"final",
"String",
"environment",
",",
"final",
"String",
"allowComDotStackify",
")",... | Explicitly configure the API
@param apiUrl API URL
@param apiKey API Key
@param application Configured application name
@param environment Configured environment name
@param allowComDotStackify Configured allow com.stackify.* logging
@return ApiConfiguration | [
"Explicitly",
"configure",
"the",
"API"
] | train | https://github.com/stackify/stackify-api-java/blob/d3000b7c87ed53a88b302939b0c88405d63d7b67/src/main/java/com/stackify/api/common/ApiConfigurations.java#L56-L73 |
elki-project/elki | elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkmax/MkMaxTree.java | MkMaxTree.doReverseKNNQuery | private void doReverseKNNQuery(DBIDRef q, MkMaxTreeNode<O> node, MkMaxEntry node_entry, ModifiableDoubleDBIDList result) {
"""
Performs a reverse k-nearest neighbor query in the specified subtree for
the given query object with k = {@link #getKmax()}. It recursively traverses
all paths from the specified node, which cannot be excluded from leading to
qualifying objects.
@param q the id of the query object
@param node the node of the subtree on which the query is performed
@param node_entry the entry representing the node
@param result the list for the query result
"""
// data node
if (node.isLeaf()) {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
if (distance <= entry.getKnnDistance()) {
result.add(distance, entry.getRoutingObjectID());
}
}
}
// directory node
else {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry entry = node.getEntry(i);
double node_knnDist = node_entry != null ? node_entry.getKnnDistance() : Double.POSITIVE_INFINITY;
double distance = distance(entry.getRoutingObjectID(), q);
double minDist = (entry.getCoveringRadius() > distance) ? 0.0 : distance - entry.getCoveringRadius();
if (minDist <= node_knnDist) {
MkMaxTreeNode<O> childNode = getNode(entry);
doReverseKNNQuery(q, childNode, entry, result);
}
}
}
} | java | private void doReverseKNNQuery(DBIDRef q, MkMaxTreeNode<O> node, MkMaxEntry node_entry, ModifiableDoubleDBIDList result) {
// data node
if (node.isLeaf()) {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
if (distance <= entry.getKnnDistance()) {
result.add(distance, entry.getRoutingObjectID());
}
}
}
// directory node
else {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry entry = node.getEntry(i);
double node_knnDist = node_entry != null ? node_entry.getKnnDistance() : Double.POSITIVE_INFINITY;
double distance = distance(entry.getRoutingObjectID(), q);
double minDist = (entry.getCoveringRadius() > distance) ? 0.0 : distance - entry.getCoveringRadius();
if (minDist <= node_knnDist) {
MkMaxTreeNode<O> childNode = getNode(entry);
doReverseKNNQuery(q, childNode, entry, result);
}
}
}
} | [
"private",
"void",
"doReverseKNNQuery",
"(",
"DBIDRef",
"q",
",",
"MkMaxTreeNode",
"<",
"O",
">",
"node",
",",
"MkMaxEntry",
"node_entry",
",",
"ModifiableDoubleDBIDList",
"result",
")",
"{",
"// data node",
"if",
"(",
"node",
".",
"isLeaf",
"(",
")",
")",
"... | Performs a reverse k-nearest neighbor query in the specified subtree for
the given query object with k = {@link #getKmax()}. It recursively traverses
all paths from the specified node, which cannot be excluded from leading to
qualifying objects.
@param q the id of the query object
@param node the node of the subtree on which the query is performed
@param node_entry the entry representing the node
@param result the list for the query result | [
"Performs",
"a",
"reverse",
"k",
"-",
"nearest",
"neighbor",
"query",
"in",
"the",
"specified",
"subtree",
"for",
"the",
"given",
"query",
"object",
"with",
"k",
"=",
"{",
"@link",
"#getKmax",
"()",
"}",
".",
"It",
"recursively",
"traverses",
"all",
"paths... | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/mktrees/mkmax/MkMaxTree.java#L168-L195 |
SUSE/salt-netapi-client | src/main/java/com/suse/salt/netapi/calls/SaltSSHUtils.java | SaltSSHUtils.mapConfigPropsToArgs | public static void mapConfigPropsToArgs(SaltSSHConfig cfg, Map<String, Object> props) {
"""
Maps config parameters to salt-ssh rest arguments
@param cfg SSH configuration to read values to be converted
@param props properties to be set when rest calling
"""
cfg.getExtraFilerefs().ifPresent(v -> props.put("extra_filerefs", v));
cfg.getIdentitiesOnly().ifPresent(v -> props.put("ssh_identities_only", v));
cfg.getIgnoreHostKeys().ifPresent(v -> props.put("ignore_host_keys", v));
cfg.getKeyDeploy().ifPresent(v -> props.put("ssh_key_deploy", v));
cfg.getNoHostKeys().ifPresent(v -> props.put("no_host_keys", v));
cfg.getPasswd().ifPresent(v -> props.put("ssh_passwd", v));
cfg.getPriv().ifPresent(v -> props.put("ssh_priv", v));
cfg.getRandomThinDir().ifPresent(v -> props.put("rand_thin_dir", v));
cfg.getRefreshCache().ifPresent(v -> props.put("refresh_cache", v));
cfg.getRemotePortForwards()
.ifPresent(v -> props.put("ssh_remote_port_forwards", v));
cfg.getRoster().ifPresent(v -> props.put("roster", v));
cfg.getRosterFile().ifPresent(v -> props.put("roster_file", v));
cfg.getScanPorts().ifPresent(v -> props.put("ssh_scan_ports", v));
cfg.getScanTimeout().ifPresent(v -> props.put("ssh_scan_timeout", v));
cfg.getSudo().ifPresent(v -> props.put("ssh_sudo", v));
cfg.getSSHMaxProcs().ifPresent(v -> props.put("ssh_max_procs", v));
cfg.getUser().ifPresent(v -> props.put("ssh_user", v));
cfg.getWipe().ifPresent(v -> props.put("ssh_wipe", v));
} | java | public static void mapConfigPropsToArgs(SaltSSHConfig cfg, Map<String, Object> props) {
cfg.getExtraFilerefs().ifPresent(v -> props.put("extra_filerefs", v));
cfg.getIdentitiesOnly().ifPresent(v -> props.put("ssh_identities_only", v));
cfg.getIgnoreHostKeys().ifPresent(v -> props.put("ignore_host_keys", v));
cfg.getKeyDeploy().ifPresent(v -> props.put("ssh_key_deploy", v));
cfg.getNoHostKeys().ifPresent(v -> props.put("no_host_keys", v));
cfg.getPasswd().ifPresent(v -> props.put("ssh_passwd", v));
cfg.getPriv().ifPresent(v -> props.put("ssh_priv", v));
cfg.getRandomThinDir().ifPresent(v -> props.put("rand_thin_dir", v));
cfg.getRefreshCache().ifPresent(v -> props.put("refresh_cache", v));
cfg.getRemotePortForwards()
.ifPresent(v -> props.put("ssh_remote_port_forwards", v));
cfg.getRoster().ifPresent(v -> props.put("roster", v));
cfg.getRosterFile().ifPresent(v -> props.put("roster_file", v));
cfg.getScanPorts().ifPresent(v -> props.put("ssh_scan_ports", v));
cfg.getScanTimeout().ifPresent(v -> props.put("ssh_scan_timeout", v));
cfg.getSudo().ifPresent(v -> props.put("ssh_sudo", v));
cfg.getSSHMaxProcs().ifPresent(v -> props.put("ssh_max_procs", v));
cfg.getUser().ifPresent(v -> props.put("ssh_user", v));
cfg.getWipe().ifPresent(v -> props.put("ssh_wipe", v));
} | [
"public",
"static",
"void",
"mapConfigPropsToArgs",
"(",
"SaltSSHConfig",
"cfg",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"props",
")",
"{",
"cfg",
".",
"getExtraFilerefs",
"(",
")",
".",
"ifPresent",
"(",
"v",
"->",
"props",
".",
"put",
"(",
"\"ex... | Maps config parameters to salt-ssh rest arguments
@param cfg SSH configuration to read values to be converted
@param props properties to be set when rest calling | [
"Maps",
"config",
"parameters",
"to",
"salt",
"-",
"ssh",
"rest",
"arguments"
] | train | https://github.com/SUSE/salt-netapi-client/blob/a0bdf643c8e34fa4def4b915366594c1491fdad5/src/main/java/com/suse/salt/netapi/calls/SaltSSHUtils.java#L15-L35 |
wisdom-framework/wisdom | framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/EhCacheService.java | EhCacheService.set | @Override
public void set(String key, Object value, int expiration) {
"""
Adds an entry in the cache.
@param key Item key.
@param value Item value.
@param expiration Expiration time in seconds (0 second means eternity).
"""
Element element = new Element(key, value);
if (expiration == 0) {
element.setEternal(true);
}
element.setTimeToLive(expiration);
cache.put(element);
} | java | @Override
public void set(String key, Object value, int expiration) {
Element element = new Element(key, value);
if (expiration == 0) {
element.setEternal(true);
}
element.setTimeToLive(expiration);
cache.put(element);
} | [
"@",
"Override",
"public",
"void",
"set",
"(",
"String",
"key",
",",
"Object",
"value",
",",
"int",
"expiration",
")",
"{",
"Element",
"element",
"=",
"new",
"Element",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"expiration",
"==",
"0",
")",
"{",... | Adds an entry in the cache.
@param key Item key.
@param value Item value.
@param expiration Expiration time in seconds (0 second means eternity). | [
"Adds",
"an",
"entry",
"in",
"the",
"cache",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/EhCacheService.java#L125-L133 |
JodaOrg/joda-beans | src/main/java/org/joda/beans/impl/direct/DirectMetaBean.java | DirectMetaBean.propertySet | protected void propertySet(Bean bean, String propertyName, Object value, boolean quiet) {
"""
Sets the value of the property.
@param bean the bean to update, not null
@param propertyName the property name, not null
@param value the value of the property, may be null
@param quiet true to take no action if unable to write
@throws NoSuchElementException if the property name is invalid
"""
// used to enable 100% test coverage in beans
if (quiet) {
return;
}
throw new NoSuchElementException("Unknown property: " + propertyName);
} | java | protected void propertySet(Bean bean, String propertyName, Object value, boolean quiet) {
// used to enable 100% test coverage in beans
if (quiet) {
return;
}
throw new NoSuchElementException("Unknown property: " + propertyName);
} | [
"protected",
"void",
"propertySet",
"(",
"Bean",
"bean",
",",
"String",
"propertyName",
",",
"Object",
"value",
",",
"boolean",
"quiet",
")",
"{",
"// used to enable 100% test coverage in beans",
"if",
"(",
"quiet",
")",
"{",
"return",
";",
"}",
"throw",
"new",
... | Sets the value of the property.
@param bean the bean to update, not null
@param propertyName the property name, not null
@param value the value of the property, may be null
@param quiet true to take no action if unable to write
@throws NoSuchElementException if the property name is invalid | [
"Sets",
"the",
"value",
"of",
"the",
"property",
"."
] | train | https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/impl/direct/DirectMetaBean.java#L100-L106 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java | Uris.isNormalized | public static boolean isNormalized(final URI uri, final boolean strict) {
"""
Returns whether or not the given URI is normalized according to our rules.
@param uri the uri to check normalization status
@param strict whether or not to do strict escaping
@return true if the given uri is already normalized
"""
return !Strings.isNullOrEmpty(uri.getScheme()) &&
Objects.equal(Uris.getRawUserInfo(uri), uri.getRawUserInfo()) &&
!Strings.isNullOrEmpty(uri.getHost()) &&
hasPort(uri) &&
Objects.equal(Uris.getRawPath(uri, strict), uri.getRawPath()) &&
Objects.equal(Uris.getRawQuery(uri, strict), uri.getRawQuery()) &&
Objects.equal(Uris.getRawFragment(uri, strict), uri.getRawFragment());
} | java | public static boolean isNormalized(final URI uri, final boolean strict) {
return !Strings.isNullOrEmpty(uri.getScheme()) &&
Objects.equal(Uris.getRawUserInfo(uri), uri.getRawUserInfo()) &&
!Strings.isNullOrEmpty(uri.getHost()) &&
hasPort(uri) &&
Objects.equal(Uris.getRawPath(uri, strict), uri.getRawPath()) &&
Objects.equal(Uris.getRawQuery(uri, strict), uri.getRawQuery()) &&
Objects.equal(Uris.getRawFragment(uri, strict), uri.getRawFragment());
} | [
"public",
"static",
"boolean",
"isNormalized",
"(",
"final",
"URI",
"uri",
",",
"final",
"boolean",
"strict",
")",
"{",
"return",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"uri",
".",
"getScheme",
"(",
")",
")",
"&&",
"Objects",
".",
"equal",
"(",
"Uris... | Returns whether or not the given URI is normalized according to our rules.
@param uri the uri to check normalization status
@param strict whether or not to do strict escaping
@return true if the given uri is already normalized | [
"Returns",
"whether",
"or",
"not",
"the",
"given",
"URI",
"is",
"normalized",
"according",
"to",
"our",
"rules",
"."
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java#L453-L461 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserRte.java | AbstractGpxParserRte.startElement | @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
"""
Fires whenever an XML start markup is encountered. It creates a new
routePoint when a <rtept> markup is encountered.
@param uri URI of the local element
@param localName Name of the local element (without prefix)
@param qName qName of the local element (with prefix)
@param attributes Attributes of the local element (contained in the
markup)
@throws SAXException Any SAX exception, possibly wrapping another
exception
"""
if (localName.equalsIgnoreCase(GPXTags.RTEPT)) {
point = true;
GPXPoint routePoint = new GPXPoint(GpxMetadata.RTEPTFIELDCOUNT);
try {
Coordinate coordinate = GPXCoordinate.createCoordinate(attributes);
Point geom = getGeometryFactory().createPoint(coordinate);
geom.setSRID(4326);
routePoint.setValue(GpxMetadata.THE_GEOM, geom);
routePoint.setValue(GpxMetadata.PTLAT, coordinate.y);
routePoint.setValue(GpxMetadata.PTLON, coordinate.x);
routePoint.setValue(GpxMetadata.PTELE, coordinate.z);
routePoint.setValue(GpxMetadata.PTID, idRtPt++);
routePoint.setValue(GpxMetadata.RTEPT_RTEID, getCurrentLine().getValues()[GpxMetadata.LINEID]);
rteList.add(coordinate);
} catch (NumberFormatException ex) {
throw new SAXException(ex);
}
setCurrentPoint(routePoint);
}
// Clear content buffer
getContentBuffer().delete(0, getContentBuffer().length());
// Store name of current element in stack
getElementNames().push(qName);
} | java | @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase(GPXTags.RTEPT)) {
point = true;
GPXPoint routePoint = new GPXPoint(GpxMetadata.RTEPTFIELDCOUNT);
try {
Coordinate coordinate = GPXCoordinate.createCoordinate(attributes);
Point geom = getGeometryFactory().createPoint(coordinate);
geom.setSRID(4326);
routePoint.setValue(GpxMetadata.THE_GEOM, geom);
routePoint.setValue(GpxMetadata.PTLAT, coordinate.y);
routePoint.setValue(GpxMetadata.PTLON, coordinate.x);
routePoint.setValue(GpxMetadata.PTELE, coordinate.z);
routePoint.setValue(GpxMetadata.PTID, idRtPt++);
routePoint.setValue(GpxMetadata.RTEPT_RTEID, getCurrentLine().getValues()[GpxMetadata.LINEID]);
rteList.add(coordinate);
} catch (NumberFormatException ex) {
throw new SAXException(ex);
}
setCurrentPoint(routePoint);
}
// Clear content buffer
getContentBuffer().delete(0, getContentBuffer().length());
// Store name of current element in stack
getElementNames().push(qName);
} | [
"@",
"Override",
"public",
"void",
"startElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
",",
"Attributes",
"attributes",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"localName",
".",
"equalsIgnoreCase",
"(",
"GPXTags",
"... | Fires whenever an XML start markup is encountered. It creates a new
routePoint when a <rtept> markup is encountered.
@param uri URI of the local element
@param localName Name of the local element (without prefix)
@param qName qName of the local element (with prefix)
@param attributes Attributes of the local element (contained in the
markup)
@throws SAXException Any SAX exception, possibly wrapping another
exception | [
"Fires",
"whenever",
"an",
"XML",
"start",
"markup",
"is",
"encountered",
".",
"It",
"creates",
"a",
"new",
"routePoint",
"when",
"a",
"<rtept",
">",
"markup",
"is",
"encountered",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/gpx/model/AbstractGpxParserRte.java#L81-L108 |
eclipse/xtext-extras | org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/impl/IndexedJvmTypeAccess.java | IndexedJvmTypeAccess.findAccessibleType | protected EObject findAccessibleType(String fragment, ResourceSet resourceSet, Iterator<IEObjectDescription> fromIndex) throws UnknownNestedTypeException {
"""
Returns the first type that was found in the index. May be overridden to honor visibility semantics.
The given iterator is never empty.
@since 2.8
"""
IEObjectDescription description = fromIndex.next();
return getAccessibleType(description, fragment, resourceSet);
} | java | protected EObject findAccessibleType(String fragment, ResourceSet resourceSet, Iterator<IEObjectDescription> fromIndex) throws UnknownNestedTypeException {
IEObjectDescription description = fromIndex.next();
return getAccessibleType(description, fragment, resourceSet);
} | [
"protected",
"EObject",
"findAccessibleType",
"(",
"String",
"fragment",
",",
"ResourceSet",
"resourceSet",
",",
"Iterator",
"<",
"IEObjectDescription",
">",
"fromIndex",
")",
"throws",
"UnknownNestedTypeException",
"{",
"IEObjectDescription",
"description",
"=",
"fromInd... | Returns the first type that was found in the index. May be overridden to honor visibility semantics.
The given iterator is never empty.
@since 2.8 | [
"Returns",
"the",
"first",
"type",
"that",
"was",
"found",
"in",
"the",
"index",
".",
"May",
"be",
"overridden",
"to",
"honor",
"visibility",
"semantics",
".",
"The",
"given",
"iterator",
"is",
"never",
"empty",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/impl/IndexedJvmTypeAccess.java#L129-L132 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java | SynchronousRequest.getCurrentDailyAchievements | public DailyAchievement getCurrentDailyAchievements() throws GuildWars2Exception {
"""
For more info on achievements daily API go <a href="https://wiki.guildwars2.com/wiki/API:2/achievements/daily">here</a><br/>
Get list of current daily achievements
@return list of current daily achievements
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see DailyAchievement daily achievement info
"""
try {
Response<DailyAchievement> response = gw2API.getCurrentDailyAchievements().execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | java | public DailyAchievement getCurrentDailyAchievements() throws GuildWars2Exception {
try {
Response<DailyAchievement> response = gw2API.getCurrentDailyAchievements().execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | [
"public",
"DailyAchievement",
"getCurrentDailyAchievements",
"(",
")",
"throws",
"GuildWars2Exception",
"{",
"try",
"{",
"Response",
"<",
"DailyAchievement",
">",
"response",
"=",
"gw2API",
".",
"getCurrentDailyAchievements",
"(",
")",
".",
"execute",
"(",
")",
";",... | For more info on achievements daily API go <a href="https://wiki.guildwars2.com/wiki/API:2/achievements/daily">here</a><br/>
Get list of current daily achievements
@return list of current daily achievements
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see DailyAchievement daily achievement info | [
"For",
"more",
"info",
"on",
"achievements",
"daily",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"achievements",
"/",
"daily",
">",
"here<",
"/",
"a",
">",
"<br... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L686-L694 |
JakeWharton/ActionBarSherlock | actionbarsherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java | PropertyValuesHolder.setupValue | private void setupValue(Object target, Keyframe kf) {
"""
Utility function to set the value stored in a particular Keyframe. The value used is
whatever the value is for the property name specified in the keyframe on the target object.
@param target The target object from which the current value should be extracted.
@param kf The keyframe which holds the property name and value.
"""
//if (mProperty != null) {
// kf.setValue(mProperty.get(target));
//}
try {
if (mGetter == null) {
Class targetClass = target.getClass();
setupGetter(targetClass);
}
kf.setValue(mGetter.invoke(target));
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
} | java | private void setupValue(Object target, Keyframe kf) {
//if (mProperty != null) {
// kf.setValue(mProperty.get(target));
//}
try {
if (mGetter == null) {
Class targetClass = target.getClass();
setupGetter(targetClass);
}
kf.setValue(mGetter.invoke(target));
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
} | [
"private",
"void",
"setupValue",
"(",
"Object",
"target",
",",
"Keyframe",
"kf",
")",
"{",
"//if (mProperty != null) {",
"// kf.setValue(mProperty.get(target));",
"//}",
"try",
"{",
"if",
"(",
"mGetter",
"==",
"null",
")",
"{",
"Class",
"targetClass",
"=",
"tar... | Utility function to set the value stored in a particular Keyframe. The value used is
whatever the value is for the property name specified in the keyframe on the target object.
@param target The target object from which the current value should be extracted.
@param kf The keyframe which holds the property name and value. | [
"Utility",
"function",
"to",
"set",
"the",
"value",
"stored",
"in",
"a",
"particular",
"Keyframe",
".",
"The",
"value",
"used",
"is",
"whatever",
"the",
"value",
"is",
"for",
"the",
"property",
"name",
"specified",
"in",
"the",
"keyframe",
"on",
"the",
"ta... | train | https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java#L532-L547 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.addExplicitListItemWithServiceResponseAsync | public Observable<ServiceResponse<Integer>> addExplicitListItemWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, AddExplicitListItemOptionalParameter addExplicitListItemOptionalParameter) {
"""
Add a new item to the explicit list for the Pattern.Any entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId The Pattern.Any entity extractor ID.
@param addExplicitListItemOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Integer object
"""
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (entityId == null) {
throw new IllegalArgumentException("Parameter entityId is required and cannot be null.");
}
final String explicitListItem = addExplicitListItemOptionalParameter != null ? addExplicitListItemOptionalParameter.explicitListItem() : null;
return addExplicitListItemWithServiceResponseAsync(appId, versionId, entityId, explicitListItem);
} | java | public Observable<ServiceResponse<Integer>> addExplicitListItemWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, AddExplicitListItemOptionalParameter addExplicitListItemOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
if (entityId == null) {
throw new IllegalArgumentException("Parameter entityId is required and cannot be null.");
}
final String explicitListItem = addExplicitListItemOptionalParameter != null ? addExplicitListItemOptionalParameter.explicitListItem() : null;
return addExplicitListItemWithServiceResponseAsync(appId, versionId, entityId, explicitListItem);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Integer",
">",
">",
"addExplicitListItemWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
",",
"AddExplicitListItemOptionalParameter",
"addExplicitListItemOptionalParamet... | Add a new item to the explicit list for the Pattern.Any entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId The Pattern.Any entity extractor ID.
@param addExplicitListItemOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the Integer object | [
"Add",
"a",
"new",
"item",
"to",
"the",
"explicit",
"list",
"for",
"the",
"Pattern",
".",
"Any",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L10040-L10056 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/SnsAPI.java | SnsAPI.oauth2ComponentAccessToken | public static SnsToken oauth2ComponentAccessToken(String appid,String code,String component_appid,String component_access_token ) {
"""
通过code换取网页授权access_token (第三方平台开发)
@param appid appid
@param code code
@param component_appid 服务开发方的appid
@param component_access_token 服务开发方的access_token
@return SnsToken
"""
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/component/access_token")
.addParameter("appid", appid)
.addParameter("code", code)
.addParameter("grant_type", "authorization_code")
.addParameter("component_appid", component_appid)
.addParameter("component_access_token", component_access_token)
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | java | public static SnsToken oauth2ComponentAccessToken(String appid,String code,String component_appid,String component_access_token ){
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/component/access_token")
.addParameter("appid", appid)
.addParameter("code", code)
.addParameter("grant_type", "authorization_code")
.addParameter("component_appid", component_appid)
.addParameter("component_access_token", component_access_token)
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | [
"public",
"static",
"SnsToken",
"oauth2ComponentAccessToken",
"(",
"String",
"appid",
",",
"String",
"code",
",",
"String",
"component_appid",
",",
"String",
"component_access_token",
")",
"{",
"HttpUriRequest",
"httpUriRequest",
"=",
"RequestBuilder",
".",
"post",
"(... | 通过code换取网页授权access_token (第三方平台开发)
@param appid appid
@param code code
@param component_appid 服务开发方的appid
@param component_access_token 服务开发方的access_token
@return SnsToken | [
"通过code换取网页授权access_token",
"(",
"第三方平台开发",
")"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/SnsAPI.java#L53-L63 |
hawtio/hawtio | hawtio-ide/src/main/java/io/hawt/ide/IdeFacade.java | IdeFacade.findClassAbsoluteFileName | @Override
public String findClassAbsoluteFileName(String fileName, String className, List<String> sourceRoots) {
"""
Given a class name and a file name, try to find the absolute file name of the
source file on the users machine or null if it cannot be found
"""
// usually the fileName is just the name of the file without any package information
// so lets turn the package name into a path
int lastIdx = className.lastIndexOf('.');
if (lastIdx > 0 && !(fileName.contains("/") || fileName.contains(File.separator))) {
String packagePath = className.substring(0, lastIdx).replace('.', File.separatorChar);
fileName = packagePath + File.separator + fileName;
}
File baseDir = getBaseDir();
String answer = findInSourceFolders(baseDir, fileName);
if (answer == null && sourceRoots != null) {
for (String sourceRoot : sourceRoots) {
answer = findInSourceFolders(new File(sourceRoot), fileName);
if (answer != null) break;
}
}
return answer;
} | java | @Override
public String findClassAbsoluteFileName(String fileName, String className, List<String> sourceRoots) {
// usually the fileName is just the name of the file without any package information
// so lets turn the package name into a path
int lastIdx = className.lastIndexOf('.');
if (lastIdx > 0 && !(fileName.contains("/") || fileName.contains(File.separator))) {
String packagePath = className.substring(0, lastIdx).replace('.', File.separatorChar);
fileName = packagePath + File.separator + fileName;
}
File baseDir = getBaseDir();
String answer = findInSourceFolders(baseDir, fileName);
if (answer == null && sourceRoots != null) {
for (String sourceRoot : sourceRoots) {
answer = findInSourceFolders(new File(sourceRoot), fileName);
if (answer != null) break;
}
}
return answer;
} | [
"@",
"Override",
"public",
"String",
"findClassAbsoluteFileName",
"(",
"String",
"fileName",
",",
"String",
"className",
",",
"List",
"<",
"String",
">",
"sourceRoots",
")",
"{",
"// usually the fileName is just the name of the file without any package information",
"// so le... | Given a class name and a file name, try to find the absolute file name of the
source file on the users machine or null if it cannot be found | [
"Given",
"a",
"class",
"name",
"and",
"a",
"file",
"name",
"try",
"to",
"find",
"the",
"absolute",
"file",
"name",
"of",
"the",
"source",
"file",
"on",
"the",
"users",
"machine",
"or",
"null",
"if",
"it",
"cannot",
"be",
"found"
] | train | https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/hawtio-ide/src/main/java/io/hawt/ide/IdeFacade.java#L63-L81 |
twilio/twilio-java | src/main/java/com/twilio/Twilio.java | Twilio.validateSslCertificate | public static void validateSslCertificate() {
"""
Validate that we can connect to the new SSL certificate posted on api.twilio.com.
@throws com.twilio.exception.CertificateValidationException if the connection fails
"""
final NetworkHttpClient client = new NetworkHttpClient();
final Request request = new Request(HttpMethod.GET, "https://api.twilio.com:8443");
try {
final Response response = client.makeRequest(request);
if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
throw new CertificateValidationException(
"Unexpected response from certificate endpoint", request, response
);
}
} catch (final ApiException e) {
throw new CertificateValidationException("Could not get response from certificate endpoint", request);
}
} | java | public static void validateSslCertificate() {
final NetworkHttpClient client = new NetworkHttpClient();
final Request request = new Request(HttpMethod.GET, "https://api.twilio.com:8443");
try {
final Response response = client.makeRequest(request);
if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
throw new CertificateValidationException(
"Unexpected response from certificate endpoint", request, response
);
}
} catch (final ApiException e) {
throw new CertificateValidationException("Could not get response from certificate endpoint", request);
}
} | [
"public",
"static",
"void",
"validateSslCertificate",
"(",
")",
"{",
"final",
"NetworkHttpClient",
"client",
"=",
"new",
"NetworkHttpClient",
"(",
")",
";",
"final",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
",",
"\"https://api.... | Validate that we can connect to the new SSL certificate posted on api.twilio.com.
@throws com.twilio.exception.CertificateValidationException if the connection fails | [
"Validate",
"that",
"we",
"can",
"connect",
"to",
"the",
"new",
"SSL",
"certificate",
"posted",
"on",
"api",
".",
"twilio",
".",
"com",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/Twilio.java#L170-L185 |
Viascom/groundwork | foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/header/FoxHttpHeader.java | FoxHttpHeader.addHeader | public void addHeader(HeaderTypes name, String value) {
"""
Add a new header entry
@param name name of the header entry
@param value value of the header entry
"""
headerEntries.add(new HeaderEntry(name.toString(), value));
} | java | public void addHeader(HeaderTypes name, String value) {
headerEntries.add(new HeaderEntry(name.toString(), value));
} | [
"public",
"void",
"addHeader",
"(",
"HeaderTypes",
"name",
",",
"String",
"value",
")",
"{",
"headerEntries",
".",
"add",
"(",
"new",
"HeaderEntry",
"(",
"name",
".",
"toString",
"(",
")",
",",
"value",
")",
")",
";",
"}"
] | Add a new header entry
@param name name of the header entry
@param value value of the header entry | [
"Add",
"a",
"new",
"header",
"entry"
] | train | https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/header/FoxHttpHeader.java#L42-L44 |
Azure/azure-sdk-for-java | privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java | PrivateZonesInner.listByResourceGroupAsync | public Observable<Page<PrivateZoneInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) {
"""
Lists the Private DNS zones within a resource group.
@param resourceGroupName The name of the resource group.
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<PrivateZoneInner> object
"""
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top)
.map(new Func1<ServiceResponse<Page<PrivateZoneInner>>, Page<PrivateZoneInner>>() {
@Override
public Page<PrivateZoneInner> call(ServiceResponse<Page<PrivateZoneInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<PrivateZoneInner>> listByResourceGroupAsync(final String resourceGroupName, final Integer top) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top)
.map(new Func1<ServiceResponse<Page<PrivateZoneInner>>, Page<PrivateZoneInner>>() {
@Override
public Page<PrivateZoneInner> call(ServiceResponse<Page<PrivateZoneInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"PrivateZoneInner",
">",
">",
"listByResourceGroupAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"Integer",
"top",
")",
"{",
"return",
"listByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
... | Lists the Private DNS zones within a resource group.
@param resourceGroupName The name of the resource group.
@param top The maximum number of record sets to return. If not specified, returns up to 100 record sets.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<PrivateZoneInner> object | [
"Lists",
"the",
"Private",
"DNS",
"zones",
"within",
"a",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java#L1582-L1590 |
Multifarious/MacroManager | src/main/java/com/fasterxml/mama/util/ZKUtils.java | ZKUtils.deleteAtomic | public static boolean deleteAtomic(ZooKeeperClient zk, String path, String expectedValue) {
"""
Attempts to atomically delete the ZNode with the specified path and value. Should be preferred over calling
delete() if the value is known.
@param zk ZooKeeper client.
@param path Path to be deleted.
@param expectedValue The expected value of the ZNode at the specified path.
@return True if the path was deleted, false otherwise.
"""
final Stat stat = new Stat();
String value = getWithStat(zk, path, stat);
if (!expectedValue.equals(value)) {
return false;
}
try {
zk.get().delete(path, stat.getVersion());
return true;
} catch (Exception e) {
LOG.error("Failed to delete path "+path+" with expected value '"+expectedValue+"'", e);
}
return false;
} | java | public static boolean deleteAtomic(ZooKeeperClient zk, String path, String expectedValue)
{
final Stat stat = new Stat();
String value = getWithStat(zk, path, stat);
if (!expectedValue.equals(value)) {
return false;
}
try {
zk.get().delete(path, stat.getVersion());
return true;
} catch (Exception e) {
LOG.error("Failed to delete path "+path+" with expected value '"+expectedValue+"'", e);
}
return false;
} | [
"public",
"static",
"boolean",
"deleteAtomic",
"(",
"ZooKeeperClient",
"zk",
",",
"String",
"path",
",",
"String",
"expectedValue",
")",
"{",
"final",
"Stat",
"stat",
"=",
"new",
"Stat",
"(",
")",
";",
"String",
"value",
"=",
"getWithStat",
"(",
"zk",
",",... | Attempts to atomically delete the ZNode with the specified path and value. Should be preferred over calling
delete() if the value is known.
@param zk ZooKeeper client.
@param path Path to be deleted.
@param expectedValue The expected value of the ZNode at the specified path.
@return True if the path was deleted, false otherwise. | [
"Attempts",
"to",
"atomically",
"delete",
"the",
"ZNode",
"with",
"the",
"specified",
"path",
"and",
"value",
".",
"Should",
"be",
"preferred",
"over",
"calling",
"delete",
"()",
"if",
"the",
"value",
"is",
"known",
"."
] | train | https://github.com/Multifarious/MacroManager/blob/559785839981f460aaeba3c3fddff7fb667d9581/src/main/java/com/fasterxml/mama/util/ZKUtils.java#L97-L111 |
jetty-project/jetty-npn | npn-boot/src/main/java/sun/security/ssl/SSLEngineImpl.java | SSLEngineImpl.needToSplitPayload | boolean needToSplitPayload(CipherBox cipher, ProtocolVersion protocol) {
"""
/*
Need to split the payload except the following cases:
1. protocol version is TLS 1.1 or later;
2. bulk cipher does not use CBC mode, including null bulk cipher suites.
3. the payload is the first application record of a freshly
negotiated TLS session.
4. the CBC protection is disabled;
More details, please refer to
EngineOutputRecord.write(EngineArgs, MAC, CipherBox).
"""
return (protocol.v <= ProtocolVersion.TLS10.v) &&
cipher.isCBCMode() && !isFirstAppOutputRecord &&
Record.enableCBCProtection;
} | java | boolean needToSplitPayload(CipherBox cipher, ProtocolVersion protocol) {
return (protocol.v <= ProtocolVersion.TLS10.v) &&
cipher.isCBCMode() && !isFirstAppOutputRecord &&
Record.enableCBCProtection;
} | [
"boolean",
"needToSplitPayload",
"(",
"CipherBox",
"cipher",
",",
"ProtocolVersion",
"protocol",
")",
"{",
"return",
"(",
"protocol",
".",
"v",
"<=",
"ProtocolVersion",
".",
"TLS10",
".",
"v",
")",
"&&",
"cipher",
".",
"isCBCMode",
"(",
")",
"&&",
"!",
"is... | /*
Need to split the payload except the following cases:
1. protocol version is TLS 1.1 or later;
2. bulk cipher does not use CBC mode, including null bulk cipher suites.
3. the payload is the first application record of a freshly
negotiated TLS session.
4. the CBC protection is disabled;
More details, please refer to
EngineOutputRecord.write(EngineArgs, MAC, CipherBox). | [
"/",
"*",
"Need",
"to",
"split",
"the",
"payload",
"except",
"the",
"following",
"cases",
":"
] | train | https://github.com/jetty-project/jetty-npn/blob/a26a7a5eabeeb57a63c6ee08fcf9b8cec1fa6c0d/npn-boot/src/main/java/sun/security/ssl/SSLEngineImpl.java#L1337-L1341 |
OpenLiberty/open-liberty | dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java | AuditEvent.setTarget | public void setTarget(Map<String, Object> target) {
"""
Set the target keys/values. The provided Map will completely replace
the existing target, i.e. all current target keys/values will be removed
and the new target keys/values will be added.
@param target - Map of all the target keys/values
"""
removeEntriesStartingWith(TARGET);
eventMap.putAll(target);
} | java | public void setTarget(Map<String, Object> target) {
removeEntriesStartingWith(TARGET);
eventMap.putAll(target);
} | [
"public",
"void",
"setTarget",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"target",
")",
"{",
"removeEntriesStartingWith",
"(",
"TARGET",
")",
";",
"eventMap",
".",
"putAll",
"(",
"target",
")",
";",
"}"
] | Set the target keys/values. The provided Map will completely replace
the existing target, i.e. all current target keys/values will be removed
and the new target keys/values will be added.
@param target - Map of all the target keys/values | [
"Set",
"the",
"target",
"keys",
"/",
"values",
".",
"The",
"provided",
"Map",
"will",
"completely",
"replace",
"the",
"existing",
"target",
"i",
".",
"e",
".",
"all",
"current",
"target",
"keys",
"/",
"values",
"will",
"be",
"removed",
"and",
"the",
"new... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java#L343-L346 |
pravega/pravega | client/src/main/java/io/pravega/client/stream/impl/StreamSegments.java | StreamSegments.verifyReplacementRange | private void verifyReplacementRange(SegmentWithRange replacedSegment, StreamSegmentsWithPredecessors replacementSegments) {
"""
Checks that replacementSegments provided are consistent with the segments that are currently being used.
@param replacedSegment The segment on which EOS was reached
@param replacementSegments The StreamSegmentsWithPredecessors to verify
"""
log.debug("Verification of replacement segments {} with the current segments {}", replacementSegments, segments);
Map<Long, List<SegmentWithRange>> replacementRanges = replacementSegments.getReplacementRanges();
List<SegmentWithRange> replacements = replacementRanges.get(replacedSegment.getSegment().getSegmentId());
Preconditions.checkArgument(replacements != null, "Replacement segments did not contain replacements for segment being replaced");
if (replacementRanges.size() == 1) {
//Simple split
Preconditions.checkArgument(replacedSegment.getHigh() == getUpperBound(replacements));
Preconditions.checkArgument(replacedSegment.getLow() == getLowerBound(replacements));
} else {
Preconditions.checkArgument(replacedSegment.getHigh() <= getUpperBound(replacements));
Preconditions.checkArgument(replacedSegment.getLow() >= getLowerBound(replacements));
}
for (Entry<Long, List<SegmentWithRange>> ranges : replacementRanges.entrySet()) {
Entry<Double, SegmentWithRange> upperReplacedSegment = segments.floorEntry(getUpperBound(ranges.getValue()));
Entry<Double, SegmentWithRange> lowerReplacedSegment = segments.higherEntry(getLowerBound(ranges.getValue()));
Preconditions.checkArgument(upperReplacedSegment != null, "Missing replaced replacement segments %s",
replacementSegments);
Preconditions.checkArgument(lowerReplacedSegment != null, "Missing replaced replacement segments %s",
replacementSegments);
}
} | java | private void verifyReplacementRange(SegmentWithRange replacedSegment, StreamSegmentsWithPredecessors replacementSegments) {
log.debug("Verification of replacement segments {} with the current segments {}", replacementSegments, segments);
Map<Long, List<SegmentWithRange>> replacementRanges = replacementSegments.getReplacementRanges();
List<SegmentWithRange> replacements = replacementRanges.get(replacedSegment.getSegment().getSegmentId());
Preconditions.checkArgument(replacements != null, "Replacement segments did not contain replacements for segment being replaced");
if (replacementRanges.size() == 1) {
//Simple split
Preconditions.checkArgument(replacedSegment.getHigh() == getUpperBound(replacements));
Preconditions.checkArgument(replacedSegment.getLow() == getLowerBound(replacements));
} else {
Preconditions.checkArgument(replacedSegment.getHigh() <= getUpperBound(replacements));
Preconditions.checkArgument(replacedSegment.getLow() >= getLowerBound(replacements));
}
for (Entry<Long, List<SegmentWithRange>> ranges : replacementRanges.entrySet()) {
Entry<Double, SegmentWithRange> upperReplacedSegment = segments.floorEntry(getUpperBound(ranges.getValue()));
Entry<Double, SegmentWithRange> lowerReplacedSegment = segments.higherEntry(getLowerBound(ranges.getValue()));
Preconditions.checkArgument(upperReplacedSegment != null, "Missing replaced replacement segments %s",
replacementSegments);
Preconditions.checkArgument(lowerReplacedSegment != null, "Missing replaced replacement segments %s",
replacementSegments);
}
} | [
"private",
"void",
"verifyReplacementRange",
"(",
"SegmentWithRange",
"replacedSegment",
",",
"StreamSegmentsWithPredecessors",
"replacementSegments",
")",
"{",
"log",
".",
"debug",
"(",
"\"Verification of replacement segments {} with the current segments {}\"",
",",
"replacementSe... | Checks that replacementSegments provided are consistent with the segments that are currently being used.
@param replacedSegment The segment on which EOS was reached
@param replacementSegments The StreamSegmentsWithPredecessors to verify | [
"Checks",
"that",
"replacementSegments",
"provided",
"are",
"consistent",
"with",
"the",
"segments",
"that",
"are",
"currently",
"being",
"used",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/StreamSegments.java#L145-L166 |
fcrepo4/fcrepo4 | fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/utils/FedoraTypesUtils.java | FedoraTypesUtils.getClosestExistingAncestor | public static Node getClosestExistingAncestor(final Session session, final String path)
throws RepositoryException {
"""
Get the closest ancestor that current exists
@param session the given session
@param path the given path
@return the closest ancestor that current exists
@throws RepositoryException if repository exception occurred
"""
String potentialPath = path.startsWith("/") ? path : "/" + path;
while (!potentialPath.isEmpty()) {
if (session.nodeExists(potentialPath)) {
return session.getNode(potentialPath);
}
potentialPath = potentialPath.substring(0, potentialPath.lastIndexOf('/'));
}
return session.getRootNode();
} | java | public static Node getClosestExistingAncestor(final Session session, final String path)
throws RepositoryException {
String potentialPath = path.startsWith("/") ? path : "/" + path;
while (!potentialPath.isEmpty()) {
if (session.nodeExists(potentialPath)) {
return session.getNode(potentialPath);
}
potentialPath = potentialPath.substring(0, potentialPath.lastIndexOf('/'));
}
return session.getRootNode();
} | [
"public",
"static",
"Node",
"getClosestExistingAncestor",
"(",
"final",
"Session",
"session",
",",
"final",
"String",
"path",
")",
"throws",
"RepositoryException",
"{",
"String",
"potentialPath",
"=",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
"?",
"path",
":... | Get the closest ancestor that current exists
@param session the given session
@param path the given path
@return the closest ancestor that current exists
@throws RepositoryException if repository exception occurred | [
"Get",
"the",
"closest",
"ancestor",
"that",
"current",
"exists"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/utils/FedoraTypesUtils.java#L342-L353 |
versionone/VersionOne.SDK.Java.ObjectModel | src/main/java/com/versionone/om/V1InstanceCreator.java | V1InstanceCreator.regressionPlan | public RegressionPlan regressionPlan(String name, Project project) {
"""
Creates a new Regression Plan with title and project.
@param name Title of the plan.
@param project Project to assign.
@return A newly minted Regression Plan that exists in the VersionOne system.
"""
return regressionPlan(name, project, null);
} | java | public RegressionPlan regressionPlan(String name, Project project) {
return regressionPlan(name, project, null);
} | [
"public",
"RegressionPlan",
"regressionPlan",
"(",
"String",
"name",
",",
"Project",
"project",
")",
"{",
"return",
"regressionPlan",
"(",
"name",
",",
"project",
",",
"null",
")",
";",
"}"
] | Creates a new Regression Plan with title and project.
@param name Title of the plan.
@param project Project to assign.
@return A newly minted Regression Plan that exists in the VersionOne system. | [
"Creates",
"a",
"new",
"Regression",
"Plan",
"with",
"title",
"and",
"project",
"."
] | train | https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1InstanceCreator.java#L1142-L1144 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java | FtpFileUtil.loadFileFromFTPServer | public static String loadFileFromFTPServer(String hostName, Integer port,
String userName, String password, String filePath, int numberOfLines) {
"""
Reads content of file on from FTP server to String.
@param hostName the FTP server host name to connect
@param port the port to connect
@param userName the user name
@param password the password
@param filePath file to read.
@return file's content.
@throws RuntimeException in case any exception has been thrown.
"""
String result = null;
FTPClient ftpClient = new FTPClient();
InputStream inputStream = null;
String errorMessage = "Unable to connect and download file '%s' from FTP server '%s'.";
try {
connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password);
// load file into string
ftpClient.enterLocalPassiveMode();
inputStream = ftpClient.retrieveFileStream(filePath);
validatResponse(ftpClient);
result = FileUtil.streamToString(inputStream, filePath, numberOfLines);
ftpClient.completePendingCommand();
} catch (IOException ex) {
throw new RuntimeException(String.format(errorMessage, filePath, hostName), ex);
} finally {
closeInputStream(inputStream);
disconnectAndLogoutFromFTPServer(ftpClient, hostName);
}
return result;
} | java | public static String loadFileFromFTPServer(String hostName, Integer port,
String userName, String password, String filePath, int numberOfLines) {
String result = null;
FTPClient ftpClient = new FTPClient();
InputStream inputStream = null;
String errorMessage = "Unable to connect and download file '%s' from FTP server '%s'.";
try {
connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password);
// load file into string
ftpClient.enterLocalPassiveMode();
inputStream = ftpClient.retrieveFileStream(filePath);
validatResponse(ftpClient);
result = FileUtil.streamToString(inputStream, filePath, numberOfLines);
ftpClient.completePendingCommand();
} catch (IOException ex) {
throw new RuntimeException(String.format(errorMessage, filePath, hostName), ex);
} finally {
closeInputStream(inputStream);
disconnectAndLogoutFromFTPServer(ftpClient, hostName);
}
return result;
} | [
"public",
"static",
"String",
"loadFileFromFTPServer",
"(",
"String",
"hostName",
",",
"Integer",
"port",
",",
"String",
"userName",
",",
"String",
"password",
",",
"String",
"filePath",
",",
"int",
"numberOfLines",
")",
"{",
"String",
"result",
"=",
"null",
"... | Reads content of file on from FTP server to String.
@param hostName the FTP server host name to connect
@param port the port to connect
@param userName the user name
@param password the password
@param filePath file to read.
@return file's content.
@throws RuntimeException in case any exception has been thrown. | [
"Reads",
"content",
"of",
"file",
"on",
"from",
"FTP",
"server",
"to",
"String",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FtpFileUtil.java#L169-L196 |
JavaMoney/jsr354-api | src/main/java/javax/money/convert/ConversionQueryBuilder.java | ConversionQueryBuilder.setRateTypes | public ConversionQueryBuilder setRateTypes(RateType... rateTypes) {
"""
Set the providers to be considered. If not set explicitly the <i>default</i> ISO currencies as
returned by {@link java.util.Currency} is used.
@param rateTypes the rate types to use, not null.
@return the query for chaining.
"""
return set(ConversionQuery.KEY_RATE_TYPES, new HashSet<>(Arrays.asList(rateTypes)));
} | java | public ConversionQueryBuilder setRateTypes(RateType... rateTypes) {
return set(ConversionQuery.KEY_RATE_TYPES, new HashSet<>(Arrays.asList(rateTypes)));
} | [
"public",
"ConversionQueryBuilder",
"setRateTypes",
"(",
"RateType",
"...",
"rateTypes",
")",
"{",
"return",
"set",
"(",
"ConversionQuery",
".",
"KEY_RATE_TYPES",
",",
"new",
"HashSet",
"<>",
"(",
"Arrays",
".",
"asList",
"(",
"rateTypes",
")",
")",
")",
";",
... | Set the providers to be considered. If not set explicitly the <i>default</i> ISO currencies as
returned by {@link java.util.Currency} is used.
@param rateTypes the rate types to use, not null.
@return the query for chaining. | [
"Set",
"the",
"providers",
"to",
"be",
"considered",
".",
"If",
"not",
"set",
"explicitly",
"the",
"<i",
">",
"default<",
"/",
"i",
">",
"ISO",
"currencies",
"as",
"returned",
"by",
"{",
"@link",
"java",
".",
"util",
".",
"Currency",
"}",
"is",
"used",... | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/convert/ConversionQueryBuilder.java#L46-L48 |
TheHortonMachine/hortonmachine | gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/AnnotationUtilities.java | AnnotationUtilities.getLocalizedDescription | public static String getLocalizedDescription( Description description ) throws Exception {
"""
Gets the localized description of the {@link Description}.
@param description the {@link Description} annotation.
@return the description string or " - ".
@throws Exception
"""
// try to get the language
Class< ? > annotationclass = Description.class;
return getLocalizedString(description, annotationclass);
} | java | public static String getLocalizedDescription( Description description ) throws Exception {
// try to get the language
Class< ? > annotationclass = Description.class;
return getLocalizedString(description, annotationclass);
} | [
"public",
"static",
"String",
"getLocalizedDescription",
"(",
"Description",
"description",
")",
"throws",
"Exception",
"{",
"// try to get the language",
"Class",
"<",
"?",
">",
"annotationclass",
"=",
"Description",
".",
"class",
";",
"return",
"getLocalizedString",
... | Gets the localized description of the {@link Description}.
@param description the {@link Description} annotation.
@return the description string or " - ".
@throws Exception | [
"Gets",
"the",
"localized",
"description",
"of",
"the",
"{",
"@link",
"Description",
"}",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gui/src/main/java/org/hortonmachine/gui/spatialtoolbox/core/AnnotationUtilities.java#L48-L52 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java | Feature.setIntegerAttribute | public void setIntegerAttribute(String name, Integer value) {
"""
Set attribute value of given type.
@param name attribute name
@param value attribute value
"""
Attribute attribute = getAttributes().get(name);
if (!(attribute instanceof IntegerAttribute)) {
throw new IllegalStateException("Cannot set integer value on attribute with different type, " +
attribute.getClass().getName() + " setting value " + value);
}
((IntegerAttribute) attribute).setValue(value);
} | java | public void setIntegerAttribute(String name, Integer value) {
Attribute attribute = getAttributes().get(name);
if (!(attribute instanceof IntegerAttribute)) {
throw new IllegalStateException("Cannot set integer value on attribute with different type, " +
attribute.getClass().getName() + " setting value " + value);
}
((IntegerAttribute) attribute).setValue(value);
} | [
"public",
"void",
"setIntegerAttribute",
"(",
"String",
"name",
",",
"Integer",
"value",
")",
"{",
"Attribute",
"attribute",
"=",
"getAttributes",
"(",
")",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"!",
"(",
"attribute",
"instanceof",
"IntegerAttribute"... | Set attribute value of given type.
@param name attribute name
@param value attribute value | [
"Set",
"attribute",
"value",
"of",
"given",
"type",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java#L305-L312 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java | ParameterFormatter.countArgumentPlaceholders2 | static int countArgumentPlaceholders2(final String messagePattern, final int[] indices) {
"""
Counts the number of unescaped placeholders in the given messagePattern.
@param messagePattern the message pattern to be analyzed.
@return the number of unescaped placeholders.
"""
if (messagePattern == null) {
return 0;
}
final int length = messagePattern.length();
int result = 0;
boolean isEscaped = false;
for (int i = 0; i < length - 1; i++) {
final char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) {
isEscaped = !isEscaped;
indices[0] = -1; // escaping means fast path is not available...
result++;
} else if (curChar == DELIM_START) {
if (!isEscaped && messagePattern.charAt(i + 1) == DELIM_STOP) {
indices[result] = i;
result++;
i++;
}
isEscaped = false;
} else {
isEscaped = false;
}
}
return result;
} | java | static int countArgumentPlaceholders2(final String messagePattern, final int[] indices) {
if (messagePattern == null) {
return 0;
}
final int length = messagePattern.length();
int result = 0;
boolean isEscaped = false;
for (int i = 0; i < length - 1; i++) {
final char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) {
isEscaped = !isEscaped;
indices[0] = -1; // escaping means fast path is not available...
result++;
} else if (curChar == DELIM_START) {
if (!isEscaped && messagePattern.charAt(i + 1) == DELIM_STOP) {
indices[result] = i;
result++;
i++;
}
isEscaped = false;
} else {
isEscaped = false;
}
}
return result;
} | [
"static",
"int",
"countArgumentPlaceholders2",
"(",
"final",
"String",
"messagePattern",
",",
"final",
"int",
"[",
"]",
"indices",
")",
"{",
"if",
"(",
"messagePattern",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"final",
"int",
"length",
"=",
"messa... | Counts the number of unescaped placeholders in the given messagePattern.
@param messagePattern the message pattern to be analyzed.
@return the number of unescaped placeholders. | [
"Counts",
"the",
"number",
"of",
"unescaped",
"placeholders",
"in",
"the",
"given",
"messagePattern",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/message/ParameterFormatter.java#L104-L129 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.email_exchange_organizationName_service_exchangeService_account_GET | public ArrayList<String> email_exchange_organizationName_service_exchangeService_account_GET(String organizationName, String exchangeService, OvhOvhLicenceEnum licence, Long number, OvhAccountQuotaEnum storageQuota) throws IOException {
"""
Get allowed durations for 'account' option
REST: GET /order/email/exchange/{organizationName}/service/{exchangeService}/account
@param storageQuota [required] The storage quota for the account(s) in GB (default = 50)
@param number [required] Number of Accounts to order
@param licence [required] Licence type for the account
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
"""
String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/account";
StringBuilder sb = path(qPath, organizationName, exchangeService);
query(sb, "licence", licence);
query(sb, "number", number);
query(sb, "storageQuota", storageQuota);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> email_exchange_organizationName_service_exchangeService_account_GET(String organizationName, String exchangeService, OvhOvhLicenceEnum licence, Long number, OvhAccountQuotaEnum storageQuota) throws IOException {
String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/account";
StringBuilder sb = path(qPath, organizationName, exchangeService);
query(sb, "licence", licence);
query(sb, "number", number);
query(sb, "storageQuota", storageQuota);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"email_exchange_organizationName_service_exchangeService_account_GET",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"OvhOvhLicenceEnum",
"licence",
",",
"Long",
"number",
",",
"OvhAccountQuotaEnum",
"stor... | Get allowed durations for 'account' option
REST: GET /order/email/exchange/{organizationName}/service/{exchangeService}/account
@param storageQuota [required] The storage quota for the account(s) in GB (default = 50)
@param number [required] Number of Accounts to order
@param licence [required] Licence type for the account
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service | [
"Get",
"allowed",
"durations",
"for",
"account",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3903-L3911 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.renameJob | public JenkinsServer renameJob(String oldJobName, String newJobName) throws IOException {
"""
Rename a job
@param oldJobName existing job name.
@param newJobName The new job name.
@throws IOException In case of a failure.
"""
return renameJob(null, oldJobName, newJobName, false);
} | java | public JenkinsServer renameJob(String oldJobName, String newJobName) throws IOException {
return renameJob(null, oldJobName, newJobName, false);
} | [
"public",
"JenkinsServer",
"renameJob",
"(",
"String",
"oldJobName",
",",
"String",
"newJobName",
")",
"throws",
"IOException",
"{",
"return",
"renameJob",
"(",
"null",
",",
"oldJobName",
",",
"newJobName",
",",
"false",
")",
";",
"}"
] | Rename a job
@param oldJobName existing job name.
@param newJobName The new job name.
@throws IOException In case of a failure. | [
"Rename",
"a",
"job"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L861-L863 |
Impetus/Kundera | src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBSchemaManager.java | CouchDBSchemaManager.createViewForSelectAllIfNotExist | private void createViewForSelectAllIfNotExist(TableInfo tableInfo, Map<String, MapReduce> views) {
"""
Creates the view for select all if not exist.
@param tableInfo
the table info
@param views
the views
"""
if (views.get("all") == null)
{
createViewForSelectAll(tableInfo, views);
}
} | java | private void createViewForSelectAllIfNotExist(TableInfo tableInfo, Map<String, MapReduce> views)
{
if (views.get("all") == null)
{
createViewForSelectAll(tableInfo, views);
}
} | [
"private",
"void",
"createViewForSelectAllIfNotExist",
"(",
"TableInfo",
"tableInfo",
",",
"Map",
"<",
"String",
",",
"MapReduce",
">",
"views",
")",
"{",
"if",
"(",
"views",
".",
"get",
"(",
"\"all\"",
")",
"==",
"null",
")",
"{",
"createViewForSelectAll",
... | Creates the view for select all if not exist.
@param tableInfo
the table info
@param views
the views | [
"Creates",
"the",
"view",
"for",
"select",
"all",
"if",
"not",
"exist",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBSchemaManager.java#L642-L648 |
google/error-prone | check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java | NullnessPropagationTransfer.setContext | NullnessPropagationTransfer setContext(@Nullable Context context) {
"""
Stores the given Javac context to find and analyze field initializers. Set before analyzing a
method and reset after.
"""
// This is a best-effort check (similar to ArrayList iterators, for instance), no guarantee
Preconditions.checkArgument(
context == null || this.context == null,
"Context already set: reset after use and don't use this class concurrently");
this.context = context;
// Clear traversed set just-in-case as this marks the beginning or end of analyzing a method
this.traversed.clear();
// Null out local inference results when leaving a method
this.inferenceResults = null;
return this;
} | java | NullnessPropagationTransfer setContext(@Nullable Context context) {
// This is a best-effort check (similar to ArrayList iterators, for instance), no guarantee
Preconditions.checkArgument(
context == null || this.context == null,
"Context already set: reset after use and don't use this class concurrently");
this.context = context;
// Clear traversed set just-in-case as this marks the beginning or end of analyzing a method
this.traversed.clear();
// Null out local inference results when leaving a method
this.inferenceResults = null;
return this;
} | [
"NullnessPropagationTransfer",
"setContext",
"(",
"@",
"Nullable",
"Context",
"context",
")",
"{",
"// This is a best-effort check (similar to ArrayList iterators, for instance), no guarantee",
"Preconditions",
".",
"checkArgument",
"(",
"context",
"==",
"null",
"||",
"this",
"... | Stores the given Javac context to find and analyze field initializers. Set before analyzing a
method and reset after. | [
"Stores",
"the",
"given",
"Javac",
"context",
"to",
"find",
"and",
"analyze",
"field",
"initializers",
".",
"Set",
"before",
"analyzing",
"a",
"method",
"and",
"reset",
"after",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java#L329-L340 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/core/PersistenceBrokerThreadMapping.java | PersistenceBrokerThreadMapping.setCurrentPersistenceBroker | public static void setCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)
throws PBFactoryException {
"""
Mark a PersistenceBroker as preferred choice for current Thread
@param key The PBKey the broker is associated to
@param broker The PersistenceBroker to mark as current
"""
HashMap map = (HashMap) currentBrokerMap.get();
WeakHashMap set = null;
if(map == null)
{
map = new HashMap();
currentBrokerMap.set(map);
synchronized(lock) {
loadedHMs.add(map);
}
}
else
{
set = (WeakHashMap) map.get(key);
}
if(set == null)
{
// We emulate weak HashSet using WeakHashMap
set = new WeakHashMap();
map.put(key, set);
}
set.put(broker, null);
} | java | public static void setCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker)
throws PBFactoryException
{
HashMap map = (HashMap) currentBrokerMap.get();
WeakHashMap set = null;
if(map == null)
{
map = new HashMap();
currentBrokerMap.set(map);
synchronized(lock) {
loadedHMs.add(map);
}
}
else
{
set = (WeakHashMap) map.get(key);
}
if(set == null)
{
// We emulate weak HashSet using WeakHashMap
set = new WeakHashMap();
map.put(key, set);
}
set.put(broker, null);
} | [
"public",
"static",
"void",
"setCurrentPersistenceBroker",
"(",
"PBKey",
"key",
",",
"PersistenceBrokerInternal",
"broker",
")",
"throws",
"PBFactoryException",
"{",
"HashMap",
"map",
"=",
"(",
"HashMap",
")",
"currentBrokerMap",
".",
"get",
"(",
")",
";",
"WeakHa... | Mark a PersistenceBroker as preferred choice for current Thread
@param key The PBKey the broker is associated to
@param broker The PersistenceBroker to mark as current | [
"Mark",
"a",
"PersistenceBroker",
"as",
"preferred",
"choice",
"for",
"current",
"Thread"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerThreadMapping.java#L59-L85 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java | FuncExtFunction.fixupVariables | public void fixupVariables(java.util.Vector vars, int globalsSize) {
"""
This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame).
NEEDSDOC @param globalsSize
"""
if (null != m_argVec)
{
int nArgs = m_argVec.size();
for (int i = 0; i < nArgs; i++)
{
Expression arg = (Expression) m_argVec.elementAt(i);
arg.fixupVariables(vars, globalsSize);
}
}
} | java | public void fixupVariables(java.util.Vector vars, int globalsSize)
{
if (null != m_argVec)
{
int nArgs = m_argVec.size();
for (int i = 0; i < nArgs; i++)
{
Expression arg = (Expression) m_argVec.elementAt(i);
arg.fixupVariables(vars, globalsSize);
}
}
} | [
"public",
"void",
"fixupVariables",
"(",
"java",
".",
"util",
".",
"Vector",
"vars",
",",
"int",
"globalsSize",
")",
"{",
"if",
"(",
"null",
"!=",
"m_argVec",
")",
"{",
"int",
"nArgs",
"=",
"m_argVec",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
... | This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame).
NEEDSDOC @param globalsSize | [
"This",
"function",
"is",
"used",
"to",
"fixup",
"variables",
"from",
"QNames",
"to",
"stack",
"frame",
"indexes",
"at",
"stylesheet",
"build",
"time",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/FuncExtFunction.java#L85-L99 |
drinkjava2/jDialects | core/src/main/java/com/github/drinkjava2/jdialects/StrUtils.java | StrUtils.replaceIgnoreCase | public static String replaceIgnoreCase(String text, String findtxt, String replacetxt) {
"""
Replace all sub strings ignore case <br/>
replaceIgnoreCase("AbcDECd", "Cd", "FF") = "AbFFEFF"
"""
if (text == null)
return null;
String str = text;
if (findtxt == null || findtxt.length() == 0) {
return str;
}
if (findtxt.length() > str.length()) {
return str;
}
int counter = 0;
String thesubstr;
while ((counter < str.length()) && (str.substring(counter).length() >= findtxt.length())) {
thesubstr = str.substring(counter, counter + findtxt.length());
if (thesubstr.equalsIgnoreCase(findtxt)) {
str = str.substring(0, counter) + replacetxt + str.substring(counter + findtxt.length());
counter += replacetxt.length();
} else {
counter++;
}
}
return str;
} | java | public static String replaceIgnoreCase(String text, String findtxt, String replacetxt) {
if (text == null)
return null;
String str = text;
if (findtxt == null || findtxt.length() == 0) {
return str;
}
if (findtxt.length() > str.length()) {
return str;
}
int counter = 0;
String thesubstr;
while ((counter < str.length()) && (str.substring(counter).length() >= findtxt.length())) {
thesubstr = str.substring(counter, counter + findtxt.length());
if (thesubstr.equalsIgnoreCase(findtxt)) {
str = str.substring(0, counter) + replacetxt + str.substring(counter + findtxt.length());
counter += replacetxt.length();
} else {
counter++;
}
}
return str;
} | [
"public",
"static",
"String",
"replaceIgnoreCase",
"(",
"String",
"text",
",",
"String",
"findtxt",
",",
"String",
"replacetxt",
")",
"{",
"if",
"(",
"text",
"==",
"null",
")",
"return",
"null",
";",
"String",
"str",
"=",
"text",
";",
"if",
"(",
"findtxt... | Replace all sub strings ignore case <br/>
replaceIgnoreCase("AbcDECd", "Cd", "FF") = "AbFFEFF" | [
"Replace",
"all",
"sub",
"strings",
"ignore",
"case",
"<br",
"/",
">",
"replaceIgnoreCase",
"(",
"AbcDECd",
"Cd",
"FF",
")",
"=",
"AbFFEFF"
] | train | https://github.com/drinkjava2/jDialects/blob/1c165f09c6042a599b681c279024abcc1b848b88/core/src/main/java/com/github/drinkjava2/jdialects/StrUtils.java#L338-L360 |
amaembo/streamex | src/main/java/one/util/streamex/DoubleStreamEx.java | DoubleStreamEx.mapFirst | public DoubleStreamEx mapFirst(DoubleUnaryOperator mapper) {
"""
Returns a stream where the first element is the replaced with the result
of applying the given function while the other elements are left intact.
<p>
This is a <a href="package-summary.html#StreamOps">quasi-intermediate
operation</a>.
@param mapper a
<a href="package-summary.html#NonInterference">non-interfering
</a>, <a href="package-summary.html#Statelessness">stateless</a>
function to apply to the first element
@return the new stream
@since 0.4.1
"""
return delegate(new PairSpliterator.PSOfDouble((a, b) -> b, mapper, spliterator(),
PairSpliterator.MODE_MAP_FIRST));
} | java | public DoubleStreamEx mapFirst(DoubleUnaryOperator mapper) {
return delegate(new PairSpliterator.PSOfDouble((a, b) -> b, mapper, spliterator(),
PairSpliterator.MODE_MAP_FIRST));
} | [
"public",
"DoubleStreamEx",
"mapFirst",
"(",
"DoubleUnaryOperator",
"mapper",
")",
"{",
"return",
"delegate",
"(",
"new",
"PairSpliterator",
".",
"PSOfDouble",
"(",
"(",
"a",
",",
"b",
")",
"->",
"b",
",",
"mapper",
",",
"spliterator",
"(",
")",
",",
"Pair... | Returns a stream where the first element is the replaced with the result
of applying the given function while the other elements are left intact.
<p>
This is a <a href="package-summary.html#StreamOps">quasi-intermediate
operation</a>.
@param mapper a
<a href="package-summary.html#NonInterference">non-interfering
</a>, <a href="package-summary.html#Statelessness">stateless</a>
function to apply to the first element
@return the new stream
@since 0.4.1 | [
"Returns",
"a",
"stream",
"where",
"the",
"first",
"element",
"is",
"the",
"replaced",
"with",
"the",
"result",
"of",
"applying",
"the",
"given",
"function",
"while",
"the",
"other",
"elements",
"are",
"left",
"intact",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/DoubleStreamEx.java#L166-L169 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/rights/GranteeManager.java | GranteeManager.addRole | public Grantee addRole(HsqlName name) {
"""
Creates a new Role object under management of this object. <p>
A set of constraints regarding user creation is imposed: <p>
<OL>
<LI>Can't create a role with name same as any right.
<LI>If this object's collection already contains an element whose
name attribute equals the name argument, then
a GRANTEE_ALREADY_EXISTS or ROLE_ALREADY_EXISTS Trace
is thrown.
(This will catch attempts to create Reserved grantee names).
</OL>
"""
if (map.containsKey(name.name)) {
throw Error.error(ErrorCode.X_28503, name.name);
}
Grantee g = new Grantee(name, this);
g.isRole = true;
map.put(name.name, g);
roleMap.add(name.name, g);
return g;
} | java | public Grantee addRole(HsqlName name) {
if (map.containsKey(name.name)) {
throw Error.error(ErrorCode.X_28503, name.name);
}
Grantee g = new Grantee(name, this);
g.isRole = true;
map.put(name.name, g);
roleMap.add(name.name, g);
return g;
} | [
"public",
"Grantee",
"addRole",
"(",
"HsqlName",
"name",
")",
"{",
"if",
"(",
"map",
".",
"containsKey",
"(",
"name",
".",
"name",
")",
")",
"{",
"throw",
"Error",
".",
"error",
"(",
"ErrorCode",
".",
"X_28503",
",",
"name",
".",
"name",
")",
";",
... | Creates a new Role object under management of this object. <p>
A set of constraints regarding user creation is imposed: <p>
<OL>
<LI>Can't create a role with name same as any right.
<LI>If this object's collection already contains an element whose
name attribute equals the name argument, then
a GRANTEE_ALREADY_EXISTS or ROLE_ALREADY_EXISTS Trace
is thrown.
(This will catch attempts to create Reserved grantee names).
</OL> | [
"Creates",
"a",
"new",
"Role",
"object",
"under",
"management",
"of",
"this",
"object",
".",
"<p",
">"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/rights/GranteeManager.java#L513-L527 |
apache/flink | flink-yarn/src/main/java/org/apache/flink/yarn/AbstractYarnClusterDescriptor.java | AbstractYarnClusterDescriptor.failSessionDuringDeployment | private void failSessionDuringDeployment(YarnClient yarnClient, YarnClientApplication yarnApplication) {
"""
Kills YARN application and stops YARN client.
<p>Use this method to kill the App before it has been properly deployed
"""
LOG.info("Killing YARN application");
try {
yarnClient.killApplication(yarnApplication.getNewApplicationResponse().getApplicationId());
} catch (Exception e) {
// we only log a debug message here because the "killApplication" call is a best-effort
// call (we don't know if the application has been deployed when the error occured).
LOG.debug("Error while killing YARN application", e);
}
yarnClient.stop();
} | java | private void failSessionDuringDeployment(YarnClient yarnClient, YarnClientApplication yarnApplication) {
LOG.info("Killing YARN application");
try {
yarnClient.killApplication(yarnApplication.getNewApplicationResponse().getApplicationId());
} catch (Exception e) {
// we only log a debug message here because the "killApplication" call is a best-effort
// call (we don't know if the application has been deployed when the error occured).
LOG.debug("Error while killing YARN application", e);
}
yarnClient.stop();
} | [
"private",
"void",
"failSessionDuringDeployment",
"(",
"YarnClient",
"yarnClient",
",",
"YarnClientApplication",
"yarnApplication",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Killing YARN application\"",
")",
";",
"try",
"{",
"yarnClient",
".",
"killApplication",
"(",
"yar... | Kills YARN application and stops YARN client.
<p>Use this method to kill the App before it has been properly deployed | [
"Kills",
"YARN",
"application",
"and",
"stops",
"YARN",
"client",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-yarn/src/main/java/org/apache/flink/yarn/AbstractYarnClusterDescriptor.java#L1196-L1207 |
lotaris/rox-client-java | rox-client-java/src/main/java/com/lotaris/rox/core/cache/CacheOptimizerStore.java | CacheOptimizerStore.persistCache | private void persistCache(String projectName, String projectVersion, Map<String, String> cache) {
"""
Persist a specific cache
@param projectName Project name
@param projectVersion Project version
@param cache The cache to persist
"""
File cacheFile = new File(getCacheDir(), projectName + "/" + projectVersion);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(cacheFile));
oos.writeObject(cache);
}
catch (IOException ioe) {
LOGGER.warn("Unable to create the cache file {}/{}/{}", getCacheDir().getAbsoluteFile(), projectName, projectVersion);
}
finally { if (oos != null) { try { oos.close(); } catch (IOException ioe) {} } }
} | java | private void persistCache(String projectName, String projectVersion, Map<String, String> cache) {
File cacheFile = new File(getCacheDir(), projectName + "/" + projectVersion);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(cacheFile));
oos.writeObject(cache);
}
catch (IOException ioe) {
LOGGER.warn("Unable to create the cache file {}/{}/{}", getCacheDir().getAbsoluteFile(), projectName, projectVersion);
}
finally { if (oos != null) { try { oos.close(); } catch (IOException ioe) {} } }
} | [
"private",
"void",
"persistCache",
"(",
"String",
"projectName",
",",
"String",
"projectVersion",
",",
"Map",
"<",
"String",
",",
"String",
">",
"cache",
")",
"{",
"File",
"cacheFile",
"=",
"new",
"File",
"(",
"getCacheDir",
"(",
")",
",",
"projectName",
"... | Persist a specific cache
@param projectName Project name
@param projectVersion Project version
@param cache The cache to persist | [
"Persist",
"a",
"specific",
"cache"
] | train | https://github.com/lotaris/rox-client-java/blob/1b33f7560347c382c59a40c4037d175ab8127fde/rox-client-java/src/main/java/com/lotaris/rox/core/cache/CacheOptimizerStore.java#L179-L190 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java | ClassDocImpl.getClassName | static String getClassName(ClassSymbol c, boolean full) {
"""
Return the class name as a string. If "full" is true the name is
qualified, otherwise it is qualified by its enclosing class(es) only.
"""
if (full) {
return c.getQualifiedName().toString();
} else {
String n = "";
for ( ; c != null; c = c.owner.enclClass()) {
n = c.name + (n.equals("") ? "" : ".") + n;
}
return n;
}
} | java | static String getClassName(ClassSymbol c, boolean full) {
if (full) {
return c.getQualifiedName().toString();
} else {
String n = "";
for ( ; c != null; c = c.owner.enclClass()) {
n = c.name + (n.equals("") ? "" : ".") + n;
}
return n;
}
} | [
"static",
"String",
"getClassName",
"(",
"ClassSymbol",
"c",
",",
"boolean",
"full",
")",
"{",
"if",
"(",
"full",
")",
"{",
"return",
"c",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"String",
"n",
"=",
"\"\""... | Return the class name as a string. If "full" is true the name is
qualified, otherwise it is qualified by its enclosing class(es) only. | [
"Return",
"the",
"class",
"name",
"as",
"a",
"string",
".",
"If",
"full",
"is",
"true",
"the",
"name",
"is",
"qualified",
"otherwise",
"it",
"is",
"qualified",
"by",
"its",
"enclosing",
"class",
"(",
"es",
")",
"only",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java#L416-L426 |
pressgang-ccms/PressGangCCMSCommonUtilities | src/main/java/org/jboss/pressgang/ccms/utils/common/FileUtilities.java | FileUtilities.saveFile | public static void saveFile(final File file, final String contents, final String encoding) throws IOException {
"""
Save the data, represented as a String to a file
@param file The location/name of the file to be saved.
@param contents The data that is to be written to the file.
@throws IOException
"""
saveFile(file, contents.getBytes(encoding));
} | java | public static void saveFile(final File file, final String contents, final String encoding) throws IOException {
saveFile(file, contents.getBytes(encoding));
} | [
"public",
"static",
"void",
"saveFile",
"(",
"final",
"File",
"file",
",",
"final",
"String",
"contents",
",",
"final",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"saveFile",
"(",
"file",
",",
"contents",
".",
"getBytes",
"(",
"encoding",
")",
... | Save the data, represented as a String to a file
@param file The location/name of the file to be saved.
@param contents The data that is to be written to the file.
@throws IOException | [
"Save",
"the",
"data",
"represented",
"as",
"a",
"String",
"to",
"a",
"file"
] | train | https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/FileUtilities.java#L250-L252 |
Impetus/Kundera | src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientFactory.java | DSClientFactory.getPolicy | private com.datastax.driver.core.policies.ReconnectionPolicy getPolicy(ReconnectionPolicy policy, Properties props) {
"""
Gets the policy.
@param policy
the policy
@param props
the props
@return the policy
"""
com.datastax.driver.core.policies.ReconnectionPolicy reconnectionPolicy = null;
switch (policy)
{
case ConstantReconnectionPolicy:
String property = props.getProperty("constantDelayMs");
long constantDelayMs = property != null ? new Long(property) : 0l;
reconnectionPolicy = new ConstantReconnectionPolicy(constantDelayMs);
break;
case ExponentialReconnectionPolicy:
String baseDelayMsAsStr = props.getProperty("baseDelayMs");
String maxDelayMsAsStr = props.getProperty("maxDelayMs");
if (!StringUtils.isBlank(baseDelayMsAsStr) && !StringUtils.isBlank(maxDelayMsAsStr))
{
long baseDelayMs = new Long(baseDelayMsAsStr);
long maxDelayMs = new Long(maxDelayMsAsStr);
reconnectionPolicy = new ExponentialReconnectionPolicy(baseDelayMs, maxDelayMs);
}
break;
default:
break;
}
return reconnectionPolicy;
} | java | private com.datastax.driver.core.policies.ReconnectionPolicy getPolicy(ReconnectionPolicy policy, Properties props)
{
com.datastax.driver.core.policies.ReconnectionPolicy reconnectionPolicy = null;
switch (policy)
{
case ConstantReconnectionPolicy:
String property = props.getProperty("constantDelayMs");
long constantDelayMs = property != null ? new Long(property) : 0l;
reconnectionPolicy = new ConstantReconnectionPolicy(constantDelayMs);
break;
case ExponentialReconnectionPolicy:
String baseDelayMsAsStr = props.getProperty("baseDelayMs");
String maxDelayMsAsStr = props.getProperty("maxDelayMs");
if (!StringUtils.isBlank(baseDelayMsAsStr) && !StringUtils.isBlank(maxDelayMsAsStr))
{
long baseDelayMs = new Long(baseDelayMsAsStr);
long maxDelayMs = new Long(maxDelayMsAsStr);
reconnectionPolicy = new ExponentialReconnectionPolicy(baseDelayMs, maxDelayMs);
}
break;
default:
break;
}
return reconnectionPolicy;
} | [
"private",
"com",
".",
"datastax",
".",
"driver",
".",
"core",
".",
"policies",
".",
"ReconnectionPolicy",
"getPolicy",
"(",
"ReconnectionPolicy",
"policy",
",",
"Properties",
"props",
")",
"{",
"com",
".",
"datastax",
".",
"driver",
".",
"core",
".",
"polic... | Gets the policy.
@param policy
the policy
@param props
the props
@return the policy | [
"Gets",
"the",
"policy",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientFactory.java#L669-L696 |
phax/ph-oton | ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/AbstractWebPageForm.java | AbstractWebPageForm.createViewToolbar | @Nonnull
@OverrideOnDemand
protected TOOLBAR_TYPE createViewToolbar (@Nonnull final WPECTYPE aWPEC,
final boolean bCanGoBack,
@Nonnull final DATATYPE aSelectedObject) {
"""
Create toolbar for viewing an existing object. Contains the back button and
the edit button.
@param aWPEC
The web page execution context. Never <code>null</code>.
@param bCanGoBack
<code>true</code> to enable back button
@param aSelectedObject
The selected object
@return Never <code>null</code>.
"""
final Locale aDisplayLocale = aWPEC.getDisplayLocale ();
final TOOLBAR_TYPE aToolbar = createNewViewToolbar (aWPEC);
if (bCanGoBack)
{
// Back to list
aToolbar.addButtonBack (aDisplayLocale);
}
if (isActionAllowed (aWPEC, EWebPageFormAction.EDIT, aSelectedObject))
{
// Edit object
aToolbar.addButtonEdit (aDisplayLocale, createEditURL (aWPEC, aSelectedObject));
}
// Callback
modifyViewToolbar (aWPEC, aSelectedObject, aToolbar);
return aToolbar;
} | java | @Nonnull
@OverrideOnDemand
protected TOOLBAR_TYPE createViewToolbar (@Nonnull final WPECTYPE aWPEC,
final boolean bCanGoBack,
@Nonnull final DATATYPE aSelectedObject)
{
final Locale aDisplayLocale = aWPEC.getDisplayLocale ();
final TOOLBAR_TYPE aToolbar = createNewViewToolbar (aWPEC);
if (bCanGoBack)
{
// Back to list
aToolbar.addButtonBack (aDisplayLocale);
}
if (isActionAllowed (aWPEC, EWebPageFormAction.EDIT, aSelectedObject))
{
// Edit object
aToolbar.addButtonEdit (aDisplayLocale, createEditURL (aWPEC, aSelectedObject));
}
// Callback
modifyViewToolbar (aWPEC, aSelectedObject, aToolbar);
return aToolbar;
} | [
"@",
"Nonnull",
"@",
"OverrideOnDemand",
"protected",
"TOOLBAR_TYPE",
"createViewToolbar",
"(",
"@",
"Nonnull",
"final",
"WPECTYPE",
"aWPEC",
",",
"final",
"boolean",
"bCanGoBack",
",",
"@",
"Nonnull",
"final",
"DATATYPE",
"aSelectedObject",
")",
"{",
"final",
"Lo... | Create toolbar for viewing an existing object. Contains the back button and
the edit button.
@param aWPEC
The web page execution context. Never <code>null</code>.
@param bCanGoBack
<code>true</code> to enable back button
@param aSelectedObject
The selected object
@return Never <code>null</code>. | [
"Create",
"toolbar",
"for",
"viewing",
"an",
"existing",
"object",
".",
"Contains",
"the",
"back",
"button",
"and",
"the",
"edit",
"button",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uicore/src/main/java/com/helger/photon/uicore/page/AbstractWebPageForm.java#L654-L677 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java | ServiceDirectoryConfig.getString | public String getString(String name, String defaultVal) {
"""
Get the property object as String, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as String, return defaultVal if property is undefined.
"""
if(this.configuration.containsKey(name)){
return this.configuration.getString(name);
} else {
return defaultVal;
}
} | java | public String getString(String name, String defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getString(name);
} else {
return defaultVal;
}
} | [
"public",
"String",
"getString",
"(",
"String",
"name",
",",
"String",
"defaultVal",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"return",
"this",
".",
"configuration",
".",
"getString",
"(",
"name",
... | Get the property object as String, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as String, return defaultVal if property is undefined. | [
"Get",
"the",
"property",
"object",
"as",
"String",
"or",
"return",
"defaultVal",
"if",
"property",
"is",
"not",
"defined",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java#L75-L81 |
infinispan/infinispan | commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java | MarshallUtil.unmarshallUUID | public static UUID unmarshallUUID(ObjectInput in, boolean checkNull) throws IOException {
"""
Unmarshall {@link UUID}.
@param in {@link ObjectInput} to read.
@param checkNull If {@code true}, it checks if the {@link UUID} marshalled was {@code null}.
@return {@link UUID} marshalled.
@throws IOException If any of the usual Input/Output related exceptions occur.
@see #marshallUUID(UUID, ObjectOutput, boolean).
"""
if (checkNull && in.readBoolean()) {
return null;
}
return new UUID(in.readLong(), in.readLong());
} | java | public static UUID unmarshallUUID(ObjectInput in, boolean checkNull) throws IOException {
if (checkNull && in.readBoolean()) {
return null;
}
return new UUID(in.readLong(), in.readLong());
} | [
"public",
"static",
"UUID",
"unmarshallUUID",
"(",
"ObjectInput",
"in",
",",
"boolean",
"checkNull",
")",
"throws",
"IOException",
"{",
"if",
"(",
"checkNull",
"&&",
"in",
".",
"readBoolean",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",... | Unmarshall {@link UUID}.
@param in {@link ObjectInput} to read.
@param checkNull If {@code true}, it checks if the {@link UUID} marshalled was {@code null}.
@return {@link UUID} marshalled.
@throws IOException If any of the usual Input/Output related exceptions occur.
@see #marshallUUID(UUID, ObjectOutput, boolean). | [
"Unmarshall",
"{",
"@link",
"UUID",
"}",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/marshall/MarshallUtil.java#L167-L172 |
apache/incubator-druid | server/src/main/java/org/apache/druid/server/coordinator/CostBalancerStrategy.java | CostBalancerStrategy.computeJointSegmentsCost | public static double computeJointSegmentsCost(final DataSegment segmentA, final DataSegment segmentB) {
"""
This defines the unnormalized cost function between two segments.
See https://github.com/apache/incubator-druid/pull/2972 for more details about the cost function.
intervalCost: segments close together are more likely to be queried together
multiplier: if two segments belong to the same data source, they are more likely to be involved
in the same queries
@param segmentA The first DataSegment.
@param segmentB The second DataSegment.
@return the joint cost of placing the two DataSegments together on one node.
"""
final Interval intervalA = segmentA.getInterval();
final Interval intervalB = segmentB.getInterval();
final double t0 = intervalA.getStartMillis();
final double t1 = (intervalA.getEndMillis() - t0) / MILLIS_FACTOR;
final double start = (intervalB.getStartMillis() - t0) / MILLIS_FACTOR;
final double end = (intervalB.getEndMillis() - t0) / MILLIS_FACTOR;
// constant cost-multiplier for segments of the same datsource
final double multiplier = segmentA.getDataSource().equals(segmentB.getDataSource()) ? 2.0 : 1.0;
return INV_LAMBDA_SQUARE * intervalCost(t1, start, end) * multiplier;
} | java | public static double computeJointSegmentsCost(final DataSegment segmentA, final DataSegment segmentB)
{
final Interval intervalA = segmentA.getInterval();
final Interval intervalB = segmentB.getInterval();
final double t0 = intervalA.getStartMillis();
final double t1 = (intervalA.getEndMillis() - t0) / MILLIS_FACTOR;
final double start = (intervalB.getStartMillis() - t0) / MILLIS_FACTOR;
final double end = (intervalB.getEndMillis() - t0) / MILLIS_FACTOR;
// constant cost-multiplier for segments of the same datsource
final double multiplier = segmentA.getDataSource().equals(segmentB.getDataSource()) ? 2.0 : 1.0;
return INV_LAMBDA_SQUARE * intervalCost(t1, start, end) * multiplier;
} | [
"public",
"static",
"double",
"computeJointSegmentsCost",
"(",
"final",
"DataSegment",
"segmentA",
",",
"final",
"DataSegment",
"segmentB",
")",
"{",
"final",
"Interval",
"intervalA",
"=",
"segmentA",
".",
"getInterval",
"(",
")",
";",
"final",
"Interval",
"interv... | This defines the unnormalized cost function between two segments.
See https://github.com/apache/incubator-druid/pull/2972 for more details about the cost function.
intervalCost: segments close together are more likely to be queried together
multiplier: if two segments belong to the same data source, they are more likely to be involved
in the same queries
@param segmentA The first DataSegment.
@param segmentB The second DataSegment.
@return the joint cost of placing the two DataSegments together on one node. | [
"This",
"defines",
"the",
"unnormalized",
"cost",
"function",
"between",
"two",
"segments",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/server/coordinator/CostBalancerStrategy.java#L67-L81 |
SonarSource/sonarqube | server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateFinder.java | QualityGateFinder.getQualityGate | public Optional<QualityGateData> getQualityGate(DbSession dbSession, OrganizationDto organization, ComponentDto component) {
"""
Return effective quality gate of a project.
It will first try to get the quality gate explicitly defined on a project, if none it will try to return default quality gate of the organization
"""
Optional<QualityGateData> res = dbClient.projectQgateAssociationDao().selectQGateIdByComponentId(dbSession, component.getId())
.map(qualityGateId -> dbClient.qualityGateDao().selectById(dbSession, qualityGateId))
.map(qualityGateDto -> new QualityGateData(qualityGateDto, false));
if (res.isPresent()) {
return res;
}
return ofNullable(dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, organization.getDefaultQualityGateUuid()))
.map(qualityGateDto -> new QualityGateData(qualityGateDto, true));
} | java | public Optional<QualityGateData> getQualityGate(DbSession dbSession, OrganizationDto organization, ComponentDto component) {
Optional<QualityGateData> res = dbClient.projectQgateAssociationDao().selectQGateIdByComponentId(dbSession, component.getId())
.map(qualityGateId -> dbClient.qualityGateDao().selectById(dbSession, qualityGateId))
.map(qualityGateDto -> new QualityGateData(qualityGateDto, false));
if (res.isPresent()) {
return res;
}
return ofNullable(dbClient.qualityGateDao().selectByOrganizationAndUuid(dbSession, organization, organization.getDefaultQualityGateUuid()))
.map(qualityGateDto -> new QualityGateData(qualityGateDto, true));
} | [
"public",
"Optional",
"<",
"QualityGateData",
">",
"getQualityGate",
"(",
"DbSession",
"dbSession",
",",
"OrganizationDto",
"organization",
",",
"ComponentDto",
"component",
")",
"{",
"Optional",
"<",
"QualityGateData",
">",
"res",
"=",
"dbClient",
".",
"projectQgat... | Return effective quality gate of a project.
It will first try to get the quality gate explicitly defined on a project, if none it will try to return default quality gate of the organization | [
"Return",
"effective",
"quality",
"gate",
"of",
"a",
"project",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server-common/src/main/java/org/sonar/server/qualitygate/QualityGateFinder.java#L48-L57 |
kite-sdk/kite | kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveAbstractMetadataProvider.java | HiveAbstractMetadataProvider.resolveNamespace | protected String resolveNamespace(String namespace, String name) {
"""
Checks whether the Hive table {@code namespace.name} exists or if
{@code default.name} exists and should be used.
@param namespace the requested namespace
@param name the table name
@return if namespace.name exists, namespace. if not and default.name
exists, then default. {@code null} otherwise.
"""
return resolveNamespace(namespace, name, null);
} | java | protected String resolveNamespace(String namespace, String name) {
return resolveNamespace(namespace, name, null);
} | [
"protected",
"String",
"resolveNamespace",
"(",
"String",
"namespace",
",",
"String",
"name",
")",
"{",
"return",
"resolveNamespace",
"(",
"namespace",
",",
"name",
",",
"null",
")",
";",
"}"
] | Checks whether the Hive table {@code namespace.name} exists or if
{@code default.name} exists and should be used.
@param namespace the requested namespace
@param name the table name
@return if namespace.name exists, namespace. if not and default.name
exists, then default. {@code null} otherwise. | [
"Checks",
"whether",
"the",
"Hive",
"table",
"{",
"@code",
"namespace",
".",
"name",
"}",
"exists",
"or",
"if",
"{",
"@code",
"default",
".",
"name",
"}",
"exists",
"and",
"should",
"be",
"used",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-hive/src/main/java/org/kitesdk/data/spi/hive/HiveAbstractMetadataProvider.java#L259-L261 |
xwiki/xwiki-commons | xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/AbstractXARMojo.java | AbstractXARMojo.getDocFromXML | protected XWikiDocument getDocFromXML(File file) throws MojoExecutionException {
"""
Load a XWiki document from its XML representation.
@param file the file to parse.
@return the loaded document object or null if the document cannot be parsed
"""
XWikiDocument doc;
try {
doc = new XWikiDocument();
doc.fromXML(file);
} catch (Exception e) {
throw new MojoExecutionException(String.format("Failed to parse [%s].", file.getAbsolutePath()), e);
}
return doc;
} | java | protected XWikiDocument getDocFromXML(File file) throws MojoExecutionException
{
XWikiDocument doc;
try {
doc = new XWikiDocument();
doc.fromXML(file);
} catch (Exception e) {
throw new MojoExecutionException(String.format("Failed to parse [%s].", file.getAbsolutePath()), e);
}
return doc;
} | [
"protected",
"XWikiDocument",
"getDocFromXML",
"(",
"File",
"file",
")",
"throws",
"MojoExecutionException",
"{",
"XWikiDocument",
"doc",
";",
"try",
"{",
"doc",
"=",
"new",
"XWikiDocument",
"(",
")",
";",
"doc",
".",
"fromXML",
"(",
"file",
")",
";",
"}",
... | Load a XWiki document from its XML representation.
@param file the file to parse.
@return the loaded document object or null if the document cannot be parsed | [
"Load",
"a",
"XWiki",
"document",
"from",
"its",
"XML",
"representation",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/AbstractXARMojo.java#L330-L342 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java | SVGPath.relativeSmoothCubicTo | public SVGPath relativeSmoothCubicTo(double[] c2xy, double[] xy) {
"""
Smooth Cubic Bezier line to the given relative coordinates.
@param c2xy second control point
@param xy new coordinates
@return path object, for compact syntax.
"""
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
} | java | public SVGPath relativeSmoothCubicTo(double[] c2xy, double[] xy) {
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
} | [
"public",
"SVGPath",
"relativeSmoothCubicTo",
"(",
"double",
"[",
"]",
"c2xy",
",",
"double",
"[",
"]",
"xy",
")",
"{",
"return",
"append",
"(",
"PATH_SMOOTH_CUBIC_TO_RELATIVE",
")",
".",
"append",
"(",
"c2xy",
"[",
"0",
"]",
")",
".",
"append",
"(",
"c2... | Smooth Cubic Bezier line to the given relative coordinates.
@param c2xy second control point
@param xy new coordinates
@return path object, for compact syntax. | [
"Smooth",
"Cubic",
"Bezier",
"line",
"to",
"the",
"given",
"relative",
"coordinates",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L444-L446 |
eclipse/xtext-core | org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/syntaxcoloring/DefaultSemanticHighlightingCalculator.java | DefaultSemanticHighlightingCalculator.highlightNode | protected void highlightNode(IHighlightedPositionAcceptor acceptor, INode node, String... styleIds) {
"""
Highlights the non-hidden parts of {@code node} with the styles given by the {@code styleIds}
"""
if (node == null)
return;
if (node instanceof ILeafNode) {
ITextRegion textRegion = node.getTextRegion();
acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), styleIds);
} else {
for (ILeafNode leaf : node.getLeafNodes()) {
if (!leaf.isHidden()) {
ITextRegion leafRegion = leaf.getTextRegion();
acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), styleIds);
}
}
}
} | java | protected void highlightNode(IHighlightedPositionAcceptor acceptor, INode node, String... styleIds) {
if (node == null)
return;
if (node instanceof ILeafNode) {
ITextRegion textRegion = node.getTextRegion();
acceptor.addPosition(textRegion.getOffset(), textRegion.getLength(), styleIds);
} else {
for (ILeafNode leaf : node.getLeafNodes()) {
if (!leaf.isHidden()) {
ITextRegion leafRegion = leaf.getTextRegion();
acceptor.addPosition(leafRegion.getOffset(), leafRegion.getLength(), styleIds);
}
}
}
} | [
"protected",
"void",
"highlightNode",
"(",
"IHighlightedPositionAcceptor",
"acceptor",
",",
"INode",
"node",
",",
"String",
"...",
"styleIds",
")",
"{",
"if",
"(",
"node",
"==",
"null",
")",
"return",
";",
"if",
"(",
"node",
"instanceof",
"ILeafNode",
")",
"... | Highlights the non-hidden parts of {@code node} with the styles given by the {@code styleIds} | [
"Highlights",
"the",
"non",
"-",
"hidden",
"parts",
"of",
"{"
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/syntaxcoloring/DefaultSemanticHighlightingCalculator.java#L121-L135 |
auth0/auth0-java | src/main/java/com/auth0/client/mgmt/BlacklistsEntity.java | BlacklistsEntity.blacklistToken | public Request blacklistToken(Token token) {
"""
Add a Token to the Blacklist. A token with scope blacklist:tokens is needed.
See https://auth0.com/docs/api/management/v2#!/Blacklists/post_tokens.
@param token the token to blacklist.
@return a Request to execute.
"""
Asserts.assertNotNull(token, "token");
String url = baseUrl
.newBuilder()
.addPathSegments("api/v2/blacklists/tokens")
.build()
.toString();
VoidRequest request = new VoidRequest(client, url, "POST");
request.addHeader("Authorization", "Bearer " + apiToken);
request.setBody(token);
return request;
} | java | public Request blacklistToken(Token token) {
Asserts.assertNotNull(token, "token");
String url = baseUrl
.newBuilder()
.addPathSegments("api/v2/blacklists/tokens")
.build()
.toString();
VoidRequest request = new VoidRequest(client, url, "POST");
request.addHeader("Authorization", "Bearer " + apiToken);
request.setBody(token);
return request;
} | [
"public",
"Request",
"blacklistToken",
"(",
"Token",
"token",
")",
"{",
"Asserts",
".",
"assertNotNull",
"(",
"token",
",",
"\"token\"",
")",
";",
"String",
"url",
"=",
"baseUrl",
".",
"newBuilder",
"(",
")",
".",
"addPathSegments",
"(",
"\"api/v2/blacklists/t... | Add a Token to the Blacklist. A token with scope blacklist:tokens is needed.
See https://auth0.com/docs/api/management/v2#!/Blacklists/post_tokens.
@param token the token to blacklist.
@return a Request to execute. | [
"Add",
"a",
"Token",
"to",
"the",
"Blacklist",
".",
"A",
"token",
"with",
"scope",
"blacklist",
":",
"tokens",
"is",
"needed",
".",
"See",
"https",
":",
"//",
"auth0",
".",
"com",
"/",
"docs",
"/",
"api",
"/",
"management",
"/",
"v2#!",
"/",
"Blackli... | train | https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/mgmt/BlacklistsEntity.java#L53-L65 |
ModeShape/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/NodeTypes.java | NodeTypes.isQueryable | public boolean isQueryable(Name nodeTypeName, Set<Name> mixinTypes) {
"""
Check if the node type and mixin types are queryable or not.
@param nodeTypeName a {@link Name}, never {@code null}
@param mixinTypes the mixin type names; may not be null but may be empty
@return {@code false} if at least one of the node types is not queryable, {@code true} otherwise
"""
if (nonQueryableNodeTypes.contains(nodeTypeName)) {
return false;
}
if (!mixinTypes.isEmpty()) {
for (Name mixinType : mixinTypes) {
if (nonQueryableNodeTypes.contains(mixinType)) {
return false;
}
}
}
return true;
} | java | public boolean isQueryable(Name nodeTypeName, Set<Name> mixinTypes) {
if (nonQueryableNodeTypes.contains(nodeTypeName)) {
return false;
}
if (!mixinTypes.isEmpty()) {
for (Name mixinType : mixinTypes) {
if (nonQueryableNodeTypes.contains(mixinType)) {
return false;
}
}
}
return true;
} | [
"public",
"boolean",
"isQueryable",
"(",
"Name",
"nodeTypeName",
",",
"Set",
"<",
"Name",
">",
"mixinTypes",
")",
"{",
"if",
"(",
"nonQueryableNodeTypes",
".",
"contains",
"(",
"nodeTypeName",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"... | Check if the node type and mixin types are queryable or not.
@param nodeTypeName a {@link Name}, never {@code null}
@param mixinTypes the mixin type names; may not be null but may be empty
@return {@code false} if at least one of the node types is not queryable, {@code true} otherwise | [
"Check",
"if",
"the",
"node",
"type",
"and",
"mixin",
"types",
"are",
"queryable",
"or",
"not",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/NodeTypes.java#L885-L897 |
jiaqi/caff | src/main/java/org/cyclopsgroup/caff/util/UUIDUtils.java | UUIDUtils.fromBytes | public static UUID fromBytes(byte[] bytes) {
"""
Convert byte array into UUID. Byte array is a compact form of bits in UUID
@param bytes Byte array to convert from
@return UUID result
"""
long mostBits = ByteUtils.readLong(bytes, 0);
long leastBits = 0;
if (bytes.length > 8) {
leastBits = ByteUtils.readLong(bytes, 8);
}
return new UUID(mostBits, leastBits);
} | java | public static UUID fromBytes(byte[] bytes) {
long mostBits = ByteUtils.readLong(bytes, 0);
long leastBits = 0;
if (bytes.length > 8) {
leastBits = ByteUtils.readLong(bytes, 8);
}
return new UUID(mostBits, leastBits);
} | [
"public",
"static",
"UUID",
"fromBytes",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"long",
"mostBits",
"=",
"ByteUtils",
".",
"readLong",
"(",
"bytes",
",",
"0",
")",
";",
"long",
"leastBits",
"=",
"0",
";",
"if",
"(",
"bytes",
".",
"length",
">",
... | Convert byte array into UUID. Byte array is a compact form of bits in UUID
@param bytes Byte array to convert from
@return UUID result | [
"Convert",
"byte",
"array",
"into",
"UUID",
".",
"Byte",
"array",
"is",
"a",
"compact",
"form",
"of",
"bits",
"in",
"UUID"
] | train | https://github.com/jiaqi/caff/blob/dba4b937a0afc844eb37ccf74dd04dd78f0c1314/src/main/java/org/cyclopsgroup/caff/util/UUIDUtils.java#L18-L25 |
soi-toolkit/soi-toolkit-mule | commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/rest/RestClient.java | RestClient.doHttpReceiveRequest | public MuleMessage doHttpReceiveRequest(String url, String method, String acceptConentType, String acceptCharSet) {
"""
Perform a HTTP call receiving information from the server using GET or DELETE
@param url
@param method, e.g. "GET" or "DELETE"
@param acceptConentType
@param acceptCharSet
@return
@throws MuleException
"""
Map<String, String> properties = new HashMap<String, String>();
properties.put("http.method", method);
properties.put("Accept", acceptConentType);
properties.put("Accept-Charset", acceptCharSet);
MuleMessage response = send(url, null, properties);
return response;
} | java | public MuleMessage doHttpReceiveRequest(String url, String method, String acceptConentType, String acceptCharSet) {
Map<String, String> properties = new HashMap<String, String>();
properties.put("http.method", method);
properties.put("Accept", acceptConentType);
properties.put("Accept-Charset", acceptCharSet);
MuleMessage response = send(url, null, properties);
return response;
} | [
"public",
"MuleMessage",
"doHttpReceiveRequest",
"(",
"String",
"url",
",",
"String",
"method",
",",
"String",
"acceptConentType",
",",
"String",
"acceptCharSet",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"properties",
"=",
"new",
"HashMap",
"<",
"St... | Perform a HTTP call receiving information from the server using GET or DELETE
@param url
@param method, e.g. "GET" or "DELETE"
@param acceptConentType
@param acceptCharSet
@return
@throws MuleException | [
"Perform",
"a",
"HTTP",
"call",
"receiving",
"information",
"from",
"the",
"server",
"using",
"GET",
"or",
"DELETE"
] | train | https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/rest/RestClient.java#L180-L190 |
NessComputing/components-ness-core | src/main/java/com/nesscomputing/callback/Callbacks.java | Callbacks.stream | @SafeVarargs
public static <T> void stream(Callback<T> callback, T... items) throws Exception {
"""
For every element, invoke the given callback.
Stops if {@link CallbackRefusedException} is thrown.
"""
stream(callback, Arrays.asList(items));
} | java | @SafeVarargs
public static <T> void stream(Callback<T> callback, T... items) throws Exception
{
stream(callback, Arrays.asList(items));
} | [
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"void",
"stream",
"(",
"Callback",
"<",
"T",
">",
"callback",
",",
"T",
"...",
"items",
")",
"throws",
"Exception",
"{",
"stream",
"(",
"callback",
",",
"Arrays",
".",
"asList",
"(",
"items",
")",
... | For every element, invoke the given callback.
Stops if {@link CallbackRefusedException} is thrown. | [
"For",
"every",
"element",
"invoke",
"the",
"given",
"callback",
".",
"Stops",
"if",
"{"
] | train | https://github.com/NessComputing/components-ness-core/blob/980db2925e5f9085c75ad3682d5314a973209297/src/main/java/com/nesscomputing/callback/Callbacks.java#L30-L34 |
windup/windup | rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/ast/TypeInterestFactory.java | TypeInterestFactory.registerInterest | public static void registerInterest(String sourceKey, String regex, String rewritePattern, TypeReferenceLocation... locations) {
"""
Register a regex pattern to filter interest in certain Java types.
@param sourceKey Identifier of who gave the pattern to us (so that we can update it).
This can be any arbitrary string.
"""
patternsBySource.put(sourceKey, new PatternAndLocation(locations, regex, rewritePattern));
} | java | public static void registerInterest(String sourceKey, String regex, String rewritePattern, TypeReferenceLocation... locations)
{
patternsBySource.put(sourceKey, new PatternAndLocation(locations, regex, rewritePattern));
} | [
"public",
"static",
"void",
"registerInterest",
"(",
"String",
"sourceKey",
",",
"String",
"regex",
",",
"String",
"rewritePattern",
",",
"TypeReferenceLocation",
"...",
"locations",
")",
"{",
"patternsBySource",
".",
"put",
"(",
"sourceKey",
",",
"new",
"PatternA... | Register a regex pattern to filter interest in certain Java types.
@param sourceKey Identifier of who gave the pattern to us (so that we can update it).
This can be any arbitrary string. | [
"Register",
"a",
"regex",
"pattern",
"to",
"filter",
"interest",
"in",
"certain",
"Java",
"types",
"."
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/ast/TypeInterestFactory.java#L98-L101 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgEndblk.java | DwgEndblk.readDwgEndblkV15 | public void readDwgEndblkV15(int[] data, int offset) throws Exception {
"""
Read a Endblk in the DWG format Version 15
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines.
"""
int bitPos = offset;
bitPos = readObjectHeaderV15(data, bitPos);
bitPos = readObjectTailV15(data, bitPos);
} | java | public void readDwgEndblkV15(int[] data, int offset) throws Exception {
int bitPos = offset;
bitPos = readObjectHeaderV15(data, bitPos);
bitPos = readObjectTailV15(data, bitPos);
} | [
"public",
"void",
"readDwgEndblkV15",
"(",
"int",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"throws",
"Exception",
"{",
"int",
"bitPos",
"=",
"offset",
";",
"bitPos",
"=",
"readObjectHeaderV15",
"(",
"data",
",",
"bitPos",
")",
";",
"bitPos",
"=",
"re... | Read a Endblk in the DWG format Version 15
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines. | [
"Read",
"a",
"Endblk",
"in",
"the",
"DWG",
"format",
"Version",
"15"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/objects/DwgEndblk.java#L38-L42 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/FunctionLibraryParser.java | FunctionLibraryParser.parseFunctionDefinitions | private void parseFunctionDefinitions(BeanDefinitionBuilder builder, Element element) {
"""
Parses all variable definitions and adds those to the bean definition
builder as property value.
@param builder the target bean definition builder.
@param element the source element.
"""
ManagedMap<String, Object> functions = new ManagedMap<String, Object>();
for (Element function : DomUtils.getChildElementsByTagName(element, "function")) {
if (function.hasAttribute("ref")) {
functions.put(function.getAttribute("name"), new RuntimeBeanReference(function.getAttribute("ref")));
} else {
functions.put(function.getAttribute("name"), BeanDefinitionBuilder.rootBeanDefinition(function.getAttribute("class")).getBeanDefinition());
}
}
if (!functions.isEmpty()) {
builder.addPropertyValue("members", functions);
}
} | java | private void parseFunctionDefinitions(BeanDefinitionBuilder builder, Element element) {
ManagedMap<String, Object> functions = new ManagedMap<String, Object>();
for (Element function : DomUtils.getChildElementsByTagName(element, "function")) {
if (function.hasAttribute("ref")) {
functions.put(function.getAttribute("name"), new RuntimeBeanReference(function.getAttribute("ref")));
} else {
functions.put(function.getAttribute("name"), BeanDefinitionBuilder.rootBeanDefinition(function.getAttribute("class")).getBeanDefinition());
}
}
if (!functions.isEmpty()) {
builder.addPropertyValue("members", functions);
}
} | [
"private",
"void",
"parseFunctionDefinitions",
"(",
"BeanDefinitionBuilder",
"builder",
",",
"Element",
"element",
")",
"{",
"ManagedMap",
"<",
"String",
",",
"Object",
">",
"functions",
"=",
"new",
"ManagedMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";... | Parses all variable definitions and adds those to the bean definition
builder as property value.
@param builder the target bean definition builder.
@param element the source element. | [
"Parses",
"all",
"variable",
"definitions",
"and",
"adds",
"those",
"to",
"the",
"bean",
"definition",
"builder",
"as",
"property",
"value",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/FunctionLibraryParser.java#L54-L67 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | StrBuilder.appendln | public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
"""
Appends part of a string builder followed by a new line to this string builder.
Appending null will call {@link #appendNull()}.
@param str the string builder to append
@param startIndex the start index, inclusive, must be valid
@param length the length to append, must be valid
@return this, to enable chaining
@since 3.2
"""
return append(str, startIndex, length).appendNewLine();
} | java | public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
} | [
"public",
"StrBuilder",
"appendln",
"(",
"final",
"StringBuilder",
"str",
",",
"final",
"int",
"startIndex",
",",
"final",
"int",
"length",
")",
"{",
"return",
"append",
"(",
"str",
",",
"startIndex",
",",
"length",
")",
".",
"appendNewLine",
"(",
")",
";"... | Appends part of a string builder followed by a new line to this string builder.
Appending null will call {@link #appendNull()}.
@param str the string builder to append
@param startIndex the start index, inclusive, must be valid
@param length the length to append, must be valid
@return this, to enable chaining
@since 3.2 | [
"Appends",
"part",
"of",
"a",
"string",
"builder",
"followed",
"by",
"a",
"new",
"line",
"to",
"this",
"string",
"builder",
".",
"Appending",
"null",
"will",
"call",
"{",
"@link",
"#appendNull",
"()",
"}",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L1042-L1044 |
phax/ph-commons | ph-xml/src/main/java/com/helger/xml/serialize/write/XMLWriter.java | XMLWriter.getNodeAsString | @Nullable
public static String getNodeAsString (@Nonnull final Node aNode, @Nonnull final IXMLWriterSettings aSettings) {
"""
Convert the passed DOM node to an XML string using the provided XML writer
settings.
@param aNode
The node to be converted to a string. May not be <code>null</code> .
@param aSettings
The XML writer settings to be used. May not be <code>null</code>.
@return The string representation of the passed node.
@since 8.6.3
"""
// start serializing
try (final NonBlockingStringWriter aWriter = new NonBlockingStringWriter (50 * CGlobal.BYTES_PER_KILOBYTE))
{
if (writeToWriter (aNode, aWriter, aSettings).isSuccess ())
{
s_aSizeHdl.addSize (aWriter.size ());
return aWriter.getAsString ();
}
}
catch (final Exception ex)
{
if (LOGGER.isErrorEnabled ())
LOGGER.error ("Error serializing DOM node with settings " + aSettings.toString (), ex);
}
return null;
} | java | @Nullable
public static String getNodeAsString (@Nonnull final Node aNode, @Nonnull final IXMLWriterSettings aSettings)
{
// start serializing
try (final NonBlockingStringWriter aWriter = new NonBlockingStringWriter (50 * CGlobal.BYTES_PER_KILOBYTE))
{
if (writeToWriter (aNode, aWriter, aSettings).isSuccess ())
{
s_aSizeHdl.addSize (aWriter.size ());
return aWriter.getAsString ();
}
}
catch (final Exception ex)
{
if (LOGGER.isErrorEnabled ())
LOGGER.error ("Error serializing DOM node with settings " + aSettings.toString (), ex);
}
return null;
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getNodeAsString",
"(",
"@",
"Nonnull",
"final",
"Node",
"aNode",
",",
"@",
"Nonnull",
"final",
"IXMLWriterSettings",
"aSettings",
")",
"{",
"// start serializing",
"try",
"(",
"final",
"NonBlockingStringWriter",
"aWrit... | Convert the passed DOM node to an XML string using the provided XML writer
settings.
@param aNode
The node to be converted to a string. May not be <code>null</code> .
@param aSettings
The XML writer settings to be used. May not be <code>null</code>.
@return The string representation of the passed node.
@since 8.6.3 | [
"Convert",
"the",
"passed",
"DOM",
"node",
"to",
"an",
"XML",
"string",
"using",
"the",
"provided",
"XML",
"writer",
"settings",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/serialize/write/XMLWriter.java#L202-L220 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/ajax/editable/tabs/AjaxAddableTabbedPanel.java | AjaxAddableTabbedPanel.newTabsLoop | protected Loop newTabsLoop(final String id, final IModel<Integer> model) {
"""
Factory method for creating a new {@link Loop} for the tabs.
@param id
the id
@param model
the model
@return the new {@link Loop} for the tabs.
"""
final Loop localTabsLoop = new Loop(id, model)
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected LoopItem newItem(final int iteration)
{
return newTabContainer(iteration);
}
/**
* {@inheritDoc}
*/
@Override
protected void populateItem(final LoopItem item)
{
final int index = item.getIndex();
final T tab = AjaxAddableTabbedPanel.this.tabs.get(index);
final WebMarkupContainer titleCloseLink = newCloseLink("closeTab", index);
titleCloseLink.add(newCloseTitle("closeTitle", tab.getCloseTitle(), index));
item.add(titleCloseLink);
final WebMarkupContainer titleLink = newLink("link", index);
titleLink.add(newTitle("title", tab.getTitle(), index));
item.add(titleLink);
item.add(new AttributeAppender("class", " label"));
}
};
localTabsLoop.setOutputMarkupId(true);
return localTabsLoop;
} | java | protected Loop newTabsLoop(final String id, final IModel<Integer> model)
{
final Loop localTabsLoop = new Loop(id, model)
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected LoopItem newItem(final int iteration)
{
return newTabContainer(iteration);
}
/**
* {@inheritDoc}
*/
@Override
protected void populateItem(final LoopItem item)
{
final int index = item.getIndex();
final T tab = AjaxAddableTabbedPanel.this.tabs.get(index);
final WebMarkupContainer titleCloseLink = newCloseLink("closeTab", index);
titleCloseLink.add(newCloseTitle("closeTitle", tab.getCloseTitle(), index));
item.add(titleCloseLink);
final WebMarkupContainer titleLink = newLink("link", index);
titleLink.add(newTitle("title", tab.getTitle(), index));
item.add(titleLink);
item.add(new AttributeAppender("class", " label"));
}
};
localTabsLoop.setOutputMarkupId(true);
return localTabsLoop;
} | [
"protected",
"Loop",
"newTabsLoop",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"Integer",
">",
"model",
")",
"{",
"final",
"Loop",
"localTabsLoop",
"=",
"new",
"Loop",
"(",
"id",
",",
"model",
")",
"{",
"/** The Constant serialVersionUID. */",
... | Factory method for creating a new {@link Loop} for the tabs.
@param id
the id
@param model
the model
@return the new {@link Loop} for the tabs. | [
"Factory",
"method",
"for",
"creating",
"a",
"new",
"{",
"@link",
"Loop",
"}",
"for",
"the",
"tabs",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/ajax/editable/tabs/AjaxAddableTabbedPanel.java#L589-L629 |
actframework/actframework | src/main/java/act/ws/WebSocketConnectionManager.java | WebSocketConnectionManager.sendJsonToTagged | public void sendJsonToTagged(Object data, String label) {
"""
Send JSON representation of given data object to all connections tagged with
given label
@param data the data object
@param label the tag label
"""
sendToTagged(JSON.toJSONString(data), label);
} | java | public void sendJsonToTagged(Object data, String label) {
sendToTagged(JSON.toJSONString(data), label);
} | [
"public",
"void",
"sendJsonToTagged",
"(",
"Object",
"data",
",",
"String",
"label",
")",
"{",
"sendToTagged",
"(",
"JSON",
".",
"toJSONString",
"(",
"data",
")",
",",
"label",
")",
";",
"}"
] | Send JSON representation of given data object to all connections tagged with
given label
@param data the data object
@param label the tag label | [
"Send",
"JSON",
"representation",
"of",
"given",
"data",
"object",
"to",
"all",
"connections",
"tagged",
"with",
"given",
"label"
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L170-L172 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.replaceWhere | public SDVariable replaceWhere(String name, SDVariable update, Number value, Condition condition) {
"""
Element-wise replace where condition:<br>
out[i] = value if condition(update[i]) is satisfied, or<br>
out[i] = update[i] if condition(update[i]) is NOT satisfied
@param name Name of the output variable
@param update Source array
@param value Value to set at the output, if the condition is satisfied
@param condition Condition to check on update array elements
@return New array with values replaced where condition is satisfied
"""
SDVariable ret = f().replaceWhere(update, value, condition);
return updateVariableNameAndReference(ret, name);
} | java | public SDVariable replaceWhere(String name, SDVariable update, Number value, Condition condition) {
SDVariable ret = f().replaceWhere(update, value, condition);
return updateVariableNameAndReference(ret, name);
} | [
"public",
"SDVariable",
"replaceWhere",
"(",
"String",
"name",
",",
"SDVariable",
"update",
",",
"Number",
"value",
",",
"Condition",
"condition",
")",
"{",
"SDVariable",
"ret",
"=",
"f",
"(",
")",
".",
"replaceWhere",
"(",
"update",
",",
"value",
",",
"co... | Element-wise replace where condition:<br>
out[i] = value if condition(update[i]) is satisfied, or<br>
out[i] = update[i] if condition(update[i]) is NOT satisfied
@param name Name of the output variable
@param update Source array
@param value Value to set at the output, if the condition is satisfied
@param condition Condition to check on update array elements
@return New array with values replaced where condition is satisfied | [
"Element",
"-",
"wise",
"replace",
"where",
"condition",
":",
"<br",
">",
"out",
"[",
"i",
"]",
"=",
"value",
"if",
"condition",
"(",
"update",
"[",
"i",
"]",
")",
"is",
"satisfied",
"or<br",
">",
"out",
"[",
"i",
"]",
"=",
"update",
"[",
"i",
"]... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L1747-L1750 |
fcrepo3/fcrepo | fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java | JRDF.samePredicate | public static boolean samePredicate(PredicateNode p1, PredicateNode p2) {
"""
Tells whether the given predicates are equivalent.
<p>
Two predicates are equivalent if they match according to the rules for
resources.
@param p1
first predicate.
@param p2
second predicate.
@return true if equivalent, false otherwise.
"""
return sameResource((URIReference) p1, (URIReference) p2);
} | java | public static boolean samePredicate(PredicateNode p1, PredicateNode p2) {
return sameResource((URIReference) p1, (URIReference) p2);
} | [
"public",
"static",
"boolean",
"samePredicate",
"(",
"PredicateNode",
"p1",
",",
"PredicateNode",
"p2",
")",
"{",
"return",
"sameResource",
"(",
"(",
"URIReference",
")",
"p1",
",",
"(",
"URIReference",
")",
"p2",
")",
";",
"}"
] | Tells whether the given predicates are equivalent.
<p>
Two predicates are equivalent if they match according to the rules for
resources.
@param p1
first predicate.
@param p2
second predicate.
@return true if equivalent, false otherwise. | [
"Tells",
"whether",
"the",
"given",
"predicates",
"are",
"equivalent",
".",
"<p",
">",
"Two",
"predicates",
"are",
"equivalent",
"if",
"they",
"match",
"according",
"to",
"the",
"rules",
"for",
"resources",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-common/src/main/java/org/fcrepo/common/rdf/JRDF.java#L171-L173 |
synchronoss/cpo-api | cpo-jdbc/src/main/java/org/synchronoss/cpo/transform/jdbc/TransformBlob.java | TransformBlob.transformOut | @Override
public Blob transformOut(JdbcPreparedStatementFactory jpsf, byte[] attributeObject) throws CpoException {
"""
Transforms the data from the class attribute to the object required by the datasource
@param cpoAdapter The CpoAdapter for the datasource where the attribute is being persisted
@param parentObject The object that contains the attribute being persisted.
@param attributeObject The object that represents the attribute being persisted.
@return The object to be stored in the datasource
@throws CpoException
"""
BLOB newBlob = null;
try {
if (attributeObject != null) {
newBlob = BLOB.createTemporary(jpsf.getPreparedStatement().getConnection(), false, BLOB.DURATION_SESSION);
jpsf.AddReleasible(new OracleTemporaryBlob(newBlob));
//OutputStream os = newBlob.getBinaryOutputStream();
OutputStream os = newBlob.setBinaryStream(0);
os.write(attributeObject);
os.close();
}
} catch (Exception e) {
String msg = "Error BLOBing Byte Array";
logger.error(msg, e);
throw new CpoException(msg, e);
}
return newBlob;
} | java | @Override
public Blob transformOut(JdbcPreparedStatementFactory jpsf, byte[] attributeObject) throws CpoException {
BLOB newBlob = null;
try {
if (attributeObject != null) {
newBlob = BLOB.createTemporary(jpsf.getPreparedStatement().getConnection(), false, BLOB.DURATION_SESSION);
jpsf.AddReleasible(new OracleTemporaryBlob(newBlob));
//OutputStream os = newBlob.getBinaryOutputStream();
OutputStream os = newBlob.setBinaryStream(0);
os.write(attributeObject);
os.close();
}
} catch (Exception e) {
String msg = "Error BLOBing Byte Array";
logger.error(msg, e);
throw new CpoException(msg, e);
}
return newBlob;
} | [
"@",
"Override",
"public",
"Blob",
"transformOut",
"(",
"JdbcPreparedStatementFactory",
"jpsf",
",",
"byte",
"[",
"]",
"attributeObject",
")",
"throws",
"CpoException",
"{",
"BLOB",
"newBlob",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"attributeObject",
"!=",
"... | Transforms the data from the class attribute to the object required by the datasource
@param cpoAdapter The CpoAdapter for the datasource where the attribute is being persisted
@param parentObject The object that contains the attribute being persisted.
@param attributeObject The object that represents the attribute being persisted.
@return The object to be stored in the datasource
@throws CpoException | [
"Transforms",
"the",
"data",
"from",
"the",
"class",
"attribute",
"to",
"the",
"object",
"required",
"by",
"the",
"datasource"
] | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/transform/jdbc/TransformBlob.java#L87-L108 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java | SecStrucCalc.calc_H | @SuppressWarnings("unused")
private static Atom calc_H(Atom C, Atom N, Atom CA)
throws StructureException {
"""
Use unit vectors NC and NCalpha Add them. Calc unit vector and
substract it from N.
C coordinates are from amino acid i-1
N, CA atoms from amino acid i
@link http://openbioinformatics.blogspot.com/
2009/08/how-to-calculate-h-atoms-for-nitrogens.html
"""
Atom nc = Calc.subtract(N,C);
Atom nca = Calc.subtract(N,CA);
Atom u_nc = Calc.unitVector(nc) ;
Atom u_nca = Calc.unitVector(nca);
Atom added = Calc.add(u_nc,u_nca);
Atom U = Calc.unitVector(added);
// according to Creighton distance N-H is 1.03 +/- 0.02A
Atom H = Calc.add(N,U);
H.setName("H");
// this atom does not have a pdbserial number ...
return H;
} | java | @SuppressWarnings("unused")
private static Atom calc_H(Atom C, Atom N, Atom CA)
throws StructureException {
Atom nc = Calc.subtract(N,C);
Atom nca = Calc.subtract(N,CA);
Atom u_nc = Calc.unitVector(nc) ;
Atom u_nca = Calc.unitVector(nca);
Atom added = Calc.add(u_nc,u_nca);
Atom U = Calc.unitVector(added);
// according to Creighton distance N-H is 1.03 +/- 0.02A
Atom H = Calc.add(N,U);
H.setName("H");
// this atom does not have a pdbserial number ...
return H;
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"private",
"static",
"Atom",
"calc_H",
"(",
"Atom",
"C",
",",
"Atom",
"N",
",",
"Atom",
"CA",
")",
"throws",
"StructureException",
"{",
"Atom",
"nc",
"=",
"Calc",
".",
"subtract",
"(",
"N",
",",
"C",
")"... | Use unit vectors NC and NCalpha Add them. Calc unit vector and
substract it from N.
C coordinates are from amino acid i-1
N, CA atoms from amino acid i
@link http://openbioinformatics.blogspot.com/
2009/08/how-to-calculate-h-atoms-for-nitrogens.html | [
"Use",
"unit",
"vectors",
"NC",
"and",
"NCalpha",
"Add",
"them",
".",
"Calc",
"unit",
"vector",
"and",
"substract",
"it",
"from",
"N",
".",
"C",
"coordinates",
"are",
"from",
"amino",
"acid",
"i",
"-",
"1",
"N",
"CA",
"atoms",
"from",
"amino",
"acid",
... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java#L1011-L1032 |
Coolerfall/Android-HttpDownloadManager | library/src/main/java/com/coolerfall/download/DownloadDelivery.java | DownloadDelivery.postProgress | void postProgress(final DownloadRequest request, final long bytesWritten, final long totalBytes) {
"""
Post download progress event.
@param request download request
@param bytesWritten the bytes have written to file
@param totalBytes the total bytes of currnet file in downloading
"""
downloadPoster.execute(new Runnable() {
@Override public void run() {
request.downloadCallback().onProgress(request.downloadId(), bytesWritten, totalBytes);
}
});
} | java | void postProgress(final DownloadRequest request, final long bytesWritten, final long totalBytes) {
downloadPoster.execute(new Runnable() {
@Override public void run() {
request.downloadCallback().onProgress(request.downloadId(), bytesWritten, totalBytes);
}
});
} | [
"void",
"postProgress",
"(",
"final",
"DownloadRequest",
"request",
",",
"final",
"long",
"bytesWritten",
",",
"final",
"long",
"totalBytes",
")",
"{",
"downloadPoster",
".",
"execute",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
... | Post download progress event.
@param request download request
@param bytesWritten the bytes have written to file
@param totalBytes the total bytes of currnet file in downloading | [
"Post",
"download",
"progress",
"event",
"."
] | train | https://github.com/Coolerfall/Android-HttpDownloadManager/blob/2b32451c1799c77708c12bf8155e43c7dc25bc57/library/src/main/java/com/coolerfall/download/DownloadDelivery.java#L57-L63 |
facebookarchive/hadoop-20 | src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/SimpleSeekableFormatInputStream.java | SimpleSeekableFormatInputStream.createInterleavedInputStream | protected InterleavedInputStream createInterleavedInputStream(InputStream in,
int metaDataBlockLength, int dataBlockLength,
SimpleSeekableFormat.MetaDataConsumer consumer) {
"""
This factory method can be overwritten by subclass to provide different behavior.
It's only called in the constructor.
"""
return new InterleavedInputStream(in, metaDataBlockLength, dataBlockLength, consumer);
} | java | protected InterleavedInputStream createInterleavedInputStream(InputStream in,
int metaDataBlockLength, int dataBlockLength,
SimpleSeekableFormat.MetaDataConsumer consumer) {
return new InterleavedInputStream(in, metaDataBlockLength, dataBlockLength, consumer);
} | [
"protected",
"InterleavedInputStream",
"createInterleavedInputStream",
"(",
"InputStream",
"in",
",",
"int",
"metaDataBlockLength",
",",
"int",
"dataBlockLength",
",",
"SimpleSeekableFormat",
".",
"MetaDataConsumer",
"consumer",
")",
"{",
"return",
"new",
"InterleavedInputS... | This factory method can be overwritten by subclass to provide different behavior.
It's only called in the constructor. | [
"This",
"factory",
"method",
"can",
"be",
"overwritten",
"by",
"subclass",
"to",
"provide",
"different",
"behavior",
".",
"It",
"s",
"only",
"called",
"in",
"the",
"constructor",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/seekablecompression/src/java/org/apache/hadoop/io/simpleseekableformat/SimpleSeekableFormatInputStream.java#L54-L58 |
fabric8io/fabric8-forge | addons/utils/src/main/java/io/fabric8/forge/addon/utils/MavenHelpers.java | MavenHelpers.getVersion | public static String getVersion(String groupId, String artifactId) {
"""
Returns the version from the list of pre-configured versions of common groupId/artifact pairs
"""
String key = "" + groupId + "/" + artifactId;
Map<String, String> map = getGroupArtifactVersionMap();
String version = map.get(key);
if (version == null) {
getLOG().warn("Could not find the version for groupId: " + groupId + " artifactId: " + artifactId + " in: " + map);
}
return version;
} | java | public static String getVersion(String groupId, String artifactId) {
String key = "" + groupId + "/" + artifactId;
Map<String, String> map = getGroupArtifactVersionMap();
String version = map.get(key);
if (version == null) {
getLOG().warn("Could not find the version for groupId: " + groupId + " artifactId: " + artifactId + " in: " + map);
}
return version;
} | [
"public",
"static",
"String",
"getVersion",
"(",
"String",
"groupId",
",",
"String",
"artifactId",
")",
"{",
"String",
"key",
"=",
"\"\"",
"+",
"groupId",
"+",
"\"/\"",
"+",
"artifactId",
";",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"getGro... | Returns the version from the list of pre-configured versions of common groupId/artifact pairs | [
"Returns",
"the",
"version",
"from",
"the",
"list",
"of",
"pre",
"-",
"configured",
"versions",
"of",
"common",
"groupId",
"/",
"artifact",
"pairs"
] | train | https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/utils/src/main/java/io/fabric8/forge/addon/utils/MavenHelpers.java#L152-L160 |
Azure/azure-sdk-for-java | edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java | DevicesInner.downloadUpdatesAsync | public Observable<Void> downloadUpdatesAsync(String deviceName, String resourceGroupName) {
"""
Downloads the updates on a data box edge/gateway device.
@param deviceName The device name.
@param resourceGroupName The resource group name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return downloadUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> downloadUpdatesAsync(String deviceName, String resourceGroupName) {
return downloadUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"downloadUpdatesAsync",
"(",
"String",
"deviceName",
",",
"String",
"resourceGroupName",
")",
"{",
"return",
"downloadUpdatesWithServiceResponseAsync",
"(",
"deviceName",
",",
"resourceGroupName",
")",
".",
"map",
"(",
"new",
... | Downloads the updates on a data box edge/gateway device.
@param deviceName The device name.
@param resourceGroupName The resource group name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Downloads",
"the",
"updates",
"on",
"a",
"data",
"box",
"edge",
"/",
"gateway",
"device",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1227-L1234 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jEntityQueries.java | EmbeddedNeo4jEntityQueries.findEntities | public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine, EntityKey[] keys) {
"""
Find the nodes corresponding to an array of entity keys.
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param keys an array of keys identifying the nodes to return
@return the list of nodes representing the entities
"""
if ( singlePropertyKey ) {
return singlePropertyIdFindEntities( executionEngine, keys );
}
else {
return multiPropertiesIdFindEntities( executionEngine, keys );
}
} | java | public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine, EntityKey[] keys) {
if ( singlePropertyKey ) {
return singlePropertyIdFindEntities( executionEngine, keys );
}
else {
return multiPropertiesIdFindEntities( executionEngine, keys );
}
} | [
"public",
"ResourceIterator",
"<",
"Node",
">",
"findEntities",
"(",
"GraphDatabaseService",
"executionEngine",
",",
"EntityKey",
"[",
"]",
"keys",
")",
"{",
"if",
"(",
"singlePropertyKey",
")",
"{",
"return",
"singlePropertyIdFindEntities",
"(",
"executionEngine",
... | Find the nodes corresponding to an array of entity keys.
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param keys an array of keys identifying the nodes to return
@return the list of nodes representing the entities | [
"Find",
"the",
"nodes",
"corresponding",
"to",
"an",
"array",
"of",
"entity",
"keys",
"."
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jEntityQueries.java#L92-L99 |
apache/incubator-druid | extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchMergeBufferAggregator.java | DoublesSketchMergeBufferAggregator.relocate | @Override
public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer) {
"""
In that case we need to reuse the object from the cache as opposed to wrapping the new buffer.
"""
DoublesUnion union = unions.get(oldBuffer).get(oldPosition);
final WritableMemory oldMem = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize);
if (union.isSameResource(oldMem)) { // union was not relocated on heap
final WritableMemory newMem = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize);
union = DoublesUnion.wrap(newMem);
}
putUnion(newBuffer, newPosition, union);
Int2ObjectMap<DoublesUnion> map = unions.get(oldBuffer);
map.remove(oldPosition);
if (map.isEmpty()) {
unions.remove(oldBuffer);
memCache.remove(oldBuffer);
}
} | java | @Override
public synchronized void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer)
{
DoublesUnion union = unions.get(oldBuffer).get(oldPosition);
final WritableMemory oldMem = getMemory(oldBuffer).writableRegion(oldPosition, maxIntermediateSize);
if (union.isSameResource(oldMem)) { // union was not relocated on heap
final WritableMemory newMem = getMemory(newBuffer).writableRegion(newPosition, maxIntermediateSize);
union = DoublesUnion.wrap(newMem);
}
putUnion(newBuffer, newPosition, union);
Int2ObjectMap<DoublesUnion> map = unions.get(oldBuffer);
map.remove(oldPosition);
if (map.isEmpty()) {
unions.remove(oldBuffer);
memCache.remove(oldBuffer);
}
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"relocate",
"(",
"int",
"oldPosition",
",",
"int",
"newPosition",
",",
"ByteBuffer",
"oldBuffer",
",",
"ByteBuffer",
"newBuffer",
")",
"{",
"DoublesUnion",
"union",
"=",
"unions",
".",
"get",
"(",
"oldBuffer",
... | In that case we need to reuse the object from the cache as opposed to wrapping the new buffer. | [
"In",
"that",
"case",
"we",
"need",
"to",
"reuse",
"the",
"object",
"from",
"the",
"cache",
"as",
"opposed",
"to",
"wrapping",
"the",
"new",
"buffer",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/quantiles/DoublesSketchMergeBufferAggregator.java#L100-L117 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AoImplCodeGen.java | AoImplCodeGen.writeClassBody | @Override
public void writeClassBody(Definition def, Writer out) throws IOException {
"""
Output class
@param def definition
@param out Writer
@throws IOException ioException
"""
if (def.isUseAnnotation())
{
out.write("@AdministeredObject(adminObjectInterfaces = { ");
out.write(def.getAdminObjects().get(numOfAo).getAdminObjectInterface());
out.write(".class })\n");
}
out.write("public class " + getClassName(def) + " implements " +
def.getAdminObjects().get(numOfAo).getAdminObjectInterface());
if (def.isAdminObjectImplRaAssociation())
{
out.write(",\n");
writeIndent(out, 1);
out.write("ResourceAdapterAssociation, Referenceable, Serializable");
}
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeIndent(out, indent);
out.write("/** Serial version uid */\n");
writeIndent(out, indent);
out.write("private static final long serialVersionUID = 1L;\n\n");
if (def.isAdminObjectImplRaAssociation())
{
writeWithIndent(out, indent, "/** The resource adapter */\n");
writeIndent(out, indent);
if (def.isRaSerial())
{
out.write("private ResourceAdapter ra;\n\n");
}
else
{
out.write("private transient ResourceAdapter ra;\n\n");
}
writeWithIndent(out, indent, "/** Reference */\n");
writeWithIndent(out, indent, "private Reference reference;\n\n");
}
writeConfigPropsDeclare(def, out, indent);
writeDefaultConstructor(def, out, indent);
writeConfigProps(def, out, indent);
if (def.isAdminObjectImplRaAssociation())
{
writeResourceAdapter(def, out, indent);
writeReference(def, out, indent);
}
writeHashCode(def, out, indent);
writeEquals(def, out, indent);
writeRightCurlyBracket(out, 0);
} | java | @Override
public void writeClassBody(Definition def, Writer out) throws IOException
{
if (def.isUseAnnotation())
{
out.write("@AdministeredObject(adminObjectInterfaces = { ");
out.write(def.getAdminObjects().get(numOfAo).getAdminObjectInterface());
out.write(".class })\n");
}
out.write("public class " + getClassName(def) + " implements " +
def.getAdminObjects().get(numOfAo).getAdminObjectInterface());
if (def.isAdminObjectImplRaAssociation())
{
out.write(",\n");
writeIndent(out, 1);
out.write("ResourceAdapterAssociation, Referenceable, Serializable");
}
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeIndent(out, indent);
out.write("/** Serial version uid */\n");
writeIndent(out, indent);
out.write("private static final long serialVersionUID = 1L;\n\n");
if (def.isAdminObjectImplRaAssociation())
{
writeWithIndent(out, indent, "/** The resource adapter */\n");
writeIndent(out, indent);
if (def.isRaSerial())
{
out.write("private ResourceAdapter ra;\n\n");
}
else
{
out.write("private transient ResourceAdapter ra;\n\n");
}
writeWithIndent(out, indent, "/** Reference */\n");
writeWithIndent(out, indent, "private Reference reference;\n\n");
}
writeConfigPropsDeclare(def, out, indent);
writeDefaultConstructor(def, out, indent);
writeConfigProps(def, out, indent);
if (def.isAdminObjectImplRaAssociation())
{
writeResourceAdapter(def, out, indent);
writeReference(def, out, indent);
}
writeHashCode(def, out, indent);
writeEquals(def, out, indent);
writeRightCurlyBracket(out, 0);
} | [
"@",
"Override",
"public",
"void",
"writeClassBody",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"def",
".",
"isUseAnnotation",
"(",
")",
")",
"{",
"out",
".",
"write",
"(",
"\"@AdministeredObject(adminObjectIn... | Output class
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"class"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AoImplCodeGen.java#L87-L143 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.createGraphicsShapes | public java.awt.Graphics2D createGraphicsShapes(float width, float height) {
"""
Gets a <CODE>Graphics2D</CODE> to write on. The graphics
are translated to PDF commands as shapes. No PDF fonts will appear.
@param width the width of the panel
@param height the height of the panel
@return a <CODE>Graphics2D</CODE>
"""
return new PdfGraphics2D(this, width, height, null, true, false, 0);
} | java | public java.awt.Graphics2D createGraphicsShapes(float width, float height) {
return new PdfGraphics2D(this, width, height, null, true, false, 0);
} | [
"public",
"java",
".",
"awt",
".",
"Graphics2D",
"createGraphicsShapes",
"(",
"float",
"width",
",",
"float",
"height",
")",
"{",
"return",
"new",
"PdfGraphics2D",
"(",
"this",
",",
"width",
",",
"height",
",",
"null",
",",
"true",
",",
"false",
",",
"0"... | Gets a <CODE>Graphics2D</CODE> to write on. The graphics
are translated to PDF commands as shapes. No PDF fonts will appear.
@param width the width of the panel
@param height the height of the panel
@return a <CODE>Graphics2D</CODE> | [
"Gets",
"a",
"<CODE",
">",
"Graphics2D<",
"/",
"CODE",
">",
"to",
"write",
"on",
".",
"The",
"graphics",
"are",
"translated",
"to",
"PDF",
"commands",
"as",
"shapes",
".",
"No",
"PDF",
"fonts",
"will",
"appear",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L2791-L2793 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/InstanceHelpers.java | InstanceHelpers.insertChild | public static void insertChild( Instance parent, Instance child ) {
"""
Inserts a child instance.
<p>
This method does not check anything.
In real implementations, such as in the DM, one should
use {@link #tryToInsertChildInstance(AbstractApplication, Instance, Instance)}.
</p>
@param child a child instance (not null)
@param parent a parent instance (not null)
"""
child.setParent( parent );
parent.getChildren().add( child );
} | java | public static void insertChild( Instance parent, Instance child ) {
child.setParent( parent );
parent.getChildren().add( child );
} | [
"public",
"static",
"void",
"insertChild",
"(",
"Instance",
"parent",
",",
"Instance",
"child",
")",
"{",
"child",
".",
"setParent",
"(",
"parent",
")",
";",
"parent",
".",
"getChildren",
"(",
")",
".",
"add",
"(",
"child",
")",
";",
"}"
] | Inserts a child instance.
<p>
This method does not check anything.
In real implementations, such as in the DM, one should
use {@link #tryToInsertChildInstance(AbstractApplication, Instance, Instance)}.
</p>
@param child a child instance (not null)
@param parent a parent instance (not null) | [
"Inserts",
"a",
"child",
"instance",
".",
"<p",
">",
"This",
"method",
"does",
"not",
"check",
"anything",
".",
"In",
"real",
"implementations",
"such",
"as",
"in",
"the",
"DM",
"one",
"should",
"use",
"{",
"@link",
"#tryToInsertChildInstance",
"(",
"Abstrac... | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/helpers/InstanceHelpers.java#L166-L169 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTimeoutWarningRenderer.java | WTimeoutWarningRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
"""
Paints the given WTimeoutWarning if the component's timeout period is greater than 0.
@param component the WTimeoutWarning to paint.
@param renderContext the RenderContext to paint to.
"""
WTimeoutWarning warning = (WTimeoutWarning) component;
XmlStringBuilder xml = renderContext.getWriter();
final int timoutPeriod = warning.getTimeoutPeriod();
if (timoutPeriod > 0) {
xml.appendTagOpen("ui:session");
xml.appendAttribute("timeout", String.valueOf(timoutPeriod));
int warningPeriod = warning.getWarningPeriod();
xml.appendOptionalAttribute("warn", warningPeriod > 0, warningPeriod);
xml.appendEnd();
}
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WTimeoutWarning warning = (WTimeoutWarning) component;
XmlStringBuilder xml = renderContext.getWriter();
final int timoutPeriod = warning.getTimeoutPeriod();
if (timoutPeriod > 0) {
xml.appendTagOpen("ui:session");
xml.appendAttribute("timeout", String.valueOf(timoutPeriod));
int warningPeriod = warning.getWarningPeriod();
xml.appendOptionalAttribute("warn", warningPeriod > 0, warningPeriod);
xml.appendEnd();
}
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WTimeoutWarning",
"warning",
"=",
"(",
"WTimeoutWarning",
")",
"component",
";",
"XmlStringBuilder",
"xml",
"=",
... | Paints the given WTimeoutWarning if the component's timeout period is greater than 0.
@param component the WTimeoutWarning to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WTimeoutWarning",
"if",
"the",
"component",
"s",
"timeout",
"period",
"is",
"greater",
"than",
"0",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTimeoutWarningRenderer.java#L22-L36 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java | CPDefinitionPersistenceImpl.findByC_S | @Override
public List<CPDefinition> findByC_S(long CProductId, int status, int start,
int end, OrderByComparator<CPDefinition> orderByComparator) {
"""
Returns an ordered range of all the cp definitions where CProductId = ? and status = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CProductId the c product ID
@param status the status
@param start the lower bound of the range of cp definitions
@param end the upper bound of the range of cp definitions (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching cp definitions
"""
return findByC_S(CProductId, status, start, end, orderByComparator, true);
} | java | @Override
public List<CPDefinition> findByC_S(long CProductId, int status, int start,
int end, OrderByComparator<CPDefinition> orderByComparator) {
return findByC_S(CProductId, status, start, end, orderByComparator, true);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinition",
">",
"findByC_S",
"(",
"long",
"CProductId",
",",
"int",
"status",
",",
"int",
"start",
",",
"int",
"end",
",",
"OrderByComparator",
"<",
"CPDefinition",
">",
"orderByComparator",
")",
"{",
"return",
"f... | Returns an ordered range of all the cp definitions where CProductId = ? and status = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CProductId the c product ID
@param status the status
@param start the lower bound of the range of cp definitions
@param end the upper bound of the range of cp definitions (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching cp definitions | [
"Returns",
"an",
"ordered",
"range",
"of",
"all",
"the",
"cp",
"definitions",
"where",
"CProductId",
"=",
"?",
";",
"and",
"status",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java#L4139-L4143 |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/V1JsExprTranslator.java | V1JsExprTranslator.getLocalVarTranslation | @Nullable
private static String getLocalVarTranslation(String ident, SoyToJsVariableMappings mappings) {
"""
Gets the translated expression for an in-scope local variable (or special "variable" derived
from a foreach-loop var), or null if not found.
@param ident The Soy local variable to translate.
@param mappings The replacement JS expressions for the local variables (and foreach-loop
special functions) current in scope.
@return The translated string for the given variable, or null if not found.
"""
Expression translation = mappings.maybeGet(ident);
if (translation == null) {
return null;
}
JsExpr asExpr = translation.assertExpr();
return asExpr.getPrecedence() != Integer.MAX_VALUE
? "(" + asExpr.getText() + ")"
: asExpr.getText();
} | java | @Nullable
private static String getLocalVarTranslation(String ident, SoyToJsVariableMappings mappings) {
Expression translation = mappings.maybeGet(ident);
if (translation == null) {
return null;
}
JsExpr asExpr = translation.assertExpr();
return asExpr.getPrecedence() != Integer.MAX_VALUE
? "(" + asExpr.getText() + ")"
: asExpr.getText();
} | [
"@",
"Nullable",
"private",
"static",
"String",
"getLocalVarTranslation",
"(",
"String",
"ident",
",",
"SoyToJsVariableMappings",
"mappings",
")",
"{",
"Expression",
"translation",
"=",
"mappings",
".",
"maybeGet",
"(",
"ident",
")",
";",
"if",
"(",
"translation",... | Gets the translated expression for an in-scope local variable (or special "variable" derived
from a foreach-loop var), or null if not found.
@param ident The Soy local variable to translate.
@param mappings The replacement JS expressions for the local variables (and foreach-loop
special functions) current in scope.
@return The translated string for the given variable, or null if not found. | [
"Gets",
"the",
"translated",
"expression",
"for",
"an",
"in",
"-",
"scope",
"local",
"variable",
"(",
"or",
"special",
"variable",
"derived",
"from",
"a",
"foreach",
"-",
"loop",
"var",
")",
"or",
"null",
"if",
"not",
"found",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/V1JsExprTranslator.java#L171-L181 |
apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java | SchedulerStateManagerAdaptor.getPackingPlan | public PackingPlans.PackingPlan getPackingPlan(String topologyName) {
"""
Get the packing plan for the given topology
@return PackingPlans.PackingPlan
"""
return awaitResult(delegate.getPackingPlan(null, topologyName));
} | java | public PackingPlans.PackingPlan getPackingPlan(String topologyName) {
return awaitResult(delegate.getPackingPlan(null, topologyName));
} | [
"public",
"PackingPlans",
".",
"PackingPlan",
"getPackingPlan",
"(",
"String",
"topologyName",
")",
"{",
"return",
"awaitResult",
"(",
"delegate",
".",
"getPackingPlan",
"(",
"null",
",",
"topologyName",
")",
")",
";",
"}"
] | Get the packing plan for the given topology
@return PackingPlans.PackingPlan | [
"Get",
"the",
"packing",
"plan",
"for",
"the",
"given",
"topology"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java#L302-L304 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/apache/logging/log4j/util/StringBuilders.java | StringBuilders.trimToMaxSize | public static void trimToMaxSize(final StringBuilder stringBuilder, final int maxSize) {
"""
Ensures that the char[] array of the specified StringBuilder does not exceed the specified number of characters.
This method is useful to ensure that excessively long char[] arrays are not kept in memory forever.
@param stringBuilder the StringBuilder to check
@param maxSize the maximum number of characters the StringBuilder is allowed to have
@since 2.9
"""
if (stringBuilder != null && stringBuilder.capacity() > maxSize) {
stringBuilder.setLength(maxSize);
stringBuilder.trimToSize();
}
} | java | public static void trimToMaxSize(final StringBuilder stringBuilder, final int maxSize) {
if (stringBuilder != null && stringBuilder.capacity() > maxSize) {
stringBuilder.setLength(maxSize);
stringBuilder.trimToSize();
}
} | [
"public",
"static",
"void",
"trimToMaxSize",
"(",
"final",
"StringBuilder",
"stringBuilder",
",",
"final",
"int",
"maxSize",
")",
"{",
"if",
"(",
"stringBuilder",
"!=",
"null",
"&&",
"stringBuilder",
".",
"capacity",
"(",
")",
">",
"maxSize",
")",
"{",
"stri... | Ensures that the char[] array of the specified StringBuilder does not exceed the specified number of characters.
This method is useful to ensure that excessively long char[] arrays are not kept in memory forever.
@param stringBuilder the StringBuilder to check
@param maxSize the maximum number of characters the StringBuilder is allowed to have
@since 2.9 | [
"Ensures",
"that",
"the",
"char",
"[]",
"array",
"of",
"the",
"specified",
"StringBuilder",
"does",
"not",
"exceed",
"the",
"specified",
"number",
"of",
"characters",
".",
"This",
"method",
"is",
"useful",
"to",
"ensure",
"that",
"excessively",
"long",
"char",... | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/util/StringBuilders.java#L155-L160 |
arquillian/arquillian-recorder | arquillian-recorder-reporter/arquillian-recorder-reporter-impl/src/main/java/org/arquillian/recorder/reporter/exporter/impl/AsciiDocExporter.java | AsciiDocExporter.writeTime | protected void writeTime(Date start, Date stop, long duration) throws IOException {
"""
Method that is called to write test suite time to AsciiDoc document.
@param start time.
@param stop end time.
@param duration in millis.
"""
writer.append(".").append(this.resourceBundle.getString("asciidoc.reporter.time")).append(NEW_LINE);
writer.append("****").append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.start")).append("*").append(" ")
.append(SIMPLE_DATE_FORMAT.format(start)).append(NEW_LINE).append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.stop")).append("*").append(" ")
.append(SIMPLE_DATE_FORMAT.format(stop)).append(NEW_LINE).append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.duration")).append("*").append(" ")
.append(convertDuration(duration, TimeUnit.MILLISECONDS, TimeUnit.SECONDS)).append("s")
.append(NEW_LINE);
writer.append("****").append(NEW_LINE).append(NEW_LINE);
} | java | protected void writeTime(Date start, Date stop, long duration) throws IOException {
writer.append(".").append(this.resourceBundle.getString("asciidoc.reporter.time")).append(NEW_LINE);
writer.append("****").append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.start")).append("*").append(" ")
.append(SIMPLE_DATE_FORMAT.format(start)).append(NEW_LINE).append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.stop")).append("*").append(" ")
.append(SIMPLE_DATE_FORMAT.format(stop)).append(NEW_LINE).append(NEW_LINE);
writer.append("*").append(this.resourceBundle.getString("asciidoc.reporter.duration")).append("*").append(" ")
.append(convertDuration(duration, TimeUnit.MILLISECONDS, TimeUnit.SECONDS)).append("s")
.append(NEW_LINE);
writer.append("****").append(NEW_LINE).append(NEW_LINE);
} | [
"protected",
"void",
"writeTime",
"(",
"Date",
"start",
",",
"Date",
"stop",
",",
"long",
"duration",
")",
"throws",
"IOException",
"{",
"writer",
".",
"append",
"(",
"\".\"",
")",
".",
"append",
"(",
"this",
".",
"resourceBundle",
".",
"getString",
"(",
... | Method that is called to write test suite time to AsciiDoc document.
@param start time.
@param stop end time.
@param duration in millis. | [
"Method",
"that",
"is",
"called",
"to",
"write",
"test",
"suite",
"time",
"to",
"AsciiDoc",
"document",
"."
] | train | https://github.com/arquillian/arquillian-recorder/blob/e3417111deb03a2e2d9b96d38b986db17e2c1d19/arquillian-recorder-reporter/arquillian-recorder-reporter-impl/src/main/java/org/arquillian/recorder/reporter/exporter/impl/AsciiDocExporter.java#L180-L193 |
canoo/dolphin-platform | platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/legacy/ServerModelStore.java | ServerModelStore.presentationModelCommand | @Deprecated
public static void presentationModelCommand(final List<Command> response, final String id, final String presentationModelType, final DTO dto) {
"""
Convenience method to let the client (!) dolphin create a presentation model as specified by the DTO.
The server model store remains untouched until the client has issued the notification.
"""
if (response == null) {
return;
}
List<Map<String, Object>> list = new ArrayList<>();
for (Slot slot : dto.getSlots()) {
Map<String, Object> map = new HashMap<>();
map.put("propertyName", slot.getPropertyName());
map.put("value", slot.getValue());
map.put("qualifier", slot.getQualifier());
list.add(map);
}
response.add(new CreatePresentationModelCommand(id, presentationModelType, list));
} | java | @Deprecated
public static void presentationModelCommand(final List<Command> response, final String id, final String presentationModelType, final DTO dto) {
if (response == null) {
return;
}
List<Map<String, Object>> list = new ArrayList<>();
for (Slot slot : dto.getSlots()) {
Map<String, Object> map = new HashMap<>();
map.put("propertyName", slot.getPropertyName());
map.put("value", slot.getValue());
map.put("qualifier", slot.getQualifier());
list.add(map);
}
response.add(new CreatePresentationModelCommand(id, presentationModelType, list));
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"presentationModelCommand",
"(",
"final",
"List",
"<",
"Command",
">",
"response",
",",
"final",
"String",
"id",
",",
"final",
"String",
"presentationModelType",
",",
"final",
"DTO",
"dto",
")",
"{",
"if",
"(",
... | Convenience method to let the client (!) dolphin create a presentation model as specified by the DTO.
The server model store remains untouched until the client has issued the notification. | [
"Convenience",
"method",
"to",
"let",
"the",
"client",
"(",
"!",
")",
"dolphin",
"create",
"a",
"presentation",
"model",
"as",
"specified",
"by",
"the",
"DTO",
".",
"The",
"server",
"model",
"store",
"remains",
"untouched",
"until",
"the",
"client",
"has",
... | train | https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/legacy/ServerModelStore.java#L183-L197 |
networknt/light-4j | service/src/main/java/com/networknt/service/SingletonServiceFactory.java | SingletonServiceFactory.getBean | public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
"""
Get a cached singleton object from service map by interface class and generic type class.
The serviceMap is constructed from service.yml which defines interface and generic type
to implementation mapping.
@param interfaceClass Interface class
@param <T> class type
@param typeClass Generic type class
@return The implementation object
"""
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
return (T)object;
}
} | java | public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
return (T)object;
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getBean",
"(",
"Class",
"<",
"T",
">",
"interfaceClass",
",",
"Class",
"typeClass",
")",
"{",
"Object",
"object",
"=",
"serviceMap",
".",
"get",
"(",
"interfaceClass",
".",
"getName",
"(",
")",
"+",
"\"<\"",
"+"... | Get a cached singleton object from service map by interface class and generic type class.
The serviceMap is constructed from service.yml which defines interface and generic type
to implementation mapping.
@param interfaceClass Interface class
@param <T> class type
@param typeClass Generic type class
@return The implementation object | [
"Get",
"a",
"cached",
"singleton",
"object",
"from",
"service",
"map",
"by",
"interface",
"class",
"and",
"generic",
"type",
"class",
".",
"The",
"serviceMap",
"is",
"constructed",
"from",
"service",
".",
"yml",
"which",
"defines",
"interface",
"and",
"generic... | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/service/src/main/java/com/networknt/service/SingletonServiceFactory.java#L282-L290 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/observer/SubjectRegistry.java | SubjectRegistry.register | @SuppressWarnings("unchecked")
public <T> void register(String subjectName, SubjectObserver<T> subjectObserver) {
"""
Add the subject Observer (default Topic implementation may be used)
@param <T> the class type
@param subjectName the subject name
@param subjectObserver the subject observer
"""
Subject<?> subject = (Subject<?>)this.registry.get(subjectName);
if(subject == null)
subject = new Topic<T>();
register(subjectName, subjectObserver, (Subject<T>)subject);
} | java | @SuppressWarnings("unchecked")
public <T> void register(String subjectName, SubjectObserver<T> subjectObserver)
{
Subject<?> subject = (Subject<?>)this.registry.get(subjectName);
if(subject == null)
subject = new Topic<T>();
register(subjectName, subjectObserver, (Subject<T>)subject);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"void",
"register",
"(",
"String",
"subjectName",
",",
"SubjectObserver",
"<",
"T",
">",
"subjectObserver",
")",
"{",
"Subject",
"<",
"?",
">",
"subject",
"=",
"(",
"Subject",
"<"... | Add the subject Observer (default Topic implementation may be used)
@param <T> the class type
@param subjectName the subject name
@param subjectObserver the subject observer | [
"Add",
"the",
"subject",
"Observer",
"(",
"default",
"Topic",
"implementation",
"may",
"be",
"used",
")"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/observer/SubjectRegistry.java#L49-L59 |
web3j/web3j | crypto/src/main/java/org/web3j/crypto/ECDSASignature.java | ECDSASignature.toCanonicalised | public ECDSASignature toCanonicalised() {
"""
Will automatically adjust the S component to be less than or equal to half the curve
order, if necessary. This is required because for every signature (r,s) the signature
(r, -s (mod N)) is a valid signature of the same message. However, we dislike the
ability to modify the bits of a Bitcoin transaction after it's been signed, as that
violates various assumed invariants. Thus in future only one of those forms will be
considered legal and the other will be banned.
@return the signature in a canonicalised form.
"""
if (!isCanonical()) {
// The order of the curve is the number of valid points that exist on that curve.
// If S is in the upper half of the number of valid points, then bring it back to
// the lower half. Otherwise, imagine that
// N = 10
// s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions.
// 10 - 8 == 2, giving us always the latter solution, which is canonical.
return new ECDSASignature(r, Sign.CURVE.getN().subtract(s));
} else {
return this;
}
} | java | public ECDSASignature toCanonicalised() {
if (!isCanonical()) {
// The order of the curve is the number of valid points that exist on that curve.
// If S is in the upper half of the number of valid points, then bring it back to
// the lower half. Otherwise, imagine that
// N = 10
// s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions.
// 10 - 8 == 2, giving us always the latter solution, which is canonical.
return new ECDSASignature(r, Sign.CURVE.getN().subtract(s));
} else {
return this;
}
} | [
"public",
"ECDSASignature",
"toCanonicalised",
"(",
")",
"{",
"if",
"(",
"!",
"isCanonical",
"(",
")",
")",
"{",
"// The order of the curve is the number of valid points that exist on that curve.",
"// If S is in the upper half of the number of valid points, then bring it back to",
"... | Will automatically adjust the S component to be less than or equal to half the curve
order, if necessary. This is required because for every signature (r,s) the signature
(r, -s (mod N)) is a valid signature of the same message. However, we dislike the
ability to modify the bits of a Bitcoin transaction after it's been signed, as that
violates various assumed invariants. Thus in future only one of those forms will be
considered legal and the other will be banned.
@return the signature in a canonicalised form. | [
"Will",
"automatically",
"adjust",
"the",
"S",
"component",
"to",
"be",
"less",
"than",
"or",
"equal",
"to",
"half",
"the",
"curve",
"order",
"if",
"necessary",
".",
"This",
"is",
"required",
"because",
"for",
"every",
"signature",
"(",
"r",
"s",
")",
"t... | train | https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/ECDSASignature.java#L38-L50 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedBreakIterator.java | RuleBasedBreakIterator.checkOffset | protected static final void checkOffset(int offset, CharacterIterator text) {
"""
Throw IllegalArgumentException unless begin <= offset < end.
"""
if (offset < text.getBeginIndex() || offset > text.getEndIndex()) {
throw new IllegalArgumentException("offset out of bounds");
}
} | java | protected static final void checkOffset(int offset, CharacterIterator text) {
if (offset < text.getBeginIndex() || offset > text.getEndIndex()) {
throw new IllegalArgumentException("offset out of bounds");
}
} | [
"protected",
"static",
"final",
"void",
"checkOffset",
"(",
"int",
"offset",
",",
"CharacterIterator",
"text",
")",
"{",
"if",
"(",
"offset",
"<",
"text",
".",
"getBeginIndex",
"(",
")",
"||",
"offset",
">",
"text",
".",
"getEndIndex",
"(",
")",
")",
"{"... | Throw IllegalArgumentException unless begin <= offset < end. | [
"Throw",
"IllegalArgumentException",
"unless",
"begin",
"<",
";",
"=",
"offset",
"<",
";",
"end",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedBreakIterator.java#L893-L897 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/cql3/ErrorCollector.java | ErrorCollector.insertChar | private static String insertChar(String s, int index, char c) {
"""
Inserts a character at a given position within a <code>String</code>.
@param s the <code>String</code> in which the character must be inserted
@param index the position where the character must be inserted
@param c the character to insert
@return the modified <code>String</code>
"""
return new StringBuilder().append(s.substring(0, index))
.append(c)
.append(s.substring(index))
.toString();
} | java | private static String insertChar(String s, int index, char c)
{
return new StringBuilder().append(s.substring(0, index))
.append(c)
.append(s.substring(index))
.toString();
} | [
"private",
"static",
"String",
"insertChar",
"(",
"String",
"s",
",",
"int",
"index",
",",
"char",
"c",
")",
"{",
"return",
"new",
"StringBuilder",
"(",
")",
".",
"append",
"(",
"s",
".",
"substring",
"(",
"0",
",",
"index",
")",
")",
".",
"append",
... | Inserts a character at a given position within a <code>String</code>.
@param s the <code>String</code> in which the character must be inserted
@param index the position where the character must be inserted
@param c the character to insert
@return the modified <code>String</code> | [
"Inserts",
"a",
"character",
"at",
"a",
"given",
"position",
"within",
"a",
"<code",
">",
"String<",
"/",
"code",
">",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/ErrorCollector.java#L246-L252 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/xpath/XPathQueryBuilder.java | XPathQueryBuilder.createQuery | public static QueryRootNode createQuery(String statement,
LocationFactory resolver,
QueryNodeFactory factory)
throws InvalidQueryException {
"""
Creates a <code>QueryNode</code> tree from a XPath statement using the
passed query node <code>factory</code>.
@param statement the XPath statement.
@param resolver the name resolver to use.
@param factory the query node factory.
@return the <code>QueryNode</code> tree for the XPath statement.
@throws InvalidQueryException if the XPath statement is malformed.
"""
return new XPathQueryBuilder(statement, resolver, factory).getRootNode();
} | java | public static QueryRootNode createQuery(String statement,
LocationFactory resolver,
QueryNodeFactory factory)
throws InvalidQueryException {
return new XPathQueryBuilder(statement, resolver, factory).getRootNode();
} | [
"public",
"static",
"QueryRootNode",
"createQuery",
"(",
"String",
"statement",
",",
"LocationFactory",
"resolver",
",",
"QueryNodeFactory",
"factory",
")",
"throws",
"InvalidQueryException",
"{",
"return",
"new",
"XPathQueryBuilder",
"(",
"statement",
",",
"resolver",
... | Creates a <code>QueryNode</code> tree from a XPath statement using the
passed query node <code>factory</code>.
@param statement the XPath statement.
@param resolver the name resolver to use.
@param factory the query node factory.
@return the <code>QueryNode</code> tree for the XPath statement.
@throws InvalidQueryException if the XPath statement is malformed. | [
"Creates",
"a",
"<code",
">",
"QueryNode<",
"/",
"code",
">",
"tree",
"from",
"a",
"XPath",
"statement",
"using",
"the",
"passed",
"query",
"node",
"<code",
">",
"factory<",
"/",
"code",
">",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/xpath/XPathQueryBuilder.java#L319-L324 |
tango-controls/JTango | server/src/main/java/org/tango/server/servant/DeviceImpl.java | DeviceImpl.command_inout | @Override
public Any command_inout(final String command, final Any argin) throws DevFailed {
"""
Execute a command. IDL 1 version
@param command command name
@param argin command parameters
@return command result
@throws DevFailed
"""
MDC.setContextMap(contextMap);
xlogger.entry();
if (!command.equalsIgnoreCase(DeviceImpl.STATE_NAME) && !command.equalsIgnoreCase(DeviceImpl.STATUS_NAME)) {
checkInitialization();
}
final long request = deviceMonitoring.startRequest("command_inout " + command);
clientIdentity.set(null);
Any argout = null;
try {
argout = commandHandler(command, argin, DevSource.CACHE_DEV, null);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
} finally {
deviceMonitoring.endRequest(request);
}
xlogger.exit();
return argout;
} | java | @Override
public Any command_inout(final String command, final Any argin) throws DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
if (!command.equalsIgnoreCase(DeviceImpl.STATE_NAME) && !command.equalsIgnoreCase(DeviceImpl.STATUS_NAME)) {
checkInitialization();
}
final long request = deviceMonitoring.startRequest("command_inout " + command);
clientIdentity.set(null);
Any argout = null;
try {
argout = commandHandler(command, argin, DevSource.CACHE_DEV, null);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
} finally {
deviceMonitoring.endRequest(request);
}
xlogger.exit();
return argout;
} | [
"@",
"Override",
"public",
"Any",
"command_inout",
"(",
"final",
"String",
"command",
",",
"final",
"Any",
"argin",
")",
"throws",
"DevFailed",
"{",
"MDC",
".",
"setContextMap",
"(",
"contextMap",
")",
";",
"xlogger",
".",
"entry",
"(",
")",
";",
"if",
"... | Execute a command. IDL 1 version
@param command command name
@param argin command parameters
@return command result
@throws DevFailed | [
"Execute",
"a",
"command",
".",
"IDL",
"1",
"version"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L1565-L1591 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/layout/LayoutFactory.java | LayoutFactory.layoutFor | public Layout layoutFor(Class<? extends Storable> type)
throws FetchException, PersistException {
"""
Returns the layout matching the current definition of the given type.
@throws PersistException if type represents a new generation, but
persisting this information failed
"""
return layoutFor(type, null);
} | java | public Layout layoutFor(Class<? extends Storable> type)
throws FetchException, PersistException
{
return layoutFor(type, null);
} | [
"public",
"Layout",
"layoutFor",
"(",
"Class",
"<",
"?",
"extends",
"Storable",
">",
"type",
")",
"throws",
"FetchException",
",",
"PersistException",
"{",
"return",
"layoutFor",
"(",
"type",
",",
"null",
")",
";",
"}"
] | Returns the layout matching the current definition of the given type.
@throws PersistException if type represents a new generation, but
persisting this information failed | [
"Returns",
"the",
"layout",
"matching",
"the",
"current",
"definition",
"of",
"the",
"given",
"type",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/layout/LayoutFactory.java#L97-L101 |
brianwhu/xillium | base/src/main/java/org/xillium/base/beans/Strings.java | Strings.extractArguments | public static String extractArguments(List<String> params, String original) {
"""
Extracts specially marked arguments from a string, and returns the string with such arguments replaced with "{}".
<ol>
<li> Arguments are enclosed between '{' and '}'</li>
<li> Optional extra text is allowed at the end of line starting with '#', which is removed before returning</li>
</ol>
@param params - a list to hold extracted arguments in the original string
@param original - a text string
@return the string with arguments replaced with "{}"
"""
Matcher matcher = PARAM_SYNTAX.matcher(substringBefore(original, '#'));
while (matcher.find()) {
try {
params.add(matcher.group(1));
} catch (Exception x) {
throw new IllegalArgumentException("Translation format specification", x);
}
}
return matcher.replaceAll("{}");
} | java | public static String extractArguments(List<String> params, String original) {
Matcher matcher = PARAM_SYNTAX.matcher(substringBefore(original, '#'));
while (matcher.find()) {
try {
params.add(matcher.group(1));
} catch (Exception x) {
throw new IllegalArgumentException("Translation format specification", x);
}
}
return matcher.replaceAll("{}");
} | [
"public",
"static",
"String",
"extractArguments",
"(",
"List",
"<",
"String",
">",
"params",
",",
"String",
"original",
")",
"{",
"Matcher",
"matcher",
"=",
"PARAM_SYNTAX",
".",
"matcher",
"(",
"substringBefore",
"(",
"original",
",",
"'",
"'",
")",
")",
"... | Extracts specially marked arguments from a string, and returns the string with such arguments replaced with "{}".
<ol>
<li> Arguments are enclosed between '{' and '}'</li>
<li> Optional extra text is allowed at the end of line starting with '#', which is removed before returning</li>
</ol>
@param params - a list to hold extracted arguments in the original string
@param original - a text string
@return the string with arguments replaced with "{}" | [
"Extracts",
"specially",
"marked",
"arguments",
"from",
"a",
"string",
"and",
"returns",
"the",
"string",
"with",
"such",
"arguments",
"replaced",
"with",
"{}",
".",
"<ol",
">",
"<li",
">",
"Arguments",
"are",
"enclosed",
"between",
"{",
"and",
"}",
"<",
"... | train | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/beans/Strings.java#L223-L233 |
Red5/red5-io | src/main/java/org/red5/io/matroska/ParserUtils.java | ParserUtils.parseInteger | public static long parseInteger(InputStream inputStream, final int size) throws IOException {
"""
method used to parse : int, uint and date
@param inputStream
- stream to get value
@param size
- size of the value in bytes
@return - parsed value as long
@throws IOException
- in case of IO error
"""
byte[] buffer = new byte[size];
int numberOfReadsBytes = inputStream.read(buffer, 0, size);
assert numberOfReadsBytes == size;
long value = buffer[0] & (long) 0xff;
for (int i = 1; i < size; ++i) {
value = (value << BIT_IN_BYTE) | ((long) buffer[i] & (long) 0xff);
}
return value;
} | java | public static long parseInteger(InputStream inputStream, final int size) throws IOException {
byte[] buffer = new byte[size];
int numberOfReadsBytes = inputStream.read(buffer, 0, size);
assert numberOfReadsBytes == size;
long value = buffer[0] & (long) 0xff;
for (int i = 1; i < size; ++i) {
value = (value << BIT_IN_BYTE) | ((long) buffer[i] & (long) 0xff);
}
return value;
} | [
"public",
"static",
"long",
"parseInteger",
"(",
"InputStream",
"inputStream",
",",
"final",
"int",
"size",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"size",
"]",
";",
"int",
"numberOfReadsBytes",
"=",
"inputStre... | method used to parse : int, uint and date
@param inputStream
- stream to get value
@param size
- size of the value in bytes
@return - parsed value as long
@throws IOException
- in case of IO error | [
"method",
"used",
"to",
"parse",
":",
"int",
"uint",
"and",
"date"
] | train | https://github.com/Red5/red5-io/blob/9bbbc506423c5a8f18169d46d400df56c0072a33/src/main/java/org/red5/io/matroska/ParserUtils.java#L53-L64 |
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ReflectionUtils.java | ReflectionUtils.getFieldValue | public static Object getFieldValue(Field field, Object obj) {
"""
Convenience method to retrieve the field value for the specified object wrapped to
catch exceptions and re throw as <code>Siren4JRuntimeException</code>.
@param field cannot be <code>null</code>.
@param obj may be <code>null</code>.
@return the value, may be <code>null</code>.
"""
if (field == null) {
throw new IllegalArgumentException("field cannot be null.");
}
try {
return field.get(obj);
} catch (IllegalArgumentException e) {
throw new Siren4JRuntimeException(e);
} catch (IllegalAccessException e) {
throw new Siren4JRuntimeException(e);
}
} | java | public static Object getFieldValue(Field field, Object obj) {
if (field == null) {
throw new IllegalArgumentException("field cannot be null.");
}
try {
return field.get(obj);
} catch (IllegalArgumentException e) {
throw new Siren4JRuntimeException(e);
} catch (IllegalAccessException e) {
throw new Siren4JRuntimeException(e);
}
} | [
"public",
"static",
"Object",
"getFieldValue",
"(",
"Field",
"field",
",",
"Object",
"obj",
")",
"{",
"if",
"(",
"field",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"field cannot be null.\"",
")",
";",
"}",
"try",
"{",
"return... | Convenience method to retrieve the field value for the specified object wrapped to
catch exceptions and re throw as <code>Siren4JRuntimeException</code>.
@param field cannot be <code>null</code>.
@param obj may be <code>null</code>.
@return the value, may be <code>null</code>. | [
"Convenience",
"method",
"to",
"retrieve",
"the",
"field",
"value",
"for",
"the",
"specified",
"object",
"wrapped",
"to",
"catch",
"exceptions",
"and",
"re",
"throw",
"as",
"<code",
">",
"Siren4JRuntimeException<",
"/",
"code",
">",
"."
] | train | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L344-L355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.