repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
datasift/datasift-java | src/main/java/com/datasift/client/push/connectors/Prepared.java | Prepared.verifyAndGet | public Map<String, String> verifyAndGet() {
for (String paramName : required) {
if (params.get(paramName) == null) {
throw new IllegalStateException(format("Param %s is required but has not been supplied", paramName));
}
}
return params;
} | java | public Map<String, String> verifyAndGet() {
for (String paramName : required) {
if (params.get(paramName) == null) {
throw new IllegalStateException(format("Param %s is required but has not been supplied", paramName));
}
}
return params;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"verifyAndGet",
"(",
")",
"{",
"for",
"(",
"String",
"paramName",
":",
"required",
")",
"{",
"if",
"(",
"params",
".",
"get",
"(",
"paramName",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalS... | /*
Verifies that all required parameters have been set
@return a map of the parameters | [
"/",
"*",
"Verifies",
"that",
"all",
"required",
"parameters",
"have",
"been",
"set"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/push/connectors/Prepared.java#L27-L34 |
aws/aws-sdk-java | aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/EndpointUser.java | EndpointUser.setUserAttributes | public void setUserAttributes(java.util.Map<String, java.util.List<String>> userAttributes) {
this.userAttributes = userAttributes;
} | java | public void setUserAttributes(java.util.Map<String, java.util.List<String>> userAttributes) {
this.userAttributes = userAttributes;
} | [
"public",
"void",
"setUserAttributes",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
">",
"userAttributes",
")",
"{",
"this",
".",
"userAttributes",
"=",
"userAttributes",
";",
"}"
] | Custom attributes that describe the user by associating a name with an array of values. For example, an attribute
named "interests" might have the following values: ["science", "politics", "travel"]. You can use these
attributes as selection criteria when you create segments.
The Amazon Pinpoint console can't display attribute names that include the following characters: hash/pound sign
(#), colon (:), question mark (?), backslash (\), and forward slash (/). For this reason, you should avoid using
these characters in the names of custom attributes.
@param userAttributes
Custom attributes that describe the user by associating a name with an array of values. For example, an
attribute named "interests" might have the following values: ["science", "politics", "travel"]. You can
use these attributes as selection criteria when you create segments.
The Amazon Pinpoint console can't display attribute names that include the following characters:
hash/pound sign (#), colon (:), question mark (?), backslash (\), and forward slash (/). For this reason,
you should avoid using these characters in the names of custom attributes. | [
"Custom",
"attributes",
"that",
"describe",
"the",
"user",
"by",
"associating",
"a",
"name",
"with",
"an",
"array",
"of",
"values",
".",
"For",
"example",
"an",
"attribute",
"named",
"interests",
"might",
"have",
"the",
"following",
"values",
":",
"[",
"scie... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/EndpointUser.java#L83-L85 |
sebastiangraf/jSCSI | bundles/target/src/main/java/org/jscsi/target/util/BitManip.java | BitManip.getByteWithBitSet | public static final byte getByteWithBitSet (final byte b, final int bitNumber, final boolean value) {
int number = b;
if (value) {
// make sure bit is set to true
int mask = 1;
mask <<= bitNumber;
number |= mask;
} else {
int mask = 1;
mask <<= bitNumber;
mask ^= 255;// flip bits
number &= mask;
}
return (byte) number;
} | java | public static final byte getByteWithBitSet (final byte b, final int bitNumber, final boolean value) {
int number = b;
if (value) {
// make sure bit is set to true
int mask = 1;
mask <<= bitNumber;
number |= mask;
} else {
int mask = 1;
mask <<= bitNumber;
mask ^= 255;// flip bits
number &= mask;
}
return (byte) number;
} | [
"public",
"static",
"final",
"byte",
"getByteWithBitSet",
"(",
"final",
"byte",
"b",
",",
"final",
"int",
"bitNumber",
",",
"final",
"boolean",
"value",
")",
"{",
"int",
"number",
"=",
"b",
";",
"if",
"(",
"value",
")",
"{",
"// make sure bit is set to true\... | Sets a single bit. If the <i>value</i> parameter is <code>true</code>, the bit will be set to <code>one</code>,
and to <code>zero</code> otherwise. All other bits will be left unchanged.
<p>
The bits are numbered in big-endian format, from 0 (LSB) to 7 (MSB).
<p>
<code>
+---+---+---+---+---+---+---+---+<br>
| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | bit number<br>
+---+---+---+---+---+---+---+---+<br>
</code>
@param b the original byte value
@param bitNumber the big-endian position of the bit to be changed, from 0 to 7
@param value <code>true</code> for <i>1</i>, <code>false</code> for <i>0</i>
@return the edited byte value | [
"Sets",
"a",
"single",
"bit",
".",
"If",
"the",
"<i",
">",
"value<",
"/",
"i",
">",
"parameter",
"is",
"<code",
">",
"true<",
"/",
"code",
">",
"the",
"bit",
"will",
"be",
"set",
"to",
"<code",
">",
"one<",
"/",
"code",
">",
"and",
"to",
"<code",... | train | https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/util/BitManip.java#L35-L52 |
wildfly/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/jvm/JvmType.java | JvmType.createFromJavaHome | public static JvmType createFromJavaHome(final String javaHome, boolean forLaunch) {
if (javaHome == null || javaHome.trim().equals("")) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHome(javaHome);
}
final File javaHomeDir = new File(javaHome);
if (forLaunch && !javaHomeDir.exists()) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHome(javaHomeDir.getAbsolutePath());
}
final File javaBinDir = new File(javaHomeDir, BIN_DIR);
if (forLaunch && !javaBinDir.exists()) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHomeBin(javaBinDir.getAbsolutePath(), javaHomeDir.getAbsolutePath());
}
final File javaExecutable = new File(javaBinDir, JAVA_EXECUTABLE);
if (forLaunch && !javaExecutable.exists()) {
throw HostControllerLogger.ROOT_LOGGER.cannotFindJavaExe(javaBinDir.getAbsolutePath());
}
return new JvmType(forLaunch, isModularJvm(javaExecutable.getAbsolutePath(), forLaunch), javaExecutable.getAbsolutePath());
} | java | public static JvmType createFromJavaHome(final String javaHome, boolean forLaunch) {
if (javaHome == null || javaHome.trim().equals("")) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHome(javaHome);
}
final File javaHomeDir = new File(javaHome);
if (forLaunch && !javaHomeDir.exists()) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHome(javaHomeDir.getAbsolutePath());
}
final File javaBinDir = new File(javaHomeDir, BIN_DIR);
if (forLaunch && !javaBinDir.exists()) {
throw HostControllerLogger.ROOT_LOGGER.invalidJavaHomeBin(javaBinDir.getAbsolutePath(), javaHomeDir.getAbsolutePath());
}
final File javaExecutable = new File(javaBinDir, JAVA_EXECUTABLE);
if (forLaunch && !javaExecutable.exists()) {
throw HostControllerLogger.ROOT_LOGGER.cannotFindJavaExe(javaBinDir.getAbsolutePath());
}
return new JvmType(forLaunch, isModularJvm(javaExecutable.getAbsolutePath(), forLaunch), javaExecutable.getAbsolutePath());
} | [
"public",
"static",
"JvmType",
"createFromJavaHome",
"(",
"final",
"String",
"javaHome",
",",
"boolean",
"forLaunch",
")",
"{",
"if",
"(",
"javaHome",
"==",
"null",
"||",
"javaHome",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"thro... | Create a {@code JvmType} based on the location of the root dir of the JRE/JDK installation.
@param javaHome the root dir of the JRE/JDK installation. Cannot be {@code null} or empty
@param forLaunch {@code true} if the created object will be used for launching servers; {@code false}
if it is simply a data holder. A value of {@code true} will disable
some validity checks and may disable determining if the JVM is modular
@return the {@code JvmType}. Will not return {@code null}
@throws IllegalStateException if the {@code JvmType} cannot be determined. | [
"Create",
"a",
"{",
"@code",
"JvmType",
"}",
"based",
"on",
"the",
"location",
"of",
"the",
"root",
"dir",
"of",
"the",
"JRE",
"/",
"JDK",
"installation",
".",
"@param",
"javaHome",
"the",
"root",
"dir",
"of",
"the",
"JRE",
"/",
"JDK",
"installation",
... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/jvm/JvmType.java#L106-L123 |
diffplug/durian | src/com/diffplug/common/base/MoreCollectors.java | MoreCollectors.singleOrEmpty | public static <T> Collector<T, ?, Optional<T>> singleOrEmpty() {
return Collectors.collectingAndThen(Collectors.toList(),
lst -> lst.size() == 1 ? Optional.of(lst.get(0)) : Optional.empty());
} | java | public static <T> Collector<T, ?, Optional<T>> singleOrEmpty() {
return Collectors.collectingAndThen(Collectors.toList(),
lst -> lst.size() == 1 ? Optional.of(lst.get(0)) : Optional.empty());
} | [
"public",
"static",
"<",
"T",
">",
"Collector",
"<",
"T",
",",
"?",
",",
"Optional",
"<",
"T",
">",
">",
"singleOrEmpty",
"(",
")",
"{",
"return",
"Collectors",
".",
"collectingAndThen",
"(",
"Collectors",
".",
"toList",
"(",
")",
",",
"lst",
"->",
"... | Collector which traverses a stream and returns either a single element
(if there was only one element) or empty (if there were 0 or more than 1
elements). It traverses the entire stream, even if two elements
have been encountered and the empty return value is now certain.
<p>
Implementation credit to Misha <a href="http://stackoverflow.com/a/26812693/1153071">on StackOverflow</a>. | [
"Collector",
"which",
"traverses",
"a",
"stream",
"and",
"returns",
"either",
"a",
"single",
"element",
"(",
"if",
"there",
"was",
"only",
"one",
"element",
")",
"or",
"empty",
"(",
"if",
"there",
"were",
"0",
"or",
"more",
"than",
"1",
"elements",
")",
... | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/MoreCollectors.java#L34-L37 |
fracpete/multisearch-weka-package | src/main/java/weka/classifiers/meta/multisearch/Performance.java | Performance.setPerformance | public void setPerformance(int evaluation, double value) {
if ((m_Metrics != null) && !m_Metrics.check(evaluation))
return;
m_MetricValues.put(evaluation, value);
} | java | public void setPerformance(int evaluation, double value) {
if ((m_Metrics != null) && !m_Metrics.check(evaluation))
return;
m_MetricValues.put(evaluation, value);
} | [
"public",
"void",
"setPerformance",
"(",
"int",
"evaluation",
",",
"double",
"value",
")",
"{",
"if",
"(",
"(",
"m_Metrics",
"!=",
"null",
")",
"&&",
"!",
"m_Metrics",
".",
"check",
"(",
"evaluation",
")",
")",
"return",
";",
"m_MetricValues",
".",
"put"... | returns the performance measure.
@param evaluation the type of evaluation to return
@param value the performance measure | [
"returns",
"the",
"performance",
"measure",
"."
] | train | https://github.com/fracpete/multisearch-weka-package/blob/756fcf343e7cc9fd3844c99a0e1e828368f393d0/src/main/java/weka/classifiers/meta/multisearch/Performance.java#L148-L152 |
VoltDB/voltdb | src/frontend/org/voltdb/AbstractTopology.java | AbstractTopology.getTopology | public static AbstractTopology getTopology(Map<Integer, HostInfo> hostInfos, Set<Integer> missingHosts,
int kfactor) {
return getTopology(hostInfos, missingHosts, kfactor, false);
} | java | public static AbstractTopology getTopology(Map<Integer, HostInfo> hostInfos, Set<Integer> missingHosts,
int kfactor) {
return getTopology(hostInfos, missingHosts, kfactor, false);
} | [
"public",
"static",
"AbstractTopology",
"getTopology",
"(",
"Map",
"<",
"Integer",
",",
"HostInfo",
">",
"hostInfos",
",",
"Set",
"<",
"Integer",
">",
"missingHosts",
",",
"int",
"kfactor",
")",
"{",
"return",
"getTopology",
"(",
"hostInfos",
",",
"missingHost... | Create a new topology using {@code hosts}
@param hostInfos hosts to put in topology
@param missingHosts set of missing host IDs
@param kfactor for cluster
@return {@link AbstractTopology} for cluster
@throws RuntimeException if hosts are not valid for topology | [
"Create",
"a",
"new",
"topology",
"using",
"{",
"@code",
"hosts",
"}"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/AbstractTopology.java#L961-L964 |
structr/structr | structr-core/src/main/java/org/structr/schema/action/Function.java | Function.logException | protected void logException (final Throwable t, final String msg, final Object[] messageParams) {
logger.error(msg, messageParams, t);
} | java | protected void logException (final Throwable t, final String msg, final Object[] messageParams) {
logger.error(msg, messageParams, t);
} | [
"protected",
"void",
"logException",
"(",
"final",
"Throwable",
"t",
",",
"final",
"String",
"msg",
",",
"final",
"Object",
"[",
"]",
"messageParams",
")",
"{",
"logger",
".",
"error",
"(",
"msg",
",",
"messageParams",
",",
"t",
")",
";",
"}"
] | Logging of an Exception in a function with custom message and message parameters.
@param t The thrown Exception
@param msg The message to be printed
@param messageParams The parameters for the message | [
"Logging",
"of",
"an",
"Exception",
"in",
"a",
"function",
"with",
"custom",
"message",
"and",
"message",
"parameters",
"."
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/schema/action/Function.java#L109-L111 |
Netflix/conductor | grpc-client/src/main/java/com/netflix/conductor/client/grpc/WorkflowClient.java | WorkflowClient.deleteWorkflow | public void deleteWorkflow(String workflowId, boolean archiveWorkflow) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "Workflow id cannot be blank");
stub.removeWorkflow(
WorkflowServicePb.RemoveWorkflowRequest.newBuilder()
.setWorkflodId(workflowId)
.setArchiveWorkflow(archiveWorkflow)
.build()
);
} | java | public void deleteWorkflow(String workflowId, boolean archiveWorkflow) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "Workflow id cannot be blank");
stub.removeWorkflow(
WorkflowServicePb.RemoveWorkflowRequest.newBuilder()
.setWorkflodId(workflowId)
.setArchiveWorkflow(archiveWorkflow)
.build()
);
} | [
"public",
"void",
"deleteWorkflow",
"(",
"String",
"workflowId",
",",
"boolean",
"archiveWorkflow",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"workflowId",
")",
",",
"\"Workflow id cannot be blank\"",
")",
";",
"stu... | Removes a workflow from the system
@param workflowId the id of the workflow to be deleted
@param archiveWorkflow flag to indicate if the workflow should be archived before deletion | [
"Removes",
"a",
"workflow",
"from",
"the",
"system"
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/grpc-client/src/main/java/com/netflix/conductor/client/grpc/WorkflowClient.java#L97-L105 |
contentful/contentful-management.java | src/main/java/com/contentful/java/cma/ModuleSpaceMemberships.java | ModuleSpaceMemberships.fetchAll | public CMAArray<CMASpaceMembership> fetchAll(Map<String, String> query) {
throwIfEnvironmentIdIsSet();
return fetchAll(spaceId, query);
} | java | public CMAArray<CMASpaceMembership> fetchAll(Map<String, String> query) {
throwIfEnvironmentIdIsSet();
return fetchAll(spaceId, query);
} | [
"public",
"CMAArray",
"<",
"CMASpaceMembership",
">",
"fetchAll",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"query",
")",
"{",
"throwIfEnvironmentIdIsSet",
"(",
")",
";",
"return",
"fetchAll",
"(",
"spaceId",
",",
"query",
")",
";",
"}"
] | Fetch all memberships of the configured space.
@param query define which space memberships to return.
@return the array of memberships.
@throws IllegalArgumentException if spaceId is null.
@throws CMANotWithEnvironmentsException if environmentId was set using
{@link CMAClient.Builder#setEnvironmentId(String)}.
@see CMAClient.Builder#setSpaceId(String) | [
"Fetch",
"all",
"memberships",
"of",
"the",
"configured",
"space",
"."
] | train | https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleSpaceMemberships.java#L100-L103 |
acromusashi/acromusashi-stream | src/main/java/acromusashi/stream/component/rabbitmq/DefaultRabbitmqClient.java | DefaultRabbitmqClient.sendAndRetry | private void sendAndRetry(AmqpTemplate template, Object message) throws InterruptedException
{
try
{
template.convertAndSend(message);
}
catch (AmqpException ex)
{
Thread.sleep(getRetryInterval());
template.convertAndSend(message);
}
} | java | private void sendAndRetry(AmqpTemplate template, Object message) throws InterruptedException
{
try
{
template.convertAndSend(message);
}
catch (AmqpException ex)
{
Thread.sleep(getRetryInterval());
template.convertAndSend(message);
}
} | [
"private",
"void",
"sendAndRetry",
"(",
"AmqpTemplate",
"template",
",",
"Object",
"message",
")",
"throws",
"InterruptedException",
"{",
"try",
"{",
"template",
".",
"convertAndSend",
"(",
"message",
")",
";",
"}",
"catch",
"(",
"AmqpException",
"ex",
")",
"{... | メッセージを送信する。
@param template キューへのコネクション
@param message メッセージ
@throws InterruptedException スレッド割り込みが発生した場合 | [
"メッセージを送信する。"
] | train | https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/component/rabbitmq/DefaultRabbitmqClient.java#L81-L92 |
GerdHolz/TOVAL | src/de/invation/code/toval/graphic/util/GraphicUtils.java | GraphicUtils.fillCircle | public static void fillCircle(Graphics g, Point center, int diameter, Color color){
fillCircle(g, (int) center.x, (int) center.y, diameter, color);
} | java | public static void fillCircle(Graphics g, Point center, int diameter, Color color){
fillCircle(g, (int) center.x, (int) center.y, diameter, color);
} | [
"public",
"static",
"void",
"fillCircle",
"(",
"Graphics",
"g",
",",
"Point",
"center",
",",
"int",
"diameter",
",",
"Color",
"color",
")",
"{",
"fillCircle",
"(",
"g",
",",
"(",
"int",
")",
"center",
".",
"x",
",",
"(",
"int",
")",
"center",
".",
... | Draws a circle with the specified diameter using the given point as center
and fills it with the given color.
@param g Graphics context
@param center Circle center
@param diameter Circle diameter | [
"Draws",
"a",
"circle",
"with",
"the",
"specified",
"diameter",
"using",
"the",
"given",
"point",
"as",
"center",
"and",
"fills",
"it",
"with",
"the",
"given",
"color",
"."
] | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/graphic/util/GraphicUtils.java#L64-L66 |
FINRAOS/DataGenerator | dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java | SCXMLGapper.reproduce | public Frontier reproduce(Map<String, String> decomposition, List<CustomTagExtension> tagExtensionList) {
tagExtensionList = new LinkedList<>(tagExtensionList);
tagExtensionList.add(new SetAssignExtension());
tagExtensionList.add(new SingleValueAssignExtension());
tagExtensionList.add(new FileExtension());
tagExtensionList.add(new RangeExtension());
setModel(decomposition.get("model"), tagExtensionList);
TransitionTarget target = (TransitionTarget) model.getTargets().get(decomposition.get("target"));
Map<String, String> variables = new HashMap<>();
String[] assignments = decomposition.get("variables").split(";");
for (int i = 0; i < assignments.length; i++) {
String[] a = assignments[i].split("::");
if (a.length == 2) {
variables.put(a[0], a[1]);
} else {
variables.put(a[0], "");
}
}
return new SCXMLFrontier(new PossibleState(target, variables), model, tagExtensionList);
} | java | public Frontier reproduce(Map<String, String> decomposition, List<CustomTagExtension> tagExtensionList) {
tagExtensionList = new LinkedList<>(tagExtensionList);
tagExtensionList.add(new SetAssignExtension());
tagExtensionList.add(new SingleValueAssignExtension());
tagExtensionList.add(new FileExtension());
tagExtensionList.add(new RangeExtension());
setModel(decomposition.get("model"), tagExtensionList);
TransitionTarget target = (TransitionTarget) model.getTargets().get(decomposition.get("target"));
Map<String, String> variables = new HashMap<>();
String[] assignments = decomposition.get("variables").split(";");
for (int i = 0; i < assignments.length; i++) {
String[] a = assignments[i].split("::");
if (a.length == 2) {
variables.put(a[0], a[1]);
} else {
variables.put(a[0], "");
}
}
return new SCXMLFrontier(new PossibleState(target, variables), model, tagExtensionList);
} | [
"public",
"Frontier",
"reproduce",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"decomposition",
",",
"List",
"<",
"CustomTagExtension",
">",
"tagExtensionList",
")",
"{",
"tagExtensionList",
"=",
"new",
"LinkedList",
"<>",
"(",
"tagExtensionList",
")",
";",
... | Produces an SCXMLFrontier by reversing a decomposition; the model text is bundled into the decomposition.
@param decomposition the decomposition, assembled back into a map
@param tagExtensionList custom tags to use in the model
@return a rebuilt SCXMLFrontier | [
"Produces",
"an",
"SCXMLFrontier",
"by",
"reversing",
"a",
"decomposition",
";",
"the",
"model",
"text",
"is",
"bundled",
"into",
"the",
"decomposition",
"."
] | train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java#L117-L139 |
yan74/afplib | org.afplib/src/main/java/org/afplib/base/util/BaseValidator.java | BaseValidator.validateModcaString32_MaxLength | public boolean validateModcaString32_MaxLength(String modcaString32, DiagnosticChain diagnostics, Map<Object, Object> context) {
int length = modcaString32.length();
boolean result = length <= 32;
if (!result && diagnostics != null)
reportMaxLengthViolation(BasePackage.Literals.MODCA_STRING32, modcaString32, length, 32, diagnostics, context);
return result;
} | java | public boolean validateModcaString32_MaxLength(String modcaString32, DiagnosticChain diagnostics, Map<Object, Object> context) {
int length = modcaString32.length();
boolean result = length <= 32;
if (!result && diagnostics != null)
reportMaxLengthViolation(BasePackage.Literals.MODCA_STRING32, modcaString32, length, 32, diagnostics, context);
return result;
} | [
"public",
"boolean",
"validateModcaString32_MaxLength",
"(",
"String",
"modcaString32",
",",
"DiagnosticChain",
"diagnostics",
",",
"Map",
"<",
"Object",
",",
"Object",
">",
"context",
")",
"{",
"int",
"length",
"=",
"modcaString32",
".",
"length",
"(",
")",
";"... | Validates the MaxLength constraint of '<em>Modca String32</em>'.
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | [
"Validates",
"the",
"MaxLength",
"constraint",
"of",
"<em",
">",
"Modca",
"String32<",
"/",
"em",
">",
".",
"<!",
"--",
"begin",
"-",
"user",
"-",
"doc",
"--",
">",
"<!",
"--",
"end",
"-",
"user",
"-",
"doc",
"--",
">"
] | train | https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/base/util/BaseValidator.java#L278-L284 |
ecclesia/kipeto | kipeto-common/src/main/java/de/ecclesia/kipeto/common/util/Files.java | Files.copyFile | public static void copyFile(File sourceFile, File destinationFile) throws FileNotFoundException, IOException {
Streams.copyStream(new FileInputStream(sourceFile), new FileOutputStream(destinationFile), true);
} | java | public static void copyFile(File sourceFile, File destinationFile) throws FileNotFoundException, IOException {
Streams.copyStream(new FileInputStream(sourceFile), new FileOutputStream(destinationFile), true);
} | [
"public",
"static",
"void",
"copyFile",
"(",
"File",
"sourceFile",
",",
"File",
"destinationFile",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"Streams",
".",
"copyStream",
"(",
"new",
"FileInputStream",
"(",
"sourceFile",
")",
",",
"new",
"... | Kopiert eine Datei
@param sourceFile
Quelldatei
@param destinationFile
Zieldatei
@throws IOException
@throws FileNotFoundException | [
"Kopiert",
"eine",
"Datei"
] | train | https://github.com/ecclesia/kipeto/blob/ea39a10ae4eaa550f71a856ab2f2845270a64913/kipeto-common/src/main/java/de/ecclesia/kipeto/common/util/Files.java#L77-L79 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/mps_ssl_certkey.java | mps_ssl_certkey.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
mps_ssl_certkey_responses result = (mps_ssl_certkey_responses) service.get_payload_formatter().string_to_resource(mps_ssl_certkey_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_ssl_certkey_response_array);
}
mps_ssl_certkey[] result_mps_ssl_certkey = new mps_ssl_certkey[result.mps_ssl_certkey_response_array.length];
for(int i = 0; i < result.mps_ssl_certkey_response_array.length; i++)
{
result_mps_ssl_certkey[i] = result.mps_ssl_certkey_response_array[i].mps_ssl_certkey[0];
}
return result_mps_ssl_certkey;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
mps_ssl_certkey_responses result = (mps_ssl_certkey_responses) service.get_payload_formatter().string_to_resource(mps_ssl_certkey_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_ssl_certkey_response_array);
}
mps_ssl_certkey[] result_mps_ssl_certkey = new mps_ssl_certkey[result.mps_ssl_certkey_response_array.length];
for(int i = 0; i < result.mps_ssl_certkey_response_array.length; i++)
{
result_mps_ssl_certkey[i] = result.mps_ssl_certkey_response_array[i].mps_ssl_certkey[0];
}
return result_mps_ssl_certkey;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"mps_ssl_certkey_responses",
"result",
"=",
"(",
"mps_ssl_certkey_responses",
")",
"service",
".",
"get_payloa... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/mps_ssl_certkey.java#L442-L459 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.newCloseShieldZipInputStream | private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) {
InputStream in = new BufferedInputStream(new CloseShieldInputStream(is));
if (charset == null) {
return new ZipInputStream(in);
}
return ZipFileUtil.createZipInputStream(in, charset);
} | java | private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) {
InputStream in = new BufferedInputStream(new CloseShieldInputStream(is));
if (charset == null) {
return new ZipInputStream(in);
}
return ZipFileUtil.createZipInputStream(in, charset);
} | [
"private",
"static",
"ZipInputStream",
"newCloseShieldZipInputStream",
"(",
"final",
"InputStream",
"is",
",",
"Charset",
"charset",
")",
"{",
"InputStream",
"in",
"=",
"new",
"BufferedInputStream",
"(",
"new",
"CloseShieldInputStream",
"(",
"is",
")",
")",
";",
"... | Creates a new {@link ZipInputStream} based on the given {@link InputStream}. It will be buffered and close-shielded.
Closing the result stream flushes the buffers and frees up resources of the {@link ZipInputStream}. However the source stream itself remains open. | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L825-L831 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java | NodeSetDTM.addNode | public void addNode(int n)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!");
this.addElement(n);
} | java | public void addNode(int n)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!");
this.addElement(n);
} | [
"public",
"void",
"addNode",
"(",
"int",
"n",
")",
"{",
"if",
"(",
"!",
"m_mutable",
")",
"throw",
"new",
"RuntimeException",
"(",
"XSLMessages",
".",
"createXPATHMessage",
"(",
"XPATHErrorResources",
".",
"ER_NODESETDTM_NOT_MUTABLE",
",",
"null",
")",
")",
";... | Add a node to the NodeSetDTM. Not all types of NodeSetDTMs support this
operation
@param n Node to be added
@throws RuntimeException thrown if this NodeSetDTM is not of
a mutable type. | [
"Add",
"a",
"node",
"to",
"the",
"NodeSetDTM",
".",
"Not",
"all",
"types",
"of",
"NodeSetDTMs",
"support",
"this",
"operation"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java#L535-L542 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaCoreUtils.java | KunderaCoreUtils.prepareCompositeKey | public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey)
{
Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder();
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
try
{
String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
// what if field value is null????
stringBuilder.append(fieldValue);
stringBuilder.append(COMPOSITE_KEY_SEPERATOR);
}
catch (IllegalArgumentException e)
{
logger.error("Error during prepare composite key, Caused by {}.", e);
throw new PersistenceException(e);
}
}
}
if (stringBuilder.length() > 0)
{
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR));
}
return stringBuilder.toString();
} | java | public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey)
{
Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder();
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
try
{
String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
// what if field value is null????
stringBuilder.append(fieldValue);
stringBuilder.append(COMPOSITE_KEY_SEPERATOR);
}
catch (IllegalArgumentException e)
{
logger.error("Error during prepare composite key, Caused by {}.", e);
throw new PersistenceException(e);
}
}
}
if (stringBuilder.length() > 0)
{
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR));
}
return stringBuilder.toString();
} | [
"public",
"static",
"String",
"prepareCompositeKey",
"(",
"final",
"EntityMetadata",
"m",
",",
"final",
"Object",
"compositeKey",
")",
"{",
"Field",
"[",
"]",
"fields",
"=",
"m",
".",
"getIdAttribute",
"(",
")",
".",
"getBindableJavaType",
"(",
")",
".",
"ge... | Prepares composite key .
@param m
entity metadata
@param compositeKey
composite key instance
@return redis key | [
"Prepares",
"composite",
"key",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaCoreUtils.java#L148-L178 |
ralscha/extdirectspring | src/main/java/ch/ralscha/extdirectspring/util/JsonHandler.java | JsonHandler.readValue | public <T> T readValue(String json, Class<T> clazz) {
try {
return this.mapper.readValue(json, clazz);
}
catch (Exception e) {
LogFactory.getLog(JsonHandler.class).info("deserialize json to object", e);
return null;
}
} | java | public <T> T readValue(String json, Class<T> clazz) {
try {
return this.mapper.readValue(json, clazz);
}
catch (Exception e) {
LogFactory.getLog(JsonHandler.class).info("deserialize json to object", e);
return null;
}
} | [
"public",
"<",
"T",
">",
"T",
"readValue",
"(",
"String",
"json",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"try",
"{",
"return",
"this",
".",
"mapper",
".",
"readValue",
"(",
"json",
",",
"clazz",
")",
";",
"}",
"catch",
"(",
"Exception",
... | Converts a JSON string into an object. In case of an exception returns null and
logs the exception.
@param <T> type of the object to create
@param json string with the JSON
@param clazz class of object to create
@return the converted object, null if there is an exception | [
"Converts",
"a",
"JSON",
"string",
"into",
"an",
"object",
".",
"In",
"case",
"of",
"an",
"exception",
"returns",
"null",
"and",
"logs",
"the",
"exception",
"."
] | train | https://github.com/ralscha/extdirectspring/blob/4b018497c4e7503033f91d0491b4e74bf8291d2c/src/main/java/ch/ralscha/extdirectspring/util/JsonHandler.java#L124-L132 |
deeplearning4j/deeplearning4j | nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/NDArrayMessage.java | NDArrayMessage.numChunksForMessage | public static int numChunksForMessage(NDArrayMessage message, int chunkSize) {
int sizeOfMessage = NDArrayMessage.byteBufferSizeForMessage(message);
int numMessages = sizeOfMessage / chunkSize;
//increase by 1 for padding
if (numMessages * chunkSize < sizeOfMessage)
numMessages++;
return numMessages;
} | java | public static int numChunksForMessage(NDArrayMessage message, int chunkSize) {
int sizeOfMessage = NDArrayMessage.byteBufferSizeForMessage(message);
int numMessages = sizeOfMessage / chunkSize;
//increase by 1 for padding
if (numMessages * chunkSize < sizeOfMessage)
numMessages++;
return numMessages;
} | [
"public",
"static",
"int",
"numChunksForMessage",
"(",
"NDArrayMessage",
"message",
",",
"int",
"chunkSize",
")",
"{",
"int",
"sizeOfMessage",
"=",
"NDArrayMessage",
".",
"byteBufferSizeForMessage",
"(",
"message",
")",
";",
"int",
"numMessages",
"=",
"sizeOfMessage... | Determine the number of chunks
@param message
@param chunkSize
@return | [
"Determine",
"the",
"number",
"of",
"chunks"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/NDArrayMessage.java#L85-L92 |
EdwardRaff/JSAT | JSAT/src/jsat/distributions/kernels/RBFKernel.java | RBFKernel.setSigma | public void setSigma(double sigma)
{
if(sigma <= 0)
throw new IllegalArgumentException("Sigma must be a positive constant, not " + sigma);
this.sigma = sigma;
this.sigmaSqrd2Inv = 0.5/(sigma*sigma);
} | java | public void setSigma(double sigma)
{
if(sigma <= 0)
throw new IllegalArgumentException("Sigma must be a positive constant, not " + sigma);
this.sigma = sigma;
this.sigmaSqrd2Inv = 0.5/(sigma*sigma);
} | [
"public",
"void",
"setSigma",
"(",
"double",
"sigma",
")",
"{",
"if",
"(",
"sigma",
"<=",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Sigma must be a positive constant, not \"",
"+",
"sigma",
")",
";",
"this",
".",
"sigma",
"=",
"sigma",
";",... | Sets the sigma parameter, which must be a positive value
@param sigma the sigma value | [
"Sets",
"the",
"sigma",
"parameter",
"which",
"must",
"be",
"a",
"positive",
"value"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/RBFKernel.java#L79-L85 |
molgenis/molgenis | molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/PackageCopier.java | PackageCopier.assignUniqueLabel | private void assignUniqueLabel(Package pack, Package targetPackage) {
Set<String> existingLabels;
if (targetPackage != null) {
existingLabels = stream(targetPackage.getChildren()).map(Package::getLabel).collect(toSet());
} else {
existingLabels =
dataService
.query(PACKAGE, Package.class)
.eq(PackageMetadata.PARENT, null)
.findAll()
.map(Package::getLabel)
.collect(toSet());
}
pack.setLabel(generateUniqueLabel(pack.getLabel(), existingLabels));
} | java | private void assignUniqueLabel(Package pack, Package targetPackage) {
Set<String> existingLabels;
if (targetPackage != null) {
existingLabels = stream(targetPackage.getChildren()).map(Package::getLabel).collect(toSet());
} else {
existingLabels =
dataService
.query(PACKAGE, Package.class)
.eq(PackageMetadata.PARENT, null)
.findAll()
.map(Package::getLabel)
.collect(toSet());
}
pack.setLabel(generateUniqueLabel(pack.getLabel(), existingLabels));
} | [
"private",
"void",
"assignUniqueLabel",
"(",
"Package",
"pack",
",",
"Package",
"targetPackage",
")",
"{",
"Set",
"<",
"String",
">",
"existingLabels",
";",
"if",
"(",
"targetPackage",
"!=",
"null",
")",
"{",
"existingLabels",
"=",
"stream",
"(",
"targetPackag... | Checks if there's a Package in the target location with the same label. If so, keeps adding a
postfix until the label is unique. | [
"Checks",
"if",
"there",
"s",
"a",
"Package",
"in",
"the",
"target",
"location",
"with",
"the",
"same",
"label",
".",
"If",
"so",
"keeps",
"adding",
"a",
"postfix",
"until",
"the",
"label",
"is",
"unique",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/PackageCopier.java#L62-L76 |
google/closure-compiler | src/com/google/javascript/jscomp/NodeUtil.java | NodeUtil.getDeclaringParent | public static Node getDeclaringParent(Node targetNode) {
Node rootTarget = getRootTarget(targetNode);
Node parent = rootTarget.getParent();
if (parent.isRest() || parent.isDefaultValue()) {
// e.g. `function foo(targetNode1 = default, ...targetNode2) {}`
parent = parent.getParent();
checkState(parent.isParamList(), parent);
} else if (parent.isDestructuringLhs()) {
// e.g. `let [a, b] = something;` targetNode is `[a, b]`
parent = parent.getParent();
checkState(isNameDeclaration(parent), parent);
} else if (parent.isClass() || parent.isFunction()) {
// e.g. `function targetNode() {}`
// e.g. `class targetNode {}`
checkState(targetNode == parent.getFirstChild(), targetNode);
} else if (parent.isImportSpec()) {
// e.g. `import {foo as targetNode} from './foo';
checkState(targetNode == parent.getSecondChild(), targetNode);
// import -> import_specs -> import_spec
// we want import
parent = parent.getGrandparent();
checkState(parent.isImport(), parent);
} else {
// e.g. `function foo(targetNode) {};`
// e.g. `let targetNode = something;`
// e.g. `import targetNode from './foo';
// e.g. `} catch (foo) {`
checkState(
parent.isParamList()
|| isNameDeclaration(parent)
|| parent.isImport()
|| parent.isCatch(),
parent);
}
return parent;
} | java | public static Node getDeclaringParent(Node targetNode) {
Node rootTarget = getRootTarget(targetNode);
Node parent = rootTarget.getParent();
if (parent.isRest() || parent.isDefaultValue()) {
// e.g. `function foo(targetNode1 = default, ...targetNode2) {}`
parent = parent.getParent();
checkState(parent.isParamList(), parent);
} else if (parent.isDestructuringLhs()) {
// e.g. `let [a, b] = something;` targetNode is `[a, b]`
parent = parent.getParent();
checkState(isNameDeclaration(parent), parent);
} else if (parent.isClass() || parent.isFunction()) {
// e.g. `function targetNode() {}`
// e.g. `class targetNode {}`
checkState(targetNode == parent.getFirstChild(), targetNode);
} else if (parent.isImportSpec()) {
// e.g. `import {foo as targetNode} from './foo';
checkState(targetNode == parent.getSecondChild(), targetNode);
// import -> import_specs -> import_spec
// we want import
parent = parent.getGrandparent();
checkState(parent.isImport(), parent);
} else {
// e.g. `function foo(targetNode) {};`
// e.g. `let targetNode = something;`
// e.g. `import targetNode from './foo';
// e.g. `} catch (foo) {`
checkState(
parent.isParamList()
|| isNameDeclaration(parent)
|| parent.isImport()
|| parent.isCatch(),
parent);
}
return parent;
} | [
"public",
"static",
"Node",
"getDeclaringParent",
"(",
"Node",
"targetNode",
")",
"{",
"Node",
"rootTarget",
"=",
"getRootTarget",
"(",
"targetNode",
")",
";",
"Node",
"parent",
"=",
"rootTarget",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
... | Returns the node that is effectively declaring the given target.
<p>Examples:
<pre><code>
const a = 1; // getDeclaringParent(a) returns CONST
let {[expression]: [x = 3]} = obj; // getDeclaringParent(x) returns LET
function foo({a, b}) {}; // getDeclaringParent(a) returns PARAM_LIST
function foo(a = 1) {}; // getDeclaringParent(a) returns PARAM_LIST
function foo({a, b} = obj) {}; // getDeclaringParent(a) returns PARAM_LIST
function foo(...a) {}; // getDeclaringParent(a) returns PARAM_LIST
function foo() {}; // gotRootTarget(foo) returns FUNCTION
class foo {}; // gotRootTarget(foo) returns CLASS
import foo from './foo'; // getDeclaringParent(foo) returns IMPORT
import {foo} from './foo'; // getDeclaringParent(foo) returns IMPORT
import {foo as bar} from './foo'; // getDeclaringParent(bar) returns IMPORT
} catch (err) { // getDeclaringParent(err) returns CATCH
</code></pre>
@param targetNode a NAME, OBJECT_PATTERN, or ARRAY_PATTERN
@return node of type LET, CONST, VAR, FUNCTION, CLASS, PARAM_LIST, CATCH, or IMPORT
@throws IllegalStateException if targetNode is not actually used as a declaration target | [
"Returns",
"the",
"node",
"that",
"is",
"effectively",
"declaring",
"the",
"given",
"target",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L3439-L3474 |
alkacon/opencms-core | src/org/opencms/importexport/CmsImportVersion10.java | CmsImportVersion10.addRelation | public void addRelation() {
try {
if (m_throwable != null) {
// relation data is corrupt, ignore relation
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_IMPORTEXPORT_ERROR_IMPORTING_RELATION_1,
m_destination),
m_throwable);
}
getReport().println(m_throwable);
getReport().addError(m_throwable);
m_throwable = null;
return;
}
RelationData relData = new RelationData(m_relationPath, m_relationId, m_relationType);
m_relationsForResource.add(relData);
m_relationData.put(Integer.valueOf(m_fileCounter), relData);
} finally {
m_relationId = null;
m_relationPath = null;
m_relationType = null;
}
} | java | public void addRelation() {
try {
if (m_throwable != null) {
// relation data is corrupt, ignore relation
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(
Messages.LOG_IMPORTEXPORT_ERROR_IMPORTING_RELATION_1,
m_destination),
m_throwable);
}
getReport().println(m_throwable);
getReport().addError(m_throwable);
m_throwable = null;
return;
}
RelationData relData = new RelationData(m_relationPath, m_relationId, m_relationType);
m_relationsForResource.add(relData);
m_relationData.put(Integer.valueOf(m_fileCounter), relData);
} finally {
m_relationId = null;
m_relationPath = null;
m_relationType = null;
}
} | [
"public",
"void",
"addRelation",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"m_throwable",
"!=",
"null",
")",
"{",
"// relation data is corrupt, ignore relation",
"if",
"(",
"LOG",
".",
"isWarnEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"Messages",
"... | Adds a relation to be imported from the current xml data.<p>
@see #addResourceRelationRules(Digester, String) | [
"Adds",
"a",
"relation",
"to",
"be",
"imported",
"from",
"the",
"current",
"xml",
"data",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportVersion10.java#L824-L849 |
phax/ph-bdve | ph-bdve-cii/src/main/java/com/helger/bdve/cii/CIIValidation.java | CIIValidation.initCIID16B | public static void initCIID16B (@Nonnull final ValidationExecutorSetRegistry aRegistry)
{
ValueEnforcer.notNull (aRegistry, "Registry");
// For better error messages
LocationBeautifierSPI.addMappings (CIID16BNamespaceContext.getInstance ());
final boolean bNotDeprecated = false;
for (final ECIID16BDocumentType e : ECIID16BDocumentType.values ())
{
final String sName = e.getLocalName ();
final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_D16B);
// No Schematrons here
aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID,
"CII " + sName + " " + VERSION_D16B,
bNotDeprecated,
ValidationExecutorXSD.create (e)));
}
} | java | public static void initCIID16B (@Nonnull final ValidationExecutorSetRegistry aRegistry)
{
ValueEnforcer.notNull (aRegistry, "Registry");
// For better error messages
LocationBeautifierSPI.addMappings (CIID16BNamespaceContext.getInstance ());
final boolean bNotDeprecated = false;
for (final ECIID16BDocumentType e : ECIID16BDocumentType.values ())
{
final String sName = e.getLocalName ();
final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_D16B);
// No Schematrons here
aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID,
"CII " + sName + " " + VERSION_D16B,
bNotDeprecated,
ValidationExecutorXSD.create (e)));
}
} | [
"public",
"static",
"void",
"initCIID16B",
"(",
"@",
"Nonnull",
"final",
"ValidationExecutorSetRegistry",
"aRegistry",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aRegistry",
",",
"\"Registry\"",
")",
";",
"// For better error messages",
"LocationBeautifierSPI",
".... | Register all standard CII D16B validation execution sets to the provided
registry.
@param aRegistry
The registry to add the artefacts. May not be <code>null</code>. | [
"Register",
"all",
"standard",
"CII",
"D16B",
"validation",
"execution",
"sets",
"to",
"the",
"provided",
"registry",
"."
] | train | https://github.com/phax/ph-bdve/blob/2438f491174cd8989567fcdf129b273bd217e89f/ph-bdve-cii/src/main/java/com/helger/bdve/cii/CIIValidation.java#L58-L77 |
kaazing/gateway | mina.netty/src/main/java/org/kaazing/mina/core/future/DefaultBindFuture.java | DefaultBindFuture.combineFutures | public static BindFuture combineFutures(BindFuture future1, BindFuture future2) {
if (future1 == null || future1.isBound()) {
return future2;
}
else if (future2 == null || future2.isBound()) {
return future1;
}
else {
return new CompositeBindFuture(Arrays.asList(future1, future2));
}
} | java | public static BindFuture combineFutures(BindFuture future1, BindFuture future2) {
if (future1 == null || future1.isBound()) {
return future2;
}
else if (future2 == null || future2.isBound()) {
return future1;
}
else {
return new CompositeBindFuture(Arrays.asList(future1, future2));
}
} | [
"public",
"static",
"BindFuture",
"combineFutures",
"(",
"BindFuture",
"future1",
",",
"BindFuture",
"future2",
")",
"{",
"if",
"(",
"future1",
"==",
"null",
"||",
"future1",
".",
"isBound",
"(",
")",
")",
"{",
"return",
"future2",
";",
"}",
"else",
"if",
... | Combine futures in a way that minimizes cost(no object creation) for the common case where
both have already been fulfilled. | [
"Combine",
"futures",
"in",
"a",
"way",
"that",
"minimizes",
"cost",
"(",
"no",
"object",
"creation",
")",
"for",
"the",
"common",
"case",
"where",
"both",
"have",
"already",
"been",
"fulfilled",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.netty/src/main/java/org/kaazing/mina/core/future/DefaultBindFuture.java#L44-L54 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/XbaseTypeComputer.java | XbaseTypeComputer.addLocalToCurrentScope | protected void addLocalToCurrentScope(XExpression expression, ITypeComputationState state) {
if (expression instanceof XVariableDeclaration) {
addLocalToCurrentScope((XVariableDeclaration)expression, state);
}
} | java | protected void addLocalToCurrentScope(XExpression expression, ITypeComputationState state) {
if (expression instanceof XVariableDeclaration) {
addLocalToCurrentScope((XVariableDeclaration)expression, state);
}
} | [
"protected",
"void",
"addLocalToCurrentScope",
"(",
"XExpression",
"expression",
",",
"ITypeComputationState",
"state",
")",
"{",
"if",
"(",
"expression",
"instanceof",
"XVariableDeclaration",
")",
"{",
"addLocalToCurrentScope",
"(",
"(",
"XVariableDeclaration",
")",
"e... | If the expression is a variable declaration, then add it to the current scope;
DSLs introducing new containers for variable declarations should override this method
and explicitly add nested variable declarations.
@since 2.9 | [
"If",
"the",
"expression",
"is",
"a",
"variable",
"declaration",
"then",
"add",
"it",
"to",
"the",
"current",
"scope",
";",
"DSLs",
"introducing",
"new",
"containers",
"for",
"variable",
"declarations",
"should",
"override",
"this",
"method",
"and",
"explicitly"... | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/XbaseTypeComputer.java#L511-L515 |
jbehave/jbehave-core | jbehave-groovy/src/main/java/org/jbehave/core/configuration/groovy/GroovyContext.java | GroovyContext.newInstance | public Object newInstance(String resource) {
try {
String name = resource.startsWith("/") ? resource : "/" + resource;
File file = new File(this.getClass().getResource(name).toURI());
return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));
} catch (Exception e) {
throw new GroovyClassInstantiationFailed(classLoader, resource, e);
}
} | java | public Object newInstance(String resource) {
try {
String name = resource.startsWith("/") ? resource : "/" + resource;
File file = new File(this.getClass().getResource(name).toURI());
return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true));
} catch (Exception e) {
throw new GroovyClassInstantiationFailed(classLoader, resource, e);
}
} | [
"public",
"Object",
"newInstance",
"(",
"String",
"resource",
")",
"{",
"try",
"{",
"String",
"name",
"=",
"resource",
".",
"startsWith",
"(",
"\"/\"",
")",
"?",
"resource",
":",
"\"/\"",
"+",
"resource",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"... | Creates an object instance from the Groovy resource
@param resource the Groovy resource to parse
@return An Object instance | [
"Creates",
"an",
"object",
"instance",
"from",
"the",
"Groovy",
"resource"
] | train | https://github.com/jbehave/jbehave-core/blob/bdd6a6199528df3c35087e72d4644870655b23e6/jbehave-groovy/src/main/java/org/jbehave/core/configuration/groovy/GroovyContext.java#L59-L67 |
samskivert/samskivert | src/main/java/com/samskivert/swing/util/SwingUtil.java | SwingUtil.restoreAntiAliasing | public static void restoreAntiAliasing (Graphics2D gfx, Object rock)
{
if (rock != null) {
gfx.setRenderingHints((RenderingHints)rock);
}
} | java | public static void restoreAntiAliasing (Graphics2D gfx, Object rock)
{
if (rock != null) {
gfx.setRenderingHints((RenderingHints)rock);
}
} | [
"public",
"static",
"void",
"restoreAntiAliasing",
"(",
"Graphics2D",
"gfx",
",",
"Object",
"rock",
")",
"{",
"if",
"(",
"rock",
"!=",
"null",
")",
"{",
"gfx",
".",
"setRenderingHints",
"(",
"(",
"RenderingHints",
")",
"rock",
")",
";",
"}",
"}"
] | Restores anti-aliasing in the supplied graphics context to its original setting.
@param rock the results of a previous call to {@link #activateAntiAliasing} or null, in
which case this method will NOOP. This alleviates every caller having to conditionally avoid
calling restore if they chose not to activate earlier. | [
"Restores",
"anti",
"-",
"aliasing",
"in",
"the",
"supplied",
"graphics",
"context",
"to",
"its",
"original",
"setting",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/SwingUtil.java#L429-L434 |
meertensinstituut/mtas | src/main/java/mtas/codec/util/CodecCollector.java | CodecCollector.computeTermvectorNumberBasic | private static TermvectorNumberBasic computeTermvectorNumberBasic(
List<Integer> docSet, int termDocId, TermsEnum termsEnum, LeafReader r,
LeafReaderContext lrc, PostingsEnum postingsEnum) throws IOException {
TermvectorNumberBasic result = new TermvectorNumberBasic();
boolean hasDeletedDocuments = (r.getLiveDocs() != null);
if ((docSet.size() == r.numDocs()) && !hasDeletedDocuments) {
try {
return computeTermvectorNumberBasic(termsEnum, r);
} catch (IOException e) {
log.debug("problem", e);
// problem
}
}
result.docNumber = 0;
result.valueSum[0] = 0;
int localTermDocId = termDocId;
Iterator<Integer> docIterator = docSet.iterator();
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.FREQS);
int docId;
while (docIterator.hasNext()) {
docId = docIterator.next() - lrc.docBase;
if (docId >= localTermDocId && ((docId == localTermDocId)
|| ((localTermDocId = postingsEnum.advance(docId)) == docId))) {
result.docNumber++;
result.valueSum[0] += postingsEnum.freq();
}
if (localTermDocId == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
}
return result;
} | java | private static TermvectorNumberBasic computeTermvectorNumberBasic(
List<Integer> docSet, int termDocId, TermsEnum termsEnum, LeafReader r,
LeafReaderContext lrc, PostingsEnum postingsEnum) throws IOException {
TermvectorNumberBasic result = new TermvectorNumberBasic();
boolean hasDeletedDocuments = (r.getLiveDocs() != null);
if ((docSet.size() == r.numDocs()) && !hasDeletedDocuments) {
try {
return computeTermvectorNumberBasic(termsEnum, r);
} catch (IOException e) {
log.debug("problem", e);
// problem
}
}
result.docNumber = 0;
result.valueSum[0] = 0;
int localTermDocId = termDocId;
Iterator<Integer> docIterator = docSet.iterator();
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.FREQS);
int docId;
while (docIterator.hasNext()) {
docId = docIterator.next() - lrc.docBase;
if (docId >= localTermDocId && ((docId == localTermDocId)
|| ((localTermDocId = postingsEnum.advance(docId)) == docId))) {
result.docNumber++;
result.valueSum[0] += postingsEnum.freq();
}
if (localTermDocId == DocIdSetIterator.NO_MORE_DOCS) {
break;
}
}
return result;
} | [
"private",
"static",
"TermvectorNumberBasic",
"computeTermvectorNumberBasic",
"(",
"List",
"<",
"Integer",
">",
"docSet",
",",
"int",
"termDocId",
",",
"TermsEnum",
"termsEnum",
",",
"LeafReader",
"r",
",",
"LeafReaderContext",
"lrc",
",",
"PostingsEnum",
"postingsEnu... | Compute termvector number basic.
@param docSet
the doc set
@param termDocId
the term doc id
@param termsEnum
the terms enum
@param r
the r
@param lrc
the lrc
@param postingsEnum
the postings enum
@return the termvector number basic
@throws IOException
Signals that an I/O exception has occurred. | [
"Compute",
"termvector",
"number",
"basic",
"."
] | train | https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/codec/util/CodecCollector.java#L4163-L4194 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java | BouncyCastleCertProcessingFactory.createCertificate | public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType) throws IOException,
GeneralSecurityException {
return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, (X509ExtensionSet) null,
null);
} | java | public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType) throws IOException,
GeneralSecurityException {
return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, (X509ExtensionSet) null,
null);
} | [
"public",
"X509Certificate",
"createCertificate",
"(",
"InputStream",
"certRequestInputStream",
",",
"X509Certificate",
"cert",
",",
"PrivateKey",
"privateKey",
",",
"int",
"lifetime",
",",
"GSIConstants",
".",
"CertificateType",
"certType",
")",
"throws",
"IOException",
... | Creates a proxy certificate from the certificate request.
@see #createCertificate(InputStream, X509Certificate, PrivateKey, int, int, X509ExtensionSet, String)
createCertificate | [
"Creates",
"a",
"proxy",
"certificate",
"from",
"the",
"certificate",
"request",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java#L519-L524 |
azkaban/azkaban | azkaban-common/src/main/java/azkaban/project/ProjectManager.java | ProjectManager.purgeProject | public synchronized Project purgeProject(final Project project, final User deleter)
throws ProjectManagerException {
this.projectLoader.cleanOlderProjectVersion(project.getId(),
project.getVersion() + 1, Collections.emptyList());
this.projectLoader
.postEvent(project, EventType.PURGE, deleter.getUserId(), String
.format("Purged versions before %d", project.getVersion() + 1));
return project;
} | java | public synchronized Project purgeProject(final Project project, final User deleter)
throws ProjectManagerException {
this.projectLoader.cleanOlderProjectVersion(project.getId(),
project.getVersion() + 1, Collections.emptyList());
this.projectLoader
.postEvent(project, EventType.PURGE, deleter.getUserId(), String
.format("Purged versions before %d", project.getVersion() + 1));
return project;
} | [
"public",
"synchronized",
"Project",
"purgeProject",
"(",
"final",
"Project",
"project",
",",
"final",
"User",
"deleter",
")",
"throws",
"ProjectManagerException",
"{",
"this",
".",
"projectLoader",
".",
"cleanOlderProjectVersion",
"(",
"project",
".",
"getId",
"(",... | Permanently delete all project files and properties data for all versions of a project and log
event in project_events table | [
"Permanently",
"delete",
"all",
"project",
"files",
"and",
"properties",
"data",
"for",
"all",
"versions",
"of",
"a",
"project",
"and",
"log",
"event",
"in",
"project_events",
"table"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/ProjectManager.java#L315-L323 |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/Batch.java | Batch.query | private <T> QueryRequest<T> query(String fql, JavaType type) {
this.checkForBatchExecution();
if (this.multiqueryRequest == null) {
this.multiqueryRequest = new MultiqueryRequest(mapper, this.createUnmappedChain());
this.graphRequests.add(this.multiqueryRequest);
}
// There is a circular reference between the extractor and request, so construction of the chain
// is a little complicated
QueryNodeExtractor extractor = new QueryNodeExtractor(this.multiqueryRequest);
String name = "__q" + this.generatedQueryNameIndex++;
QueryRequest<T> q =
new QueryRequest<T>(fql, name,
new MapperWrapper<T>(type, this.mapper,
extractor));
extractor.setRequest(q);
this.multiqueryRequest.addQuery(q);
return q;
} | java | private <T> QueryRequest<T> query(String fql, JavaType type) {
this.checkForBatchExecution();
if (this.multiqueryRequest == null) {
this.multiqueryRequest = new MultiqueryRequest(mapper, this.createUnmappedChain());
this.graphRequests.add(this.multiqueryRequest);
}
// There is a circular reference between the extractor and request, so construction of the chain
// is a little complicated
QueryNodeExtractor extractor = new QueryNodeExtractor(this.multiqueryRequest);
String name = "__q" + this.generatedQueryNameIndex++;
QueryRequest<T> q =
new QueryRequest<T>(fql, name,
new MapperWrapper<T>(type, this.mapper,
extractor));
extractor.setRequest(q);
this.multiqueryRequest.addQuery(q);
return q;
} | [
"private",
"<",
"T",
">",
"QueryRequest",
"<",
"T",
">",
"query",
"(",
"String",
"fql",
",",
"JavaType",
"type",
")",
"{",
"this",
".",
"checkForBatchExecution",
"(",
")",
";",
"if",
"(",
"this",
".",
"multiqueryRequest",
"==",
"null",
")",
"{",
"this"... | Implementation now that we have chosen a Jackson JavaType for the return value | [
"Implementation",
"now",
"that",
"we",
"have",
"chosen",
"a",
"Jackson",
"JavaType",
"for",
"the",
"return",
"value"
] | train | https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/impl/Batch.java#L233-L255 |
ist-dresden/composum | sling/core/commons/src/main/java/com/composum/sling/core/util/JsonUtil.java | JsonUtil.getValueString | public static String getValueString(Object value, int type, MappingRules mapping) {
String string = value.toString();
if (type != PropertyType.STRING &&
mapping.propertyFormat.embedType &&
mapping.propertyFormat.scope == MappingRules.PropertyFormat.Scope.value) {
string = "{" + PropertyType.nameFromValue(type) + "}" + string;
}
return string;
} | java | public static String getValueString(Object value, int type, MappingRules mapping) {
String string = value.toString();
if (type != PropertyType.STRING &&
mapping.propertyFormat.embedType &&
mapping.propertyFormat.scope == MappingRules.PropertyFormat.Scope.value) {
string = "{" + PropertyType.nameFromValue(type) + "}" + string;
}
return string;
} | [
"public",
"static",
"String",
"getValueString",
"(",
"Object",
"value",
",",
"int",
"type",
",",
"MappingRules",
"mapping",
")",
"{",
"String",
"string",
"=",
"value",
".",
"toString",
"(",
")",
";",
"if",
"(",
"type",
"!=",
"PropertyType",
".",
"STRING",
... | Embeds the property type in the string value if the formats scope is 'value'.
@param value
@param type
@param mapping
@return | [
"Embeds",
"the",
"property",
"type",
"in",
"the",
"string",
"value",
"if",
"the",
"formats",
"scope",
"is",
"value",
"."
] | train | https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/util/JsonUtil.java#L948-L956 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/PropertiesUtils.java | PropertiesUtils.saveProperties | public static void saveProperties(final File file, final Properties props, final String comment) {
checkNotNull("file", file);
checkNotNull("props", props);
if (!file.getParentFile().exists()) {
throw new IllegalArgumentException("The parent directory '" + file.getParentFile() + "' does not exist [file='" + file + "']!");
}
try (final OutputStream outStream = new FileOutputStream(file)) {
props.store(outStream, comment);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
} | java | public static void saveProperties(final File file, final Properties props, final String comment) {
checkNotNull("file", file);
checkNotNull("props", props);
if (!file.getParentFile().exists()) {
throw new IllegalArgumentException("The parent directory '" + file.getParentFile() + "' does not exist [file='" + file + "']!");
}
try (final OutputStream outStream = new FileOutputStream(file)) {
props.store(outStream, comment);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
} | [
"public",
"static",
"void",
"saveProperties",
"(",
"final",
"File",
"file",
",",
"final",
"Properties",
"props",
",",
"final",
"String",
"comment",
")",
"{",
"checkNotNull",
"(",
"\"file\"",
",",
"file",
")",
";",
"checkNotNull",
"(",
"\"props\"",
",",
"prop... | Save properties to a file.
@param file
Destination file - Cannot be <code>null</code> and parent directory must exist.
@param props
Properties to save - Cannot be <code>null</code>.
@param comment
Comment for the file. | [
"Save",
"properties",
"to",
"a",
"file",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesUtils.java#L123-L135 |
derari/cthul | objects/src/main/java/org/cthul/objects/Boxing.java | Boxing.deepBox | public static Object[] deepBox(Class<?> resultType, final Object src) {
Class<?> compType = resultType.getComponentType();
if (compType.isArray()) {
final Object[] src2 = (Object[]) src;
final Object[] result = (Object[]) newArray(compType, src2.length);
for (int i = 0; i < src2.length; i++) {
result[i] = deepBox(compType, src2[i]);
}
return result;
} else {
return boxAll(compType, src, 0, -1);
}
} | java | public static Object[] deepBox(Class<?> resultType, final Object src) {
Class<?> compType = resultType.getComponentType();
if (compType.isArray()) {
final Object[] src2 = (Object[]) src;
final Object[] result = (Object[]) newArray(compType, src2.length);
for (int i = 0; i < src2.length; i++) {
result[i] = deepBox(compType, src2[i]);
}
return result;
} else {
return boxAll(compType, src, 0, -1);
}
} | [
"public",
"static",
"Object",
"[",
"]",
"deepBox",
"(",
"Class",
"<",
"?",
">",
"resultType",
",",
"final",
"Object",
"src",
")",
"{",
"Class",
"<",
"?",
">",
"compType",
"=",
"resultType",
".",
"getComponentType",
"(",
")",
";",
"if",
"(",
"compType",... | Returns any multidimensional array into an array of boxed values.
@param resultType target type
@param src source array
@return multidimensional array | [
"Returns",
"any",
"multidimensional",
"array",
"into",
"an",
"array",
"of",
"boxed",
"values",
"."
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/Boxing.java#L724-L736 |
RestComm/sip-servlets | sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/ExtendedListeningPoint.java | ExtendedListeningPoint.createContactHeader | public ContactHeader createContactHeader(String displayName, String userName, boolean usePublicAddress, String outboundInterface) {
try {
// FIXME : the SIP URI can be cached to improve performance
String host = null;
if(outboundInterface!=null){
javax.sip.address.SipURI outboundInterfaceURI = (javax.sip.address.SipURI) SipFactoryImpl.addressFactory.createURI(outboundInterface);
host = outboundInterfaceURI.getHost();
} else {
host = getIpAddress(usePublicAddress);
}
javax.sip.address.SipURI sipURI = SipFactoryImpl.addressFactory.createSipURI(userName, host);
sipURI.setHost(host);
sipURI.setPort(port);
// Issue 1150 : we assume that if the transport match the default protocol of the transport protocol used it is not added
// See RFC 32661 Section 19.1.2 Character Escaping Requirements :
// (2): The default transport is scheme dependent. For sip:, it is UDP. For sips:, it is TCP.
if((!sipURI.isSecure() && !ListeningPoint.UDP.equalsIgnoreCase(transport)) || (sipURI.isSecure() && !ListeningPoint.TCP.equalsIgnoreCase(transport))) {
sipURI.setTransportParam(transport);
}
javax.sip.address.Address contactAddress = SipFactoryImpl.addressFactory.createAddress(sipURI);
ContactHeader contact = SipFactoryImpl.headerFactory.createContactHeader(contactAddress);
if(displayName != null && displayName.length() > 0) {
contactAddress.setDisplayName(displayName);
}
return contact;
} catch (ParseException ex) {
logger.error ("Unexpected error while creating the contact header for the extended listening point",ex);
throw new IllegalArgumentException("Unexpected exception when creating a sip URI", ex);
}
} | java | public ContactHeader createContactHeader(String displayName, String userName, boolean usePublicAddress, String outboundInterface) {
try {
// FIXME : the SIP URI can be cached to improve performance
String host = null;
if(outboundInterface!=null){
javax.sip.address.SipURI outboundInterfaceURI = (javax.sip.address.SipURI) SipFactoryImpl.addressFactory.createURI(outboundInterface);
host = outboundInterfaceURI.getHost();
} else {
host = getIpAddress(usePublicAddress);
}
javax.sip.address.SipURI sipURI = SipFactoryImpl.addressFactory.createSipURI(userName, host);
sipURI.setHost(host);
sipURI.setPort(port);
// Issue 1150 : we assume that if the transport match the default protocol of the transport protocol used it is not added
// See RFC 32661 Section 19.1.2 Character Escaping Requirements :
// (2): The default transport is scheme dependent. For sip:, it is UDP. For sips:, it is TCP.
if((!sipURI.isSecure() && !ListeningPoint.UDP.equalsIgnoreCase(transport)) || (sipURI.isSecure() && !ListeningPoint.TCP.equalsIgnoreCase(transport))) {
sipURI.setTransportParam(transport);
}
javax.sip.address.Address contactAddress = SipFactoryImpl.addressFactory.createAddress(sipURI);
ContactHeader contact = SipFactoryImpl.headerFactory.createContactHeader(contactAddress);
if(displayName != null && displayName.length() > 0) {
contactAddress.setDisplayName(displayName);
}
return contact;
} catch (ParseException ex) {
logger.error ("Unexpected error while creating the contact header for the extended listening point",ex);
throw new IllegalArgumentException("Unexpected exception when creating a sip URI", ex);
}
} | [
"public",
"ContactHeader",
"createContactHeader",
"(",
"String",
"displayName",
",",
"String",
"userName",
",",
"boolean",
"usePublicAddress",
",",
"String",
"outboundInterface",
")",
"{",
"try",
"{",
"// FIXME : the SIP URI can be cached to improve performance ",
"String",
... | Create a Contact Header based on the host, port and transport of this listening point
@param usePublicAddress if true, the host will be the global ip address found by STUN otherwise
it will be the local network interface ipaddress
@param displayName the display name to use
@param outboundInterface the outbound interface ip address to be used for the host part of the Contact header
@return the Contact header | [
"Create",
"a",
"Contact",
"Header",
"based",
"on",
"the",
"host",
"port",
"and",
"transport",
"of",
"this",
"listening",
"point"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/ExtendedListeningPoint.java#L143-L174 |
jMetal/jMetal | jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java | ScalarizationUtils.weightedProduct | public static <S extends Solution<?>> void weightedProduct(List<S> solutionsList, double[] weights) {
for (S solution : solutionsList) {
double product = Math.pow(solution.getObjective(0), weights[0]);
for (int i = 1; i < solution.getNumberOfObjectives(); i++) {
product *= Math.pow(solution.getObjective(i), weights[i]);
}
setScalarizationValue(solution, product);
}
} | java | public static <S extends Solution<?>> void weightedProduct(List<S> solutionsList, double[] weights) {
for (S solution : solutionsList) {
double product = Math.pow(solution.getObjective(0), weights[0]);
for (int i = 1; i < solution.getNumberOfObjectives(); i++) {
product *= Math.pow(solution.getObjective(i), weights[i]);
}
setScalarizationValue(solution, product);
}
} | [
"public",
"static",
"<",
"S",
"extends",
"Solution",
"<",
"?",
">",
">",
"void",
"weightedProduct",
"(",
"List",
"<",
"S",
">",
"solutionsList",
",",
"double",
"[",
"]",
"weights",
")",
"{",
"for",
"(",
"S",
"solution",
":",
"solutionsList",
")",
"{",
... | Objectives are exponentiated by a positive weight and afterwards
multiplied.
@param solutionsList A list of solutions.
@param weights Weights by objectives are exponentiated | [
"Objectives",
"are",
"exponentiated",
"by",
"a",
"positive",
"weight",
"and",
"afterwards",
"multiplied",
"."
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java#L161-L169 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Maps.java | Maps.removeIf | public static <K, V, E extends Exception> boolean removeIf(final Map<K, V> map, final Try.Predicate<? super Map.Entry<K, V>, E> filter) throws E {
List<K> keysToRemove = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (filter.test(entry)) {
if (keysToRemove == null) {
keysToRemove = new ArrayList<>(7);
}
keysToRemove.add(entry.getKey());
}
}
if (N.notNullOrEmpty(keysToRemove)) {
for (K key : keysToRemove) {
map.remove(key);
}
return true;
}
return false;
} | java | public static <K, V, E extends Exception> boolean removeIf(final Map<K, V> map, final Try.Predicate<? super Map.Entry<K, V>, E> filter) throws E {
List<K> keysToRemove = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
if (filter.test(entry)) {
if (keysToRemove == null) {
keysToRemove = new ArrayList<>(7);
}
keysToRemove.add(entry.getKey());
}
}
if (N.notNullOrEmpty(keysToRemove)) {
for (K key : keysToRemove) {
map.remove(key);
}
return true;
}
return false;
} | [
"public",
"static",
"<",
"K",
",",
"V",
",",
"E",
"extends",
"Exception",
">",
"boolean",
"removeIf",
"(",
"final",
"Map",
"<",
"K",
",",
"V",
">",
"map",
",",
"final",
"Try",
".",
"Predicate",
"<",
"?",
"super",
"Map",
".",
"Entry",
"<",
"K",
",... | Removes entries from the specified {@code map} by the the specified {@code filter}.
@param map
@param filter
@return {@code true} if there are one or more than one entries removed from the specified map.
@throws E | [
"Removes",
"entries",
"from",
"the",
"specified",
"{",
"@code",
"map",
"}",
"by",
"the",
"the",
"specified",
"{",
"@code",
"filter",
"}",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Maps.java#L599-L621 |
spring-projects/spring-social-facebook | spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java | FqlResult.getLong | public Long getLong(String fieldName) {
try {
return hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
} | java | public Long getLong(String fieldName) {
try {
return hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
} | [
"public",
"Long",
"getLong",
"(",
"String",
"fieldName",
")",
"{",
"try",
"{",
"return",
"hasValue",
"(",
"fieldName",
")",
"?",
"Long",
".",
"valueOf",
"(",
"String",
".",
"valueOf",
"(",
"resultMap",
".",
"get",
"(",
"fieldName",
")",
")",
")",
":",
... | Returns the value of the identified field as a Long.
@param fieldName the name of the field
@return the value of the field as a Long
@throws FqlException if the field cannot be expressed as an Long | [
"Returns",
"the",
"value",
"of",
"the",
"identified",
"field",
"as",
"a",
"Long",
"."
] | train | https://github.com/spring-projects/spring-social-facebook/blob/ae2234d94367eaa3adbba251ec7790d5ba7ffa41/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/FqlResult.java#L69-L75 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java | IntrospectionUtils.getFieldValue | public static Object getFieldValue(FieldMetadata fieldMetadata, Object target) {
MethodHandle readMethod = fieldMetadata.getReadMethod();
try {
return readMethod.invoke(target);
} catch (Throwable t) {
throw new EntityManagerException(t.getMessage(), t);
}
} | java | public static Object getFieldValue(FieldMetadata fieldMetadata, Object target) {
MethodHandle readMethod = fieldMetadata.getReadMethod();
try {
return readMethod.invoke(target);
} catch (Throwable t) {
throw new EntityManagerException(t.getMessage(), t);
}
} | [
"public",
"static",
"Object",
"getFieldValue",
"(",
"FieldMetadata",
"fieldMetadata",
",",
"Object",
"target",
")",
"{",
"MethodHandle",
"readMethod",
"=",
"fieldMetadata",
".",
"getReadMethod",
"(",
")",
";",
"try",
"{",
"return",
"readMethod",
".",
"invoke",
"... | Returns the value of the field represented by the given metadata.
@param fieldMetadata
the metadata of the field
@param target
the target object to which the field belongs.
@return the value of the field. | [
"Returns",
"the",
"value",
"of",
"the",
"field",
"represented",
"by",
"the",
"given",
"metadata",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/IntrospectionUtils.java#L376-L383 |
FINRAOS/DataGenerator | dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java | SocialNetworkUtilities.areCoordinatesWithinThreshold | public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {
return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD;
} | java | public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) {
return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD;
} | [
"public",
"static",
"Boolean",
"areCoordinatesWithinThreshold",
"(",
"Tuple2",
"<",
"Double",
",",
"Double",
">",
"point1",
",",
"Tuple2",
"<",
"Double",
",",
"Double",
">",
"point2",
")",
"{",
"return",
"getDistanceBetweenCoordinates",
"(",
"point1",
",",
"poin... | Whether or not points are within some threshold.
@param point1 Point 1
@param point2 Point 2
@return True or false | [
"Whether",
"or",
"not",
"points",
"are",
"within",
"some",
"threshold",
"."
] | train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L94-L96 |
moparisthebest/beehive | beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ReflectionFragment.java | ReflectionFragment.hasComplexValue | protected boolean hasComplexValue(ControlBeanContext context, Method m, Object[] args) {
Object val = getParameterValue(context, m, args);
return val instanceof JdbcControl.ComplexSqlFragment;
} | java | protected boolean hasComplexValue(ControlBeanContext context, Method m, Object[] args) {
Object val = getParameterValue(context, m, args);
return val instanceof JdbcControl.ComplexSqlFragment;
} | [
"protected",
"boolean",
"hasComplexValue",
"(",
"ControlBeanContext",
"context",
",",
"Method",
"m",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"Object",
"val",
"=",
"getParameterValue",
"(",
"context",
",",
"m",
",",
"args",
")",
";",
"return",
"val",
"in... | A reflection fragment may evaluate to an JdbcControl.ComplexSqlFragment type,
which requires additional steps to evaluate after reflection.
@param context Control bean context.
@param m Method.
@param args Method args.
@return true or false. | [
"A",
"reflection",
"fragment",
"may",
"evaluate",
"to",
"an",
"JdbcControl",
".",
"ComplexSqlFragment",
"type",
"which",
"requires",
"additional",
"steps",
"to",
"evaluate",
"after",
"reflection",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jdbc-control/src/main/java/org/apache/beehive/controls/system/jdbc/parser/ReflectionFragment.java#L101-L104 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.scale | public static void scale(Image srcImage, ImageOutputStream destImageStream, int width, int height, Color fixedColor) throws IORuntimeException {
writeJpg(scale(srcImage, width, height, fixedColor), destImageStream);
} | java | public static void scale(Image srcImage, ImageOutputStream destImageStream, int width, int height, Color fixedColor) throws IORuntimeException {
writeJpg(scale(srcImage, width, height, fixedColor), destImageStream);
} | [
"public",
"static",
"void",
"scale",
"(",
"Image",
"srcImage",
",",
"ImageOutputStream",
"destImageStream",
",",
"int",
"width",
",",
"int",
"height",
",",
"Color",
"fixedColor",
")",
"throws",
"IORuntimeException",
"{",
"writeJpg",
"(",
"scale",
"(",
"srcImage"... | 缩放图像(按高度和宽度缩放)<br>
缩放后默认为jpeg格式,此方法并不关闭流
@param srcImage 源图像
@param destImageStream 缩放后的图像目标流
@param width 缩放后的宽度
@param height 缩放后的高度
@param fixedColor 比例不对时补充的颜色,不补充为<code>null</code>
@throws IORuntimeException IO异常 | [
"缩放图像(按高度和宽度缩放)<br",
">",
"缩放后默认为jpeg格式,此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L229-L231 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/SetOptions.java | SetOptions.mergeFields | @Nonnull
public static SetOptions mergeFields(List<String> fields) {
List<FieldPath> fieldPaths = new ArrayList<>();
for (String field : fields) {
fieldPaths.add(FieldPath.fromDotSeparatedString(field));
}
return new SetOptions(true, fieldPaths);
} | java | @Nonnull
public static SetOptions mergeFields(List<String> fields) {
List<FieldPath> fieldPaths = new ArrayList<>();
for (String field : fields) {
fieldPaths.add(FieldPath.fromDotSeparatedString(field));
}
return new SetOptions(true, fieldPaths);
} | [
"@",
"Nonnull",
"public",
"static",
"SetOptions",
"mergeFields",
"(",
"List",
"<",
"String",
">",
"fields",
")",
"{",
"List",
"<",
"FieldPath",
">",
"fieldPaths",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"String",
"field",
":",
"fields",... | Changes the behavior of set() calls to only replace the fields under fieldPaths. Any field that
is not specified in fieldPaths is ignored and remains untouched.
<p>It is an error to pass a SetOptions object to a set() call that is missing a value for any
of the fields specified here.
@param fields The list of fields to merge. Fields can contain dots to reference nested fields
within the document. | [
"Changes",
"the",
"behavior",
"of",
"set",
"()",
"calls",
"to",
"only",
"replace",
"the",
"fields",
"under",
"fieldPaths",
".",
"Any",
"field",
"that",
"is",
"not",
"specified",
"in",
"fieldPaths",
"is",
"ignored",
"and",
"remains",
"untouched",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/SetOptions.java#L76-L85 |
sailthru/sailthru-java-client | src/main/com/sailthru/client/SailthruClient.java | SailthruClient.getTemplate | public JsonResponse getTemplate(String template) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Template.PARAM_TEMPLATE, template);
return apiGet(ApiAction.template, data);
} | java | public JsonResponse getTemplate(String template) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Template.PARAM_TEMPLATE, template);
return apiGet(ApiAction.template, data);
} | [
"public",
"JsonResponse",
"getTemplate",
"(",
"String",
"template",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"data",
".",
"put",
"(",
"... | Get template information
@param template template name
@throws IOException | [
"Get",
"template",
"information"
] | train | https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L281-L285 |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilder.java | WebMvcLinkBuilder.methodOn | public static <T> T methodOn(Class<T> controller, Object... parameters) {
return DummyInvocationUtils.methodOn(controller, parameters);
} | java | public static <T> T methodOn(Class<T> controller, Object... parameters) {
return DummyInvocationUtils.methodOn(controller, parameters);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"methodOn",
"(",
"Class",
"<",
"T",
">",
"controller",
",",
"Object",
"...",
"parameters",
")",
"{",
"return",
"DummyInvocationUtils",
".",
"methodOn",
"(",
"controller",
",",
"parameters",
")",
";",
"}"
] | Wrapper for {@link DummyInvocationUtils#methodOn(Class, Object...)} to be available in case you work with static
imports of {@link WebMvcLinkBuilder}.
@param controller must not be {@literal null}.
@param parameters parameters to extend template variables in the type level mapping.
@return | [
"Wrapper",
"for",
"{",
"@link",
"DummyInvocationUtils#methodOn",
"(",
"Class",
"Object",
"...",
")",
"}",
"to",
"be",
"available",
"in",
"case",
"you",
"work",
"with",
"static",
"imports",
"of",
"{",
"@link",
"WebMvcLinkBuilder",
"}",
"."
] | train | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilder.java#L209-L211 |
messagebird/java-rest-api | api/src/main/java/com/messagebird/MessageBirdClient.java | MessageBirdClient.updateConversation | public Conversation updateConversation(final String id, final ConversationStatus status)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified.");
}
String url = String.format("%s%s/%s", CONVERSATIONS_BASE_URL, CONVERSATION_PATH, id);
return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class);
} | java | public Conversation updateConversation(final String id, final ConversationStatus status)
throws UnauthorizedException, GeneralException {
if (id == null) {
throw new IllegalArgumentException("Id must be specified.");
}
String url = String.format("%s%s/%s", CONVERSATIONS_BASE_URL, CONVERSATION_PATH, id);
return messageBirdService.sendPayLoad("PATCH", url, status, Conversation.class);
} | [
"public",
"Conversation",
"updateConversation",
"(",
"final",
"String",
"id",
",",
"final",
"ConversationStatus",
"status",
")",
"throws",
"UnauthorizedException",
",",
"GeneralException",
"{",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgum... | Updates a conversation.
@param id Conversation to update.
@param status New status for the conversation.
@return The updated Conversation. | [
"Updates",
"a",
"conversation",
"."
] | train | https://github.com/messagebird/java-rest-api/blob/f92cd93afff413e6dc12aa6e41e69f26cbae8941/api/src/main/java/com/messagebird/MessageBirdClient.java#L724-L731 |
apache/incubator-druid | sql/src/main/java/org/apache/druid/sql/calcite/planner/Calcites.java | Calcites.calciteDateToJoda | public static DateTime calciteDateToJoda(final int date, final DateTimeZone timeZone)
{
return DateTimes.EPOCH.plusDays(date).withZoneRetainFields(timeZone);
} | java | public static DateTime calciteDateToJoda(final int date, final DateTimeZone timeZone)
{
return DateTimes.EPOCH.plusDays(date).withZoneRetainFields(timeZone);
} | [
"public",
"static",
"DateTime",
"calciteDateToJoda",
"(",
"final",
"int",
"date",
",",
"final",
"DateTimeZone",
"timeZone",
")",
"{",
"return",
"DateTimes",
".",
"EPOCH",
".",
"plusDays",
"(",
"date",
")",
".",
"withZoneRetainFields",
"(",
"timeZone",
")",
";"... | The inverse of {@link #jodaToCalciteDate(DateTime, DateTimeZone)}.
@param date Calcite style date
@param timeZone session time zone
@return joda timestamp, with time zone set to the session time zone | [
"The",
"inverse",
"of",
"{",
"@link",
"#jodaToCalciteDate",
"(",
"DateTime",
"DateTimeZone",
")",
"}",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/sql/src/main/java/org/apache/druid/sql/calcite/planner/Calcites.java#L338-L341 |
Addicticks/httpsupload | src/main/java/com/addicticks/net/httpsupload/SSLUtils.java | SSLUtils.setNoValidate | public static void setNoValidate(HttpsURLConnection connection, String[] acceptedIssuers) {
SSLContext sc;
try {
// Using "SSL" below means protocols: SSLv3, TLSv1
sc = SSLContext.getInstance("SSL");
sc.init(null, getNonValidatingTrustManagers(acceptedIssuers), new java.security.SecureRandom());
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(SSLUtils.ALLHOSTSVALID_HOSTNAMEVERIFIER);
} catch (NoSuchAlgorithmException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Algorithm SSL not found.", ex);
} catch (KeyManagementException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Error initializing SSL security context.", ex);
}
} | java | public static void setNoValidate(HttpsURLConnection connection, String[] acceptedIssuers) {
SSLContext sc;
try {
// Using "SSL" below means protocols: SSLv3, TLSv1
sc = SSLContext.getInstance("SSL");
sc.init(null, getNonValidatingTrustManagers(acceptedIssuers), new java.security.SecureRandom());
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(SSLUtils.ALLHOSTSVALID_HOSTNAMEVERIFIER);
} catch (NoSuchAlgorithmException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Algorithm SSL not found.", ex);
} catch (KeyManagementException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Error initializing SSL security context.", ex);
}
} | [
"public",
"static",
"void",
"setNoValidate",
"(",
"HttpsURLConnection",
"connection",
",",
"String",
"[",
"]",
"acceptedIssuers",
")",
"{",
"SSLContext",
"sc",
";",
"try",
"{",
"// Using \"SSL\" below means protocols: SSLv3, TLSv1\r",
"sc",
"=",
"SSLContext",
".",
"ge... | Changes the HTTPS connection so that it will not validate the endpoint's
certificates. Also it will not require the URL hostname to match the
common name presented by the endpoint's certificate. This method should
be called <i>before</i> a connection is made on the {@code connection}
object.
<p>
This method is equivalent to <code>--no-check-certificate</code> option when
using the Unix/Linux <code>wget</code> command line tool.
<p>
As an additional feature the issuer of the certificate can be checked
to match (any of) a certain string. If - for example - you create
a self-signed certificate then you decide the 'issuer organization'
yourself and the issuer organization name you used when you created the
certificate can then be validated here. This provides a
little extra security than simply accepting any type of certificate.
@param connection connection to change (must not yet be connected)
@param acceptedIssuers accept only a certificate from one of these issuer
organizations. Checks against the Organization (O) field in the 'Issued
By' section of the server's certficate. This parameter provides some
minimal security. A {@code null} means all issuer organizations are
accepted. | [
"Changes",
"the",
"HTTPS",
"connection",
"so",
"that",
"it",
"will",
"not",
"validate",
"the",
"endpoint",
"s",
"certificates",
".",
"Also",
"it",
"will",
"not",
"require",
"the",
"URL",
"hostname",
"to",
"match",
"the",
"common",
"name",
"presented",
"by",
... | train | https://github.com/Addicticks/httpsupload/blob/261a8e63ec923482a74ffe1352024c1900c55a55/src/main/java/com/addicticks/net/httpsupload/SSLUtils.java#L94-L109 |
GoSimpleLLC/nbvcxz | src/main/java/me/gosimple/nbvcxz/Nbvcxz.java | Nbvcxz.getBestCombination | private List<Match> getBestCombination(final Configuration configuration, final String password)
{
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i));
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches);
Collections.sort(matches, comparator);
return matches;
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches);
}
catch (TimeoutException e)
{
return good_enough_matches;
}
} | java | private List<Match> getBestCombination(final Configuration configuration, final String password)
{
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i));
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches);
Collections.sort(matches, comparator);
return matches;
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches);
}
catch (TimeoutException e)
{
return good_enough_matches;
}
} | [
"private",
"List",
"<",
"Match",
">",
"getBestCombination",
"(",
"final",
"Configuration",
"configuration",
",",
"final",
"String",
"password",
")",
"{",
"this",
".",
"best_matches",
".",
"clear",
"(",
")",
";",
"this",
".",
"best_matches_length",
"=",
"0",
... | Returns the best combination of matches based on multiple methods. We run the password through the
{@code findGoodEnoughCombination} method test to see if is considered "random". If it isn't, we
run it through the {@code findBestCombination} method, which is much more expensive for large
passwords.
@param configuration the configuration
@param password the password
@return the best list of matches, sorted by start index. | [
"Returns",
"the",
"best",
"combination",
"of",
"matches",
"based",
"on",
"multiple",
"methods",
".",
"We",
"run",
"the",
"password",
"through",
"the",
"{",
"@code",
"findGoodEnoughCombination",
"}",
"method",
"test",
"to",
"see",
"if",
"is",
"considered",
"ran... | train | https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/Nbvcxz.java#L262-L292 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.replaceEntries | public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) {
if (log.isDebugEnabled()) {
log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + ".");
}
final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries);
final int entryCount = entryByPath.size();
try {
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip)));
try {
final Set<String> names = new HashSet<String>();
iterate(zip, new ZipEntryCallback() {
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
if (names.add(zipEntry.getName())) {
ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName());
if (entry != null) {
addEntry(entry, out);
}
else {
ZipEntryUtil.copyEntry(zipEntry, in, out);
}
}
else if (log.isDebugEnabled()) {
log.debug("Duplicate entry: {}", zipEntry.getName());
}
}
});
}
finally {
IOUtils.closeQuietly(out);
}
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
return entryByPath.size() < entryCount;
} | java | public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) {
if (log.isDebugEnabled()) {
log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + ".");
}
final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries);
final int entryCount = entryByPath.size();
try {
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip)));
try {
final Set<String> names = new HashSet<String>();
iterate(zip, new ZipEntryCallback() {
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
if (names.add(zipEntry.getName())) {
ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName());
if (entry != null) {
addEntry(entry, out);
}
else {
ZipEntryUtil.copyEntry(zipEntry, in, out);
}
}
else if (log.isDebugEnabled()) {
log.debug("Duplicate entry: {}", zipEntry.getName());
}
}
});
}
finally {
IOUtils.closeQuietly(out);
}
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
return entryByPath.size() < entryCount;
} | [
"public",
"static",
"boolean",
"replaceEntries",
"(",
"File",
"zip",
",",
"ZipEntrySource",
"[",
"]",
"entries",
",",
"File",
"destZip",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Copying '\"",
"+"... | Copies an existing ZIP file and replaces the given entries in it.
@param zip
an existing ZIP file (only read).
@param entries
new ZIP entries to be replaced with.
@param destZip
new ZIP file created.
@return <code>true</code> if at least one entry was replaced. | [
"Copies",
"an",
"existing",
"ZIP",
"file",
"and",
"replaces",
"the",
"given",
"entries",
"in",
"it",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2626-L2662 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/comp/TransTypes.java | TransTypes.addBridges | void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
Type st = types.supertype(origin.type);
while (st.hasTag(CLASS)) {
// if (isSpecialization(st))
addBridges(pos, st.tsym, origin, bridges);
st = types.supertype(st);
}
for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
// if (isSpecialization(l.head))
addBridges(pos, l.head.tsym, origin, bridges);
} | java | void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
Type st = types.supertype(origin.type);
while (st.hasTag(CLASS)) {
// if (isSpecialization(st))
addBridges(pos, st.tsym, origin, bridges);
st = types.supertype(st);
}
for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
// if (isSpecialization(l.head))
addBridges(pos, l.head.tsym, origin, bridges);
} | [
"void",
"addBridges",
"(",
"DiagnosticPosition",
"pos",
",",
"ClassSymbol",
"origin",
",",
"ListBuffer",
"<",
"JCTree",
">",
"bridges",
")",
"{",
"Type",
"st",
"=",
"types",
".",
"supertype",
"(",
"origin",
".",
"type",
")",
";",
"while",
"(",
"st",
".",... | Add all necessary bridges to some class appending them to list buffer.
@param pos The source code position to be used for the bridges.
@param origin The class in which the bridges go.
@param bridges The list buffer to which the bridges are added. | [
"Add",
"all",
"necessary",
"bridges",
"to",
"some",
"class",
"appending",
"them",
"to",
"list",
"buffer",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/comp/TransTypes.java#L464-L474 |
google/gson | gson/src/main/java/com/google/gson/Gson.java | Gson.toJson | public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter();
toJson(src, typeOfSrc, writer);
return writer.toString();
} | java | public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter();
toJson(src, typeOfSrc, writer);
return writer.toString();
} | [
"public",
"String",
"toJson",
"(",
"Object",
"src",
",",
"Type",
"typeOfSrc",
")",
"{",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"toJson",
"(",
"src",
",",
"typeOfSrc",
",",
"writer",
")",
";",
"return",
"writer",
".",
"toStri... | This method serializes the specified object, including those of generic types, into its
equivalent Json representation. This method must be used if the specified object is a generic
type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out
the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
@param src the object for which JSON representation is to be created
@param typeOfSrc The specific genericized type of src. You can obtain
this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
to get the type for {@code Collection<Foo>}, you should use:
<pre>
Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
</pre>
@return Json representation of {@code src} | [
"This",
"method",
"serializes",
"the",
"specified",
"object",
"including",
"those",
"of",
"generic",
"types",
"into",
"its",
"equivalent",
"Json",
"representation",
".",
"This",
"method",
"must",
"be",
"used",
"if",
"the",
"specified",
"object",
"is",
"a",
"ge... | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/Gson.java#L636-L640 |
alkacon/opencms-core | src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java | CmsDefaultAppButtonProvider.createAppFolderButton | public static Component createAppFolderButton(CmsObject cms, final CmsAppCategoryNode node, final Locale locale) {
Button button = createAppFolderIconButton((I_CmsFolderAppCategory)node.getCategory(), locale);
button.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_WIDTH = 855;
private static final int DEFAULT_MAX_APP_PER_ROW = 5;
private static final int MARGIN = 10;
public void buttonClick(ClickEvent event) {
CmsAppHierarchyPanel panel = new CmsAppHierarchyPanel(new CmsDefaultAppButtonProvider());
// panel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
panel.setCaption("Test caption");
panel.fill(node, locale);
Panel realPanel = new Panel();
realPanel.setContent(panel);
realPanel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
int browtherWidth = A_CmsUI.get().getPage().getBrowserWindowWidth();
if (node.getAppConfigurations().size() <= DEFAULT_MAX_APP_PER_ROW) {
panel.setComponentAlignment(panel.getComponent(0), com.vaadin.ui.Alignment.MIDDLE_CENTER);
}
if (browtherWidth < DEFAULT_WIDTH) {
realPanel.setWidth((browtherWidth - (2 * MARGIN)) + "px");
} else {
realPanel.setWidth(DEFAULT_WIDTH + "px");
}
final Window window = CmsBasicDialog.prepareWindow(DialogWidth.content);
window.setResizable(false);
window.setContent(realPanel);
window.setClosable(true);
window.addStyleName("o-close-on-background");
window.setModal(true);
window.setDraggable(false);
CmsAppWorkplaceUi.get().addWindow(window);
}
});
return button;
} | java | public static Component createAppFolderButton(CmsObject cms, final CmsAppCategoryNode node, final Locale locale) {
Button button = createAppFolderIconButton((I_CmsFolderAppCategory)node.getCategory(), locale);
button.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_WIDTH = 855;
private static final int DEFAULT_MAX_APP_PER_ROW = 5;
private static final int MARGIN = 10;
public void buttonClick(ClickEvent event) {
CmsAppHierarchyPanel panel = new CmsAppHierarchyPanel(new CmsDefaultAppButtonProvider());
// panel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
panel.setCaption("Test caption");
panel.fill(node, locale);
Panel realPanel = new Panel();
realPanel.setContent(panel);
realPanel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
int browtherWidth = A_CmsUI.get().getPage().getBrowserWindowWidth();
if (node.getAppConfigurations().size() <= DEFAULT_MAX_APP_PER_ROW) {
panel.setComponentAlignment(panel.getComponent(0), com.vaadin.ui.Alignment.MIDDLE_CENTER);
}
if (browtherWidth < DEFAULT_WIDTH) {
realPanel.setWidth((browtherWidth - (2 * MARGIN)) + "px");
} else {
realPanel.setWidth(DEFAULT_WIDTH + "px");
}
final Window window = CmsBasicDialog.prepareWindow(DialogWidth.content);
window.setResizable(false);
window.setContent(realPanel);
window.setClosable(true);
window.addStyleName("o-close-on-background");
window.setModal(true);
window.setDraggable(false);
CmsAppWorkplaceUi.get().addWindow(window);
}
});
return button;
} | [
"public",
"static",
"Component",
"createAppFolderButton",
"(",
"CmsObject",
"cms",
",",
"final",
"CmsAppCategoryNode",
"node",
",",
"final",
"Locale",
"locale",
")",
"{",
"Button",
"button",
"=",
"createAppFolderIconButton",
"(",
"(",
"I_CmsFolderAppCategory",
")",
... | Creates a properly styled button for the given app.<p>
@param cms the cms context
@param node the node to display a buttom for
@param locale the locale
@return the button component
(I_CmsFolderAppCategory)childNode.getCategory(),
childNode.getAppConfigurations()) | [
"Creates",
"a",
"properly",
"styled",
"button",
"for",
"the",
"given",
"app",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java#L107-L150 |
OpenLiberty/open-liberty | dev/com.ibm.ws.persistence/src/com/ibm/wsspi/persistence/internal/SchemaManager.java | SchemaManager.overrideDatabaseTerminationToken | private void overrideDatabaseTerminationToken(Map<Object, Object> props) {
String overrideTermToken = null;
String platformClassName = _dbMgr.getDatabasePlatformClassName(_pui);
if (platformClassName != null) {
overrideTermToken = platformTerminationToken.get(platformClassName);
}
if (overrideTermToken != null) {
String existing = (String) props.get(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES);
if (existing != null) {
existing = existing + ",";
} else {
existing = "";
}
existing = (existing + "StoredProcedureTerminationToken=" + overrideTermToken);
props.put(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, existing);
}
} | java | private void overrideDatabaseTerminationToken(Map<Object, Object> props) {
String overrideTermToken = null;
String platformClassName = _dbMgr.getDatabasePlatformClassName(_pui);
if (platformClassName != null) {
overrideTermToken = platformTerminationToken.get(platformClassName);
}
if (overrideTermToken != null) {
String existing = (String) props.get(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES);
if (existing != null) {
existing = existing + ",";
} else {
existing = "";
}
existing = (existing + "StoredProcedureTerminationToken=" + overrideTermToken);
props.put(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, existing);
}
} | [
"private",
"void",
"overrideDatabaseTerminationToken",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"props",
")",
"{",
"String",
"overrideTermToken",
"=",
"null",
";",
"String",
"platformClassName",
"=",
"_dbMgr",
".",
"getDatabasePlatformClassName",
"(",
"_pui",
... | Helper method that will override the termination token if the database detected is in our
platformTerminationToken list. | [
"Helper",
"method",
"that",
"will",
"override",
"the",
"termination",
"token",
"if",
"the",
"database",
"detected",
"is",
"in",
"our",
"platformTerminationToken",
"list",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.persistence/src/com/ibm/wsspi/persistence/internal/SchemaManager.java#L163-L182 |
xcesco/kripton | kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java | XMLSerializer.addPrintable | private static void addPrintable(StringBuffer retval, char ch) {
switch (ch) {
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
final String ss = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + ss.substring(ss.length() - 4, ss.length()));
} else {
retval.append(ch);
}
}
} | java | private static void addPrintable(StringBuffer retval, char ch) {
switch (ch) {
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
final String ss = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + ss.substring(ss.length() - 4, ss.length()));
} else {
retval.append(ch);
}
}
} | [
"private",
"static",
"void",
"addPrintable",
"(",
"StringBuffer",
"retval",
",",
"char",
"ch",
")",
"{",
"switch",
"(",
"ch",
")",
"{",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\b\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
... | Adds the printable.
@param retval the retval
@param ch the ch | [
"Adds",
"the",
"printable",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java#L1457-L1491 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findIndexOf | public static int findIndexOf(Object self, int startIndex, Closure condition) {
return findIndexOf(InvokerHelper.asIterator(self), condition);
} | java | public static int findIndexOf(Object self, int startIndex, Closure condition) {
return findIndexOf(InvokerHelper.asIterator(self), condition);
} | [
"public",
"static",
"int",
"findIndexOf",
"(",
"Object",
"self",
",",
"int",
"startIndex",
",",
"Closure",
"condition",
")",
"{",
"return",
"findIndexOf",
"(",
"InvokerHelper",
".",
"asIterator",
"(",
"self",
")",
",",
"condition",
")",
";",
"}"
] | Iterates over the elements of an aggregate of items, starting from a
specified startIndex, and returns the index of the first item that matches the
condition specified in the closure.
@param self the iteration object over which to iterate
@param startIndex start matching from this index
@param condition the matching condition
@return an integer that is the index of the first matched object or -1 if no match was found
@since 1.5.0 | [
"Iterates",
"over",
"the",
"elements",
"of",
"an",
"aggregate",
"of",
"items",
"starting",
"from",
"a",
"specified",
"startIndex",
"and",
"returns",
"the",
"index",
"of",
"the",
"first",
"item",
"that",
"matches",
"the",
"condition",
"specified",
"in",
"the",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L16709-L16711 |
FitLayout/segmentation | src/main/java/org/fit/segm/grouping/op/GroupAnalyzerByStyles.java | GroupAnalyzerByStyles.limitReached | private boolean limitReached(Rectangular gp, Rectangular limit, short required)
{
switch (required)
{
case REQ_HORIZONTAL:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2();
case REQ_VERTICAL:
return gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
case REQ_BOTH:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2()
&& gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
}
return false;
} | java | private boolean limitReached(Rectangular gp, Rectangular limit, short required)
{
switch (required)
{
case REQ_HORIZONTAL:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2();
case REQ_VERTICAL:
return gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
case REQ_BOTH:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2()
&& gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
}
return false;
} | [
"private",
"boolean",
"limitReached",
"(",
"Rectangular",
"gp",
",",
"Rectangular",
"limit",
",",
"short",
"required",
")",
"{",
"switch",
"(",
"required",
")",
"{",
"case",
"REQ_HORIZONTAL",
":",
"return",
"gp",
".",
"getX1",
"(",
")",
"<=",
"limit",
".",... | Checks if the grid bounds have reached a specified limit in the specified direction.
@param gp the bounds to check
@param limit the limit to be reached
@param required the required direction (use the REQ_* constants)
@return true if the limit has been reached or exceeded | [
"Checks",
"if",
"the",
"grid",
"bounds",
"have",
"reached",
"a",
"specified",
"limit",
"in",
"the",
"specified",
"direction",
"."
] | train | https://github.com/FitLayout/segmentation/blob/12998087d576640c2f2a6360cf6088af95eea5f4/src/main/java/org/fit/segm/grouping/op/GroupAnalyzerByStyles.java#L221-L235 |
jcustenborder/connect-utils | connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java | ConfigUtils.keyManagerFactory | public static KeyManagerFactory keyManagerFactory(AbstractConfig config, String key) {
final String keyManagerFactoryType = config.getString(key);
try {
return KeyManagerFactory.getInstance(keyManagerFactoryType);
} catch (NoSuchAlgorithmException e) {
ConfigException exception = new ConfigException(
key,
keyManagerFactoryType,
"Unknown Algorithm."
);
exception.initCause(e);
throw exception;
}
} | java | public static KeyManagerFactory keyManagerFactory(AbstractConfig config, String key) {
final String keyManagerFactoryType = config.getString(key);
try {
return KeyManagerFactory.getInstance(keyManagerFactoryType);
} catch (NoSuchAlgorithmException e) {
ConfigException exception = new ConfigException(
key,
keyManagerFactoryType,
"Unknown Algorithm."
);
exception.initCause(e);
throw exception;
}
} | [
"public",
"static",
"KeyManagerFactory",
"keyManagerFactory",
"(",
"AbstractConfig",
"config",
",",
"String",
"key",
")",
"{",
"final",
"String",
"keyManagerFactoryType",
"=",
"config",
".",
"getString",
"(",
"key",
")",
";",
"try",
"{",
"return",
"KeyManagerFacto... | Method will create a KeyManagerFactory based on the Algorithm type specified in the config.
@param config Config to read from.
@param key Key to read from
@return KeyManagerFactory based on the type specified in the config. | [
"Method",
"will",
"create",
"a",
"KeyManagerFactory",
"based",
"on",
"the",
"Algorithm",
"type",
"specified",
"in",
"the",
"config",
"."
] | train | https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java#L399-L412 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FastHessianFeatureDetector.java | FastHessianFeatureDetector.findLocalScaleSpaceMax | private void findLocalScaleSpaceMax(int []size, int level, int skip) {
int index0 = spaceIndex;
int index1 = (spaceIndex + 1) % 3;
int index2 = (spaceIndex + 2) % 3;
ImageBorder_F32 inten0 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index0], 0);
GrayF32 inten1 = intensity[index1];
ImageBorder_F32 inten2 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index2], 0);
// find local maximums in image 2D space. Borders need to be ignored since
// false positives are found around them as an artifact of pixels outside being
// treated as being zero.
foundFeatures.reset();
extractor.setIgnoreBorder(size[level] / (2 * skip));
extractor.process(intensity[index1],null,null,null,foundFeatures);
// Can't consider feature which are right up against the border since they might not be a true local
// maximum when you consider the features on the other side of the ignore border
int ignoreRadius = extractor.getIgnoreBorder() + extractor.getSearchRadius();
int ignoreWidth = intensity[index1].width-ignoreRadius;
int ignoreHeight = intensity[index1].height-ignoreRadius;
// number of features which can be added
int numberRemaining;
// if configured to do so, only select the features with the highest intensity
QueueCorner features;
if( sortBest != null ) {
sortBest.process(intensity[index1],foundFeatures,true);
features = sortBest.getBestCorners();
numberRemaining = maxFeaturesPerScale;
} else {
features = foundFeatures;
numberRemaining = Integer.MAX_VALUE;
}
int levelSize = size[level];
int sizeStep = levelSize-size[level-1];
// see if these local maximums are also a maximum in scale-space
for( int i = 0; i < features.size && numberRemaining > 0; i++ ) {
Point2D_I16 f = features.get(i);
// avoid false positives. see above comment
if( f.x < ignoreRadius || f.x >= ignoreWidth || f.y < ignoreRadius || f.y >= ignoreHeight )
continue;
float val = inten1.get(f.x,f.y);
// see if it is a max in scale-space too
if( checkMax(inten0,val,f.x,f.y) && checkMax(inten2,val,f.x,f.y) ) {
// find the feature's location to sub-pixel accuracy using a second order polynomial
// NOTE: In the original paper this was done using a quadratic. See comments above.
// NOTE: Using a 2D polynomial for x and y might produce better results.
float peakX = polyPeak(inten1.get(f.x-1,f.y),inten1.get(f.x,f.y),inten1.get(f.x+1,f.y));
float peakY = polyPeak(inten1.get(f.x,f.y-1),inten1.get(f.x,f.y),inten1.get(f.x,f.y+1));
float peakS = polyPeak(inten0.get(f.x,f.y),inten1.get(f.x,f.y),inten2.get(f.x,f.y));
float interpX = (f.x+peakX)*skip;
float interpY = (f.y+peakY)*skip;
float interpS = levelSize+peakS*sizeStep;
double scale = 1.2*interpS/9.0;
foundPoints.grow().set(interpX,interpY,scale);
numberRemaining--;
}
}
} | java | private void findLocalScaleSpaceMax(int []size, int level, int skip) {
int index0 = spaceIndex;
int index1 = (spaceIndex + 1) % 3;
int index2 = (spaceIndex + 2) % 3;
ImageBorder_F32 inten0 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index0], 0);
GrayF32 inten1 = intensity[index1];
ImageBorder_F32 inten2 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index2], 0);
// find local maximums in image 2D space. Borders need to be ignored since
// false positives are found around them as an artifact of pixels outside being
// treated as being zero.
foundFeatures.reset();
extractor.setIgnoreBorder(size[level] / (2 * skip));
extractor.process(intensity[index1],null,null,null,foundFeatures);
// Can't consider feature which are right up against the border since they might not be a true local
// maximum when you consider the features on the other side of the ignore border
int ignoreRadius = extractor.getIgnoreBorder() + extractor.getSearchRadius();
int ignoreWidth = intensity[index1].width-ignoreRadius;
int ignoreHeight = intensity[index1].height-ignoreRadius;
// number of features which can be added
int numberRemaining;
// if configured to do so, only select the features with the highest intensity
QueueCorner features;
if( sortBest != null ) {
sortBest.process(intensity[index1],foundFeatures,true);
features = sortBest.getBestCorners();
numberRemaining = maxFeaturesPerScale;
} else {
features = foundFeatures;
numberRemaining = Integer.MAX_VALUE;
}
int levelSize = size[level];
int sizeStep = levelSize-size[level-1];
// see if these local maximums are also a maximum in scale-space
for( int i = 0; i < features.size && numberRemaining > 0; i++ ) {
Point2D_I16 f = features.get(i);
// avoid false positives. see above comment
if( f.x < ignoreRadius || f.x >= ignoreWidth || f.y < ignoreRadius || f.y >= ignoreHeight )
continue;
float val = inten1.get(f.x,f.y);
// see if it is a max in scale-space too
if( checkMax(inten0,val,f.x,f.y) && checkMax(inten2,val,f.x,f.y) ) {
// find the feature's location to sub-pixel accuracy using a second order polynomial
// NOTE: In the original paper this was done using a quadratic. See comments above.
// NOTE: Using a 2D polynomial for x and y might produce better results.
float peakX = polyPeak(inten1.get(f.x-1,f.y),inten1.get(f.x,f.y),inten1.get(f.x+1,f.y));
float peakY = polyPeak(inten1.get(f.x,f.y-1),inten1.get(f.x,f.y),inten1.get(f.x,f.y+1));
float peakS = polyPeak(inten0.get(f.x,f.y),inten1.get(f.x,f.y),inten2.get(f.x,f.y));
float interpX = (f.x+peakX)*skip;
float interpY = (f.y+peakY)*skip;
float interpS = levelSize+peakS*sizeStep;
double scale = 1.2*interpS/9.0;
foundPoints.grow().set(interpX,interpY,scale);
numberRemaining--;
}
}
} | [
"private",
"void",
"findLocalScaleSpaceMax",
"(",
"int",
"[",
"]",
"size",
",",
"int",
"level",
",",
"int",
"skip",
")",
"{",
"int",
"index0",
"=",
"spaceIndex",
";",
"int",
"index1",
"=",
"(",
"spaceIndex",
"+",
"1",
")",
"%",
"3",
";",
"int",
"inde... | Looks for features which are local maximums in the image and scale-space.
@param size Size of features in different scale-spaces.
@param level Which level in the scale-space
@param skip How many pixels are skipped over. | [
"Looks",
"for",
"features",
"which",
"are",
"local",
"maximums",
"in",
"the",
"image",
"and",
"scale",
"-",
"space",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FastHessianFeatureDetector.java#L230-L298 |
wisdom-framework/wisdom | core/content-manager/src/main/java/org/wisdom/content/converters/ParamConverterEngine.java | ParamConverterEngine.convertValues | @Override
public <T> T convertValues(Collection<String> input, Class<T> rawType, Type type, String defaultValue) throws IllegalArgumentException {
if (rawType.isArray()) {
if (input == null) {
input = getMultipleValues(defaultValue, null);
}
return createArray(input, rawType.getComponentType());
} else if (Collection.class.isAssignableFrom(rawType)) {
if (input == null) {
input = getMultipleValues(defaultValue, null);
}
return createCollection(input, rawType, type);
} else {
return convertSingleValue(input, rawType, defaultValue);
}
} | java | @Override
public <T> T convertValues(Collection<String> input, Class<T> rawType, Type type, String defaultValue) throws IllegalArgumentException {
if (rawType.isArray()) {
if (input == null) {
input = getMultipleValues(defaultValue, null);
}
return createArray(input, rawType.getComponentType());
} else if (Collection.class.isAssignableFrom(rawType)) {
if (input == null) {
input = getMultipleValues(defaultValue, null);
}
return createCollection(input, rawType, type);
} else {
return convertSingleValue(input, rawType, defaultValue);
}
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"T",
"convertValues",
"(",
"Collection",
"<",
"String",
">",
"input",
",",
"Class",
"<",
"T",
">",
"rawType",
",",
"Type",
"type",
",",
"String",
"defaultValue",
")",
"throws",
"IllegalArgumentException",
"{",
"if"... | Creates an instance of T from the given input. Unlike {@link #convertValue(String, Class,
java.lang.reflect.Type, String)}, this method support multi-value parameters.
@param input the input Strings, may be {@literal null} or empty
@param rawType the target class
@param type the type representation of the raw type, may contains metadata about generics
@param defaultValue the default value if any
@return the created object
@throws IllegalArgumentException if there are no converter available from the type T at the moment | [
"Creates",
"an",
"instance",
"of",
"T",
"from",
"the",
"given",
"input",
".",
"Unlike",
"{",
"@link",
"#convertValue",
"(",
"String",
"Class",
"java",
".",
"lang",
".",
"reflect",
".",
"Type",
"String",
")",
"}",
"this",
"method",
"support",
"multi",
"-"... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/content-manager/src/main/java/org/wisdom/content/converters/ParamConverterEngine.java#L111-L126 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/FaultManager.java | FaultManager.isBlacklisted | public boolean isBlacklisted(String nodeName, ResourceType type) {
List<ResourceType> blacklistedResourceTypes =
blacklistedNodes.get(nodeName);
if (blacklistedResourceTypes != null) {
synchronized (blacklistedResourceTypes) {
return blacklistedResourceTypes.contains(type);
}
} else {
return false;
}
} | java | public boolean isBlacklisted(String nodeName, ResourceType type) {
List<ResourceType> blacklistedResourceTypes =
blacklistedNodes.get(nodeName);
if (blacklistedResourceTypes != null) {
synchronized (blacklistedResourceTypes) {
return blacklistedResourceTypes.contains(type);
}
} else {
return false;
}
} | [
"public",
"boolean",
"isBlacklisted",
"(",
"String",
"nodeName",
",",
"ResourceType",
"type",
")",
"{",
"List",
"<",
"ResourceType",
">",
"blacklistedResourceTypes",
"=",
"blacklistedNodes",
".",
"get",
"(",
"nodeName",
")",
";",
"if",
"(",
"blacklistedResourceTyp... | Check if a resource on a node is blacklisted.
@param nodeName The node name.
@param type The type of resource to check for blacklisting.
@return A boolean value that is true if blacklisted, false if not. | [
"Check",
"if",
"a",
"resource",
"on",
"a",
"node",
"is",
"blacklisted",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/FaultManager.java#L191-L201 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/Client.java | Client.initializeState | public Completable initializeState(final StreamFrom from, final StreamTo to) {
if (from == StreamFrom.BEGINNING && to == StreamTo.INFINITY) {
buzzMe();
return initFromBeginningToInfinity();
} else if (from == StreamFrom.BEGINNING && to == StreamTo.NOW) {
return initFromBeginningToNow();
} else if (from == StreamFrom.NOW && to == StreamTo.INFINITY) {
buzzMe();
return initFromNowToInfinity();
} else {
throw new IllegalStateException("Unsupported FROM/TO combination: " + from + " -> " + to);
}
} | java | public Completable initializeState(final StreamFrom from, final StreamTo to) {
if (from == StreamFrom.BEGINNING && to == StreamTo.INFINITY) {
buzzMe();
return initFromBeginningToInfinity();
} else if (from == StreamFrom.BEGINNING && to == StreamTo.NOW) {
return initFromBeginningToNow();
} else if (from == StreamFrom.NOW && to == StreamTo.INFINITY) {
buzzMe();
return initFromNowToInfinity();
} else {
throw new IllegalStateException("Unsupported FROM/TO combination: " + from + " -> " + to);
}
} | [
"public",
"Completable",
"initializeState",
"(",
"final",
"StreamFrom",
"from",
",",
"final",
"StreamTo",
"to",
")",
"{",
"if",
"(",
"from",
"==",
"StreamFrom",
".",
"BEGINNING",
"&&",
"to",
"==",
"StreamTo",
".",
"INFINITY",
")",
"{",
"buzzMe",
"(",
")",
... | Initialize the {@link SessionState} based on arbitrary time points.
<p>
The following combinations are supported and make sense:
<p>
- {@link StreamFrom#BEGINNING} to {@link StreamTo#NOW}
- {@link StreamFrom#BEGINNING} to {@link StreamTo#INFINITY}
- {@link StreamFrom#NOW} to {@link StreamTo#INFINITY}
<p>
If you already have state captured and you want to resume from this position, use
{@link #recoverState(StateFormat, byte[])} or {@link #recoverOrInitializeState(StateFormat, byte[], StreamFrom, StreamTo)}
instead.
@param from where to start streaming from.
@param to when to stop streaming.
@return A {@link Completable} indicating the success or failure of the state init. | [
"Initialize",
"the",
"{",
"@link",
"SessionState",
"}",
"based",
"on",
"arbitrary",
"time",
"points",
".",
"<p",
">",
"The",
"following",
"combinations",
"are",
"supported",
"and",
"make",
"sense",
":",
"<p",
">",
"-",
"{",
"@link",
"StreamFrom#BEGINNING",
"... | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/Client.java#L575-L587 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/KeyUpdateCollection.java | KeyUpdateCollection.add | void add(BucketUpdate.KeyUpdate update, int entryLength, long originalOffset) {
val existing = this.updates.get(update.getKey());
if (existing == null || update.supersedes(existing)) {
this.updates.put(update.getKey(), update);
}
// Update remaining counters, regardless of whether we considered this update or not.
this.totalUpdateCount.incrementAndGet();
long lastOffset = update.getOffset() + entryLength;
this.lastIndexedOffset.updateAndGet(e -> Math.max(lastOffset, e));
if (originalOffset >= 0) {
this.highestCopiedOffset.updateAndGet(e -> Math.max(e, originalOffset + entryLength));
}
} | java | void add(BucketUpdate.KeyUpdate update, int entryLength, long originalOffset) {
val existing = this.updates.get(update.getKey());
if (existing == null || update.supersedes(existing)) {
this.updates.put(update.getKey(), update);
}
// Update remaining counters, regardless of whether we considered this update or not.
this.totalUpdateCount.incrementAndGet();
long lastOffset = update.getOffset() + entryLength;
this.lastIndexedOffset.updateAndGet(e -> Math.max(lastOffset, e));
if (originalOffset >= 0) {
this.highestCopiedOffset.updateAndGet(e -> Math.max(e, originalOffset + entryLength));
}
} | [
"void",
"add",
"(",
"BucketUpdate",
".",
"KeyUpdate",
"update",
",",
"int",
"entryLength",
",",
"long",
"originalOffset",
")",
"{",
"val",
"existing",
"=",
"this",
".",
"updates",
".",
"get",
"(",
"update",
".",
"getKey",
"(",
")",
")",
";",
"if",
"(",... | Includes the given {@link BucketUpdate.KeyUpdate} into this collection.
If we get multiple updates for the same key, only the one with highest version will be kept. Due to compaction,
it is possible that a lower version of a Key will end up after a higher version of the same Key, in which case
the higher version should take precedence.
@param update The {@link BucketUpdate.KeyUpdate} to include.
@param entryLength The total length of the given update, as serialized in the Segment.
@param originalOffset If this update was a result of a compaction copy, then this should be the original offset
where it was copied from (as serialized in the Segment). If no such information exists, then
{@link TableKey#NO_VERSION} should be used. | [
"Includes",
"the",
"given",
"{",
"@link",
"BucketUpdate",
".",
"KeyUpdate",
"}",
"into",
"this",
"collection",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/KeyUpdateCollection.java#L72-L85 |
jMetal/jMetal | jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/UniformMutation.java | UniformMutation.doMutation | public void doMutation(double probability, DoubleSolution solution) {
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
if (randomGenenerator.getRandomValue() < probability) {
double rand = randomGenenerator.getRandomValue();
double tmp = (rand - 0.5) * perturbation;
tmp += solution.getVariableValue(i);
if (tmp < solution.getLowerBound(i)) {
tmp = solution.getLowerBound(i);
} else if (tmp > solution.getUpperBound(i)) {
tmp = solution.getUpperBound(i);
}
solution.setVariableValue(i, tmp);
}
}
} | java | public void doMutation(double probability, DoubleSolution solution) {
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
if (randomGenenerator.getRandomValue() < probability) {
double rand = randomGenenerator.getRandomValue();
double tmp = (rand - 0.5) * perturbation;
tmp += solution.getVariableValue(i);
if (tmp < solution.getLowerBound(i)) {
tmp = solution.getLowerBound(i);
} else if (tmp > solution.getUpperBound(i)) {
tmp = solution.getUpperBound(i);
}
solution.setVariableValue(i, tmp);
}
}
} | [
"public",
"void",
"doMutation",
"(",
"double",
"probability",
",",
"DoubleSolution",
"solution",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"solution",
".",
"getNumberOfVariables",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"randomG... | Perform the operation
@param probability Mutation setProbability
@param solution The solution to mutate | [
"Perform",
"the",
"operation"
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/UniformMutation.java#L57-L74 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java | ChannelHelper.readAll | public static final int readAll(ReadableByteChannel ch, ByteBuffer dst) throws IOException
{
int count = 0;
while (dst.hasRemaining())
{
int rc = ch.read(dst);
if (rc == -1)
{
if (count > 0)
{
return count;
}
return -1;
}
count += rc;
}
return count;
} | java | public static final int readAll(ReadableByteChannel ch, ByteBuffer dst) throws IOException
{
int count = 0;
while (dst.hasRemaining())
{
int rc = ch.read(dst);
if (rc == -1)
{
if (count > 0)
{
return count;
}
return -1;
}
count += rc;
}
return count;
} | [
"public",
"static",
"final",
"int",
"readAll",
"(",
"ReadableByteChannel",
"ch",
",",
"ByteBuffer",
"dst",
")",
"throws",
"IOException",
"{",
"int",
"count",
"=",
"0",
";",
"while",
"(",
"dst",
".",
"hasRemaining",
"(",
")",
")",
"{",
"int",
"rc",
"=",
... | Read channel until dst has remaining or eof.
@param ch
@param dst
@return Returns number of bytes or -1 if no bytes were read and eof reached.
@throws IOException | [
"Read",
"channel",
"until",
"dst",
"has",
"remaining",
"or",
"eof",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java#L118-L135 |
biezhi/webp-io | src/main/java/io/github/biezhi/webp/WebpIO.java | WebpIO.toNormalImage | public void toNormalImage(String src, String dest) {
toNormalImage(new File(src), new File(dest));
} | java | public void toNormalImage(String src, String dest) {
toNormalImage(new File(src), new File(dest));
} | [
"public",
"void",
"toNormalImage",
"(",
"String",
"src",
",",
"String",
"dest",
")",
"{",
"toNormalImage",
"(",
"new",
"File",
"(",
"src",
")",
",",
"new",
"File",
"(",
"dest",
")",
")",
";",
"}"
] | Converter webp file to normal image
@param src webp file path
@param dest normal image path | [
"Converter",
"webp",
"file",
"to",
"normal",
"image"
] | train | https://github.com/biezhi/webp-io/blob/8eefe535087b3abccacff76de2b6e27bb7301bcc/src/main/java/io/github/biezhi/webp/WebpIO.java#L76-L78 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbAuthentication.java | TmdbAuthentication.getAuthorisationToken | public TokenAuthorisation getAuthorisationToken() throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
URL url = new ApiUrl(apiKey, MethodBase.AUTH).subMethod(MethodSub.TOKEN_NEW).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, TokenAuthorisation.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Failed to get Authorisation Token", url, ex);
}
} | java | public TokenAuthorisation getAuthorisationToken() throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
URL url = new ApiUrl(apiKey, MethodBase.AUTH).subMethod(MethodSub.TOKEN_NEW).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, TokenAuthorisation.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Failed to get Authorisation Token", url, ex);
}
} | [
"public",
"TokenAuthorisation",
"getAuthorisationToken",
"(",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
"URL",
"url",
"=",
"new",
"ApiUrl",
"(",
"apiKey",
",",
"MethodBase",
".",
"AUTH",
... | This method is used to generate a valid request token for user based
authentication.
A request token is required in order to request a session id.
You can generate any number of request tokens but they will expire after
60 minutes.
As soon as a valid session id has been created the token will be
destroyed.
@return
@throws MovieDbException | [
"This",
"method",
"is",
"used",
"to",
"generate",
"a",
"valid",
"request",
"token",
"for",
"user",
"based",
"authentication",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbAuthentication.java#L67-L78 |
jenkinsci/jenkins | core/src/main/java/jenkins/util/xml/XMLUtils.java | XMLUtils.getValue | public static @Nonnull String getValue(@Nonnull String xpath, @Nonnull File file, @Nonnull String fileDataEncoding) throws IOException, SAXException, XPathExpressionException {
Document document = parse(file, fileDataEncoding);
return getValue(xpath, document);
} | java | public static @Nonnull String getValue(@Nonnull String xpath, @Nonnull File file, @Nonnull String fileDataEncoding) throws IOException, SAXException, XPathExpressionException {
Document document = parse(file, fileDataEncoding);
return getValue(xpath, document);
} | [
"public",
"static",
"@",
"Nonnull",
"String",
"getValue",
"(",
"@",
"Nonnull",
"String",
"xpath",
",",
"@",
"Nonnull",
"File",
"file",
",",
"@",
"Nonnull",
"String",
"fileDataEncoding",
")",
"throws",
"IOException",
",",
"SAXException",
",",
"XPathExpressionExce... | The a "value" from an XML file using XPath.
@param xpath The XPath expression to select the value.
@param file The file to read.
@param fileDataEncoding The file data format.
@return The data value. An empty {@link String} is returned when the expression does not evaluate
to anything in the document.
@throws IOException Error reading from the file.
@throws SAXException Error parsing the XML file data e.g. badly formed XML.
@throws XPathExpressionException Invalid XPath expression.
@since 2.0 | [
"The",
"a",
"value",
"from",
"an",
"XML",
"file",
"using",
"XPath",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/xml/XMLUtils.java#L179-L182 |
geomajas/geomajas-project-client-gwt2 | plugin/editing/common/src/main/java/org/geomajas/plugin/editing/client/operation/InsertVertexOperation.java | InsertVertexOperation.insertAfterEdge | private void insertAfterEdge(Geometry geom, GeometryIndex index, Coordinate coordinate)
throws GeometryIndexNotFoundException {
// First we check the geometry type:
if (!Geometry.LINE_STRING.equals(geom.getGeometryType())
&& !Geometry.LINEAR_RING.equals(geom.getGeometryType())) {
throw new GeometryIndexNotFoundException("Could not match index with given geometry.");
}
if (index.getValue() < 0) {
throw new GeometryIndexNotFoundException("Cannot insert in a negative index.");
}
// Then we check if the edge exists:
if (geom.getCoordinates() != null && geom.getCoordinates().length > index.getValue() + 1) {
// Inserting on edges allows only to insert on existing edges. No adding at the end:
Coordinate[] result = new Coordinate[geom.getCoordinates().length + 1];
int count = 0;
for (int i = 0; i < geom.getCoordinates().length; i++) {
if (i == (index.getValue() + 1)) {
result[i] = coordinate;
count++;
}
result[i + count] = geom.getCoordinates()[i];
}
geom.setCoordinates(result);
} else {
throw new GeometryIndexNotFoundException("Cannot insert a vertex into an edge that does not exist.");
}
} | java | private void insertAfterEdge(Geometry geom, GeometryIndex index, Coordinate coordinate)
throws GeometryIndexNotFoundException {
// First we check the geometry type:
if (!Geometry.LINE_STRING.equals(geom.getGeometryType())
&& !Geometry.LINEAR_RING.equals(geom.getGeometryType())) {
throw new GeometryIndexNotFoundException("Could not match index with given geometry.");
}
if (index.getValue() < 0) {
throw new GeometryIndexNotFoundException("Cannot insert in a negative index.");
}
// Then we check if the edge exists:
if (geom.getCoordinates() != null && geom.getCoordinates().length > index.getValue() + 1) {
// Inserting on edges allows only to insert on existing edges. No adding at the end:
Coordinate[] result = new Coordinate[geom.getCoordinates().length + 1];
int count = 0;
for (int i = 0; i < geom.getCoordinates().length; i++) {
if (i == (index.getValue() + 1)) {
result[i] = coordinate;
count++;
}
result[i + count] = geom.getCoordinates()[i];
}
geom.setCoordinates(result);
} else {
throw new GeometryIndexNotFoundException("Cannot insert a vertex into an edge that does not exist.");
}
} | [
"private",
"void",
"insertAfterEdge",
"(",
"Geometry",
"geom",
",",
"GeometryIndex",
"index",
",",
"Coordinate",
"coordinate",
")",
"throws",
"GeometryIndexNotFoundException",
"{",
"// First we check the geometry type:",
"if",
"(",
"!",
"Geometry",
".",
"LINE_STRING",
"... | Insert a point into a given edge. There can be only edges if there are at least 2 points in a LineString
geometry. | [
"Insert",
"a",
"point",
"into",
"a",
"given",
"edge",
".",
"There",
"can",
"be",
"only",
"edges",
"if",
"there",
"are",
"at",
"least",
"2",
"points",
"in",
"a",
"LineString",
"geometry",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/editing/common/src/main/java/org/geomajas/plugin/editing/client/operation/InsertVertexOperation.java#L111-L138 |
xwiki/xwiki-rendering | xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroErrorManager.java | MacroErrorManager.generateError | public void generateError(MacroBlock macroToReplace, String message, Throwable throwable)
{
List<Block> errorBlocks =
this.errorBlockGenerator.generateErrorBlocks(message, throwable, macroToReplace.isInline());
macroToReplace.getParent().replaceChild(wrapInMacroMarker(macroToReplace, errorBlocks), macroToReplace);
} | java | public void generateError(MacroBlock macroToReplace, String message, Throwable throwable)
{
List<Block> errorBlocks =
this.errorBlockGenerator.generateErrorBlocks(message, throwable, macroToReplace.isInline());
macroToReplace.getParent().replaceChild(wrapInMacroMarker(macroToReplace, errorBlocks), macroToReplace);
} | [
"public",
"void",
"generateError",
"(",
"MacroBlock",
"macroToReplace",
",",
"String",
"message",
",",
"Throwable",
"throwable",
")",
"{",
"List",
"<",
"Block",
">",
"errorBlocks",
"=",
"this",
".",
"errorBlockGenerator",
".",
"generateErrorBlocks",
"(",
"message"... | Generates Blocks to signify that the passed Macro Block has failed to execute.
@param macroToReplace the block for the macro that failed to execute and that we'll replace with Block
showing to the user that macro has failed
@param message the message to display to the user in place of the macro result
@param throwable the exception for the failed macro execution to display to the user in place of the macro result | [
"Generates",
"Blocks",
"to",
"signify",
"that",
"the",
"passed",
"Macro",
"Block",
"has",
"failed",
"to",
"execute",
"."
] | train | https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/main/java/org/xwiki/rendering/internal/transformation/macro/MacroErrorManager.java#L75-L80 |
OpenCompare/OpenCompare | org.opencompare/pcmdata-importers/src/main/java/data_off/OFFDumpRetriever.java | OFFDumpRetriever.unGzip | private File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {
_log.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
//final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3));
final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));
final FileOutputStream out = new FileOutputStream(outputDir);
IOUtils.copy(in, out);
in.close();
out.close();
return outputDir;
} | java | private File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {
_log.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));
//final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3));
final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));
final FileOutputStream out = new FileOutputStream(outputDir);
IOUtils.copy(in, out);
in.close();
out.close();
return outputDir;
} | [
"private",
"File",
"unGzip",
"(",
"final",
"File",
"inputFile",
",",
"final",
"File",
"outputDir",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"_log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Ungzipping %s to dir %s.\"",
",",
"inpu... | Ungzip an input file into an output file.
<p>
The output file is created in the output folder, having the same name
as the input file, minus the '.gz' extension.
@param inputFile the input .gz file
@param outputDir the output directory file.
@throws IOException
@throws FileNotFoundException
@return The {@File} with the ungzipped content. | [
"Ungzip",
"an",
"input",
"file",
"into",
"an",
"output",
"file",
".",
"<p",
">",
"The",
"output",
"file",
"is",
"created",
"in",
"the",
"output",
"folder",
"having",
"the",
"same",
"name",
"as",
"the",
"input",
"file",
"minus",
"the",
".",
"gz",
"exten... | train | https://github.com/OpenCompare/OpenCompare/blob/6cd776466b375cb8ecca08fcd94e573d65e20b14/org.opencompare/pcmdata-importers/src/main/java/data_off/OFFDumpRetriever.java#L100-L115 |
alkacon/opencms-core | src/org/opencms/workplace/CmsWorkplace.java | CmsWorkplace.getWorkplaceExplorerLink | public static String getWorkplaceExplorerLink(final CmsJspActionElement jsp, final String explorerRootPath) {
return getWorkplaceExplorerLink(jsp.getCmsObject(), explorerRootPath);
} | java | public static String getWorkplaceExplorerLink(final CmsJspActionElement jsp, final String explorerRootPath) {
return getWorkplaceExplorerLink(jsp.getCmsObject(), explorerRootPath);
} | [
"public",
"static",
"String",
"getWorkplaceExplorerLink",
"(",
"final",
"CmsJspActionElement",
"jsp",
",",
"final",
"String",
"explorerRootPath",
")",
"{",
"return",
"getWorkplaceExplorerLink",
"(",
"jsp",
".",
"getCmsObject",
"(",
")",
",",
"explorerRootPath",
")",
... | Creates a link for the OpenCms workplace that will reload the whole workplace, switch to the explorer view, the
site of the given explorerRootPath and show the folder given in the explorerRootPath.
<p>
@param jsp
needed for link functionality.
@param explorerRootPath
a root relative folder link (has to end with '/').
@return a link for the OpenCms workplace that will reload the whole workplace, switch to the explorer view, the
site of the given explorerRootPath and show the folder given in the explorerRootPath. | [
"Creates",
"a",
"link",
"for",
"the",
"OpenCms",
"workplace",
"that",
"will",
"reload",
"the",
"whole",
"workplace",
"switch",
"to",
"the",
"explorer",
"view",
"the",
"site",
"of",
"the",
"given",
"explorerRootPath",
"and",
"show",
"the",
"folder",
"given",
... | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L753-L757 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/br/br_vm_template.java | br_vm_template.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_vm_template_responses result = (br_vm_template_responses) service.get_payload_formatter().string_to_resource(br_vm_template_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_vm_template_response_array);
}
br_vm_template[] result_br_vm_template = new br_vm_template[result.br_vm_template_response_array.length];
for(int i = 0; i < result.br_vm_template_response_array.length; i++)
{
result_br_vm_template[i] = result.br_vm_template_response_array[i].br_vm_template[0];
}
return result_br_vm_template;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_vm_template_responses result = (br_vm_template_responses) service.get_payload_formatter().string_to_resource(br_vm_template_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_vm_template_response_array);
}
br_vm_template[] result_br_vm_template = new br_vm_template[result.br_vm_template_response_array.length];
for(int i = 0; i < result.br_vm_template_response_array.length; i++)
{
result_br_vm_template[i] = result.br_vm_template_response_array[i].br_vm_template[0];
}
return result_br_vm_template;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"br_vm_template_responses",
"result",
"=",
"(",
"br_vm_template_responses",
")",
"service",
".",
"get_payload_... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_vm_template.java#L173-L190 |
wuman/orientdb-android | core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java | OUser.checkIfAllowed | public ORole checkIfAllowed(final String iResource, final int iOperation) {
for (ORole r : roles)
if (r.allow(iResource, iOperation))
return r;
return null;
} | java | public ORole checkIfAllowed(final String iResource, final int iOperation) {
for (ORole r : roles)
if (r.allow(iResource, iOperation))
return r;
return null;
} | [
"public",
"ORole",
"checkIfAllowed",
"(",
"final",
"String",
"iResource",
",",
"final",
"int",
"iOperation",
")",
"{",
"for",
"(",
"ORole",
"r",
":",
"roles",
")",
"if",
"(",
"r",
".",
"allow",
"(",
"iResource",
",",
"iOperation",
")",
")",
"return",
"... | Checks if the user has the permission to access to the requested resource for the requested operation.
@param iResource
Requested resource
@param iOperation
Requested operation
@return The role that has granted the permission if any, otherwise null | [
"Checks",
"if",
"the",
"user",
"has",
"the",
"permission",
"to",
"access",
"to",
"the",
"requested",
"resource",
"for",
"the",
"requested",
"operation",
"."
] | train | https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java#L122-L128 |
MutabilityDetector/MutabilityDetector | src/main/java/org/mutabilitydetector/checkers/settermethod/AliasFinder.java | AliasFinder.newInstance | public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {
checkArgument(!variableName.isEmpty());
return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));
} | java | public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) {
checkArgument(!variableName.isEmpty());
return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine));
} | [
"public",
"static",
"AliasFinder",
"newInstance",
"(",
"final",
"String",
"variableName",
",",
"final",
"ControlFlowBlock",
"controlFlowBlockToExamine",
")",
"{",
"checkArgument",
"(",
"!",
"variableName",
".",
"isEmpty",
"(",
")",
")",
";",
"return",
"new",
"Alia... | Creates a new instance of this class.
@param variableName
name of the instance variable to search aliases for. Must
neither be {@code null} nor empty.
@param controlFlowBlockToExamine
a {@link ControlFlowBlock} which possibly contains the setup
of an alias for a lazy variable. This method thereby examines
predecessors of {@code block}, too. This parameter must not be
{@code null}.
@return a new instance of this class. | [
"Creates",
"a",
"new",
"instance",
"of",
"this",
"class",
"."
] | train | https://github.com/MutabilityDetector/MutabilityDetector/blob/36014d2f9e45cf0cc6d67b81395942cd39c4f6ae/src/main/java/org/mutabilitydetector/checkers/settermethod/AliasFinder.java#L74-L77 |
eurekaclinical/aiw-i2b2-etl | src/main/java/edu/emory/cci/aiw/i2b2etl/dest/metadata/conceptid/PropDefConceptId.java | PropDefConceptId.getInstance | public static PropDefConceptId getInstance(String propId,
String propertyName, Value value, Metadata metadata) {
List<Object> key = new ArrayList<>(4);
key.add(propId);
key.add(propertyName);
key.add(value);
key.add(Boolean.TRUE); //distinguishes these from properties represented as a modifier.
PropDefConceptId conceptId = (PropDefConceptId) metadata.getFromConceptIdCache(key);
if (conceptId == null) {
conceptId = new PropDefConceptId(propId, propertyName, value, metadata);
metadata.putInConceptIdCache(key, conceptId);
}
return conceptId;
} | java | public static PropDefConceptId getInstance(String propId,
String propertyName, Value value, Metadata metadata) {
List<Object> key = new ArrayList<>(4);
key.add(propId);
key.add(propertyName);
key.add(value);
key.add(Boolean.TRUE); //distinguishes these from properties represented as a modifier.
PropDefConceptId conceptId = (PropDefConceptId) metadata.getFromConceptIdCache(key);
if (conceptId == null) {
conceptId = new PropDefConceptId(propId, propertyName, value, metadata);
metadata.putInConceptIdCache(key, conceptId);
}
return conceptId;
} | [
"public",
"static",
"PropDefConceptId",
"getInstance",
"(",
"String",
"propId",
",",
"String",
"propertyName",
",",
"Value",
"value",
",",
"Metadata",
"metadata",
")",
"{",
"List",
"<",
"Object",
">",
"key",
"=",
"new",
"ArrayList",
"<>",
"(",
"4",
")",
";... | Returns a concept propId with the given proposition propId, property name and
value.
@param propId a proposition propId {@link String}. Cannot be
<code>null</code>.
@param propertyName a property name {@link String}.
@param value a {@link Value}.
@return a {@link PropDefConceptId}. | [
"Returns",
"a",
"concept",
"propId",
"with",
"the",
"given",
"proposition",
"propId",
"property",
"name",
"and",
"value",
"."
] | train | https://github.com/eurekaclinical/aiw-i2b2-etl/blob/3eed6bda7755919cb9466d2930723a0f4748341a/src/main/java/edu/emory/cci/aiw/i2b2etl/dest/metadata/conceptid/PropDefConceptId.java#L67-L80 |
Metatavu/edelphi | rest/src/main/java/fi/metatavu/edelphi/users/UserController.java | UserController.getUserKeycloakId | public UUID getUserKeycloakId(User user) {
AuthSource authSource = authSourceDAO.findByStrategy(KEYCLOAK_AUTH_SOURCE);
if (authSource == null) {
logger.error("Could not find Keycloak auth source");
}
List<UserIdentification> userIdentifications = userIdentificationDAO.listByUserAndAuthSource(user, authSource);
if (userIdentifications.size() == 1) {
return UUID.fromString(userIdentifications.get(0).getExternalId());
}
if (userIdentifications.size() > 1) {
logger.warn("User {} has more than one identity", user.getId());
}
return new UUID(0L, 0L);
} | java | public UUID getUserKeycloakId(User user) {
AuthSource authSource = authSourceDAO.findByStrategy(KEYCLOAK_AUTH_SOURCE);
if (authSource == null) {
logger.error("Could not find Keycloak auth source");
}
List<UserIdentification> userIdentifications = userIdentificationDAO.listByUserAndAuthSource(user, authSource);
if (userIdentifications.size() == 1) {
return UUID.fromString(userIdentifications.get(0).getExternalId());
}
if (userIdentifications.size() > 1) {
logger.warn("User {} has more than one identity", user.getId());
}
return new UUID(0L, 0L);
} | [
"public",
"UUID",
"getUserKeycloakId",
"(",
"User",
"user",
")",
"{",
"AuthSource",
"authSource",
"=",
"authSourceDAO",
".",
"findByStrategy",
"(",
"KEYCLOAK_AUTH_SOURCE",
")",
";",
"if",
"(",
"authSource",
"==",
"null",
")",
"{",
"logger",
".",
"error",
"(",
... | Returns Keycloak id for an user
@param user user
@return Keycloak id or null if id could not be resolved | [
"Returns",
"Keycloak",
"id",
"for",
"an",
"user"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/rest/src/main/java/fi/metatavu/edelphi/users/UserController.java#L62-L78 |
graknlabs/grakn | server/src/server/exception/TransactionException.java | TransactionException.closingFailed | public static TransactionException closingFailed(TransactionOLTP tx, Exception e) {
return new TransactionException(CLOSE_FAILURE.getMessage(tx.keyspace()), e);
} | java | public static TransactionException closingFailed(TransactionOLTP tx, Exception e) {
return new TransactionException(CLOSE_FAILURE.getMessage(tx.keyspace()), e);
} | [
"public",
"static",
"TransactionException",
"closingFailed",
"(",
"TransactionOLTP",
"tx",
",",
"Exception",
"e",
")",
"{",
"return",
"new",
"TransactionException",
"(",
"CLOSE_FAILURE",
".",
"getMessage",
"(",
"tx",
".",
"keyspace",
"(",
")",
")",
",",
"e",
"... | Thrown when the graph can not be closed due to an unknown reason. | [
"Thrown",
"when",
"the",
"graph",
"can",
"not",
"be",
"closed",
"due",
"to",
"an",
"unknown",
"reason",
"."
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L227-L229 |
vipshop/vjtools | vjkit/src/main/java/com/vip/vjtools/vjkit/io/FileUtil.java | FileUtil.copy | public static void copy(@NotNull Path from, @NotNull Path to) throws IOException {
Validate.notNull(from);
Validate.notNull(to);
if (Files.isDirectory(from)) {
copyDir(from, to);
} else {
copyFile(from, to);
}
} | java | public static void copy(@NotNull Path from, @NotNull Path to) throws IOException {
Validate.notNull(from);
Validate.notNull(to);
if (Files.isDirectory(from)) {
copyDir(from, to);
} else {
copyFile(from, to);
}
} | [
"public",
"static",
"void",
"copy",
"(",
"@",
"NotNull",
"Path",
"from",
",",
"@",
"NotNull",
"Path",
"to",
")",
"throws",
"IOException",
"{",
"Validate",
".",
"notNull",
"(",
"from",
")",
";",
"Validate",
".",
"notNull",
"(",
"to",
")",
";",
"if",
"... | 复制文件或目录, not following links.
@param from 如果为null,或者是不存在的文件或目录,抛出异常.
@param to 如果为null,或者from是目录而to是已存在文件,或相反 | [
"复制文件或目录",
"not",
"following",
"links",
"."
] | train | https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjkit/src/main/java/com/vip/vjtools/vjkit/io/FileUtil.java#L220-L229 |
aws/aws-sdk-java | aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/emitters/CodeWriter.java | CodeWriter.flush | @Override
public void flush() {
PrintWriter out = null;
try {
try {
out = new PrintWriter(Utils.createFile(dir, file), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
String contents = getBuffer().toString();
out.write(processor.apply(contents));
} finally {
closeQuietly(out);
}
} | java | @Override
public void flush() {
PrintWriter out = null;
try {
try {
out = new PrintWriter(Utils.createFile(dir, file), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
String contents = getBuffer().toString();
out.write(processor.apply(contents));
} finally {
closeQuietly(out);
}
} | [
"@",
"Override",
"public",
"void",
"flush",
"(",
")",
"{",
"PrintWriter",
"out",
"=",
"null",
";",
"try",
"{",
"try",
"{",
"out",
"=",
"new",
"PrintWriter",
"(",
"Utils",
".",
"createFile",
"(",
"dir",
",",
"file",
")",
",",
"\"UTF-8\"",
")",
";",
... | This method is expected to be called only once during the code generation process after the
template processing is done. | [
"This",
"method",
"is",
"expected",
"to",
"be",
"called",
"only",
"once",
"during",
"the",
"code",
"generation",
"process",
"after",
"the",
"template",
"processing",
"is",
"done",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/emitters/CodeWriter.java#L87-L102 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_config_diff.java | ns_config_diff.diff_table | public static ns_config_diff diff_table(nitro_service client, ns_config_diff resource) throws Exception
{
return ((ns_config_diff[]) resource.perform_operation(client, "diff_table"))[0];
} | java | public static ns_config_diff diff_table(nitro_service client, ns_config_diff resource) throws Exception
{
return ((ns_config_diff[]) resource.perform_operation(client, "diff_table"))[0];
} | [
"public",
"static",
"ns_config_diff",
"diff_table",
"(",
"nitro_service",
"client",
",",
"ns_config_diff",
"resource",
")",
"throws",
"Exception",
"{",
"return",
"(",
"(",
"ns_config_diff",
"[",
"]",
")",
"resource",
".",
"perform_operation",
"(",
"client",
",",
... | <pre>
Use this operation to get config diff between source and target configuration files in the tabular format.
</pre> | [
"<pre",
">",
"Use",
"this",
"operation",
"to",
"get",
"config",
"diff",
"between",
"source",
"and",
"target",
"configuration",
"files",
"in",
"the",
"tabular",
"format",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_config_diff.java#L175-L178 |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.getIncludedProjectIdentifiers | private static Set<String> getIncludedProjectIdentifiers(final Project project) {
return getCachedReference(project, "thorntail_included_project_identifiers", () -> {
Set<String> identifiers = new HashSet<>();
// Check for included builds as well.
project.getGradle().getIncludedBuilds().forEach(build -> {
// Determine if the given reference has the following method definition,
// org.gradle.internal.build.IncludedBuildState#getAvailableModules()
try {
Method method = build.getClass().getMethod("getAvailableModules");
Class<?> retType = method.getReturnType();
if (Set.class.isAssignableFrom(retType)) {
// We have identified the right method. Get the values out of it.
Set availableModules = (Set) method.invoke(build);
for (Object entry : availableModules) {
Field field = entry.getClass().getField("left");
Object value = field.get(entry);
if (value instanceof ModuleVersionIdentifier) {
ModuleVersionIdentifier mv = (ModuleVersionIdentifier) value;
identifiers.add(String.format("%s:%s:%s", mv.getGroup(), mv.getName(), mv.getVersion()));
} else {
project.getLogger().debug("Unable to determine field type: {}", field);
}
}
} else {
project.getLogger().debug("Unable to determine method return type: {}", retType);
}
} catch (ReflectiveOperationException e) {
project.getLogger().debug("Unable to determine the included projects.", e);
}
});
return identifiers;
});
} | java | private static Set<String> getIncludedProjectIdentifiers(final Project project) {
return getCachedReference(project, "thorntail_included_project_identifiers", () -> {
Set<String> identifiers = new HashSet<>();
// Check for included builds as well.
project.getGradle().getIncludedBuilds().forEach(build -> {
// Determine if the given reference has the following method definition,
// org.gradle.internal.build.IncludedBuildState#getAvailableModules()
try {
Method method = build.getClass().getMethod("getAvailableModules");
Class<?> retType = method.getReturnType();
if (Set.class.isAssignableFrom(retType)) {
// We have identified the right method. Get the values out of it.
Set availableModules = (Set) method.invoke(build);
for (Object entry : availableModules) {
Field field = entry.getClass().getField("left");
Object value = field.get(entry);
if (value instanceof ModuleVersionIdentifier) {
ModuleVersionIdentifier mv = (ModuleVersionIdentifier) value;
identifiers.add(String.format("%s:%s:%s", mv.getGroup(), mv.getName(), mv.getVersion()));
} else {
project.getLogger().debug("Unable to determine field type: {}", field);
}
}
} else {
project.getLogger().debug("Unable to determine method return type: {}", retType);
}
} catch (ReflectiveOperationException e) {
project.getLogger().debug("Unable to determine the included projects.", e);
}
});
return identifiers;
});
} | [
"private",
"static",
"Set",
"<",
"String",
">",
"getIncludedProjectIdentifiers",
"(",
"final",
"Project",
"project",
")",
"{",
"return",
"getCachedReference",
"(",
"project",
",",
"\"thorntail_included_project_identifiers\"",
",",
"(",
")",
"->",
"{",
"Set",
"<",
... | Attempt to load the project identifiers (group:artifact) for projects that have been included. This method isn't
guaranteed to work all the time since there is no good API that we can use and need to rely on reflection for now.
@param project the project reference.
@return a collection of "included" project identifiers (a.k.a., composite projects). | [
"Attempt",
"to",
"load",
"the",
"project",
"identifiers",
"(",
"group",
":",
"artifact",
")",
"for",
"projects",
"that",
"have",
"been",
"included",
".",
"This",
"method",
"isn",
"t",
"guaranteed",
"to",
"work",
"all",
"the",
"time",
"since",
"there",
"is"... | train | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L338-L371 |
febit/wit | wit-core/src/main/java/org/febit/wit_shaded/asm/MethodWriter.java | MethodWriter.addSuccessor | private void addSuccessor(final int stackSize, final Label successor) {
Edge b;
// creates a new Edge object or reuses one from the shared pool
synchronized (SIZE) {
if (pool == null) {
b = new Edge();
} else {
b = pool;
// removes b from the pool
pool = pool.poolNext;
}
}
// adds the previous Edge to the list of Edges used by this MethodWriter
if (tail == null) {
tail = b;
}
b.poolNext = head;
head = b;
// initializes the previous Edge object...
b.stackSize = stackSize;
b.successor = successor;
// ...and adds it to the successor list of the currentBlock block
b.next = currentBlock.successors;
currentBlock.successors = b;
} | java | private void addSuccessor(final int stackSize, final Label successor) {
Edge b;
// creates a new Edge object or reuses one from the shared pool
synchronized (SIZE) {
if (pool == null) {
b = new Edge();
} else {
b = pool;
// removes b from the pool
pool = pool.poolNext;
}
}
// adds the previous Edge to the list of Edges used by this MethodWriter
if (tail == null) {
tail = b;
}
b.poolNext = head;
head = b;
// initializes the previous Edge object...
b.stackSize = stackSize;
b.successor = successor;
// ...and adds it to the successor list of the currentBlock block
b.next = currentBlock.successors;
currentBlock.successors = b;
} | [
"private",
"void",
"addSuccessor",
"(",
"final",
"int",
"stackSize",
",",
"final",
"Label",
"successor",
")",
"{",
"Edge",
"b",
";",
"// creates a new Edge object or reuses one from the shared pool",
"synchronized",
"(",
"SIZE",
")",
"{",
"if",
"(",
"pool",
"==",
... | Adds a successor to the {@link #currentBlock currentBlock} block.
@param stackSize the current (relative) stack size in the current block.
@param successor the successor block to be added to the current block. | [
"Adds",
"a",
"successor",
"to",
"the",
"{",
"@link",
"#currentBlock",
"currentBlock",
"}",
"block",
"."
] | train | https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit_shaded/asm/MethodWriter.java#L955-L979 |
OpenLiberty/open-liberty | dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java | SessionManager.modified | protected void modified(Map<?, ?> properties) {
if (properties instanceof Dictionary) {
processConfig((Dictionary<?, ?>) properties);
} else {
Dictionary<?, ?> newconfig = new Hashtable<Object, Object>(properties);
processConfig(newconfig);
}
} | java | protected void modified(Map<?, ?> properties) {
if (properties instanceof Dictionary) {
processConfig((Dictionary<?, ?>) properties);
} else {
Dictionary<?, ?> newconfig = new Hashtable<Object, Object>(properties);
processConfig(newconfig);
}
} | [
"protected",
"void",
"modified",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"properties",
")",
"{",
"if",
"(",
"properties",
"instanceof",
"Dictionary",
")",
"{",
"processConfig",
"(",
"(",
"Dictionary",
"<",
"?",
",",
"?",
">",
")",
"properties",
")",
";",
... | DS method for runtime updates to configuration without stopping and
restarting the component.
@param properties | [
"DS",
"method",
"for",
"runtime",
"updates",
"to",
"configuration",
"without",
"stopping",
"and",
"restarting",
"the",
"component",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionManager.java#L97-L104 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.getErasedTypeTree | public static Tree getErasedTypeTree(Tree tree) {
return tree.accept(
new SimpleTreeVisitor<Tree, Void>() {
@Override
public Tree visitIdentifier(IdentifierTree tree, Void unused) {
return tree;
}
@Override
public Tree visitParameterizedType(ParameterizedTypeTree tree, Void unused) {
return tree.getType();
}
},
null);
} | java | public static Tree getErasedTypeTree(Tree tree) {
return tree.accept(
new SimpleTreeVisitor<Tree, Void>() {
@Override
public Tree visitIdentifier(IdentifierTree tree, Void unused) {
return tree;
}
@Override
public Tree visitParameterizedType(ParameterizedTypeTree tree, Void unused) {
return tree.getType();
}
},
null);
} | [
"public",
"static",
"Tree",
"getErasedTypeTree",
"(",
"Tree",
"tree",
")",
"{",
"return",
"tree",
".",
"accept",
"(",
"new",
"SimpleTreeVisitor",
"<",
"Tree",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Tree",
"visitIdentifier",
"(",
"Iden... | Returns the erasure of the given type tree, i.e. {@code List} for {@code List<Foo>}. | [
"Returns",
"the",
"erasure",
"of",
"the",
"given",
"type",
"tree",
"i",
".",
"e",
".",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L862-L876 |
inferred/FreeBuilder | generated/main/java/org/inferred/freebuilder/processor/Datatype_Builder.java | Datatype_Builder.putStandardMethodUnderrides | public Datatype.Builder putStandardMethodUnderrides(StandardMethod key, UnderrideLevel value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
standardMethodUnderrides.put(key, value);
return (Datatype.Builder) this;
} | java | public Datatype.Builder putStandardMethodUnderrides(StandardMethod key, UnderrideLevel value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
standardMethodUnderrides.put(key, value);
return (Datatype.Builder) this;
} | [
"public",
"Datatype",
".",
"Builder",
"putStandardMethodUnderrides",
"(",
"StandardMethod",
"key",
",",
"UnderrideLevel",
"value",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"key",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"value",
")",
";",
"standa... | Associates {@code key} with {@code value} in the map to be returned from {@link
Datatype#getStandardMethodUnderrides()}. If the map previously contained a mapping for the key,
the old value is replaced by the specified value.
@return this {@code Builder} object
@throws NullPointerException if either {@code key} or {@code value} are null | [
"Associates",
"{",
"@code",
"key",
"}",
"with",
"{",
"@code",
"value",
"}",
"in",
"the",
"map",
"to",
"be",
"returned",
"from",
"{",
"@link",
"Datatype#getStandardMethodUnderrides",
"()",
"}",
".",
"If",
"the",
"map",
"previously",
"contained",
"a",
"mapping... | train | https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/generated/main/java/org/inferred/freebuilder/processor/Datatype_Builder.java#L522-L527 |
baasbox/Android-SDK | library/src/main/java/com/baasbox/android/json/JsonReader.java | JsonReader.decodeLiteral | private JsonToken decodeLiteral() throws IOException {
if (valuePos == -1) {
// it was too long to fit in the buffer so it can only be a string
return JsonToken.STRING;
} else if (valueLength == 4
&& ('n' == buffer[valuePos] || 'N' == buffer[valuePos])
&& ('u' == buffer[valuePos + 1] || 'U' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('l' == buffer[valuePos + 3] || 'L' == buffer[valuePos + 3])) {
value = "null";
return JsonToken.NULL;
} else if (valueLength == 4
&& ('t' == buffer[valuePos] || 'T' == buffer[valuePos])
&& ('r' == buffer[valuePos + 1] || 'R' == buffer[valuePos + 1])
&& ('u' == buffer[valuePos + 2] || 'U' == buffer[valuePos + 2])
&& ('e' == buffer[valuePos + 3] || 'E' == buffer[valuePos + 3])) {
value = TRUE;
return JsonToken.BOOLEAN;
} else if (valueLength == 5
&& ('f' == buffer[valuePos] || 'F' == buffer[valuePos])
&& ('a' == buffer[valuePos + 1] || 'A' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('s' == buffer[valuePos + 3] || 'S' == buffer[valuePos + 3])
&& ('e' == buffer[valuePos + 4] || 'E' == buffer[valuePos + 4])) {
value = FALSE;
return JsonToken.BOOLEAN;
} else {
value = stringPool.get(buffer, valuePos, valueLength);
return decodeNumber(buffer, valuePos, valueLength);
}
} | java | private JsonToken decodeLiteral() throws IOException {
if (valuePos == -1) {
// it was too long to fit in the buffer so it can only be a string
return JsonToken.STRING;
} else if (valueLength == 4
&& ('n' == buffer[valuePos] || 'N' == buffer[valuePos])
&& ('u' == buffer[valuePos + 1] || 'U' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('l' == buffer[valuePos + 3] || 'L' == buffer[valuePos + 3])) {
value = "null";
return JsonToken.NULL;
} else if (valueLength == 4
&& ('t' == buffer[valuePos] || 'T' == buffer[valuePos])
&& ('r' == buffer[valuePos + 1] || 'R' == buffer[valuePos + 1])
&& ('u' == buffer[valuePos + 2] || 'U' == buffer[valuePos + 2])
&& ('e' == buffer[valuePos + 3] || 'E' == buffer[valuePos + 3])) {
value = TRUE;
return JsonToken.BOOLEAN;
} else if (valueLength == 5
&& ('f' == buffer[valuePos] || 'F' == buffer[valuePos])
&& ('a' == buffer[valuePos + 1] || 'A' == buffer[valuePos + 1])
&& ('l' == buffer[valuePos + 2] || 'L' == buffer[valuePos + 2])
&& ('s' == buffer[valuePos + 3] || 'S' == buffer[valuePos + 3])
&& ('e' == buffer[valuePos + 4] || 'E' == buffer[valuePos + 4])) {
value = FALSE;
return JsonToken.BOOLEAN;
} else {
value = stringPool.get(buffer, valuePos, valueLength);
return decodeNumber(buffer, valuePos, valueLength);
}
} | [
"private",
"JsonToken",
"decodeLiteral",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"valuePos",
"==",
"-",
"1",
")",
"{",
"// it was too long to fit in the buffer so it can only be a string",
"return",
"JsonToken",
".",
"STRING",
";",
"}",
"else",
"if",
"(",... | Assigns {@code nextToken} based on the value of {@code nextValue}. | [
"Assigns",
"{"
] | train | https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L857-L887 |
Azure/azure-sdk-for-java | containerservice/resource-manager/v2017_08_31/src/main/java/com/microsoft/azure/management/containerservice/v2017_08_31/implementation/ManagedClustersInner.java | ManagedClustersInner.getUpgradeProfileAsync | public Observable<ManagedClusterUpgradeProfileInner> getUpgradeProfileAsync(String resourceGroupName, String resourceName) {
return getUpgradeProfileWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterUpgradeProfileInner>, ManagedClusterUpgradeProfileInner>() {
@Override
public ManagedClusterUpgradeProfileInner call(ServiceResponse<ManagedClusterUpgradeProfileInner> response) {
return response.body();
}
});
} | java | public Observable<ManagedClusterUpgradeProfileInner> getUpgradeProfileAsync(String resourceGroupName, String resourceName) {
return getUpgradeProfileWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterUpgradeProfileInner>, ManagedClusterUpgradeProfileInner>() {
@Override
public ManagedClusterUpgradeProfileInner call(ServiceResponse<ManagedClusterUpgradeProfileInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ManagedClusterUpgradeProfileInner",
">",
"getUpgradeProfileAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"getUpgradeProfileWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
... | Gets upgrade profile for a managed cluster.
Gets the details of the upgrade profile for a managed cluster with a specified resource group and name.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the managed cluster resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ManagedClusterUpgradeProfileInner object | [
"Gets",
"upgrade",
"profile",
"for",
"a",
"managed",
"cluster",
".",
"Gets",
"the",
"details",
"of",
"the",
"upgrade",
"profile",
"for",
"a",
"managed",
"cluster",
"with",
"a",
"specified",
"resource",
"group",
"and",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2017_08_31/src/main/java/com/microsoft/azure/management/containerservice/v2017_08_31/implementation/ManagedClustersInner.java#L383-L390 |
spring-projects/spring-boot | spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java | Neo4jHealthIndicator.extractResult | protected void extractResult(Session session, Health.Builder builder)
throws Exception {
Result result = session.query(CYPHER, Collections.emptyMap());
builder.up().withDetail("nodes",
result.queryResults().iterator().next().get("nodes"));
} | java | protected void extractResult(Session session, Health.Builder builder)
throws Exception {
Result result = session.query(CYPHER, Collections.emptyMap());
builder.up().withDetail("nodes",
result.queryResults().iterator().next().get("nodes"));
} | [
"protected",
"void",
"extractResult",
"(",
"Session",
"session",
",",
"Health",
".",
"Builder",
"builder",
")",
"throws",
"Exception",
"{",
"Result",
"result",
"=",
"session",
".",
"query",
"(",
"CYPHER",
",",
"Collections",
".",
"emptyMap",
"(",
")",
")",
... | Provide health details using the specified {@link Session} and {@link Builder
Builder}.
@param session the session to use to execute a cypher statement
@param builder the builder to add details to
@throws Exception if getting health details failed | [
"Provide",
"health",
"details",
"using",
"the",
"specified",
"{"
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java#L70-L75 |
Coveros/selenified | src/main/java/com/coveros/selenified/Selenified.java | Selenified.addAdditionalDesiredCapabilities | protected static void addAdditionalDesiredCapabilities(Selenified clazz, ITestContext context, String capabilityName, Object capabilityValue) {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
if (context.getAttributeNames().contains(clazz.getClass().getName() + DESIRED_CAPABILITIES)) {
desiredCapabilities = (DesiredCapabilities) context.getAttribute(clazz.getClass().getName() + DESIRED_CAPABILITIES);
}
desiredCapabilities.setCapability(capabilityName, capabilityValue);
context.setAttribute(clazz.getClass().getName() + DESIRED_CAPABILITIES, desiredCapabilities);
} | java | protected static void addAdditionalDesiredCapabilities(Selenified clazz, ITestContext context, String capabilityName, Object capabilityValue) {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
if (context.getAttributeNames().contains(clazz.getClass().getName() + DESIRED_CAPABILITIES)) {
desiredCapabilities = (DesiredCapabilities) context.getAttribute(clazz.getClass().getName() + DESIRED_CAPABILITIES);
}
desiredCapabilities.setCapability(capabilityName, capabilityValue);
context.setAttribute(clazz.getClass().getName() + DESIRED_CAPABILITIES, desiredCapabilities);
} | [
"protected",
"static",
"void",
"addAdditionalDesiredCapabilities",
"(",
"Selenified",
"clazz",
",",
"ITestContext",
"context",
",",
"String",
"capabilityName",
",",
"Object",
"capabilityValue",
")",
"{",
"DesiredCapabilities",
"desiredCapabilities",
"=",
"new",
"DesiredCa... | Sets any additional capabilities desired for the browsers. Things like enabling javascript, accepting insecure certs. etc
can all be added here on a per test class basis.
@param clazz - the test suite class, used for making threadsafe storage of
application, allowing suites to have independent applications
under test, run at the same time
@param context - the TestNG context associated with the test suite, used for
storing app url information
@param capabilityName - the capability name to be added
@param capabilityValue - the capability value to be set | [
"Sets",
"any",
"additional",
"capabilities",
"desired",
"for",
"the",
"browsers",
".",
"Things",
"like",
"enabling",
"javascript",
"accepting",
"insecure",
"certs",
".",
"etc",
"can",
"all",
"be",
"added",
"here",
"on",
"a",
"per",
"test",
"class",
"basis",
... | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/Selenified.java#L209-L216 |
Cornutum/tcases | tcases-maven-plugin/src/main/java/org/cornutum/tcases/maven/TcasesMojo.java | TcasesMojo.getTargetDir | private File getTargetDir( File path)
{
return
path == null?
targetDir_ :
path.isAbsolute()?
path :
new File( targetDir_, path.getPath());
} | java | private File getTargetDir( File path)
{
return
path == null?
targetDir_ :
path.isAbsolute()?
path :
new File( targetDir_, path.getPath());
} | [
"private",
"File",
"getTargetDir",
"(",
"File",
"path",
")",
"{",
"return",
"path",
"==",
"null",
"?",
"targetDir_",
":",
"path",
".",
"isAbsolute",
"(",
")",
"?",
"path",
":",
"new",
"File",
"(",
"targetDir_",
",",
"path",
".",
"getPath",
"(",
")",
... | If the given path is not absolute, returns it as an absolute path relative to the
project target directory. Otherwise, returns the given absolute path. | [
"If",
"the",
"given",
"path",
"is",
"not",
"absolute",
"returns",
"it",
"as",
"an",
"absolute",
"path",
"relative",
"to",
"the",
"project",
"target",
"directory",
".",
"Otherwise",
"returns",
"the",
"given",
"absolute",
"path",
"."
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-maven-plugin/src/main/java/org/cornutum/tcases/maven/TcasesMojo.java#L197-L207 |
korpling/ANNIS | annis-service/src/main/java/annis/sqlgen/SaltAnnotateExtractor.java | SaltAnnotateExtractor.addMatchInformation | public static void addMatchInformation(SaltProject p, MatchGroup matchGroup)
{
int matchIndex = 0;
for (Match m : matchGroup.getMatches())
{
// get the corresponding SDocument of the salt project
SCorpusGraph corpusGraph = p.getCorpusGraphs().get(matchIndex);
SDocument doc = corpusGraph.getDocuments().get(0);
setMatchedIDs(doc.getDocumentGraph(), m);
matchIndex++;
}
} | java | public static void addMatchInformation(SaltProject p, MatchGroup matchGroup)
{
int matchIndex = 0;
for (Match m : matchGroup.getMatches())
{
// get the corresponding SDocument of the salt project
SCorpusGraph corpusGraph = p.getCorpusGraphs().get(matchIndex);
SDocument doc = corpusGraph.getDocuments().get(0);
setMatchedIDs(doc.getDocumentGraph(), m);
matchIndex++;
}
} | [
"public",
"static",
"void",
"addMatchInformation",
"(",
"SaltProject",
"p",
",",
"MatchGroup",
"matchGroup",
")",
"{",
"int",
"matchIndex",
"=",
"0",
";",
"for",
"(",
"Match",
"m",
":",
"matchGroup",
".",
"getMatches",
"(",
")",
")",
"{",
"// get the corresp... | Sets additional match (global) information about the matched nodes and
annotations.
This will add the {@link AnnisConstants#FEAT_MATCHEDIDS) to all {@link SDocument} elements of the
salt project.
@param p The salt project to add the features to.
@param matchGroup A list of matches in the same order as the corpus graphs
of the salt project. | [
"Sets",
"additional",
"match",
"(",
"global",
")",
"information",
"about",
"the",
"matched",
"nodes",
"and",
"annotations",
"."
] | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-service/src/main/java/annis/sqlgen/SaltAnnotateExtractor.java#L1116-L1129 |
VoltDB/voltdb | src/frontend/org/voltdb/planner/ParsedUnionStmt.java | ParsedUnionStmt.parseOrderColumn | private void parseOrderColumn(VoltXMLElement orderByNode, ParsedSelectStmt leftmostSelectChild) {
ParsedColInfo.ExpressionAdjuster adjuster = new ParsedColInfo.ExpressionAdjuster() {
@Override
public AbstractExpression adjust(AbstractExpression expr) {
// Union itself can't have aggregate expression
return expr;
}
};
// Get the display columns from the first child
List<ParsedColInfo> displayColumns = leftmostSelectChild.displayColumns();
ParsedColInfo order_col = ParsedColInfo.fromOrderByXml(leftmostSelectChild, orderByNode, adjuster);
AbstractExpression order_exp = order_col.m_expression;
assert(order_exp != null);
// Mark the order by column if it is in displayColumns
// The ORDER BY column MAY be identical to a simple display column, in which case,
// tagging the actual display column as being also an order by column
// helps later when trying to determine ORDER BY coverage (for determinism).
for (ParsedColInfo col : displayColumns) {
if (col.m_alias.equals(order_col.m_alias) || col.m_expression.equals(order_exp)) {
col.m_orderBy = true;
col.m_ascending = order_col.m_ascending;
order_col.m_alias = col.m_alias;
order_col.m_columnName = col.m_columnName;
order_col.m_tableName = col.m_tableName;
break;
}
}
assert( ! (order_exp instanceof ConstantValueExpression));
assert( ! (order_exp instanceof ParameterValueExpression));
m_orderColumns.add(order_col);
} | java | private void parseOrderColumn(VoltXMLElement orderByNode, ParsedSelectStmt leftmostSelectChild) {
ParsedColInfo.ExpressionAdjuster adjuster = new ParsedColInfo.ExpressionAdjuster() {
@Override
public AbstractExpression adjust(AbstractExpression expr) {
// Union itself can't have aggregate expression
return expr;
}
};
// Get the display columns from the first child
List<ParsedColInfo> displayColumns = leftmostSelectChild.displayColumns();
ParsedColInfo order_col = ParsedColInfo.fromOrderByXml(leftmostSelectChild, orderByNode, adjuster);
AbstractExpression order_exp = order_col.m_expression;
assert(order_exp != null);
// Mark the order by column if it is in displayColumns
// The ORDER BY column MAY be identical to a simple display column, in which case,
// tagging the actual display column as being also an order by column
// helps later when trying to determine ORDER BY coverage (for determinism).
for (ParsedColInfo col : displayColumns) {
if (col.m_alias.equals(order_col.m_alias) || col.m_expression.equals(order_exp)) {
col.m_orderBy = true;
col.m_ascending = order_col.m_ascending;
order_col.m_alias = col.m_alias;
order_col.m_columnName = col.m_columnName;
order_col.m_tableName = col.m_tableName;
break;
}
}
assert( ! (order_exp instanceof ConstantValueExpression));
assert( ! (order_exp instanceof ParameterValueExpression));
m_orderColumns.add(order_col);
} | [
"private",
"void",
"parseOrderColumn",
"(",
"VoltXMLElement",
"orderByNode",
",",
"ParsedSelectStmt",
"leftmostSelectChild",
")",
"{",
"ParsedColInfo",
".",
"ExpressionAdjuster",
"adjuster",
"=",
"new",
"ParsedColInfo",
".",
"ExpressionAdjuster",
"(",
")",
"{",
"@",
"... | This is a stripped down version of the ParsedSelectStmt.parseOrderColumn. Since the SET ops
are not allowed to have aggregate expressions (HAVING, GROUP BY) (except the individual SELECTS)
all the logic handling the aggregates is omitted here
@param orderByNode
@param leftmostSelectChild | [
"This",
"is",
"a",
"stripped",
"down",
"version",
"of",
"the",
"ParsedSelectStmt",
".",
"parseOrderColumn",
".",
"Since",
"the",
"SET",
"ops",
"are",
"not",
"allowed",
"to",
"have",
"aggregate",
"expressions",
"(",
"HAVING",
"GROUP",
"BY",
")",
"(",
"except"... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/ParsedUnionStmt.java#L312-L347 |
jbundle/jbundle | thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageHeader.java | BaseMessageHeader.init | public void init(String strQueueName, String strQueueType, Object source, Map<String,Object> properties)
{
if (strQueueName == null)
if ((strQueueType == null)
|| (strQueueType.equals(MessageConstants.INTRANET_QUEUE)))
{
strQueueType = MessageConstants.INTRANET_QUEUE;
strQueueName = MessageConstants.RECORD_QUEUE_NAME;
}
if (strQueueType == null)
strQueueType = MessageConstants.INTERNET_QUEUE;
m_strQueueName = strQueueName;
m_strQueueType = strQueueType;
m_source = source;
m_mxProperties = this.createNameValueTree(null, properties);
} | java | public void init(String strQueueName, String strQueueType, Object source, Map<String,Object> properties)
{
if (strQueueName == null)
if ((strQueueType == null)
|| (strQueueType.equals(MessageConstants.INTRANET_QUEUE)))
{
strQueueType = MessageConstants.INTRANET_QUEUE;
strQueueName = MessageConstants.RECORD_QUEUE_NAME;
}
if (strQueueType == null)
strQueueType = MessageConstants.INTERNET_QUEUE;
m_strQueueName = strQueueName;
m_strQueueType = strQueueType;
m_source = source;
m_mxProperties = this.createNameValueTree(null, properties);
} | [
"public",
"void",
"init",
"(",
"String",
"strQueueName",
",",
"String",
"strQueueType",
",",
"Object",
"source",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"if",
"(",
"strQueueName",
"==",
"null",
")",
"if",
"(",
"(",
"strQueu... | Constructor.
@param strQueueName Name of the queue.
@param strQueueType Type of queue - remote or local.
@param source usually the object sending or listening for the message, to reduce echos. | [
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageHeader.java#L96-L112 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/PropertyUtils.java | PropertyUtils.getProperty | public static String getProperty(InputStream input, String key, String defaultValue) {
String property = null;
try {
property = PropertiesFactory.load(input).getProperty(key);
} catch (IOException e) {}
return property == null ? defaultValue : property;
} | java | public static String getProperty(InputStream input, String key, String defaultValue) {
String property = null;
try {
property = PropertiesFactory.load(input).getProperty(key);
} catch (IOException e) {}
return property == null ? defaultValue : property;
} | [
"public",
"static",
"String",
"getProperty",
"(",
"InputStream",
"input",
",",
"String",
"key",
",",
"String",
"defaultValue",
")",
"{",
"String",
"property",
"=",
"null",
";",
"try",
"{",
"property",
"=",
"PropertiesFactory",
".",
"load",
"(",
"input",
")",... | Retrieves a value from a properties input stream.
@since 1.2
@param input the properties input stream
@param key the property key
@param defaultValue the fallback value to use
@return the value retrieved with the supplied key | [
"Retrieves",
"a",
"value",
"from",
"a",
"properties",
"input",
"stream",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/PropertyUtils.java#L46-L52 |
HanSolo/SteelSeries-Swing | src/main/java/eu/hansolo/steelseries/extras/Poi.java | Poi.distanceTo | public double distanceTo(final double LAT, final double LON) {
final double EARTH_RADIUS = 6371000.0; // m
return Math.abs(Math.acos(Math.sin(Math.toRadians(LAT)) * Math.sin(Math.toRadians(this.lat)) + Math.cos(Math.toRadians(LAT)) * Math.cos(Math.toRadians(this.lat)) * Math.cos(Math.toRadians(LON - this.lon))) * EARTH_RADIUS);
} | java | public double distanceTo(final double LAT, final double LON) {
final double EARTH_RADIUS = 6371000.0; // m
return Math.abs(Math.acos(Math.sin(Math.toRadians(LAT)) * Math.sin(Math.toRadians(this.lat)) + Math.cos(Math.toRadians(LAT)) * Math.cos(Math.toRadians(this.lat)) * Math.cos(Math.toRadians(LON - this.lon))) * EARTH_RADIUS);
} | [
"public",
"double",
"distanceTo",
"(",
"final",
"double",
"LAT",
",",
"final",
"double",
"LON",
")",
"{",
"final",
"double",
"EARTH_RADIUS",
"=",
"6371000.0",
";",
"// m",
"return",
"Math",
".",
"abs",
"(",
"Math",
".",
"acos",
"(",
"Math",
".",
"sin",
... | Returns the distance in meters of the poi to the coordinate defined
by the given latitude and longitude. The calculation takes the
earth radius into account.
@param LAT
@param LON
@return the distance in meters to the given coordinate | [
"Returns",
"the",
"distance",
"in",
"meters",
"of",
"the",
"poi",
"to",
"the",
"coordinate",
"defined",
"by",
"the",
"given",
"latitude",
"and",
"longitude",
".",
"The",
"calculation",
"takes",
"the",
"earth",
"radius",
"into",
"account",
"."
] | train | https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/extras/Poi.java#L371-L374 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/TransformationUtils.java | TransformationUtils.scaleToWidth | public static Envelope scaleToWidth( Envelope original, double newWidth ) {
double width = original.getWidth();
double factor = newWidth / width;
double newHeight = original.getHeight() * factor;
return new Envelope(original.getMinX(), original.getMinX() + newWidth, original.getMinY(),
original.getMinY() + newHeight);
} | java | public static Envelope scaleToWidth( Envelope original, double newWidth ) {
double width = original.getWidth();
double factor = newWidth / width;
double newHeight = original.getHeight() * factor;
return new Envelope(original.getMinX(), original.getMinX() + newWidth, original.getMinY(),
original.getMinY() + newHeight);
} | [
"public",
"static",
"Envelope",
"scaleToWidth",
"(",
"Envelope",
"original",
",",
"double",
"newWidth",
")",
"{",
"double",
"width",
"=",
"original",
".",
"getWidth",
"(",
")",
";",
"double",
"factor",
"=",
"newWidth",
"/",
"width",
";",
"double",
"newHeight... | Scale an envelope to have a given width.
@param original the envelope.
@param newWidth the new width to use.
@return the scaled envelope placed in the original lower left corner position. | [
"Scale",
"an",
"envelope",
"to",
"have",
"a",
"given",
"width",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/TransformationUtils.java#L108-L116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.