repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PacketCapturesInner.java | PacketCapturesInner.beginCreateAsync | public Observable<PacketCaptureResultInner> beginCreateAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) {
"""
Create and start a packet capture on the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param packetCaptureName The name of the packet capture session.
@param parameters Parameters that define the create packet capture operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PacketCaptureResultInner object
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).map(new Func1<ServiceResponse<PacketCaptureResultInner>, PacketCaptureResultInner>() {
@Override
public PacketCaptureResultInner call(ServiceResponse<PacketCaptureResultInner> response) {
return response.body();
}
});
} | java | public Observable<PacketCaptureResultInner> beginCreateAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).map(new Func1<ServiceResponse<PacketCaptureResultInner>, PacketCaptureResultInner>() {
@Override
public PacketCaptureResultInner call(ServiceResponse<PacketCaptureResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PacketCaptureResultInner",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkWatcherName",
",",
"String",
"packetCaptureName",
",",
"PacketCaptureInner",
"parameters",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkWatcherName",
",",
"packetCaptureName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"PacketCaptureResultInner",
">",
",",
"PacketCaptureResultInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"PacketCaptureResultInner",
"call",
"(",
"ServiceResponse",
"<",
"PacketCaptureResultInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Create and start a packet capture on the specified VM.
@param resourceGroupName The name of the resource group.
@param networkWatcherName The name of the network watcher.
@param packetCaptureName The name of the packet capture session.
@param parameters Parameters that define the create packet capture operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PacketCaptureResultInner object | [
"Create",
"and",
"start",
"a",
"packet",
"capture",
"on",
"the",
"specified",
"VM",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PacketCapturesInner.java#L229-L236 |
micronaut-projects/micronaut-core | inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java | AbstractBeanDefinition.streamOfTypeForMethodArgument | @SuppressWarnings("WeakerAccess")
@Internal
protected final Stream streamOfTypeForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, MethodInjectionPoint injectionPoint, Argument argument) {
"""
Obtains all bean definitions for the method at the given index and the argument at the given index
<p>
Warning: this method is used by internal generated code and should not be called by user code.
@param resolutionContext The resolution context
@param context The context
@param injectionPoint The method injection point
@param argument The argument
@return The resolved bean
"""
return resolveBeanWithGenericsFromMethodArgument(resolutionContext, injectionPoint, argument, (beanType, qualifier) ->
((DefaultBeanContext) context).streamOfType(resolutionContext, beanType, qualifier)
);
} | java | @SuppressWarnings("WeakerAccess")
@Internal
protected final Stream streamOfTypeForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, MethodInjectionPoint injectionPoint, Argument argument) {
return resolveBeanWithGenericsFromMethodArgument(resolutionContext, injectionPoint, argument, (beanType, qualifier) ->
((DefaultBeanContext) context).streamOfType(resolutionContext, beanType, qualifier)
);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"@",
"Internal",
"protected",
"final",
"Stream",
"streamOfTypeForMethodArgument",
"(",
"BeanResolutionContext",
"resolutionContext",
",",
"BeanContext",
"context",
",",
"MethodInjectionPoint",
"injectionPoint",
",",
"Argument",
"argument",
")",
"{",
"return",
"resolveBeanWithGenericsFromMethodArgument",
"(",
"resolutionContext",
",",
"injectionPoint",
",",
"argument",
",",
"(",
"beanType",
",",
"qualifier",
")",
"->",
"(",
"(",
"DefaultBeanContext",
")",
"context",
")",
".",
"streamOfType",
"(",
"resolutionContext",
",",
"beanType",
",",
"qualifier",
")",
")",
";",
"}"
] | Obtains all bean definitions for the method at the given index and the argument at the given index
<p>
Warning: this method is used by internal generated code and should not be called by user code.
@param resolutionContext The resolution context
@param context The context
@param injectionPoint The method injection point
@param argument The argument
@return The resolved bean | [
"Obtains",
"all",
"bean",
"definitions",
"for",
"the",
"method",
"at",
"the",
"given",
"index",
"and",
"the",
"argument",
"at",
"the",
"given",
"index",
"<p",
">",
"Warning",
":",
"this",
"method",
"is",
"used",
"by",
"internal",
"generated",
"code",
"and",
"should",
"not",
"be",
"called",
"by",
"user",
"code",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L927-L933 |
google/gson | gson/src/main/java/com/google/gson/JsonObject.java | JsonObject.addProperty | public void addProperty(String property, Character value) {
"""
Convenience method to add a char member. The specified value is converted to a
JsonPrimitive of Character.
@param property name of the member.
@param value the number value associated with the member.
"""
add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
} | java | public void addProperty(String property, Character value) {
add(property, value == null ? JsonNull.INSTANCE : new JsonPrimitive(value));
} | [
"public",
"void",
"addProperty",
"(",
"String",
"property",
",",
"Character",
"value",
")",
"{",
"add",
"(",
"property",
",",
"value",
"==",
"null",
"?",
"JsonNull",
".",
"INSTANCE",
":",
"new",
"JsonPrimitive",
"(",
"value",
")",
")",
";",
"}"
] | Convenience method to add a char member. The specified value is converted to a
JsonPrimitive of Character.
@param property name of the member.
@param value the number value associated with the member. | [
"Convenience",
"method",
"to",
"add",
"a",
"char",
"member",
".",
"The",
"specified",
"value",
"is",
"converted",
"to",
"a",
"JsonPrimitive",
"of",
"Character",
"."
] | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/JsonObject.java#L112-L114 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/KeyDecoder.java | KeyDecoder.decodeSingleDesc | public static byte[] decodeSingleDesc(byte[] src, int prefixPadding, int suffixPadding)
throws CorruptEncodingException {
"""
Decodes the given byte array which was encoded by {@link
KeyEncoder#encodeSingleDesc}. Always returns a new byte array instance.
@param prefixPadding amount of extra bytes to skip from start of encoded byte array
@param suffixPadding amount of extra bytes to skip at end of encoded byte array
"""
try {
int length = src.length - suffixPadding - prefixPadding;
if (length == 0) {
return EMPTY_BYTE_ARRAY;
}
byte[] dst = new byte[length];
while (--length >= 0) {
dst[length] = (byte) (~src[prefixPadding + length]);
}
return dst;
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | java | public static byte[] decodeSingleDesc(byte[] src, int prefixPadding, int suffixPadding)
throws CorruptEncodingException
{
try {
int length = src.length - suffixPadding - prefixPadding;
if (length == 0) {
return EMPTY_BYTE_ARRAY;
}
byte[] dst = new byte[length];
while (--length >= 0) {
dst[length] = (byte) (~src[prefixPadding + length]);
}
return dst;
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | [
"public",
"static",
"byte",
"[",
"]",
"decodeSingleDesc",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"prefixPadding",
",",
"int",
"suffixPadding",
")",
"throws",
"CorruptEncodingException",
"{",
"try",
"{",
"int",
"length",
"=",
"src",
".",
"length",
"-",
"suffixPadding",
"-",
"prefixPadding",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"EMPTY_BYTE_ARRAY",
";",
"}",
"byte",
"[",
"]",
"dst",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"while",
"(",
"--",
"length",
">=",
"0",
")",
"{",
"dst",
"[",
"length",
"]",
"=",
"(",
"byte",
")",
"(",
"~",
"src",
"[",
"prefixPadding",
"+",
"length",
"]",
")",
";",
"}",
"return",
"dst",
";",
"}",
"catch",
"(",
"IndexOutOfBoundsException",
"e",
")",
"{",
"throw",
"new",
"CorruptEncodingException",
"(",
"null",
",",
"e",
")",
";",
"}",
"}"
] | Decodes the given byte array which was encoded by {@link
KeyEncoder#encodeSingleDesc}. Always returns a new byte array instance.
@param prefixPadding amount of extra bytes to skip from start of encoded byte array
@param suffixPadding amount of extra bytes to skip at end of encoded byte array | [
"Decodes",
"the",
"given",
"byte",
"array",
"which",
"was",
"encoded",
"by",
"{",
"@link",
"KeyEncoder#encodeSingleDesc",
"}",
".",
"Always",
"returns",
"a",
"new",
"byte",
"array",
"instance",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L846-L862 |
javamonkey/beetl2.0 | beetl-core/src/main/java/org/beetl/core/om/ObjectUtil.java | ObjectUtil.invokeStatic | public static Object invokeStatic(Class target, String methodName, Object[] paras) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
"""
调用类的静态方法,只知道方法名和参数,beetl将自动匹配到能调用的方法
@param target
@param methodName
@param paras
@return
@throws IllegalAccessException
@throws IllegalArgumentException
@throws InvocationTargetException
"""
return invoke(target, null, methodName, paras);
} | java | public static Object invokeStatic(Class target, String methodName, Object[] paras) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
return invoke(target, null, methodName, paras);
} | [
"public",
"static",
"Object",
"invokeStatic",
"(",
"Class",
"target",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"paras",
")",
"throws",
"IllegalAccessException",
",",
"IllegalArgumentException",
",",
"InvocationTargetException",
"{",
"return",
"invoke",
"(",
"target",
",",
"null",
",",
"methodName",
",",
"paras",
")",
";",
"}"
] | 调用类的静态方法,只知道方法名和参数,beetl将自动匹配到能调用的方法
@param target
@param methodName
@param paras
@return
@throws IllegalAccessException
@throws IllegalArgumentException
@throws InvocationTargetException | [
"调用类的静态方法,只知道方法名和参数,beetl将自动匹配到能调用的方法"
] | train | https://github.com/javamonkey/beetl2.0/blob/f32f729ad238079df5aca6e38a3c3ba0a55c78d6/beetl-core/src/main/java/org/beetl/core/om/ObjectUtil.java#L522-L527 |
micrometer-metrics/micrometer | micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java | ExecutorServiceMetrics.monitor | public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Tag... tags) {
"""
Record metrics on the use of an {@link ExecutorService}.
@param registry The registry to bind metrics to.
@param executor The executor to instrument.
@param executorServiceName Will be used to tag metrics with "name".
@param tags Tags to apply to all recorded metrics.
@return The instrumented executor, proxied.
"""
return monitor(registry, executor, executorServiceName, asList(tags));
} | java | public static ExecutorService monitor(MeterRegistry registry, ExecutorService executor, String executorServiceName, Tag... tags) {
return monitor(registry, executor, executorServiceName, asList(tags));
} | [
"public",
"static",
"ExecutorService",
"monitor",
"(",
"MeterRegistry",
"registry",
",",
"ExecutorService",
"executor",
",",
"String",
"executorServiceName",
",",
"Tag",
"...",
"tags",
")",
"{",
"return",
"monitor",
"(",
"registry",
",",
"executor",
",",
"executorServiceName",
",",
"asList",
"(",
"tags",
")",
")",
";",
"}"
] | Record metrics on the use of an {@link ExecutorService}.
@param registry The registry to bind metrics to.
@param executor The executor to instrument.
@param executorServiceName Will be used to tag metrics with "name".
@param tags Tags to apply to all recorded metrics.
@return The instrumented executor, proxied. | [
"Record",
"metrics",
"on",
"the",
"use",
"of",
"an",
"{",
"@link",
"ExecutorService",
"}",
"."
] | train | https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java#L105-L107 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging/src/com/ibm/ws/logging/collector/CollectorJsonHelpers.java | CollectorJsonHelpers.jsonEscape3 | protected static void jsonEscape3(StringBuilder sb, String s) {
"""
Escape \b, \f, \n, \r, \t, ", \, / characters and appends to a string builder
@param sb String builder to append to
@param s String to escape
"""
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
// Fall through because we just need to add \ (escaped) before the character
case '\\':
case '\"':
case '/':
sb.append("\\");
sb.append(c);
break;
default:
sb.append(c);
}
}
} | java | protected static void jsonEscape3(StringBuilder sb, String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
// Fall through because we just need to add \ (escaped) before the character
case '\\':
case '\"':
case '/':
sb.append("\\");
sb.append(c);
break;
default:
sb.append(c);
}
}
} | [
"protected",
"static",
"void",
"jsonEscape3",
"(",
"StringBuilder",
"sb",
",",
"String",
"s",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"char",
"c",
"=",
"s",
".",
"charAt",
"(",
"i",
")",
";",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\b\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\f\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\n\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\r\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\t\"",
")",
";",
"break",
";",
"// Fall through because we just need to add \\ (escaped) before the character",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"case",
"'",
"'",
":",
"sb",
".",
"append",
"(",
"\"\\\\\"",
")",
";",
"sb",
".",
"append",
"(",
"c",
")",
";",
"break",
";",
"default",
":",
"sb",
".",
"append",
"(",
"c",
")",
";",
"}",
"}",
"}"
] | Escape \b, \f, \n, \r, \t, ", \, / characters and appends to a string builder
@param sb String builder to append to
@param s String to escape | [
"Escape",
"\\",
"b",
"\\",
"f",
"\\",
"n",
"\\",
"r",
"\\",
"t",
"\\",
"/",
"characters",
"and",
"appends",
"to",
"a",
"string",
"builder"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/collector/CollectorJsonHelpers.java#L152-L183 |
TheHortonMachine/hortonmachine | gears/src/main/java/oms3/ngmf/util/IOCase.java | IOCase.checkRegionMatches | public boolean checkRegionMatches(String str, int strStartIndex, String search) {
"""
Checks if one string contains another at a specific index using the case-sensitivity rule.
<p>
This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
but takes case-sensitivity into account.
@param str the string to check, not null
@param strStartIndex the index to start at in str
@param search the start to search for, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null
"""
return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length());
} | java | public boolean checkRegionMatches(String str, int strStartIndex, String search) {
return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length());
} | [
"public",
"boolean",
"checkRegionMatches",
"(",
"String",
"str",
",",
"int",
"strStartIndex",
",",
"String",
"search",
")",
"{",
"return",
"str",
".",
"regionMatches",
"(",
"!",
"sensitive",
",",
"strStartIndex",
",",
"search",
",",
"0",
",",
"search",
".",
"length",
"(",
")",
")",
";",
"}"
] | Checks if one string contains another at a specific index using the case-sensitivity rule.
<p>
This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
but takes case-sensitivity into account.
@param str the string to check, not null
@param strStartIndex the index to start at in str
@param search the start to search for, not null
@return true if equal using the case rules
@throws NullPointerException if either string is null | [
"Checks",
"if",
"one",
"string",
"contains",
"another",
"at",
"a",
"specific",
"index",
"using",
"the",
"case",
"-",
"sensitivity",
"rule",
".",
"<p",
">",
"This",
"method",
"mimics",
"parts",
"of",
"{",
"@link",
"String#regionMatches",
"(",
"boolean",
"int",
"String",
"int",
"int",
")",
"}",
"but",
"takes",
"case",
"-",
"sensitivity",
"into",
"account",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/ngmf/util/IOCase.java#L210-L212 |
Alluxio/alluxio | shell/src/main/java/alluxio/proxy/AlluxioProxyMonitor.java | AlluxioProxyMonitor.main | public static void main(String[] args) {
"""
Starts the Alluxio proxy monitor.
@param args command line arguments, should be empty
"""
if (args.length != 0) {
LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR,
AlluxioProxyMonitor.class.getCanonicalName());
LOG.warn("ignoring arguments");
}
HealthCheckClient client = new ProxyHealthCheckClient(
NetworkAddressUtils.getBindAddress(NetworkAddressUtils.ServiceType.PROXY_WEB,
new InstancedConfiguration(ConfigurationUtils.defaults())),
() -> new ExponentialBackoffRetry(50, 100, 2));
if (!client.isServing()) {
System.exit(1);
}
System.exit(0);
} | java | public static void main(String[] args) {
if (args.length != 0) {
LOG.info("java -cp {} {}", RuntimeConstants.ALLUXIO_JAR,
AlluxioProxyMonitor.class.getCanonicalName());
LOG.warn("ignoring arguments");
}
HealthCheckClient client = new ProxyHealthCheckClient(
NetworkAddressUtils.getBindAddress(NetworkAddressUtils.ServiceType.PROXY_WEB,
new InstancedConfiguration(ConfigurationUtils.defaults())),
() -> new ExponentialBackoffRetry(50, 100, 2));
if (!client.isServing()) {
System.exit(1);
}
System.exit(0);
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"if",
"(",
"args",
".",
"length",
"!=",
"0",
")",
"{",
"LOG",
".",
"info",
"(",
"\"java -cp {} {}\"",
",",
"RuntimeConstants",
".",
"ALLUXIO_JAR",
",",
"AlluxioProxyMonitor",
".",
"class",
".",
"getCanonicalName",
"(",
")",
")",
";",
"LOG",
".",
"warn",
"(",
"\"ignoring arguments\"",
")",
";",
"}",
"HealthCheckClient",
"client",
"=",
"new",
"ProxyHealthCheckClient",
"(",
"NetworkAddressUtils",
".",
"getBindAddress",
"(",
"NetworkAddressUtils",
".",
"ServiceType",
".",
"PROXY_WEB",
",",
"new",
"InstancedConfiguration",
"(",
"ConfigurationUtils",
".",
"defaults",
"(",
")",
")",
")",
",",
"(",
")",
"->",
"new",
"ExponentialBackoffRetry",
"(",
"50",
",",
"100",
",",
"2",
")",
")",
";",
"if",
"(",
"!",
"client",
".",
"isServing",
"(",
")",
")",
"{",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"System",
".",
"exit",
"(",
"0",
")",
";",
"}"
] | Starts the Alluxio proxy monitor.
@param args command line arguments, should be empty | [
"Starts",
"the",
"Alluxio",
"proxy",
"monitor",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/proxy/AlluxioProxyMonitor.java#L35-L50 |
phax/ph-oton | ph-oton-core/src/main/java/com/helger/photon/core/servlet/AbstractResourceDeliveryHttpHandler.java | AbstractResourceDeliveryHttpHandler.determineMimeType | @OverrideOnDemand
@Nullable
protected String determineMimeType (@Nonnull final String sFilename, @Nonnull final IReadableResource aResource) {
"""
Determine the MIME type of the resource to deliver.
@param sFilename
The passed filename to stream. Never <code>null</code>.
@param aResource
The resolved resource. Never <code>null</code>.
@return <code>null</code> if no MIME type could be determined
"""
return MimeTypeInfoManager.getDefaultInstance ().getPrimaryMimeTypeStringForFilename (sFilename);
} | java | @OverrideOnDemand
@Nullable
protected String determineMimeType (@Nonnull final String sFilename, @Nonnull final IReadableResource aResource)
{
return MimeTypeInfoManager.getDefaultInstance ().getPrimaryMimeTypeStringForFilename (sFilename);
} | [
"@",
"OverrideOnDemand",
"@",
"Nullable",
"protected",
"String",
"determineMimeType",
"(",
"@",
"Nonnull",
"final",
"String",
"sFilename",
",",
"@",
"Nonnull",
"final",
"IReadableResource",
"aResource",
")",
"{",
"return",
"MimeTypeInfoManager",
".",
"getDefaultInstance",
"(",
")",
".",
"getPrimaryMimeTypeStringForFilename",
"(",
"sFilename",
")",
";",
"}"
] | Determine the MIME type of the resource to deliver.
@param sFilename
The passed filename to stream. Never <code>null</code>.
@param aResource
The resolved resource. Never <code>null</code>.
@return <code>null</code> if no MIME type could be determined | [
"Determine",
"the",
"MIME",
"type",
"of",
"the",
"resource",
"to",
"deliver",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-core/src/main/java/com/helger/photon/core/servlet/AbstractResourceDeliveryHttpHandler.java#L159-L164 |
aws/aws-sdk-java | aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/GetDevicesInPlacementResult.java | GetDevicesInPlacementResult.withDevices | public GetDevicesInPlacementResult withDevices(java.util.Map<String, String> devices) {
"""
<p>
An object containing the devices (zero or more) within the placement.
</p>
@param devices
An object containing the devices (zero or more) within the placement.
@return Returns a reference to this object so that method calls can be chained together.
"""
setDevices(devices);
return this;
} | java | public GetDevicesInPlacementResult withDevices(java.util.Map<String, String> devices) {
setDevices(devices);
return this;
} | [
"public",
"GetDevicesInPlacementResult",
"withDevices",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"devices",
")",
"{",
"setDevices",
"(",
"devices",
")",
";",
"return",
"this",
";",
"}"
] | <p>
An object containing the devices (zero or more) within the placement.
</p>
@param devices
An object containing the devices (zero or more) within the placement.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"An",
"object",
"containing",
"the",
"devices",
"(",
"zero",
"or",
"more",
")",
"within",
"the",
"placement",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/GetDevicesInPlacementResult.java#L68-L71 |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java | KuberntesServiceUrlResourceProvider.getContainerPort | private static int getContainerPort(Service service, Annotation... qualifiers) {
"""
Find the the qualfied container port of the target service
Uses java annotations first or returns the container port.
@param service
The target service.
@param qualifiers
The set of qualifiers.
@return Returns the resolved containerPort of '0' as a fallback.
"""
for (Annotation q : qualifiers) {
if (q instanceof Port) {
Port port = (Port) q;
if (port.value() > 0) {
return port.value();
}
}
}
ServicePort servicePort = findQualifiedServicePort(service, qualifiers);
if (servicePort != null) {
return servicePort.getTargetPort().getIntVal();
}
return 0;
} | java | private static int getContainerPort(Service service, Annotation... qualifiers) {
for (Annotation q : qualifiers) {
if (q instanceof Port) {
Port port = (Port) q;
if (port.value() > 0) {
return port.value();
}
}
}
ServicePort servicePort = findQualifiedServicePort(service, qualifiers);
if (servicePort != null) {
return servicePort.getTargetPort().getIntVal();
}
return 0;
} | [
"private",
"static",
"int",
"getContainerPort",
"(",
"Service",
"service",
",",
"Annotation",
"...",
"qualifiers",
")",
"{",
"for",
"(",
"Annotation",
"q",
":",
"qualifiers",
")",
"{",
"if",
"(",
"q",
"instanceof",
"Port",
")",
"{",
"Port",
"port",
"=",
"(",
"Port",
")",
"q",
";",
"if",
"(",
"port",
".",
"value",
"(",
")",
">",
"0",
")",
"{",
"return",
"port",
".",
"value",
"(",
")",
";",
"}",
"}",
"}",
"ServicePort",
"servicePort",
"=",
"findQualifiedServicePort",
"(",
"service",
",",
"qualifiers",
")",
";",
"if",
"(",
"servicePort",
"!=",
"null",
")",
"{",
"return",
"servicePort",
".",
"getTargetPort",
"(",
")",
".",
"getIntVal",
"(",
")",
";",
"}",
"return",
"0",
";",
"}"
] | Find the the qualfied container port of the target service
Uses java annotations first or returns the container port.
@param service
The target service.
@param qualifiers
The set of qualifiers.
@return Returns the resolved containerPort of '0' as a fallback. | [
"Find",
"the",
"the",
"qualfied",
"container",
"port",
"of",
"the",
"target",
"service",
"Uses",
"java",
"annotations",
"first",
"or",
"returns",
"the",
"container",
"port",
"."
] | train | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java#L156-L171 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/processor/jasper/DataSourceProcessor.java | DataSourceProcessor.setAttribute | public void setAttribute(final String name, final Attribute attribute) {
"""
All the sub-level attributes.
@param name the attribute name.
@param attribute the attribute.
"""
if (name.equals("datasource")) {
this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes());
} else if (this.copyAttributes.contains(name)) {
this.allAttributes.put(name, attribute);
}
} | java | public void setAttribute(final String name, final Attribute attribute) {
if (name.equals("datasource")) {
this.allAttributes.putAll(((DataSourceAttribute) attribute).getAttributes());
} else if (this.copyAttributes.contains(name)) {
this.allAttributes.put(name, attribute);
}
} | [
"public",
"void",
"setAttribute",
"(",
"final",
"String",
"name",
",",
"final",
"Attribute",
"attribute",
")",
"{",
"if",
"(",
"name",
".",
"equals",
"(",
"\"datasource\"",
")",
")",
"{",
"this",
".",
"allAttributes",
".",
"putAll",
"(",
"(",
"(",
"DataSourceAttribute",
")",
"attribute",
")",
".",
"getAttributes",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"copyAttributes",
".",
"contains",
"(",
"name",
")",
")",
"{",
"this",
".",
"allAttributes",
".",
"put",
"(",
"name",
",",
"attribute",
")",
";",
"}",
"}"
] | All the sub-level attributes.
@param name the attribute name.
@param attribute the attribute. | [
"All",
"the",
"sub",
"-",
"level",
"attributes",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/processor/jasper/DataSourceProcessor.java#L188-L194 |
killbill/killbill | invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java | ItemsNodeInterval.addAdjustment | public Item addAdjustment(final InvoiceItem item, final UUID targetInvoiceId) {
"""
Add the adjustment amount on the item specified by the targetId.
@return linked item if fully adjusted, null otherwise
"""
final UUID targetId = item.getLinkedItemId();
final NodeInterval node = findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((ItemsNodeInterval) curNode).getItemsInterval().findItem(targetId) != null;
}
});
Preconditions.checkNotNull(node, "Unable to find item interval for id='%s', tree=%s", targetId, this);
final ItemsInterval targetItemsInterval = ((ItemsNodeInterval) node).getItemsInterval();
final Item targetItem = targetItemsInterval.findItem(targetId);
Preconditions.checkNotNull(targetItem, "Unable to find item with id='%s', itemsInterval=%s", targetId, targetItemsInterval);
final BigDecimal adjustmentAmount = item.getAmount().negate();
if (targetItem.getAmount().compareTo(adjustmentAmount) == 0) {
// Full item adjustment - treat it like a repair
addExistingItem(new ItemsNodeInterval(this, new Item(item, targetItem.getStartDate(), targetItem.getEndDate(), targetInvoiceId, ItemAction.CANCEL)));
return targetItem;
} else {
targetItem.incrementAdjustedAmount(adjustmentAmount);
return null;
}
} | java | public Item addAdjustment(final InvoiceItem item, final UUID targetInvoiceId) {
final UUID targetId = item.getLinkedItemId();
final NodeInterval node = findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((ItemsNodeInterval) curNode).getItemsInterval().findItem(targetId) != null;
}
});
Preconditions.checkNotNull(node, "Unable to find item interval for id='%s', tree=%s", targetId, this);
final ItemsInterval targetItemsInterval = ((ItemsNodeInterval) node).getItemsInterval();
final Item targetItem = targetItemsInterval.findItem(targetId);
Preconditions.checkNotNull(targetItem, "Unable to find item with id='%s', itemsInterval=%s", targetId, targetItemsInterval);
final BigDecimal adjustmentAmount = item.getAmount().negate();
if (targetItem.getAmount().compareTo(adjustmentAmount) == 0) {
// Full item adjustment - treat it like a repair
addExistingItem(new ItemsNodeInterval(this, new Item(item, targetItem.getStartDate(), targetItem.getEndDate(), targetInvoiceId, ItemAction.CANCEL)));
return targetItem;
} else {
targetItem.incrementAdjustedAmount(adjustmentAmount);
return null;
}
} | [
"public",
"Item",
"addAdjustment",
"(",
"final",
"InvoiceItem",
"item",
",",
"final",
"UUID",
"targetInvoiceId",
")",
"{",
"final",
"UUID",
"targetId",
"=",
"item",
".",
"getLinkedItemId",
"(",
")",
";",
"final",
"NodeInterval",
"node",
"=",
"findNode",
"(",
"new",
"SearchCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"isMatch",
"(",
"final",
"NodeInterval",
"curNode",
")",
"{",
"return",
"(",
"(",
"ItemsNodeInterval",
")",
"curNode",
")",
".",
"getItemsInterval",
"(",
")",
".",
"findItem",
"(",
"targetId",
")",
"!=",
"null",
";",
"}",
"}",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"node",
",",
"\"Unable to find item interval for id='%s', tree=%s\"",
",",
"targetId",
",",
"this",
")",
";",
"final",
"ItemsInterval",
"targetItemsInterval",
"=",
"(",
"(",
"ItemsNodeInterval",
")",
"node",
")",
".",
"getItemsInterval",
"(",
")",
";",
"final",
"Item",
"targetItem",
"=",
"targetItemsInterval",
".",
"findItem",
"(",
"targetId",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"targetItem",
",",
"\"Unable to find item with id='%s', itemsInterval=%s\"",
",",
"targetId",
",",
"targetItemsInterval",
")",
";",
"final",
"BigDecimal",
"adjustmentAmount",
"=",
"item",
".",
"getAmount",
"(",
")",
".",
"negate",
"(",
")",
";",
"if",
"(",
"targetItem",
".",
"getAmount",
"(",
")",
".",
"compareTo",
"(",
"adjustmentAmount",
")",
"==",
"0",
")",
"{",
"// Full item adjustment - treat it like a repair",
"addExistingItem",
"(",
"new",
"ItemsNodeInterval",
"(",
"this",
",",
"new",
"Item",
"(",
"item",
",",
"targetItem",
".",
"getStartDate",
"(",
")",
",",
"targetItem",
".",
"getEndDate",
"(",
")",
",",
"targetInvoiceId",
",",
"ItemAction",
".",
"CANCEL",
")",
")",
")",
";",
"return",
"targetItem",
";",
"}",
"else",
"{",
"targetItem",
".",
"incrementAdjustedAmount",
"(",
"adjustmentAmount",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Add the adjustment amount on the item specified by the targetId.
@return linked item if fully adjusted, null otherwise | [
"Add",
"the",
"adjustment",
"amount",
"on",
"the",
"item",
"specified",
"by",
"the",
"targetId",
"."
] | train | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/tree/ItemsNodeInterval.java#L203-L227 |
oboehm/jfachwert | src/main/java/de/jfachwert/bank/Geldbetrag.java | Geldbetrag.valueOf | public static Geldbetrag valueOf(Number value, CurrencyUnit currency) {
"""
Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die
Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine
neues Objekt erzeugt, wenn es sich nicht vermeiden laesst.
<p>
In Anlehnung an {@link BigDecimal} heisst die Methode "valueOf".
</p>
@param value Wert des andere Geldbetrags
@param currency Waehrung des anderen Geldbetrags
@return ein Geldbetrag
"""
return valueOf(new Geldbetrag(value, currency));
} | java | public static Geldbetrag valueOf(Number value, CurrencyUnit currency) {
return valueOf(new Geldbetrag(value, currency));
} | [
"public",
"static",
"Geldbetrag",
"valueOf",
"(",
"Number",
"value",
",",
"CurrencyUnit",
"currency",
")",
"{",
"return",
"valueOf",
"(",
"new",
"Geldbetrag",
"(",
"value",
",",
"currency",
")",
")",
";",
"}"
] | Wandelt den angegebenen MonetaryAmount in einen Geldbetrag um. Um die
Anzahl von Objekten gering zu halten, wird nur dann tatsaechlich eine
neues Objekt erzeugt, wenn es sich nicht vermeiden laesst.
<p>
In Anlehnung an {@link BigDecimal} heisst die Methode "valueOf".
</p>
@param value Wert des andere Geldbetrags
@param currency Waehrung des anderen Geldbetrags
@return ein Geldbetrag | [
"Wandelt",
"den",
"angegebenen",
"MonetaryAmount",
"in",
"einen",
"Geldbetrag",
"um",
".",
"Um",
"die",
"Anzahl",
"von",
"Objekten",
"gering",
"zu",
"halten",
"wird",
"nur",
"dann",
"tatsaechlich",
"eine",
"neues",
"Objekt",
"erzeugt",
"wenn",
"es",
"sich",
"nicht",
"vermeiden",
"laesst",
".",
"<p",
">",
"In",
"Anlehnung",
"an",
"{",
"@link",
"BigDecimal",
"}",
"heisst",
"die",
"Methode",
"valueOf",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/bank/Geldbetrag.java#L398-L400 |
Netflix/spectator | spectator-web-spring/src/main/java/com/netflix/spectator/controllers/MetricsController.java | MetricsController.getMetrics | @RequestMapping(method = RequestMethod.GET)
public ApplicationRegistry getMetrics(@RequestParam Map<String, String> filters)
throws IOException {
"""
Endpoint for querying current metric values.
The result is a JSON document describing the metrics and their values.
The result can be filtered using query parameters or configuring the
controller instance itself.
"""
boolean all = filters.get("all") != null;
String filterMeterNameRegex = filters.getOrDefault("meterNameRegex", "");
String filterTagNameRegex = filters.getOrDefault("tagNameRegex", "");
String filterTagValueRegex = filters.getOrDefault("tagValueRegex", "");
TagMeasurementFilter queryFilter = new TagMeasurementFilter(
filterMeterNameRegex, filterTagNameRegex, filterTagValueRegex);
Predicate<Measurement> filter;
if (all) {
filter = queryFilter;
} else {
filter = queryFilter.and(getDefaultMeasurementFilter());
}
ApplicationRegistry response = new ApplicationRegistry();
response.setApplicationName(applicationName);
response.setApplicationVersion(applicationVersion);
response.setMetrics(encodeRegistry(registry, filter));
return response;
} | java | @RequestMapping(method = RequestMethod.GET)
public ApplicationRegistry getMetrics(@RequestParam Map<String, String> filters)
throws IOException {
boolean all = filters.get("all") != null;
String filterMeterNameRegex = filters.getOrDefault("meterNameRegex", "");
String filterTagNameRegex = filters.getOrDefault("tagNameRegex", "");
String filterTagValueRegex = filters.getOrDefault("tagValueRegex", "");
TagMeasurementFilter queryFilter = new TagMeasurementFilter(
filterMeterNameRegex, filterTagNameRegex, filterTagValueRegex);
Predicate<Measurement> filter;
if (all) {
filter = queryFilter;
} else {
filter = queryFilter.and(getDefaultMeasurementFilter());
}
ApplicationRegistry response = new ApplicationRegistry();
response.setApplicationName(applicationName);
response.setApplicationVersion(applicationVersion);
response.setMetrics(encodeRegistry(registry, filter));
return response;
} | [
"@",
"RequestMapping",
"(",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"ApplicationRegistry",
"getMetrics",
"(",
"@",
"RequestParam",
"Map",
"<",
"String",
",",
"String",
">",
"filters",
")",
"throws",
"IOException",
"{",
"boolean",
"all",
"=",
"filters",
".",
"get",
"(",
"\"all\"",
")",
"!=",
"null",
";",
"String",
"filterMeterNameRegex",
"=",
"filters",
".",
"getOrDefault",
"(",
"\"meterNameRegex\"",
",",
"\"\"",
")",
";",
"String",
"filterTagNameRegex",
"=",
"filters",
".",
"getOrDefault",
"(",
"\"tagNameRegex\"",
",",
"\"\"",
")",
";",
"String",
"filterTagValueRegex",
"=",
"filters",
".",
"getOrDefault",
"(",
"\"tagValueRegex\"",
",",
"\"\"",
")",
";",
"TagMeasurementFilter",
"queryFilter",
"=",
"new",
"TagMeasurementFilter",
"(",
"filterMeterNameRegex",
",",
"filterTagNameRegex",
",",
"filterTagValueRegex",
")",
";",
"Predicate",
"<",
"Measurement",
">",
"filter",
";",
"if",
"(",
"all",
")",
"{",
"filter",
"=",
"queryFilter",
";",
"}",
"else",
"{",
"filter",
"=",
"queryFilter",
".",
"and",
"(",
"getDefaultMeasurementFilter",
"(",
")",
")",
";",
"}",
"ApplicationRegistry",
"response",
"=",
"new",
"ApplicationRegistry",
"(",
")",
";",
"response",
".",
"setApplicationName",
"(",
"applicationName",
")",
";",
"response",
".",
"setApplicationVersion",
"(",
"applicationVersion",
")",
";",
"response",
".",
"setMetrics",
"(",
"encodeRegistry",
"(",
"registry",
",",
"filter",
")",
")",
";",
"return",
"response",
";",
"}"
] | Endpoint for querying current metric values.
The result is a JSON document describing the metrics and their values.
The result can be filtered using query parameters or configuring the
controller instance itself. | [
"Endpoint",
"for",
"querying",
"current",
"metric",
"values",
"."
] | train | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-web-spring/src/main/java/com/netflix/spectator/controllers/MetricsController.java#L99-L120 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/MLLibUtil.java | MLLibUtil.toLabeledPoint | private static LabeledPoint toLabeledPoint(DataSet point) {
"""
Convert a dataset (feature vector) to a labeled point
@param point the point to convert
@return the labeled point derived from this dataset
"""
if (!point.getFeatures().isVector()) {
throw new IllegalArgumentException("Feature matrix must be a vector");
}
Vector features = toVector(point.getFeatures().dup());
double label = Nd4j.getBlasWrapper().iamax(point.getLabels());
return new LabeledPoint(label, features);
} | java | private static LabeledPoint toLabeledPoint(DataSet point) {
if (!point.getFeatures().isVector()) {
throw new IllegalArgumentException("Feature matrix must be a vector");
}
Vector features = toVector(point.getFeatures().dup());
double label = Nd4j.getBlasWrapper().iamax(point.getLabels());
return new LabeledPoint(label, features);
} | [
"private",
"static",
"LabeledPoint",
"toLabeledPoint",
"(",
"DataSet",
"point",
")",
"{",
"if",
"(",
"!",
"point",
".",
"getFeatures",
"(",
")",
".",
"isVector",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Feature matrix must be a vector\"",
")",
";",
"}",
"Vector",
"features",
"=",
"toVector",
"(",
"point",
".",
"getFeatures",
"(",
")",
".",
"dup",
"(",
")",
")",
";",
"double",
"label",
"=",
"Nd4j",
".",
"getBlasWrapper",
"(",
")",
".",
"iamax",
"(",
"point",
".",
"getLabels",
"(",
")",
")",
";",
"return",
"new",
"LabeledPoint",
"(",
"label",
",",
"features",
")",
";",
"}"
] | Convert a dataset (feature vector) to a labeled point
@param point the point to convert
@return the labeled point derived from this dataset | [
"Convert",
"a",
"dataset",
"(",
"feature",
"vector",
")",
"to",
"a",
"labeled",
"point"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/MLLibUtil.java#L303-L312 |
hexagonframework/spring-data-ebean | src/main/java/org/springframework/data/ebean/repository/query/EbeanQueryCreator.java | EbeanQueryCreator.toExpression | private Expression toExpression(Part part, ExpressionList<?> root) {
"""
Creates a {@link ExpressionList} from the given {@link Part}.
@param part
@param root
@return
"""
return new ExpressionBuilder(part, root).build();
} | java | private Expression toExpression(Part part, ExpressionList<?> root) {
return new ExpressionBuilder(part, root).build();
} | [
"private",
"Expression",
"toExpression",
"(",
"Part",
"part",
",",
"ExpressionList",
"<",
"?",
">",
"root",
")",
"{",
"return",
"new",
"ExpressionBuilder",
"(",
"part",
",",
"root",
")",
".",
"build",
"(",
")",
";",
"}"
] | Creates a {@link ExpressionList} from the given {@link Part}.
@param part
@param root
@return | [
"Creates",
"a",
"{",
"@link",
"ExpressionList",
"}",
"from",
"the",
"given",
"{",
"@link",
"Part",
"}",
"."
] | train | https://github.com/hexagonframework/spring-data-ebean/blob/dd11b97654982403b50dd1d5369cadad71fce410/src/main/java/org/springframework/data/ebean/repository/query/EbeanQueryCreator.java#L116-L118 |
jbundle/jbundle | thin/base/db/base/src/main/java/org/jbundle/thin/base/db/FieldList.java | FieldList.setupKeys | public void setupKeys() {
"""
Set up all the key areas for this record.
Override this to add the key areas.
""" // Override this to set up the actual keys
KeyAreaInfo keyArea = null;
keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, Constants.ASCENDING);
} | java | public void setupKeys()
{ // Override this to set up the actual keys
KeyAreaInfo keyArea = null;
keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, Constants.ASCENDING);
} | [
"public",
"void",
"setupKeys",
"(",
")",
"{",
"// Override this to set up the actual keys",
"KeyAreaInfo",
"keyArea",
"=",
"null",
";",
"keyArea",
"=",
"new",
"KeyAreaInfo",
"(",
"this",
",",
"Constants",
".",
"UNIQUE",
",",
"ID_KEY",
")",
";",
"keyArea",
".",
"addKeyField",
"(",
"ID",
",",
"Constants",
".",
"ASCENDING",
")",
";",
"}"
] | Set up all the key areas for this record.
Override this to add the key areas. | [
"Set",
"up",
"all",
"the",
"key",
"areas",
"for",
"this",
"record",
".",
"Override",
"this",
"to",
"add",
"the",
"key",
"areas",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/base/src/main/java/org/jbundle/thin/base/db/FieldList.java#L267-L272 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_portability_id_document_documentId_PUT | public void billingAccount_portability_id_document_documentId_PUT(String billingAccount, Long id, Long documentId, OvhPortabilityDocument body) throws IOException {
"""
Alter this object properties
REST: PUT /telephony/{billingAccount}/portability/{id}/document/{documentId}
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param id [required] The ID of the portability
@param documentId [required] Identifier of the document
"""
String qPath = "/telephony/{billingAccount}/portability/{id}/document/{documentId}";
StringBuilder sb = path(qPath, billingAccount, id, documentId);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void billingAccount_portability_id_document_documentId_PUT(String billingAccount, Long id, Long documentId, OvhPortabilityDocument body) throws IOException {
String qPath = "/telephony/{billingAccount}/portability/{id}/document/{documentId}";
StringBuilder sb = path(qPath, billingAccount, id, documentId);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"billingAccount_portability_id_document_documentId_PUT",
"(",
"String",
"billingAccount",
",",
"Long",
"id",
",",
"Long",
"documentId",
",",
"OvhPortabilityDocument",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/portability/{id}/document/{documentId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
",",
"id",
",",
"documentId",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
] | Alter this object properties
REST: PUT /telephony/{billingAccount}/portability/{id}/document/{documentId}
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param id [required] The ID of the portability
@param documentId [required] Identifier of the document | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L287-L291 |
algolia/instantsearch-android | ui/src/main/java/com/algolia/instantsearch/ui/views/filters/TwoValuesToggle.java | TwoValuesToggle.setValueOn | public void setValueOn(String newValue, @Nullable String newName) {
"""
Changes the Toggle's valueOn, updating facet refinements accordingly.
@param newValue valueOn's new value.
@param newName an eventual new attribute name.
"""
if (isChecked()) { // refining on valueOn: facetRefinement needs an update
searcher.updateFacetRefinement(attribute, valueOn, false)
.updateFacetRefinement(newName != null ? newName : attribute, newValue, true)
.search();
}
this.valueOn = newValue;
applyEventualNewAttribute(newName);
} | java | public void setValueOn(String newValue, @Nullable String newName) {
if (isChecked()) { // refining on valueOn: facetRefinement needs an update
searcher.updateFacetRefinement(attribute, valueOn, false)
.updateFacetRefinement(newName != null ? newName : attribute, newValue, true)
.search();
}
this.valueOn = newValue;
applyEventualNewAttribute(newName);
} | [
"public",
"void",
"setValueOn",
"(",
"String",
"newValue",
",",
"@",
"Nullable",
"String",
"newName",
")",
"{",
"if",
"(",
"isChecked",
"(",
")",
")",
"{",
"// refining on valueOn: facetRefinement needs an update",
"searcher",
".",
"updateFacetRefinement",
"(",
"attribute",
",",
"valueOn",
",",
"false",
")",
".",
"updateFacetRefinement",
"(",
"newName",
"!=",
"null",
"?",
"newName",
":",
"attribute",
",",
"newValue",
",",
"true",
")",
".",
"search",
"(",
")",
";",
"}",
"this",
".",
"valueOn",
"=",
"newValue",
";",
"applyEventualNewAttribute",
"(",
"newName",
")",
";",
"}"
] | Changes the Toggle's valueOn, updating facet refinements accordingly.
@param newValue valueOn's new value.
@param newName an eventual new attribute name. | [
"Changes",
"the",
"Toggle",
"s",
"valueOn",
"updating",
"facet",
"refinements",
"accordingly",
"."
] | train | https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/ui/src/main/java/com/algolia/instantsearch/ui/views/filters/TwoValuesToggle.java#L60-L68 |
apache/incubator-gobblin | gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java | AzkabanClient.uploadProjectZip | public AzkabanClientStatus uploadProjectZip(String projectName,
File zipFile) throws AzkabanClientException {
"""
Updates a project by uploading a new zip file. Before uploading any project zip files,
the project should be created first.
@param projectName project name
@param zipFile zip file
@return A status object indicating if AJAX request is successful.
"""
AzkabanMultiCallables.UploadProjectCallable callable =
AzkabanMultiCallables.UploadProjectCallable.builder()
.client(this)
.projectName(projectName)
.zipFile(zipFile)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
} | java | public AzkabanClientStatus uploadProjectZip(String projectName,
File zipFile) throws AzkabanClientException {
AzkabanMultiCallables.UploadProjectCallable callable =
AzkabanMultiCallables.UploadProjectCallable.builder()
.client(this)
.projectName(projectName)
.zipFile(zipFile)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
} | [
"public",
"AzkabanClientStatus",
"uploadProjectZip",
"(",
"String",
"projectName",
",",
"File",
"zipFile",
")",
"throws",
"AzkabanClientException",
"{",
"AzkabanMultiCallables",
".",
"UploadProjectCallable",
"callable",
"=",
"AzkabanMultiCallables",
".",
"UploadProjectCallable",
".",
"builder",
"(",
")",
".",
"client",
"(",
"this",
")",
".",
"projectName",
"(",
"projectName",
")",
".",
"zipFile",
"(",
"zipFile",
")",
".",
"build",
"(",
")",
";",
"return",
"runWithRetry",
"(",
"callable",
",",
"AzkabanClientStatus",
".",
"class",
")",
";",
"}"
] | Updates a project by uploading a new zip file. Before uploading any project zip files,
the project should be created first.
@param projectName project name
@param zipFile zip file
@return A status object indicating if AJAX request is successful. | [
"Updates",
"a",
"project",
"by",
"uploading",
"a",
"new",
"zip",
"file",
".",
"Before",
"uploading",
"any",
"project",
"zip",
"files",
"the",
"project",
"should",
"be",
"created",
"first",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java#L318-L329 |
hawkular/hawkular-apm | server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/SpanServiceElasticsearch.java | SpanServiceElasticsearch.processConnectedFragment | protected void processConnectedFragment(String tenantId, Trace fragment) {
"""
This method aggregates enhances the root trace, representing the
complete end to end instance view, with the details available from
a linked trace fragment that should be attached to the supplied
Producer node. If the producer node is null then don't merge
(as fragment is root) and just recursively process the fragment
to identify additional linked fragments.
@param tenantId The tenant id
@param fragment The fragment to be processed
"""
List<Producer> producers = NodeUtil.findNodes(fragment.getNodes(), Producer.class);
for (Producer producer : producers) {
if (!producer.getCorrelationIds().isEmpty()) {
List<Trace> fragments = getTraceFragments(tenantId, producer.getCorrelationIds().stream()
.map(correlationIdentifier -> correlationIdentifier.getValue())
.collect(Collectors.toList()));
for (Trace descendant : fragments) {
// Attach the fragment root nodes to the producer
producer.getNodes().addAll(descendant.getNodes());
processConnectedFragment(tenantId, descendant);
}
}
}
} | java | protected void processConnectedFragment(String tenantId, Trace fragment) {
List<Producer> producers = NodeUtil.findNodes(fragment.getNodes(), Producer.class);
for (Producer producer : producers) {
if (!producer.getCorrelationIds().isEmpty()) {
List<Trace> fragments = getTraceFragments(tenantId, producer.getCorrelationIds().stream()
.map(correlationIdentifier -> correlationIdentifier.getValue())
.collect(Collectors.toList()));
for (Trace descendant : fragments) {
// Attach the fragment root nodes to the producer
producer.getNodes().addAll(descendant.getNodes());
processConnectedFragment(tenantId, descendant);
}
}
}
} | [
"protected",
"void",
"processConnectedFragment",
"(",
"String",
"tenantId",
",",
"Trace",
"fragment",
")",
"{",
"List",
"<",
"Producer",
">",
"producers",
"=",
"NodeUtil",
".",
"findNodes",
"(",
"fragment",
".",
"getNodes",
"(",
")",
",",
"Producer",
".",
"class",
")",
";",
"for",
"(",
"Producer",
"producer",
":",
"producers",
")",
"{",
"if",
"(",
"!",
"producer",
".",
"getCorrelationIds",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"List",
"<",
"Trace",
">",
"fragments",
"=",
"getTraceFragments",
"(",
"tenantId",
",",
"producer",
".",
"getCorrelationIds",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"correlationIdentifier",
"->",
"correlationIdentifier",
".",
"getValue",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
")",
";",
"for",
"(",
"Trace",
"descendant",
":",
"fragments",
")",
"{",
"// Attach the fragment root nodes to the producer",
"producer",
".",
"getNodes",
"(",
")",
".",
"addAll",
"(",
"descendant",
".",
"getNodes",
"(",
")",
")",
";",
"processConnectedFragment",
"(",
"tenantId",
",",
"descendant",
")",
";",
"}",
"}",
"}",
"}"
] | This method aggregates enhances the root trace, representing the
complete end to end instance view, with the details available from
a linked trace fragment that should be attached to the supplied
Producer node. If the producer node is null then don't merge
(as fragment is root) and just recursively process the fragment
to identify additional linked fragments.
@param tenantId The tenant id
@param fragment The fragment to be processed | [
"This",
"method",
"aggregates",
"enhances",
"the",
"root",
"trace",
"representing",
"the",
"complete",
"end",
"to",
"end",
"instance",
"view",
"with",
"the",
"details",
"available",
"from",
"a",
"linked",
"trace",
"fragment",
"that",
"should",
"be",
"attached",
"to",
"the",
"supplied",
"Producer",
"node",
".",
"If",
"the",
"producer",
"node",
"is",
"null",
"then",
"don",
"t",
"merge",
"(",
"as",
"fragment",
"is",
"root",
")",
"and",
"just",
"recursively",
"process",
"the",
"fragment",
"to",
"identify",
"additional",
"linked",
"fragments",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/elasticsearch/src/main/java/org/hawkular/apm/server/elasticsearch/SpanServiceElasticsearch.java#L262-L279 |
apache/groovy | src/main/java/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java | TypeTransformers.addTransformer | protected static MethodHandle addTransformer(MethodHandle handle, int pos, Object arg, Class parameter) {
"""
Adds a type transformer applied at runtime.
This method handles transformations to String from GString,
array transformations and number based transformations
"""
MethodHandle transformer=null;
if (arg instanceof GString) {
transformer = TO_STRING;
} else if (arg instanceof Closure) {
transformer = createSAMTransform(arg, parameter);
} else if (Number.class.isAssignableFrom(parameter)) {
transformer = selectNumberTransformer(parameter, arg);
} else if (parameter.isArray()) {
transformer = MethodHandles.insertArguments(AS_ARRAY, 1, parameter);
}
if (transformer==null) throw new GroovyBugError("Unknown transformation for argument "+arg+" at position "+pos+" with "+arg.getClass()+" for parameter of type "+parameter);
return applyUnsharpFilter(handle, pos, transformer);
} | java | protected static MethodHandle addTransformer(MethodHandle handle, int pos, Object arg, Class parameter) {
MethodHandle transformer=null;
if (arg instanceof GString) {
transformer = TO_STRING;
} else if (arg instanceof Closure) {
transformer = createSAMTransform(arg, parameter);
} else if (Number.class.isAssignableFrom(parameter)) {
transformer = selectNumberTransformer(parameter, arg);
} else if (parameter.isArray()) {
transformer = MethodHandles.insertArguments(AS_ARRAY, 1, parameter);
}
if (transformer==null) throw new GroovyBugError("Unknown transformation for argument "+arg+" at position "+pos+" with "+arg.getClass()+" for parameter of type "+parameter);
return applyUnsharpFilter(handle, pos, transformer);
} | [
"protected",
"static",
"MethodHandle",
"addTransformer",
"(",
"MethodHandle",
"handle",
",",
"int",
"pos",
",",
"Object",
"arg",
",",
"Class",
"parameter",
")",
"{",
"MethodHandle",
"transformer",
"=",
"null",
";",
"if",
"(",
"arg",
"instanceof",
"GString",
")",
"{",
"transformer",
"=",
"TO_STRING",
";",
"}",
"else",
"if",
"(",
"arg",
"instanceof",
"Closure",
")",
"{",
"transformer",
"=",
"createSAMTransform",
"(",
"arg",
",",
"parameter",
")",
";",
"}",
"else",
"if",
"(",
"Number",
".",
"class",
".",
"isAssignableFrom",
"(",
"parameter",
")",
")",
"{",
"transformer",
"=",
"selectNumberTransformer",
"(",
"parameter",
",",
"arg",
")",
";",
"}",
"else",
"if",
"(",
"parameter",
".",
"isArray",
"(",
")",
")",
"{",
"transformer",
"=",
"MethodHandles",
".",
"insertArguments",
"(",
"AS_ARRAY",
",",
"1",
",",
"parameter",
")",
";",
"}",
"if",
"(",
"transformer",
"==",
"null",
")",
"throw",
"new",
"GroovyBugError",
"(",
"\"Unknown transformation for argument \"",
"+",
"arg",
"+",
"\" at position \"",
"+",
"pos",
"+",
"\" with \"",
"+",
"arg",
".",
"getClass",
"(",
")",
"+",
"\" for parameter of type \"",
"+",
"parameter",
")",
";",
"return",
"applyUnsharpFilter",
"(",
"handle",
",",
"pos",
",",
"transformer",
")",
";",
"}"
] | Adds a type transformer applied at runtime.
This method handles transformations to String from GString,
array transformations and number based transformations | [
"Adds",
"a",
"type",
"transformer",
"applied",
"at",
"runtime",
".",
"This",
"method",
"handles",
"transformations",
"to",
"String",
"from",
"GString",
"array",
"transformations",
"and",
"number",
"based",
"transformations"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java#L126-L139 |
Red5/red5-client | src/main/java/org/red5/client/net/rtmpe/RTMPEIoFilter.java | RTMPEIoFilter.completeConnection | private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) {
"""
Provides connection completion.
@param session
@param conn
@param rtmp
@param handshake
"""
if (handshake.useEncryption()) {
// set encryption flag the rtmp state
rtmp.setEncrypted(true);
// add the ciphers
log.debug("Adding ciphers to the session");
session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn());
session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut());
}
// set state to indicate we're connected
conn.getState().setState(RTMP.STATE_CONNECTED);
log.debug("Connected, removing handshake data");
// remove handshake from session now that we are connected
session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// add protocol filter as the last one in the chain
log.debug("Adding RTMP protocol filter");
session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory()));
// get the rtmp handler
BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER);
handler.connectionOpened(conn);
} | java | private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) {
if (handshake.useEncryption()) {
// set encryption flag the rtmp state
rtmp.setEncrypted(true);
// add the ciphers
log.debug("Adding ciphers to the session");
session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn());
session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut());
}
// set state to indicate we're connected
conn.getState().setState(RTMP.STATE_CONNECTED);
log.debug("Connected, removing handshake data");
// remove handshake from session now that we are connected
session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// add protocol filter as the last one in the chain
log.debug("Adding RTMP protocol filter");
session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory()));
// get the rtmp handler
BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER);
handler.connectionOpened(conn);
} | [
"private",
"static",
"void",
"completeConnection",
"(",
"IoSession",
"session",
",",
"RTMPMinaConnection",
"conn",
",",
"RTMP",
"rtmp",
",",
"OutboundHandshake",
"handshake",
")",
"{",
"if",
"(",
"handshake",
".",
"useEncryption",
"(",
")",
")",
"{",
"// set encryption flag the rtmp state\r",
"rtmp",
".",
"setEncrypted",
"(",
"true",
")",
";",
"// add the ciphers\r",
"log",
".",
"debug",
"(",
"\"Adding ciphers to the session\"",
")",
";",
"session",
".",
"setAttribute",
"(",
"RTMPConnection",
".",
"RTMPE_CIPHER_IN",
",",
"handshake",
".",
"getCipherIn",
"(",
")",
")",
";",
"session",
".",
"setAttribute",
"(",
"RTMPConnection",
".",
"RTMPE_CIPHER_OUT",
",",
"handshake",
".",
"getCipherOut",
"(",
")",
")",
";",
"}",
"// set state to indicate we're connected\r",
"conn",
".",
"getState",
"(",
")",
".",
"setState",
"(",
"RTMP",
".",
"STATE_CONNECTED",
")",
";",
"log",
".",
"debug",
"(",
"\"Connected, removing handshake data\"",
")",
";",
"// remove handshake from session now that we are connected\r",
"session",
".",
"removeAttribute",
"(",
"RTMPConnection",
".",
"RTMP_HANDSHAKE",
")",
";",
"// add protocol filter as the last one in the chain\r",
"log",
".",
"debug",
"(",
"\"Adding RTMP protocol filter\"",
")",
";",
"session",
".",
"getFilterChain",
"(",
")",
".",
"addAfter",
"(",
"\"rtmpeFilter\"",
",",
"\"protocolFilter\"",
",",
"new",
"ProtocolCodecFilter",
"(",
"new",
"RTMPMinaCodecFactory",
"(",
")",
")",
")",
";",
"// get the rtmp handler\r",
"BaseRTMPClientHandler",
"handler",
"=",
"(",
"BaseRTMPClientHandler",
")",
"session",
".",
"getAttribute",
"(",
"RTMPConnection",
".",
"RTMP_HANDLER",
")",
";",
"handler",
".",
"connectionOpened",
"(",
"conn",
")",
";",
"}"
] | Provides connection completion.
@param session
@param conn
@param rtmp
@param handshake | [
"Provides",
"connection",
"completion",
"."
] | train | https://github.com/Red5/red5-client/blob/f894495b60e59d7cfba647abd9b934237cac9d45/src/main/java/org/red5/client/net/rtmpe/RTMPEIoFilter.java#L206-L226 |
transloadit/java-sdk | src/main/java/com/transloadit/sdk/Assembly.java | Assembly.save | public AssemblyResponse save(boolean isResumable)
throws RequestException, LocalOperationException {
"""
Submits the configured assembly to Transloadit for processing.
@param isResumable boolean value that tells the assembly whether or not to use tus.
@return {@link AssemblyResponse} the response received from the Transloadit server.
@throws RequestException if request to Transloadit server fails.
@throws LocalOperationException if something goes wrong while running non-http operations.
"""
Request request = new Request(getClient());
options.put("steps", steps.toMap());
// only do tus uploads if files will be uploaded
if (isResumable && getFilesCount() > 0) {
Map<String, String> tusOptions = new HashMap<String, String>();
tusOptions.put("tus_num_expected_upload_files", Integer.toString(getFilesCount()));
AssemblyResponse response = new AssemblyResponse(
request.post("/assemblies", options, tusOptions, null, null), true);
// check if the assembly returned an error
if (response.hasError()) {
throw new RequestException("Request to Assembly failed: " + response.json().getString("error"));
}
try {
handleTusUpload(response);
} catch (IOException e) {
throw new LocalOperationException(e);
} catch (ProtocolException e) {
throw new RequestException(e);
}
return response;
} else {
return new AssemblyResponse(request.post("/assemblies", options, null, files, fileStreams));
}
} | java | public AssemblyResponse save(boolean isResumable)
throws RequestException, LocalOperationException {
Request request = new Request(getClient());
options.put("steps", steps.toMap());
// only do tus uploads if files will be uploaded
if (isResumable && getFilesCount() > 0) {
Map<String, String> tusOptions = new HashMap<String, String>();
tusOptions.put("tus_num_expected_upload_files", Integer.toString(getFilesCount()));
AssemblyResponse response = new AssemblyResponse(
request.post("/assemblies", options, tusOptions, null, null), true);
// check if the assembly returned an error
if (response.hasError()) {
throw new RequestException("Request to Assembly failed: " + response.json().getString("error"));
}
try {
handleTusUpload(response);
} catch (IOException e) {
throw new LocalOperationException(e);
} catch (ProtocolException e) {
throw new RequestException(e);
}
return response;
} else {
return new AssemblyResponse(request.post("/assemblies", options, null, files, fileStreams));
}
} | [
"public",
"AssemblyResponse",
"save",
"(",
"boolean",
"isResumable",
")",
"throws",
"RequestException",
",",
"LocalOperationException",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"getClient",
"(",
")",
")",
";",
"options",
".",
"put",
"(",
"\"steps\"",
",",
"steps",
".",
"toMap",
"(",
")",
")",
";",
"// only do tus uploads if files will be uploaded",
"if",
"(",
"isResumable",
"&&",
"getFilesCount",
"(",
")",
">",
"0",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"tusOptions",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"tusOptions",
".",
"put",
"(",
"\"tus_num_expected_upload_files\"",
",",
"Integer",
".",
"toString",
"(",
"getFilesCount",
"(",
")",
")",
")",
";",
"AssemblyResponse",
"response",
"=",
"new",
"AssemblyResponse",
"(",
"request",
".",
"post",
"(",
"\"/assemblies\"",
",",
"options",
",",
"tusOptions",
",",
"null",
",",
"null",
")",
",",
"true",
")",
";",
"// check if the assembly returned an error",
"if",
"(",
"response",
".",
"hasError",
"(",
")",
")",
"{",
"throw",
"new",
"RequestException",
"(",
"\"Request to Assembly failed: \"",
"+",
"response",
".",
"json",
"(",
")",
".",
"getString",
"(",
"\"error\"",
")",
")",
";",
"}",
"try",
"{",
"handleTusUpload",
"(",
"response",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"LocalOperationException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"ProtocolException",
"e",
")",
"{",
"throw",
"new",
"RequestException",
"(",
"e",
")",
";",
"}",
"return",
"response",
";",
"}",
"else",
"{",
"return",
"new",
"AssemblyResponse",
"(",
"request",
".",
"post",
"(",
"\"/assemblies\"",
",",
"options",
",",
"null",
",",
"files",
",",
"fileStreams",
")",
")",
";",
"}",
"}"
] | Submits the configured assembly to Transloadit for processing.
@param isResumable boolean value that tells the assembly whether or not to use tus.
@return {@link AssemblyResponse} the response received from the Transloadit server.
@throws RequestException if request to Transloadit server fails.
@throws LocalOperationException if something goes wrong while running non-http operations. | [
"Submits",
"the",
"configured",
"assembly",
"to",
"Transloadit",
"for",
"processing",
"."
] | train | https://github.com/transloadit/java-sdk/blob/9326c540a66f77b3d907d0b2c05bff1145ca14f7/src/main/java/com/transloadit/sdk/Assembly.java#L155-L184 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodePolynomialMath.java | QrCodePolynomialMath.bitPolyModulus | public static int bitPolyModulus(int data , int generator , int totalBits, int dataBits) {
"""
Performs division using xcr operators on the encoded polynomials. used in BCH encoding/decoding
@param data Data being checked
@param generator Generator polynomial
@param totalBits Total number of bits in data
@param dataBits Number of data bits. Rest are error correction bits
@return Remainder after polynomial division
"""
int errorBits = totalBits-dataBits;
for (int i = dataBits-1; i >= 0; i--) {
if( (data & (1 << (i+errorBits))) != 0 ) {
data ^= generator << i;
}
}
return data;
} | java | public static int bitPolyModulus(int data , int generator , int totalBits, int dataBits) {
int errorBits = totalBits-dataBits;
for (int i = dataBits-1; i >= 0; i--) {
if( (data & (1 << (i+errorBits))) != 0 ) {
data ^= generator << i;
}
}
return data;
} | [
"public",
"static",
"int",
"bitPolyModulus",
"(",
"int",
"data",
",",
"int",
"generator",
",",
"int",
"totalBits",
",",
"int",
"dataBits",
")",
"{",
"int",
"errorBits",
"=",
"totalBits",
"-",
"dataBits",
";",
"for",
"(",
"int",
"i",
"=",
"dataBits",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"(",
"data",
"&",
"(",
"1",
"<<",
"(",
"i",
"+",
"errorBits",
")",
")",
")",
"!=",
"0",
")",
"{",
"data",
"^=",
"generator",
"<<",
"i",
";",
"}",
"}",
"return",
"data",
";",
"}"
] | Performs division using xcr operators on the encoded polynomials. used in BCH encoding/decoding
@param data Data being checked
@param generator Generator polynomial
@param totalBits Total number of bits in data
@param dataBits Number of data bits. Rest are error correction bits
@return Remainder after polynomial division | [
"Performs",
"division",
"using",
"xcr",
"operators",
"on",
"the",
"encoded",
"polynomials",
".",
"used",
"in",
"BCH",
"encoding",
"/",
"decoding"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/qrcode/QrCodePolynomialMath.java#L153-L161 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java | SegmentsUtil.bitGet | public static boolean bitGet(MemorySegment segment, int baseOffset, int index) {
"""
read bit.
@param segment target segment.
@param baseOffset bits base offset.
@param index bit index from base offset.
"""
int offset = baseOffset + ((index & BIT_BYTE_POSITION_MASK) >>> 3);
byte current = segment.get(offset);
return (current & (1 << (index & BIT_BYTE_INDEX_MASK))) != 0;
} | java | public static boolean bitGet(MemorySegment segment, int baseOffset, int index) {
int offset = baseOffset + ((index & BIT_BYTE_POSITION_MASK) >>> 3);
byte current = segment.get(offset);
return (current & (1 << (index & BIT_BYTE_INDEX_MASK))) != 0;
} | [
"public",
"static",
"boolean",
"bitGet",
"(",
"MemorySegment",
"segment",
",",
"int",
"baseOffset",
",",
"int",
"index",
")",
"{",
"int",
"offset",
"=",
"baseOffset",
"+",
"(",
"(",
"index",
"&",
"BIT_BYTE_POSITION_MASK",
")",
">>>",
"3",
")",
";",
"byte",
"current",
"=",
"segment",
".",
"get",
"(",
"offset",
")",
";",
"return",
"(",
"current",
"&",
"(",
"1",
"<<",
"(",
"index",
"&",
"BIT_BYTE_INDEX_MASK",
")",
")",
")",
"!=",
"0",
";",
"}"
] | read bit.
@param segment target segment.
@param baseOffset bits base offset.
@param index bit index from base offset. | [
"read",
"bit",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L447-L451 |
yidongnan/grpc-spring-boot-starter | grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/inject/GrpcClientBeanPostProcessor.java | GrpcClientBeanPostProcessor.interceptorsFromAnnotation | protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
"""
Gets or creates the {@link ClientInterceptor}s that are referenced in the given annotation.
<p>
<b>Note:</b> This methods return value does not contain the global client interceptors because they are handled
by the {@link GrpcChannelFactory}.
</p>
@param annotation The annotation to get the interceptors for.
@return A list containing the interceptors for the given annotation.
@throws BeansException If the referenced interceptors weren't found or could not be created.
"""
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor clientInterceptor;
if (this.applicationContext.getBeanNamesForType(ClientInterceptor.class).length > 0) {
clientInterceptor = this.applicationContext.getBean(interceptorClass);
} else {
try {
clientInterceptor = interceptorClass.getConstructor().newInstance();
} catch (final Exception e) {
throw new BeanCreationException("Failed to create interceptor instance", e);
}
}
list.add(clientInterceptor);
}
for (final String interceptorName : annotation.interceptorNames()) {
list.add(this.applicationContext.getBean(interceptorName, ClientInterceptor.class));
}
return list;
} | java | protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor clientInterceptor;
if (this.applicationContext.getBeanNamesForType(ClientInterceptor.class).length > 0) {
clientInterceptor = this.applicationContext.getBean(interceptorClass);
} else {
try {
clientInterceptor = interceptorClass.getConstructor().newInstance();
} catch (final Exception e) {
throw new BeanCreationException("Failed to create interceptor instance", e);
}
}
list.add(clientInterceptor);
}
for (final String interceptorName : annotation.interceptorNames()) {
list.add(this.applicationContext.getBean(interceptorName, ClientInterceptor.class));
}
return list;
} | [
"protected",
"List",
"<",
"ClientInterceptor",
">",
"interceptorsFromAnnotation",
"(",
"final",
"GrpcClient",
"annotation",
")",
"throws",
"BeansException",
"{",
"final",
"List",
"<",
"ClientInterceptor",
">",
"list",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"final",
"Class",
"<",
"?",
"extends",
"ClientInterceptor",
">",
"interceptorClass",
":",
"annotation",
".",
"interceptors",
"(",
")",
")",
"{",
"final",
"ClientInterceptor",
"clientInterceptor",
";",
"if",
"(",
"this",
".",
"applicationContext",
".",
"getBeanNamesForType",
"(",
"ClientInterceptor",
".",
"class",
")",
".",
"length",
">",
"0",
")",
"{",
"clientInterceptor",
"=",
"this",
".",
"applicationContext",
".",
"getBean",
"(",
"interceptorClass",
")",
";",
"}",
"else",
"{",
"try",
"{",
"clientInterceptor",
"=",
"interceptorClass",
".",
"getConstructor",
"(",
")",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"throw",
"new",
"BeanCreationException",
"(",
"\"Failed to create interceptor instance\"",
",",
"e",
")",
";",
"}",
"}",
"list",
".",
"add",
"(",
"clientInterceptor",
")",
";",
"}",
"for",
"(",
"final",
"String",
"interceptorName",
":",
"annotation",
".",
"interceptorNames",
"(",
")",
")",
"{",
"list",
".",
"add",
"(",
"this",
".",
"applicationContext",
".",
"getBean",
"(",
"interceptorName",
",",
"ClientInterceptor",
".",
"class",
")",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Gets or creates the {@link ClientInterceptor}s that are referenced in the given annotation.
<p>
<b>Note:</b> This methods return value does not contain the global client interceptors because they are handled
by the {@link GrpcChannelFactory}.
</p>
@param annotation The annotation to get the interceptors for.
@return A list containing the interceptors for the given annotation.
@throws BeansException If the referenced interceptors weren't found or could not be created. | [
"Gets",
"or",
"creates",
"the",
"{",
"@link",
"ClientInterceptor",
"}",
"s",
"that",
"are",
"referenced",
"in",
"the",
"given",
"annotation",
"."
] | train | https://github.com/yidongnan/grpc-spring-boot-starter/blob/07f8853cfafc9707584f2371aff012e590217b85/grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/inject/GrpcClientBeanPostProcessor.java#L170-L189 |
Waikato/moa | moa/src/main/java/moa/classifiers/lazy/neighboursearch/NearestNeighbourSearch.java | NearestNeighbourSearch.quickSort | public static void quickSort(double[] arrayToSort, double[] linkedArray, int left, int right) {
"""
performs quicksort.
@param arrayToSort the array to sort
@param linkedArray the linked array
@param left the first index of the subset
@param right the last index of the subset
"""
if (left < right) {
int middle = partition(arrayToSort, linkedArray, left, right);
quickSort(arrayToSort, linkedArray, left, middle);
quickSort(arrayToSort, linkedArray, middle + 1, right);
}
} | java | public static void quickSort(double[] arrayToSort, double[] linkedArray, int left, int right) {
if (left < right) {
int middle = partition(arrayToSort, linkedArray, left, right);
quickSort(arrayToSort, linkedArray, left, middle);
quickSort(arrayToSort, linkedArray, middle + 1, right);
}
} | [
"public",
"static",
"void",
"quickSort",
"(",
"double",
"[",
"]",
"arrayToSort",
",",
"double",
"[",
"]",
"linkedArray",
",",
"int",
"left",
",",
"int",
"right",
")",
"{",
"if",
"(",
"left",
"<",
"right",
")",
"{",
"int",
"middle",
"=",
"partition",
"(",
"arrayToSort",
",",
"linkedArray",
",",
"left",
",",
"right",
")",
";",
"quickSort",
"(",
"arrayToSort",
",",
"linkedArray",
",",
"left",
",",
"middle",
")",
";",
"quickSort",
"(",
"arrayToSort",
",",
"linkedArray",
",",
"middle",
"+",
"1",
",",
"right",
")",
";",
"}",
"}"
] | performs quicksort.
@param arrayToSort the array to sort
@param linkedArray the linked array
@param left the first index of the subset
@param right the last index of the subset | [
"performs",
"quicksort",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/NearestNeighbourSearch.java#L734-L740 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/sender/TLSSyslogSenderImpl.java | TLSSyslogSenderImpl.getTLSSocket | private Socket getTLSSocket(InetAddress destination, int port) throws Exception {
"""
Gets the socket tied to the address and port for this transport
@param port Port to check
@return Port to use
"""
String key = destination.getHostAddress() + ":" + port;
synchronized (socketMap){
Socket socket = socketMap.get(key);
if (socket == null){
// create a new one
NodeAuthModuleContext nodeAuthContext = NodeAuthModuleContext.getContext();
socket = nodeAuthContext.getSocketHandler().getSocket(destination.getHostName(), port, true);
// remember it for next time
// TODO: had trouble with this with Steve Moore's online ATNA server so not caching the sockets
// need to worry about synchronization if we try to put this optimization back
// there appears to be one AuditorModuleContext per host/port so may can pool them based on that object?
socketMap.put(key, socket);
}
// whatever happened, now return the socket
return socket;
}
} | java | private Socket getTLSSocket(InetAddress destination, int port) throws Exception
{
String key = destination.getHostAddress() + ":" + port;
synchronized (socketMap){
Socket socket = socketMap.get(key);
if (socket == null){
// create a new one
NodeAuthModuleContext nodeAuthContext = NodeAuthModuleContext.getContext();
socket = nodeAuthContext.getSocketHandler().getSocket(destination.getHostName(), port, true);
// remember it for next time
// TODO: had trouble with this with Steve Moore's online ATNA server so not caching the sockets
// need to worry about synchronization if we try to put this optimization back
// there appears to be one AuditorModuleContext per host/port so may can pool them based on that object?
socketMap.put(key, socket);
}
// whatever happened, now return the socket
return socket;
}
} | [
"private",
"Socket",
"getTLSSocket",
"(",
"InetAddress",
"destination",
",",
"int",
"port",
")",
"throws",
"Exception",
"{",
"String",
"key",
"=",
"destination",
".",
"getHostAddress",
"(",
")",
"+",
"\":\"",
"+",
"port",
";",
"synchronized",
"(",
"socketMap",
")",
"{",
"Socket",
"socket",
"=",
"socketMap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"socket",
"==",
"null",
")",
"{",
"// create a new one",
"NodeAuthModuleContext",
"nodeAuthContext",
"=",
"NodeAuthModuleContext",
".",
"getContext",
"(",
")",
";",
"socket",
"=",
"nodeAuthContext",
".",
"getSocketHandler",
"(",
")",
".",
"getSocket",
"(",
"destination",
".",
"getHostName",
"(",
")",
",",
"port",
",",
"true",
")",
";",
"// remember it for next time",
"// TODO: had trouble with this with Steve Moore's online ATNA server so not caching the sockets",
"// need to worry about synchronization if we try to put this optimization back",
"// there appears to be one AuditorModuleContext per host/port so may can pool them based on that object?",
"socketMap",
".",
"put",
"(",
"key",
",",
"socket",
")",
";",
"}",
"// whatever happened, now return the socket",
"return",
"socket",
";",
"}",
"}"
] | Gets the socket tied to the address and port for this transport
@param port Port to check
@return Port to use | [
"Gets",
"the",
"socket",
"tied",
"to",
"the",
"address",
"and",
"port",
"for",
"this",
"transport"
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/sender/TLSSyslogSenderImpl.java#L171-L189 |
mangstadt/biweekly | src/main/java/biweekly/component/ICalComponent.java | ICalComponent.checkStatus | protected void checkStatus(List<ValidationWarning> warnings, Status... allowed) {
"""
Utility method for validating the {@link Status} property of a component.
@param warnings the list to add the warnings to
@param allowed the valid statuses
"""
Status actual = getProperty(Status.class);
if (actual == null) {
return;
}
List<String> allowedValues = new ArrayList<String>(allowed.length);
for (Status status : allowed) {
String value = status.getValue().toLowerCase();
allowedValues.add(value);
}
String actualValue = actual.getValue().toLowerCase();
if (!allowedValues.contains(actualValue)) {
warnings.add(new ValidationWarning(13, actual.getValue(), allowedValues));
}
} | java | protected void checkStatus(List<ValidationWarning> warnings, Status... allowed) {
Status actual = getProperty(Status.class);
if (actual == null) {
return;
}
List<String> allowedValues = new ArrayList<String>(allowed.length);
for (Status status : allowed) {
String value = status.getValue().toLowerCase();
allowedValues.add(value);
}
String actualValue = actual.getValue().toLowerCase();
if (!allowedValues.contains(actualValue)) {
warnings.add(new ValidationWarning(13, actual.getValue(), allowedValues));
}
} | [
"protected",
"void",
"checkStatus",
"(",
"List",
"<",
"ValidationWarning",
">",
"warnings",
",",
"Status",
"...",
"allowed",
")",
"{",
"Status",
"actual",
"=",
"getProperty",
"(",
"Status",
".",
"class",
")",
";",
"if",
"(",
"actual",
"==",
"null",
")",
"{",
"return",
";",
"}",
"List",
"<",
"String",
">",
"allowedValues",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"allowed",
".",
"length",
")",
";",
"for",
"(",
"Status",
"status",
":",
"allowed",
")",
"{",
"String",
"value",
"=",
"status",
".",
"getValue",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"allowedValues",
".",
"add",
"(",
"value",
")",
";",
"}",
"String",
"actualValue",
"=",
"actual",
".",
"getValue",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"!",
"allowedValues",
".",
"contains",
"(",
"actualValue",
")",
")",
"{",
"warnings",
".",
"add",
"(",
"new",
"ValidationWarning",
"(",
"13",
",",
"actual",
".",
"getValue",
"(",
")",
",",
"allowedValues",
")",
")",
";",
"}",
"}"
] | Utility method for validating the {@link Status} property of a component.
@param warnings the list to add the warnings to
@param allowed the valid statuses | [
"Utility",
"method",
"for",
"validating",
"the",
"{"
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/ICalComponent.java#L550-L566 |
eobermuhlner/big-math | ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigFloatStream.java | BigFloatStream.range | public static Stream<BigFloat> range(BigFloat startInclusive, BigFloat endExclusive, BigFloat step) {
"""
Returns a sequential ordered {@code Stream<BigFloat>} from {@code startInclusive}
(inclusive) to {@code endExclusive} (exclusive) by an incremental {@code step}.
<p>An equivalent sequence of increasing values can be produced
sequentially using a {@code for} loop as follows:
<pre>for (BigFloat i = startInclusive; i.isLessThan(endExclusive); i = i.add(step)) {
...
}</pre>
@param startInclusive the (inclusive) initial value
@param endExclusive the exclusive upper bound
@param step the step between elements
@return a sequential {@code Stream<BigFloat>}
"""
if (step.isZero()) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endExclusive.subtract(startInclusive).signum() != step.signum()) {
return Stream.empty();
}
return StreamSupport.stream(new BigFloatSpliterator(startInclusive, endExclusive, false, step), false);
} | java | public static Stream<BigFloat> range(BigFloat startInclusive, BigFloat endExclusive, BigFloat step) {
if (step.isZero()) {
throw new IllegalArgumentException("invalid step: 0");
}
if (endExclusive.subtract(startInclusive).signum() != step.signum()) {
return Stream.empty();
}
return StreamSupport.stream(new BigFloatSpliterator(startInclusive, endExclusive, false, step), false);
} | [
"public",
"static",
"Stream",
"<",
"BigFloat",
">",
"range",
"(",
"BigFloat",
"startInclusive",
",",
"BigFloat",
"endExclusive",
",",
"BigFloat",
"step",
")",
"{",
"if",
"(",
"step",
".",
"isZero",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"invalid step: 0\"",
")",
";",
"}",
"if",
"(",
"endExclusive",
".",
"subtract",
"(",
"startInclusive",
")",
".",
"signum",
"(",
")",
"!=",
"step",
".",
"signum",
"(",
")",
")",
"{",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"}",
"return",
"StreamSupport",
".",
"stream",
"(",
"new",
"BigFloatSpliterator",
"(",
"startInclusive",
",",
"endExclusive",
",",
"false",
",",
"step",
")",
",",
"false",
")",
";",
"}"
] | Returns a sequential ordered {@code Stream<BigFloat>} from {@code startInclusive}
(inclusive) to {@code endExclusive} (exclusive) by an incremental {@code step}.
<p>An equivalent sequence of increasing values can be produced
sequentially using a {@code for} loop as follows:
<pre>for (BigFloat i = startInclusive; i.isLessThan(endExclusive); i = i.add(step)) {
...
}</pre>
@param startInclusive the (inclusive) initial value
@param endExclusive the exclusive upper bound
@param step the step between elements
@return a sequential {@code Stream<BigFloat>} | [
"Returns",
"a",
"sequential",
"ordered",
"{",
"@code",
"Stream<BigFloat",
">",
"}",
"from",
"{",
"@code",
"startInclusive",
"}",
"(",
"inclusive",
")",
"to",
"{",
"@code",
"endExclusive",
"}",
"(",
"exclusive",
")",
"by",
"an",
"incremental",
"{",
"@code",
"step",
"}",
"."
] | train | https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/stream/BigFloatStream.java#L33-L41 |
patrickfav/Dali | dali/src/main/java/at/favre/lib/dali/util/BuilderUtil.java | BuilderUtil.getIBlurAlgorithm | public static IBlur getIBlurAlgorithm(EBlurAlgorithm algorithm, ContextWrapper contextWrapper) {
"""
Creates an IBlur instance for the given algorithm enum
@param algorithm
@param contextWrapper
@return
"""
RenderScript rs = contextWrapper.getRenderScript();
Context ctx = contextWrapper.getContext();
switch (algorithm) {
case RS_GAUSS_FAST:
return new RenderScriptGaussianBlur(rs);
case RS_BOX_5x5:
return new RenderScriptBox5x5Blur(rs);
case RS_GAUSS_5x5:
return new RenderScriptGaussian5x5Blur(rs);
case RS_STACKBLUR:
return new RenderScriptStackBlur(rs, ctx);
case STACKBLUR:
return new StackBlur();
case GAUSS_FAST:
return new GaussianFastBlur();
case BOX_BLUR:
return new BoxBlur();
default:
return new IgnoreBlur();
}
} | java | public static IBlur getIBlurAlgorithm(EBlurAlgorithm algorithm, ContextWrapper contextWrapper) {
RenderScript rs = contextWrapper.getRenderScript();
Context ctx = contextWrapper.getContext();
switch (algorithm) {
case RS_GAUSS_FAST:
return new RenderScriptGaussianBlur(rs);
case RS_BOX_5x5:
return new RenderScriptBox5x5Blur(rs);
case RS_GAUSS_5x5:
return new RenderScriptGaussian5x5Blur(rs);
case RS_STACKBLUR:
return new RenderScriptStackBlur(rs, ctx);
case STACKBLUR:
return new StackBlur();
case GAUSS_FAST:
return new GaussianFastBlur();
case BOX_BLUR:
return new BoxBlur();
default:
return new IgnoreBlur();
}
} | [
"public",
"static",
"IBlur",
"getIBlurAlgorithm",
"(",
"EBlurAlgorithm",
"algorithm",
",",
"ContextWrapper",
"contextWrapper",
")",
"{",
"RenderScript",
"rs",
"=",
"contextWrapper",
".",
"getRenderScript",
"(",
")",
";",
"Context",
"ctx",
"=",
"contextWrapper",
".",
"getContext",
"(",
")",
";",
"switch",
"(",
"algorithm",
")",
"{",
"case",
"RS_GAUSS_FAST",
":",
"return",
"new",
"RenderScriptGaussianBlur",
"(",
"rs",
")",
";",
"case",
"RS_BOX_5x5",
":",
"return",
"new",
"RenderScriptBox5x5Blur",
"(",
"rs",
")",
";",
"case",
"RS_GAUSS_5x5",
":",
"return",
"new",
"RenderScriptGaussian5x5Blur",
"(",
"rs",
")",
";",
"case",
"RS_STACKBLUR",
":",
"return",
"new",
"RenderScriptStackBlur",
"(",
"rs",
",",
"ctx",
")",
";",
"case",
"STACKBLUR",
":",
"return",
"new",
"StackBlur",
"(",
")",
";",
"case",
"GAUSS_FAST",
":",
"return",
"new",
"GaussianFastBlur",
"(",
")",
";",
"case",
"BOX_BLUR",
":",
"return",
"new",
"BoxBlur",
"(",
")",
";",
"default",
":",
"return",
"new",
"IgnoreBlur",
"(",
")",
";",
"}",
"}"
] | Creates an IBlur instance for the given algorithm enum
@param algorithm
@param contextWrapper
@return | [
"Creates",
"an",
"IBlur",
"instance",
"for",
"the",
"given",
"algorithm",
"enum"
] | train | https://github.com/patrickfav/Dali/blob/4c90a8c174517873844638d4b8349d890453cc17/dali/src/main/java/at/favre/lib/dali/util/BuilderUtil.java#L40-L62 |
netty/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/DelegatingDecompressorFrameListener.java | DelegatingDecompressorFrameListener.newContentDecompressor | protected EmbeddedChannel newContentDecompressor(final ChannelHandlerContext ctx, CharSequence contentEncoding)
throws Http2Exception {
"""
Returns a new {@link EmbeddedChannel} that decodes the HTTP2 message content encoded in the specified
{@code contentEncoding}.
@param contentEncoding the value of the {@code content-encoding} header
@return a new {@link ByteToMessageDecoder} if the specified encoding is supported. {@code null} otherwise
(alternatively, you can throw a {@link Http2Exception} to block unknown encoding).
@throws Http2Exception If the specified encoding is not not supported and warrants an exception
"""
if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) {
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
}
if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) {
final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE;
// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper));
}
// 'identity' or unsupported
return null;
} | java | protected EmbeddedChannel newContentDecompressor(final ChannelHandlerContext ctx, CharSequence contentEncoding)
throws Http2Exception {
if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) {
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
}
if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) {
final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE;
// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper));
}
// 'identity' or unsupported
return null;
} | [
"protected",
"EmbeddedChannel",
"newContentDecompressor",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"CharSequence",
"contentEncoding",
")",
"throws",
"Http2Exception",
"{",
"if",
"(",
"GZIP",
".",
"contentEqualsIgnoreCase",
"(",
"contentEncoding",
")",
"||",
"X_GZIP",
".",
"contentEqualsIgnoreCase",
"(",
"contentEncoding",
")",
")",
"{",
"return",
"new",
"EmbeddedChannel",
"(",
"ctx",
".",
"channel",
"(",
")",
".",
"id",
"(",
")",
",",
"ctx",
".",
"channel",
"(",
")",
".",
"metadata",
"(",
")",
".",
"hasDisconnect",
"(",
")",
",",
"ctx",
".",
"channel",
"(",
")",
".",
"config",
"(",
")",
",",
"ZlibCodecFactory",
".",
"newZlibDecoder",
"(",
"ZlibWrapper",
".",
"GZIP",
")",
")",
";",
"}",
"if",
"(",
"DEFLATE",
".",
"contentEqualsIgnoreCase",
"(",
"contentEncoding",
")",
"||",
"X_DEFLATE",
".",
"contentEqualsIgnoreCase",
"(",
"contentEncoding",
")",
")",
"{",
"final",
"ZlibWrapper",
"wrapper",
"=",
"strict",
"?",
"ZlibWrapper",
".",
"ZLIB",
":",
"ZlibWrapper",
".",
"ZLIB_OR_NONE",
";",
"// To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.",
"return",
"new",
"EmbeddedChannel",
"(",
"ctx",
".",
"channel",
"(",
")",
".",
"id",
"(",
")",
",",
"ctx",
".",
"channel",
"(",
")",
".",
"metadata",
"(",
")",
".",
"hasDisconnect",
"(",
")",
",",
"ctx",
".",
"channel",
"(",
")",
".",
"config",
"(",
")",
",",
"ZlibCodecFactory",
".",
"newZlibDecoder",
"(",
"wrapper",
")",
")",
";",
"}",
"// 'identity' or unsupported",
"return",
"null",
";",
"}"
] | Returns a new {@link EmbeddedChannel} that decodes the HTTP2 message content encoded in the specified
{@code contentEncoding}.
@param contentEncoding the value of the {@code content-encoding} header
@return a new {@link ByteToMessageDecoder} if the specified encoding is supported. {@code null} otherwise
(alternatively, you can throw a {@link Http2Exception} to block unknown encoding).
@throws Http2Exception If the specified encoding is not not supported and warrants an exception | [
"Returns",
"a",
"new",
"{",
"@link",
"EmbeddedChannel",
"}",
"that",
"decodes",
"the",
"HTTP2",
"message",
"content",
"encoded",
"in",
"the",
"specified",
"{",
"@code",
"contentEncoding",
"}",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/DelegatingDecompressorFrameListener.java#L166-L180 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/ModeUtils.java | ModeUtils.applyFileUMask | public static Mode applyFileUMask(Mode mode, String authUmask) {
"""
Applies the default umask for newly created files to this mode.
@param mode the mode to update
@param authUmask the umask to apply on the file
@return the updated object
"""
mode = applyUMask(mode, getUMask(authUmask));
mode = applyUMask(mode, FILE_UMASK);
return mode;
} | java | public static Mode applyFileUMask(Mode mode, String authUmask) {
mode = applyUMask(mode, getUMask(authUmask));
mode = applyUMask(mode, FILE_UMASK);
return mode;
} | [
"public",
"static",
"Mode",
"applyFileUMask",
"(",
"Mode",
"mode",
",",
"String",
"authUmask",
")",
"{",
"mode",
"=",
"applyUMask",
"(",
"mode",
",",
"getUMask",
"(",
"authUmask",
")",
")",
";",
"mode",
"=",
"applyUMask",
"(",
"mode",
",",
"FILE_UMASK",
")",
";",
"return",
"mode",
";",
"}"
] | Applies the default umask for newly created files to this mode.
@param mode the mode to update
@param authUmask the umask to apply on the file
@return the updated object | [
"Applies",
"the",
"default",
"umask",
"for",
"newly",
"created",
"files",
"to",
"this",
"mode",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/ModeUtils.java#L39-L43 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/guid/Guid.java | Guid.append | public Guid append(HasGuid... objs) throws IOException {
"""
Creates a new {@link Guid} which is a unique, replicable representation of the pair (this, objs).
@param objs an array of {@link HasGuid}.
@return a new {@link Guid}.
@throws IOException
"""
if (objs == null || objs.length == 0) {
return this;
}
return fromHasGuid(ArrayUtils.add(objs, new SimpleHasGuid(this)));
} | java | public Guid append(HasGuid... objs) throws IOException {
if (objs == null || objs.length == 0) {
return this;
}
return fromHasGuid(ArrayUtils.add(objs, new SimpleHasGuid(this)));
} | [
"public",
"Guid",
"append",
"(",
"HasGuid",
"...",
"objs",
")",
"throws",
"IOException",
"{",
"if",
"(",
"objs",
"==",
"null",
"||",
"objs",
".",
"length",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"return",
"fromHasGuid",
"(",
"ArrayUtils",
".",
"add",
"(",
"objs",
",",
"new",
"SimpleHasGuid",
"(",
"this",
")",
")",
")",
";",
"}"
] | Creates a new {@link Guid} which is a unique, replicable representation of the pair (this, objs).
@param objs an array of {@link HasGuid}.
@return a new {@link Guid}.
@throws IOException | [
"Creates",
"a",
"new",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/guid/Guid.java#L175-L180 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getFirstToken | @Nullable
public static String getFirstToken (@Nullable final String sStr, final char cSearch) {
"""
Get the first token up to (and excluding) the separating character.
@param sStr
The string to search. May be <code>null</code>.
@param cSearch
The search character.
@return The passed string if no such separator token was found.
"""
final int nIndex = getIndexOf (sStr, cSearch);
return nIndex == StringHelper.STRING_NOT_FOUND ? sStr : sStr.substring (0, nIndex);
} | java | @Nullable
public static String getFirstToken (@Nullable final String sStr, final char cSearch)
{
final int nIndex = getIndexOf (sStr, cSearch);
return nIndex == StringHelper.STRING_NOT_FOUND ? sStr : sStr.substring (0, nIndex);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getFirstToken",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"final",
"char",
"cSearch",
")",
"{",
"final",
"int",
"nIndex",
"=",
"getIndexOf",
"(",
"sStr",
",",
"cSearch",
")",
";",
"return",
"nIndex",
"==",
"StringHelper",
".",
"STRING_NOT_FOUND",
"?",
"sStr",
":",
"sStr",
".",
"substring",
"(",
"0",
",",
"nIndex",
")",
";",
"}"
] | Get the first token up to (and excluding) the separating character.
@param sStr
The string to search. May be <code>null</code>.
@param cSearch
The search character.
@return The passed string if no such separator token was found. | [
"Get",
"the",
"first",
"token",
"up",
"to",
"(",
"and",
"excluding",
")",
"the",
"separating",
"character",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L5104-L5109 |
EsotericSoftware/yamlbeans | src/com/esotericsoftware/yamlbeans/YamlConfig.java | YamlConfig.setPropertyElementType | public void setPropertyElementType (Class type, String propertyName, Class elementType) {
"""
Sets the default type of elements in a Collection or Map property. No tag will be output for elements of this type. This
type will be used for each element if no tag is found.
"""
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (elementType == null) throw new IllegalArgumentException("propertyType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
if (!Collection.class.isAssignableFrom(property.getType()) && !Map.class.isAssignableFrom(property.getType())) {
throw new IllegalArgumentException("The '" + propertyName + "' property on the " + type.getName()
+ " class must be a Collection or Map: " + property.getType());
}
propertyToElementType.put(property, elementType);
} | java | public void setPropertyElementType (Class type, String propertyName, Class elementType) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null.");
if (elementType == null) throw new IllegalArgumentException("propertyType cannot be null.");
Property property = Beans.getProperty(type, propertyName, beanProperties, privateFields, this);
if (property == null)
throw new IllegalArgumentException("The class " + type.getName() + " does not have a property named: " + propertyName);
if (!Collection.class.isAssignableFrom(property.getType()) && !Map.class.isAssignableFrom(property.getType())) {
throw new IllegalArgumentException("The '" + propertyName + "' property on the " + type.getName()
+ " class must be a Collection or Map: " + property.getType());
}
propertyToElementType.put(property, elementType);
} | [
"public",
"void",
"setPropertyElementType",
"(",
"Class",
"type",
",",
"String",
"propertyName",
",",
"Class",
"elementType",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"type cannot be null.\"",
")",
";",
"if",
"(",
"propertyName",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"propertyName cannot be null.\"",
")",
";",
"if",
"(",
"elementType",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"propertyType cannot be null.\"",
")",
";",
"Property",
"property",
"=",
"Beans",
".",
"getProperty",
"(",
"type",
",",
"propertyName",
",",
"beanProperties",
",",
"privateFields",
",",
"this",
")",
";",
"if",
"(",
"property",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The class \"",
"+",
"type",
".",
"getName",
"(",
")",
"+",
"\" does not have a property named: \"",
"+",
"propertyName",
")",
";",
"if",
"(",
"!",
"Collection",
".",
"class",
".",
"isAssignableFrom",
"(",
"property",
".",
"getType",
"(",
")",
")",
"&&",
"!",
"Map",
".",
"class",
".",
"isAssignableFrom",
"(",
"property",
".",
"getType",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The '\"",
"+",
"propertyName",
"+",
"\"' property on the \"",
"+",
"type",
".",
"getName",
"(",
")",
"+",
"\" class must be a Collection or Map: \"",
"+",
"property",
".",
"getType",
"(",
")",
")",
";",
"}",
"propertyToElementType",
".",
"put",
"(",
"property",
",",
"elementType",
")",
";",
"}"
] | Sets the default type of elements in a Collection or Map property. No tag will be output for elements of this type. This
type will be used for each element if no tag is found. | [
"Sets",
"the",
"default",
"type",
"of",
"elements",
"in",
"a",
"Collection",
"or",
"Map",
"property",
".",
"No",
"tag",
"will",
"be",
"output",
"for",
"elements",
"of",
"this",
"type",
".",
"This",
"type",
"will",
"be",
"used",
"for",
"each",
"element",
"if",
"no",
"tag",
"is",
"found",
"."
] | train | https://github.com/EsotericSoftware/yamlbeans/blob/f5610997edbc5534fc7e9f0a91654d14742345ca/src/com/esotericsoftware/yamlbeans/YamlConfig.java#L85-L97 |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java | CqlBlockedDataReaderDAO.rowQuery | private Iterator<Record> rowQuery(final List<Map.Entry<ByteBuffer, Key>> rowKeys, final ReadConsistency consistency,
final DeltaPlacement placement) {
"""
Returns an iterator for the Records keyed by the provided row keys. An empty record is returned for any
key which does not have a corresponding row in C*.
"""
List<ByteBuffer> keys = Lists.newArrayListWithCapacity(rowKeys.size());
final Map<ByteBuffer, Key> rawKeyMap = Maps.newHashMap();
for (Map.Entry<ByteBuffer, Key> entry : rowKeys) {
keys.add(entry.getKey());
rawKeyMap.put(entry.getKey(), entry.getValue());
}
BlockedDeltaTableDDL tableDDL = placement.getBlockedDeltaTableDDL();
Statement statement = selectDeltaFrom(tableDDL)
.where(in(tableDDL.getRowKeyColumnName(), keys))
.setConsistencyLevel(SorConsistencies.toCql(consistency));
Iterator<Iterable<Row>> rowGroups = deltaQueryAsync(placement, statement, false, "Failed to read records %s", rawKeyMap.values());
return Iterators.concat(
// First iterator reads the row groups found and transforms them to Records
Iterators.transform(rowGroups, rows -> {
ByteBuffer keyBytes = getRawKeyFromRowGroup(rows);
Key key = rawKeyMap.remove(keyBytes);
assert key != null : "Query returned row with a key out of bound";
return newRecordFromCql(key, rows, placement, ByteBufferUtil.bytesToHex(keyBytes));
}),
// Second iterator returns an empty Record for each key queried but not found.
new AbstractIterator<Record>() {
private Iterator<Key> _nonExistentKeyIterator;
@Override
protected Record computeNext() {
// Lazily return an empty record for each key not found in the previous iterator.
// rawKeyMap.iterator() must not be called until the first iterator is completely spent.
if (_nonExistentKeyIterator == null) {
_nonExistentKeyIterator = rawKeyMap.values().iterator();
}
return _nonExistentKeyIterator.hasNext() ?
emptyRecord(_nonExistentKeyIterator.next()) :
endOfData();
}
});
} | java | private Iterator<Record> rowQuery(final List<Map.Entry<ByteBuffer, Key>> rowKeys, final ReadConsistency consistency,
final DeltaPlacement placement) {
List<ByteBuffer> keys = Lists.newArrayListWithCapacity(rowKeys.size());
final Map<ByteBuffer, Key> rawKeyMap = Maps.newHashMap();
for (Map.Entry<ByteBuffer, Key> entry : rowKeys) {
keys.add(entry.getKey());
rawKeyMap.put(entry.getKey(), entry.getValue());
}
BlockedDeltaTableDDL tableDDL = placement.getBlockedDeltaTableDDL();
Statement statement = selectDeltaFrom(tableDDL)
.where(in(tableDDL.getRowKeyColumnName(), keys))
.setConsistencyLevel(SorConsistencies.toCql(consistency));
Iterator<Iterable<Row>> rowGroups = deltaQueryAsync(placement, statement, false, "Failed to read records %s", rawKeyMap.values());
return Iterators.concat(
// First iterator reads the row groups found and transforms them to Records
Iterators.transform(rowGroups, rows -> {
ByteBuffer keyBytes = getRawKeyFromRowGroup(rows);
Key key = rawKeyMap.remove(keyBytes);
assert key != null : "Query returned row with a key out of bound";
return newRecordFromCql(key, rows, placement, ByteBufferUtil.bytesToHex(keyBytes));
}),
// Second iterator returns an empty Record for each key queried but not found.
new AbstractIterator<Record>() {
private Iterator<Key> _nonExistentKeyIterator;
@Override
protected Record computeNext() {
// Lazily return an empty record for each key not found in the previous iterator.
// rawKeyMap.iterator() must not be called until the first iterator is completely spent.
if (_nonExistentKeyIterator == null) {
_nonExistentKeyIterator = rawKeyMap.values().iterator();
}
return _nonExistentKeyIterator.hasNext() ?
emptyRecord(_nonExistentKeyIterator.next()) :
endOfData();
}
});
} | [
"private",
"Iterator",
"<",
"Record",
">",
"rowQuery",
"(",
"final",
"List",
"<",
"Map",
".",
"Entry",
"<",
"ByteBuffer",
",",
"Key",
">",
">",
"rowKeys",
",",
"final",
"ReadConsistency",
"consistency",
",",
"final",
"DeltaPlacement",
"placement",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"keys",
"=",
"Lists",
".",
"newArrayListWithCapacity",
"(",
"rowKeys",
".",
"size",
"(",
")",
")",
";",
"final",
"Map",
"<",
"ByteBuffer",
",",
"Key",
">",
"rawKeyMap",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"ByteBuffer",
",",
"Key",
">",
"entry",
":",
"rowKeys",
")",
"{",
"keys",
".",
"add",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"rawKeyMap",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"BlockedDeltaTableDDL",
"tableDDL",
"=",
"placement",
".",
"getBlockedDeltaTableDDL",
"(",
")",
";",
"Statement",
"statement",
"=",
"selectDeltaFrom",
"(",
"tableDDL",
")",
".",
"where",
"(",
"in",
"(",
"tableDDL",
".",
"getRowKeyColumnName",
"(",
")",
",",
"keys",
")",
")",
".",
"setConsistencyLevel",
"(",
"SorConsistencies",
".",
"toCql",
"(",
"consistency",
")",
")",
";",
"Iterator",
"<",
"Iterable",
"<",
"Row",
">",
">",
"rowGroups",
"=",
"deltaQueryAsync",
"(",
"placement",
",",
"statement",
",",
"false",
",",
"\"Failed to read records %s\"",
",",
"rawKeyMap",
".",
"values",
"(",
")",
")",
";",
"return",
"Iterators",
".",
"concat",
"(",
"// First iterator reads the row groups found and transforms them to Records",
"Iterators",
".",
"transform",
"(",
"rowGroups",
",",
"rows",
"->",
"{",
"ByteBuffer",
"keyBytes",
"=",
"getRawKeyFromRowGroup",
"(",
"rows",
")",
";",
"Key",
"key",
"=",
"rawKeyMap",
".",
"remove",
"(",
"keyBytes",
")",
";",
"assert",
"key",
"!=",
"null",
":",
"\"Query returned row with a key out of bound\"",
";",
"return",
"newRecordFromCql",
"(",
"key",
",",
"rows",
",",
"placement",
",",
"ByteBufferUtil",
".",
"bytesToHex",
"(",
"keyBytes",
")",
")",
";",
"}",
")",
",",
"// Second iterator returns an empty Record for each key queried but not found.",
"new",
"AbstractIterator",
"<",
"Record",
">",
"(",
")",
"{",
"private",
"Iterator",
"<",
"Key",
">",
"_nonExistentKeyIterator",
";",
"@",
"Override",
"protected",
"Record",
"computeNext",
"(",
")",
"{",
"// Lazily return an empty record for each key not found in the previous iterator.",
"// rawKeyMap.iterator() must not be called until the first iterator is completely spent.",
"if",
"(",
"_nonExistentKeyIterator",
"==",
"null",
")",
"{",
"_nonExistentKeyIterator",
"=",
"rawKeyMap",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
";",
"}",
"return",
"_nonExistentKeyIterator",
".",
"hasNext",
"(",
")",
"?",
"emptyRecord",
"(",
"_nonExistentKeyIterator",
".",
"next",
"(",
")",
")",
":",
"endOfData",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Returns an iterator for the Records keyed by the provided row keys. An empty record is returned for any
key which does not have a corresponding row in C*. | [
"Returns",
"an",
"iterator",
"for",
"the",
"Records",
"keyed",
"by",
"the",
"provided",
"row",
"keys",
".",
"An",
"empty",
"record",
"is",
"returned",
"for",
"any",
"key",
"which",
"does",
"not",
"have",
"a",
"corresponding",
"row",
"in",
"C",
"*",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java#L337-L378 |
Azure/azure-sdk-for-java | containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ContainerServicesInner.java | ContainerServicesInner.createOrUpdateAsync | public Observable<ContainerServiceInner> createOrUpdateAsync(String resourceGroupName, String containerServiceName, ContainerServiceInner parameters) {
"""
Creates or updates a container service.
Creates or updates a container service with the specified configuration of orchestrator, masters, and agents.
@param resourceGroupName The name of the resource group.
@param containerServiceName The name of the container service in the specified subscription and resource group.
@param parameters Parameters supplied to the Create or Update a Container Service operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, containerServiceName, parameters).map(new Func1<ServiceResponse<ContainerServiceInner>, ContainerServiceInner>() {
@Override
public ContainerServiceInner call(ServiceResponse<ContainerServiceInner> response) {
return response.body();
}
});
} | java | public Observable<ContainerServiceInner> createOrUpdateAsync(String resourceGroupName, String containerServiceName, ContainerServiceInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, containerServiceName, parameters).map(new Func1<ServiceResponse<ContainerServiceInner>, ContainerServiceInner>() {
@Override
public ContainerServiceInner call(ServiceResponse<ContainerServiceInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ContainerServiceInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"containerServiceName",
",",
"ContainerServiceInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"containerServiceName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ContainerServiceInner",
">",
",",
"ContainerServiceInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ContainerServiceInner",
"call",
"(",
"ServiceResponse",
"<",
"ContainerServiceInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates or updates a container service.
Creates or updates a container service with the specified configuration of orchestrator, masters, and agents.
@param resourceGroupName The name of the resource group.
@param containerServiceName The name of the container service in the specified subscription and resource group.
@param parameters Parameters supplied to the Create or Update a Container Service operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"a",
"container",
"service",
".",
"Creates",
"or",
"updates",
"a",
"container",
"service",
"with",
"the",
"specified",
"configuration",
"of",
"orchestrator",
"masters",
"and",
"agents",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/ContainerServicesInner.java#L260-L267 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/SpringServlet.java | SpringServlet.failStartup | protected void failStartup(String message, Throwable th)
throws ServletException {
"""
Prints a "FEDORA STARTUP ERROR" to STDERR along with the stacktrace of
the Throwable (if given) and finally, throws a ServletException.
"""
System.err.println("\n**************************");
System.err.println("** FEDORA STARTUP ERROR **");
System.err.println("**************************\n");
System.err.println(message);
if (th == null) {
System.err.println();
throw new ServletException(message);
} else {
th.printStackTrace();
System.err.println();
throw new ServletException(message, th);
}
} | java | protected void failStartup(String message, Throwable th)
throws ServletException {
System.err.println("\n**************************");
System.err.println("** FEDORA STARTUP ERROR **");
System.err.println("**************************\n");
System.err.println(message);
if (th == null) {
System.err.println();
throw new ServletException(message);
} else {
th.printStackTrace();
System.err.println();
throw new ServletException(message, th);
}
} | [
"protected",
"void",
"failStartup",
"(",
"String",
"message",
",",
"Throwable",
"th",
")",
"throws",
"ServletException",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"\\n**************************\"",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"** FEDORA STARTUP ERROR **\"",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"**************************\\n\"",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"message",
")",
";",
"if",
"(",
"th",
"==",
"null",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
")",
";",
"throw",
"new",
"ServletException",
"(",
"message",
")",
";",
"}",
"else",
"{",
"th",
".",
"printStackTrace",
"(",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
")",
";",
"throw",
"new",
"ServletException",
"(",
"message",
",",
"th",
")",
";",
"}",
"}"
] | Prints a "FEDORA STARTUP ERROR" to STDERR along with the stacktrace of
the Throwable (if given) and finally, throws a ServletException. | [
"Prints",
"a",
"FEDORA",
"STARTUP",
"ERROR",
"to",
"STDERR",
"along",
"with",
"the",
"stacktrace",
"of",
"the",
"Throwable",
"(",
"if",
"given",
")",
"and",
"finally",
"throws",
"a",
"ServletException",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/SpringServlet.java#L30-L44 |
Azure/azure-sdk-for-java | signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java | SignalRsInner.beginUpdate | public SignalRResourceInner beginUpdate(String resourceGroupName, String resourceName) {
"""
Operation to update an exiting SignalR service.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param resourceName The name of the SignalR resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SignalRResourceInner object if successful.
"""
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | java | public SignalRResourceInner beginUpdate(String resourceGroupName, String resourceName) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | [
"public",
"SignalRResourceInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Operation to update an exiting SignalR service.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param resourceName The name of the SignalR resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the SignalRResourceInner object if successful. | [
"Operation",
"to",
"update",
"an",
"exiting",
"SignalR",
"service",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L1581-L1583 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java | DocTreeMaker.newDocCommentTree | @Override @DefinedBy(Api.COMPILER_TREE)
public DCDocComment newDocCommentTree(List<? extends DocTree> fullBody, List<? extends DocTree> tags) {
"""
/*
Primarily to produce a DocCommenTree when given a
first sentence and a body, this is useful, in cases
where the trees are being synthesized by a tool.
"""
ListBuffer<DCTree> lb = new ListBuffer<>();
lb.addAll(cast(fullBody));
List<DCTree> fBody = lb.toList();
// A dummy comment to keep the diagnostics logic happy.
Comment c = new Comment() {
@Override
public String getText() {
return null;
}
@Override
public int getSourcePos(int index) {
return Position.NOPOS;
}
@Override
public CommentStyle getStyle() {
return CommentStyle.JAVADOC;
}
@Override
public boolean isDeprecated() {
return false;
}
};
Pair<List<DCTree>, List<DCTree>> pair = splitBody(fullBody);
DCDocComment tree = new DCDocComment(c, fBody, pair.fst, pair.snd, cast(tags));
return tree;
} | java | @Override @DefinedBy(Api.COMPILER_TREE)
public DCDocComment newDocCommentTree(List<? extends DocTree> fullBody, List<? extends DocTree> tags) {
ListBuffer<DCTree> lb = new ListBuffer<>();
lb.addAll(cast(fullBody));
List<DCTree> fBody = lb.toList();
// A dummy comment to keep the diagnostics logic happy.
Comment c = new Comment() {
@Override
public String getText() {
return null;
}
@Override
public int getSourcePos(int index) {
return Position.NOPOS;
}
@Override
public CommentStyle getStyle() {
return CommentStyle.JAVADOC;
}
@Override
public boolean isDeprecated() {
return false;
}
};
Pair<List<DCTree>, List<DCTree>> pair = splitBody(fullBody);
DCDocComment tree = new DCDocComment(c, fBody, pair.fst, pair.snd, cast(tags));
return tree;
} | [
"@",
"Override",
"@",
"DefinedBy",
"(",
"Api",
".",
"COMPILER_TREE",
")",
"public",
"DCDocComment",
"newDocCommentTree",
"(",
"List",
"<",
"?",
"extends",
"DocTree",
">",
"fullBody",
",",
"List",
"<",
"?",
"extends",
"DocTree",
">",
"tags",
")",
"{",
"ListBuffer",
"<",
"DCTree",
">",
"lb",
"=",
"new",
"ListBuffer",
"<>",
"(",
")",
";",
"lb",
".",
"addAll",
"(",
"cast",
"(",
"fullBody",
")",
")",
";",
"List",
"<",
"DCTree",
">",
"fBody",
"=",
"lb",
".",
"toList",
"(",
")",
";",
"// A dummy comment to keep the diagnostics logic happy.",
"Comment",
"c",
"=",
"new",
"Comment",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"getText",
"(",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"int",
"getSourcePos",
"(",
"int",
"index",
")",
"{",
"return",
"Position",
".",
"NOPOS",
";",
"}",
"@",
"Override",
"public",
"CommentStyle",
"getStyle",
"(",
")",
"{",
"return",
"CommentStyle",
".",
"JAVADOC",
";",
"}",
"@",
"Override",
"public",
"boolean",
"isDeprecated",
"(",
")",
"{",
"return",
"false",
";",
"}",
"}",
";",
"Pair",
"<",
"List",
"<",
"DCTree",
">",
",",
"List",
"<",
"DCTree",
">",
">",
"pair",
"=",
"splitBody",
"(",
"fullBody",
")",
";",
"DCDocComment",
"tree",
"=",
"new",
"DCDocComment",
"(",
"c",
",",
"fBody",
",",
"pair",
".",
"fst",
",",
"pair",
".",
"snd",
",",
"cast",
"(",
"tags",
")",
")",
";",
"return",
"tree",
";",
"}"
] | /*
Primarily to produce a DocCommenTree when given a
first sentence and a body, this is useful, in cases
where the trees are being synthesized by a tool. | [
"/",
"*",
"Primarily",
"to",
"produce",
"a",
"DocCommenTree",
"when",
"given",
"a",
"first",
"sentence",
"and",
"a",
"body",
"this",
"is",
"useful",
"in",
"cases",
"where",
"the",
"trees",
"are",
"being",
"synthesized",
"by",
"a",
"tool",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/DocTreeMaker.java#L209-L240 |
grpc/grpc-java | examples/src/main/java/io/grpc/examples/routeguide/RouteGuideClient.java | RouteGuideClient.getFeature | public void getFeature(int lat, int lon) {
"""
Blocking unary call example. Calls getFeature and prints the response.
"""
info("*** GetFeature: lat={0} lon={1}", lat, lon);
Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build();
Feature feature;
try {
feature = blockingStub.getFeature(request);
if (testHelper != null) {
testHelper.onMessage(feature);
}
} catch (StatusRuntimeException e) {
warning("RPC failed: {0}", e.getStatus());
if (testHelper != null) {
testHelper.onRpcError(e);
}
return;
}
if (RouteGuideUtil.exists(feature)) {
info("Found feature called \"{0}\" at {1}, {2}",
feature.getName(),
RouteGuideUtil.getLatitude(feature.getLocation()),
RouteGuideUtil.getLongitude(feature.getLocation()));
} else {
info("Found no feature at {0}, {1}",
RouteGuideUtil.getLatitude(feature.getLocation()),
RouteGuideUtil.getLongitude(feature.getLocation()));
}
} | java | public void getFeature(int lat, int lon) {
info("*** GetFeature: lat={0} lon={1}", lat, lon);
Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build();
Feature feature;
try {
feature = blockingStub.getFeature(request);
if (testHelper != null) {
testHelper.onMessage(feature);
}
} catch (StatusRuntimeException e) {
warning("RPC failed: {0}", e.getStatus());
if (testHelper != null) {
testHelper.onRpcError(e);
}
return;
}
if (RouteGuideUtil.exists(feature)) {
info("Found feature called \"{0}\" at {1}, {2}",
feature.getName(),
RouteGuideUtil.getLatitude(feature.getLocation()),
RouteGuideUtil.getLongitude(feature.getLocation()));
} else {
info("Found no feature at {0}, {1}",
RouteGuideUtil.getLatitude(feature.getLocation()),
RouteGuideUtil.getLongitude(feature.getLocation()));
}
} | [
"public",
"void",
"getFeature",
"(",
"int",
"lat",
",",
"int",
"lon",
")",
"{",
"info",
"(",
"\"*** GetFeature: lat={0} lon={1}\"",
",",
"lat",
",",
"lon",
")",
";",
"Point",
"request",
"=",
"Point",
".",
"newBuilder",
"(",
")",
".",
"setLatitude",
"(",
"lat",
")",
".",
"setLongitude",
"(",
"lon",
")",
".",
"build",
"(",
")",
";",
"Feature",
"feature",
";",
"try",
"{",
"feature",
"=",
"blockingStub",
".",
"getFeature",
"(",
"request",
")",
";",
"if",
"(",
"testHelper",
"!=",
"null",
")",
"{",
"testHelper",
".",
"onMessage",
"(",
"feature",
")",
";",
"}",
"}",
"catch",
"(",
"StatusRuntimeException",
"e",
")",
"{",
"warning",
"(",
"\"RPC failed: {0}\"",
",",
"e",
".",
"getStatus",
"(",
")",
")",
";",
"if",
"(",
"testHelper",
"!=",
"null",
")",
"{",
"testHelper",
".",
"onRpcError",
"(",
"e",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"RouteGuideUtil",
".",
"exists",
"(",
"feature",
")",
")",
"{",
"info",
"(",
"\"Found feature called \\\"{0}\\\" at {1}, {2}\"",
",",
"feature",
".",
"getName",
"(",
")",
",",
"RouteGuideUtil",
".",
"getLatitude",
"(",
"feature",
".",
"getLocation",
"(",
")",
")",
",",
"RouteGuideUtil",
".",
"getLongitude",
"(",
"feature",
".",
"getLocation",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"info",
"(",
"\"Found no feature at {0}, {1}\"",
",",
"RouteGuideUtil",
".",
"getLatitude",
"(",
"feature",
".",
"getLocation",
"(",
")",
")",
",",
"RouteGuideUtil",
".",
"getLongitude",
"(",
"feature",
".",
"getLocation",
"(",
")",
")",
")",
";",
"}",
"}"
] | Blocking unary call example. Calls getFeature and prints the response. | [
"Blocking",
"unary",
"call",
"example",
".",
"Calls",
"getFeature",
"and",
"prints",
"the",
"response",
"."
] | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/examples/src/main/java/io/grpc/examples/routeguide/RouteGuideClient.java#L69-L97 |
code4everything/util | src/main/java/com/zhazhapan/util/NetUtils.java | NetUtils.removeCookie | public static boolean removeCookie(Cookie cookie, HttpServletResponse response) {
"""
删除指定Cookie
@param cookie {@link Cookie}
@param response {@link HttpServletResponse}
@return {@link Boolean}
@since 1.0.8
"""
if (Checker.isNotNull(cookie)) {
cookie.setMaxAge(0);
return addCookie(cookie, response);
}
return false;
} | java | public static boolean removeCookie(Cookie cookie, HttpServletResponse response) {
if (Checker.isNotNull(cookie)) {
cookie.setMaxAge(0);
return addCookie(cookie, response);
}
return false;
} | [
"public",
"static",
"boolean",
"removeCookie",
"(",
"Cookie",
"cookie",
",",
"HttpServletResponse",
"response",
")",
"{",
"if",
"(",
"Checker",
".",
"isNotNull",
"(",
"cookie",
")",
")",
"{",
"cookie",
".",
"setMaxAge",
"(",
"0",
")",
";",
"return",
"addCookie",
"(",
"cookie",
",",
"response",
")",
";",
"}",
"return",
"false",
";",
"}"
] | 删除指定Cookie
@param cookie {@link Cookie}
@param response {@link HttpServletResponse}
@return {@link Boolean}
@since 1.0.8 | [
"删除指定Cookie"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/NetUtils.java#L554-L560 |
jMetal/jMetal | jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/NonUniformMutation.java | NonUniformMutation.doMutation | public void doMutation(double probability, DoubleSolution solution) {
"""
Perform the mutation operation
@param probability Mutation setProbability
@param solution The solution to mutate
"""
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
if (randomGenenerator.getRandomValue() < probability) {
double rand = randomGenenerator.getRandomValue();
double tmp;
if (rand <= 0.5) {
tmp = delta(solution.getUpperBound(i) - solution.getVariableValue(i),
perturbation);
tmp += solution.getVariableValue(i);
} else {
tmp = delta(solution.getLowerBound(i) - solution.getVariableValue(i),
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;
if (rand <= 0.5) {
tmp = delta(solution.getUpperBound(i) - solution.getVariableValue(i),
perturbation);
tmp += solution.getVariableValue(i);
} else {
tmp = delta(solution.getLowerBound(i) - solution.getVariableValue(i),
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",
"(",
"randomGenenerator",
".",
"getRandomValue",
"(",
")",
"<",
"probability",
")",
"{",
"double",
"rand",
"=",
"randomGenenerator",
".",
"getRandomValue",
"(",
")",
";",
"double",
"tmp",
";",
"if",
"(",
"rand",
"<=",
"0.5",
")",
"{",
"tmp",
"=",
"delta",
"(",
"solution",
".",
"getUpperBound",
"(",
"i",
")",
"-",
"solution",
".",
"getVariableValue",
"(",
"i",
")",
",",
"perturbation",
")",
";",
"tmp",
"+=",
"solution",
".",
"getVariableValue",
"(",
"i",
")",
";",
"}",
"else",
"{",
"tmp",
"=",
"delta",
"(",
"solution",
".",
"getLowerBound",
"(",
"i",
")",
"-",
"solution",
".",
"getVariableValue",
"(",
"i",
")",
",",
"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",
")",
";",
"}",
"}",
"}"
] | Perform the mutation operation
@param probability Mutation setProbability
@param solution The solution to mutate | [
"Perform",
"the",
"mutation",
"operation"
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/NonUniformMutation.java#L94-L118 |
uber/NullAway | nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java | NullabilityUtil.getFunctionalInterfaceMethod | public static Symbol.MethodSymbol getFunctionalInterfaceMethod(ExpressionTree tree, Types types) {
"""
finds the corresponding functional interface method for a lambda expression or method reference
@param tree the lambda expression or method reference
@return the functional interface method
"""
Preconditions.checkArgument(
(tree instanceof LambdaExpressionTree) || (tree instanceof MemberReferenceTree));
Type funcInterfaceType = ((JCTree.JCFunctionalExpression) tree).type;
return (Symbol.MethodSymbol) types.findDescriptorSymbol(funcInterfaceType.tsym);
} | java | public static Symbol.MethodSymbol getFunctionalInterfaceMethod(ExpressionTree tree, Types types) {
Preconditions.checkArgument(
(tree instanceof LambdaExpressionTree) || (tree instanceof MemberReferenceTree));
Type funcInterfaceType = ((JCTree.JCFunctionalExpression) tree).type;
return (Symbol.MethodSymbol) types.findDescriptorSymbol(funcInterfaceType.tsym);
} | [
"public",
"static",
"Symbol",
".",
"MethodSymbol",
"getFunctionalInterfaceMethod",
"(",
"ExpressionTree",
"tree",
",",
"Types",
"types",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"(",
"tree",
"instanceof",
"LambdaExpressionTree",
")",
"||",
"(",
"tree",
"instanceof",
"MemberReferenceTree",
")",
")",
";",
"Type",
"funcInterfaceType",
"=",
"(",
"(",
"JCTree",
".",
"JCFunctionalExpression",
")",
"tree",
")",
".",
"type",
";",
"return",
"(",
"Symbol",
".",
"MethodSymbol",
")",
"types",
".",
"findDescriptorSymbol",
"(",
"funcInterfaceType",
".",
"tsym",
")",
";",
"}"
] | finds the corresponding functional interface method for a lambda expression or method reference
@param tree the lambda expression or method reference
@return the functional interface method | [
"finds",
"the",
"corresponding",
"functional",
"interface",
"method",
"for",
"a",
"lambda",
"expression",
"or",
"method",
"reference"
] | train | https://github.com/uber/NullAway/blob/c3979b4241f80411dbba6aac3ff653acbb88d00b/nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java#L57-L62 |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java | DfuServiceInitiator.setZip | public DfuServiceInitiator setZip(@NonNull final String path) {
"""
Sets the path to the Distribution packet (ZIP) or the a ZIP file matching the deprecated naming
convention.
@param path path to the file
@return the builder
@see #setZip(Uri)
@see #setZip(int)
"""
return init(null, path, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | java | public DfuServiceInitiator setZip(@NonNull final String path) {
return init(null, path, 0, DfuBaseService.TYPE_AUTO, DfuBaseService.MIME_TYPE_ZIP);
} | [
"public",
"DfuServiceInitiator",
"setZip",
"(",
"@",
"NonNull",
"final",
"String",
"path",
")",
"{",
"return",
"init",
"(",
"null",
",",
"path",
",",
"0",
",",
"DfuBaseService",
".",
"TYPE_AUTO",
",",
"DfuBaseService",
".",
"MIME_TYPE_ZIP",
")",
";",
"}"
] | Sets the path to the Distribution packet (ZIP) or the a ZIP file matching the deprecated naming
convention.
@param path path to the file
@return the builder
@see #setZip(Uri)
@see #setZip(int) | [
"Sets",
"the",
"path",
"to",
"the",
"Distribution",
"packet",
"(",
"ZIP",
")",
"or",
"the",
"a",
"ZIP",
"file",
"matching",
"the",
"deprecated",
"naming",
"convention",
"."
] | train | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuServiceInitiator.java#L578-L580 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/engine/impl/DB2Engine.java | DB2Engine.alterColumnSetNotNull | private String alterColumnSetNotNull(String tableName, List<String> columnNames) {
"""
Generates a command to set the specified columns to enforce non nullability.
@param tableName The table name.
@param columnNames The columns.
@return The command to perform the operation.
"""
List<String> statement = new ArrayList<>();
statement.add("ALTER TABLE");
statement.add(quotize(tableName));
for (String columnName : columnNames) {
statement.add("ALTER COLUMN");
statement.add(quotize(columnName));
statement.add("SET NOT NULL");
}
return join(statement, " ");
} | java | private String alterColumnSetNotNull(String tableName, List<String> columnNames) {
List<String> statement = new ArrayList<>();
statement.add("ALTER TABLE");
statement.add(quotize(tableName));
for (String columnName : columnNames) {
statement.add("ALTER COLUMN");
statement.add(quotize(columnName));
statement.add("SET NOT NULL");
}
return join(statement, " ");
} | [
"private",
"String",
"alterColumnSetNotNull",
"(",
"String",
"tableName",
",",
"List",
"<",
"String",
">",
"columnNames",
")",
"{",
"List",
"<",
"String",
">",
"statement",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"statement",
".",
"add",
"(",
"\"ALTER TABLE\"",
")",
";",
"statement",
".",
"add",
"(",
"quotize",
"(",
"tableName",
")",
")",
";",
"for",
"(",
"String",
"columnName",
":",
"columnNames",
")",
"{",
"statement",
".",
"add",
"(",
"\"ALTER COLUMN\"",
")",
";",
"statement",
".",
"add",
"(",
"quotize",
"(",
"columnName",
")",
")",
";",
"statement",
".",
"add",
"(",
"\"SET NOT NULL\"",
")",
";",
"}",
"return",
"join",
"(",
"statement",
",",
"\" \"",
")",
";",
"}"
] | Generates a command to set the specified columns to enforce non nullability.
@param tableName The table name.
@param columnNames The columns.
@return The command to perform the operation. | [
"Generates",
"a",
"command",
"to",
"set",
"the",
"specified",
"columns",
"to",
"enforce",
"non",
"nullability",
"."
] | train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/engine/impl/DB2Engine.java#L301-L313 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java | FSDirectory.getFileInfoExtended | FileStatusExtended getFileInfoExtended(String src, INode targetNode,
String leaseHolder)
throws IOException {
"""
Get the extended file info for a specific file.
@param src
The string representation of the path to the file
@param targetNode
the INode for the corresponding file
@param leaseHolder
the lease holder for the file
@return object containing information regarding the file or null if file
not found
@throws IOException
if permission to access file is denied by the system
"""
readLock();
try {
if (targetNode == null) {
return null;
}
FileStatus stat = createFileStatus(src, targetNode);
long hardlinkId = (targetNode instanceof INodeHardLinkFile) ? ((INodeHardLinkFile) targetNode)
.getHardLinkID() : -1;
return new FileStatusExtended(stat, ((INodeFile) targetNode).getBlocks(),
leaseHolder, hardlinkId);
} finally {
readUnlock();
}
} | java | FileStatusExtended getFileInfoExtended(String src, INode targetNode,
String leaseHolder)
throws IOException {
readLock();
try {
if (targetNode == null) {
return null;
}
FileStatus stat = createFileStatus(src, targetNode);
long hardlinkId = (targetNode instanceof INodeHardLinkFile) ? ((INodeHardLinkFile) targetNode)
.getHardLinkID() : -1;
return new FileStatusExtended(stat, ((INodeFile) targetNode).getBlocks(),
leaseHolder, hardlinkId);
} finally {
readUnlock();
}
} | [
"FileStatusExtended",
"getFileInfoExtended",
"(",
"String",
"src",
",",
"INode",
"targetNode",
",",
"String",
"leaseHolder",
")",
"throws",
"IOException",
"{",
"readLock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"targetNode",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"FileStatus",
"stat",
"=",
"createFileStatus",
"(",
"src",
",",
"targetNode",
")",
";",
"long",
"hardlinkId",
"=",
"(",
"targetNode",
"instanceof",
"INodeHardLinkFile",
")",
"?",
"(",
"(",
"INodeHardLinkFile",
")",
"targetNode",
")",
".",
"getHardLinkID",
"(",
")",
":",
"-",
"1",
";",
"return",
"new",
"FileStatusExtended",
"(",
"stat",
",",
"(",
"(",
"INodeFile",
")",
"targetNode",
")",
".",
"getBlocks",
"(",
")",
",",
"leaseHolder",
",",
"hardlinkId",
")",
";",
"}",
"finally",
"{",
"readUnlock",
"(",
")",
";",
"}",
"}"
] | Get the extended file info for a specific file.
@param src
The string representation of the path to the file
@param targetNode
the INode for the corresponding file
@param leaseHolder
the lease holder for the file
@return object containing information regarding the file or null if file
not found
@throws IOException
if permission to access file is denied by the system | [
"Get",
"the",
"extended",
"file",
"info",
"for",
"a",
"specific",
"file",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java#L1829-L1845 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/PrivateDataManager.java | PrivateDataManager.removePrivateDataProvider | public static void removePrivateDataProvider(String elementName, String namespace) {
"""
Removes a private data provider with the specified element name and namespace.
@param elementName The XML element name.
@param namespace The XML namespace.
"""
String key = XmppStringUtils.generateKey(elementName, namespace);
privateDataProviders.remove(key);
} | java | public static void removePrivateDataProvider(String elementName, String namespace) {
String key = XmppStringUtils.generateKey(elementName, namespace);
privateDataProviders.remove(key);
} | [
"public",
"static",
"void",
"removePrivateDataProvider",
"(",
"String",
"elementName",
",",
"String",
"namespace",
")",
"{",
"String",
"key",
"=",
"XmppStringUtils",
".",
"generateKey",
"(",
"elementName",
",",
"namespace",
")",
";",
"privateDataProviders",
".",
"remove",
"(",
"key",
")",
";",
"}"
] | Removes a private data provider with the specified element name and namespace.
@param elementName The XML element name.
@param namespace The XML namespace. | [
"Removes",
"a",
"private",
"data",
"provider",
"with",
"the",
"specified",
"element",
"name",
"and",
"namespace",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqprivate/PrivateDataManager.java#L129-L132 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/ChatApi.java | ChatApi.sendTypingStarted | public ApiSuccessResponse sendTypingStarted(String id, AcceptData3 acceptData) throws ApiException {
"""
Send notification that the agent is typing
Send notification that the agent is typing to the other participants in the specified chat.
@param id The ID of the chat interaction. (required)
@param acceptData Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
"""
ApiResponse<ApiSuccessResponse> resp = sendTypingStartedWithHttpInfo(id, acceptData);
return resp.getData();
} | java | public ApiSuccessResponse sendTypingStarted(String id, AcceptData3 acceptData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = sendTypingStartedWithHttpInfo(id, acceptData);
return resp.getData();
} | [
"public",
"ApiSuccessResponse",
"sendTypingStarted",
"(",
"String",
"id",
",",
"AcceptData3",
"acceptData",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"ApiSuccessResponse",
">",
"resp",
"=",
"sendTypingStartedWithHttpInfo",
"(",
"id",
",",
"acceptData",
")",
";",
"return",
"resp",
".",
"getData",
"(",
")",
";",
"}"
] | Send notification that the agent is typing
Send notification that the agent is typing to the other participants in the specified chat.
@param id The ID of the chat interaction. (required)
@param acceptData Request parameters. (optional)
@return ApiSuccessResponse
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Send",
"notification",
"that",
"the",
"agent",
"is",
"typing",
"Send",
"notification",
"that",
"the",
"agent",
"is",
"typing",
"to",
"the",
"other",
"participants",
"in",
"the",
"specified",
"chat",
"."
] | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/ChatApi.java#L1826-L1829 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/bos/BosClient.java | BosClient.putObject | public PutObjectResponse putObject(String bucketName, String key, byte[] value) {
"""
Uploads the specified bytes to Bos under the specified bucket and key name.
@param bucketName The name of an existing bucket, to which you have Write permission.
@param key The key under which to store the specified file.
@param value The bytes containing the value to be uploaded to Bos.
@return A PutObjectResponse object containing the information returned by Bos for the newly created object.
"""
return this.putObject(bucketName, key, value, new ObjectMetadata());
} | java | public PutObjectResponse putObject(String bucketName, String key, byte[] value) {
return this.putObject(bucketName, key, value, new ObjectMetadata());
} | [
"public",
"PutObjectResponse",
"putObject",
"(",
"String",
"bucketName",
",",
"String",
"key",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"return",
"this",
".",
"putObject",
"(",
"bucketName",
",",
"key",
",",
"value",
",",
"new",
"ObjectMetadata",
"(",
")",
")",
";",
"}"
] | Uploads the specified bytes to Bos under the specified bucket and key name.
@param bucketName The name of an existing bucket, to which you have Write permission.
@param key The key under which to store the specified file.
@param value The bytes containing the value to be uploaded to Bos.
@return A PutObjectResponse object containing the information returned by Bos for the newly created object. | [
"Uploads",
"the",
"specified",
"bytes",
"to",
"Bos",
"under",
"the",
"specified",
"bucket",
"and",
"key",
"name",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L848-L850 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java | HintRule.addAddVersion | public void addAddVersion(String source, String name, String value, Confidence confidence) {
"""
Adds a given version to the list of evidence to add when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param confidence the confidence of the evidence
"""
addVersion.add(new Evidence(source, name, value, confidence));
} | java | public void addAddVersion(String source, String name, String value, Confidence confidence) {
addVersion.add(new Evidence(source, name, value, confidence));
} | [
"public",
"void",
"addAddVersion",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"Confidence",
"confidence",
")",
"{",
"addVersion",
".",
"add",
"(",
"new",
"Evidence",
"(",
"source",
",",
"name",
",",
"value",
",",
"confidence",
")",
")",
";",
"}"
] | Adds a given version to the list of evidence to add when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param confidence the confidence of the evidence | [
"Adds",
"a",
"given",
"version",
"to",
"the",
"list",
"of",
"evidence",
"to",
"add",
"when",
"matched",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L170-L172 |
elki-project/elki | elki-index-rtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/AbstractRStarTree.java | AbstractRStarTree.getLeafNodes | private void getLeafNodes(N node, List<E> result, int currentLevel) {
"""
Determines the entries pointing to the leaf nodes of the specified subtree.
@param node the subtree
@param result the result to store the ids in
@param currentLevel the level of the node in the R-Tree
"""
// Level 1 are the leaf nodes, Level 2 is the one atop!
if(currentLevel == 2) {
for(int i = 0; i < node.getNumEntries(); i++) {
result.add(node.getEntry(i));
}
}
else {
for(int i = 0; i < node.getNumEntries(); i++) {
getLeafNodes(getNode(node.getEntry(i)), result, (currentLevel - 1));
}
}
} | java | private void getLeafNodes(N node, List<E> result, int currentLevel) {
// Level 1 are the leaf nodes, Level 2 is the one atop!
if(currentLevel == 2) {
for(int i = 0; i < node.getNumEntries(); i++) {
result.add(node.getEntry(i));
}
}
else {
for(int i = 0; i < node.getNumEntries(); i++) {
getLeafNodes(getNode(node.getEntry(i)), result, (currentLevel - 1));
}
}
} | [
"private",
"void",
"getLeafNodes",
"(",
"N",
"node",
",",
"List",
"<",
"E",
">",
"result",
",",
"int",
"currentLevel",
")",
"{",
"// Level 1 are the leaf nodes, Level 2 is the one atop!",
"if",
"(",
"currentLevel",
"==",
"2",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"getNumEntries",
"(",
")",
";",
"i",
"++",
")",
"{",
"result",
".",
"add",
"(",
"node",
".",
"getEntry",
"(",
"i",
")",
")",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"getNumEntries",
"(",
")",
";",
"i",
"++",
")",
"{",
"getLeafNodes",
"(",
"getNode",
"(",
"node",
".",
"getEntry",
"(",
"i",
")",
")",
",",
"result",
",",
"(",
"currentLevel",
"-",
"1",
")",
")",
";",
"}",
"}",
"}"
] | Determines the entries pointing to the leaf nodes of the specified subtree.
@param node the subtree
@param result the result to store the ids in
@param currentLevel the level of the node in the R-Tree | [
"Determines",
"the",
"entries",
"pointing",
"to",
"the",
"leaf",
"nodes",
"of",
"the",
"specified",
"subtree",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-rtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/AbstractRStarTree.java#L786-L798 |
JavaMoney/jsr354-ri | moneta-core/src/main/java/org/javamoney/moneta/function/PrecisionScaleRoundedOperator.java | PrecisionScaleRoundedOperator.of | public static PrecisionScaleRoundedOperator of(int scale, MathContext mathContext) {
"""
Creates the rounded Operator from scale and roundingMode
@param mathContext the math context, not null.
@return the {@link MonetaryOperator} using the scale and {@link RoundingMode} used in parameter
@throws NullPointerException when the {@link MathContext} is null
@throws IllegalArgumentException if {@link MathContext#getPrecision()} is lesser than zero
@throws IllegalArgumentException if {@link MathContext#getRoundingMode()} is {@link RoundingMode#UNNECESSARY}
@see RoundingMode
"""
requireNonNull(mathContext);
if(RoundingMode.UNNECESSARY.equals(mathContext.getRoundingMode())) {
throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the RoundingMode.UNNECESSARY on MathContext");
}
if(mathContext.getPrecision() <= 0) {
throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the zero precision on MathContext");
}
return new PrecisionScaleRoundedOperator(scale, mathContext);
} | java | public static PrecisionScaleRoundedOperator of(int scale, MathContext mathContext) {
requireNonNull(mathContext);
if(RoundingMode.UNNECESSARY.equals(mathContext.getRoundingMode())) {
throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the RoundingMode.UNNECESSARY on MathContext");
}
if(mathContext.getPrecision() <= 0) {
throw new IllegalArgumentException("To create the ScaleRoundedOperator you cannot use the zero precision on MathContext");
}
return new PrecisionScaleRoundedOperator(scale, mathContext);
} | [
"public",
"static",
"PrecisionScaleRoundedOperator",
"of",
"(",
"int",
"scale",
",",
"MathContext",
"mathContext",
")",
"{",
"requireNonNull",
"(",
"mathContext",
")",
";",
"if",
"(",
"RoundingMode",
".",
"UNNECESSARY",
".",
"equals",
"(",
"mathContext",
".",
"getRoundingMode",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"To create the ScaleRoundedOperator you cannot use the RoundingMode.UNNECESSARY on MathContext\"",
")",
";",
"}",
"if",
"(",
"mathContext",
".",
"getPrecision",
"(",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"To create the ScaleRoundedOperator you cannot use the zero precision on MathContext\"",
")",
";",
"}",
"return",
"new",
"PrecisionScaleRoundedOperator",
"(",
"scale",
",",
"mathContext",
")",
";",
"}"
] | Creates the rounded Operator from scale and roundingMode
@param mathContext the math context, not null.
@return the {@link MonetaryOperator} using the scale and {@link RoundingMode} used in parameter
@throws NullPointerException when the {@link MathContext} is null
@throws IllegalArgumentException if {@link MathContext#getPrecision()} is lesser than zero
@throws IllegalArgumentException if {@link MathContext#getRoundingMode()} is {@link RoundingMode#UNNECESSARY}
@see RoundingMode | [
"Creates",
"the",
"rounded",
"Operator",
"from",
"scale",
"and",
"roundingMode"
] | train | https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/function/PrecisionScaleRoundedOperator.java#L77-L89 |
soi-toolkit/soi-toolkit-mule | commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/ftp/FtpUtil.java | FtpUtil.recursiveDeleteDirectory | static public void recursiveDeleteDirectory(FTPClient ftpClient, String path) throws IOException {
"""
Deletes a directory with all its files and sub-directories.
@param ftpClient
@param path
@throws IOException
"""
logger.info("Delete directory: {}", path);
FTPFile[] ftpFiles = ftpClient.listFiles(path);
logger.debug("Number of files that will be deleted: {}", ftpFiles.length);
for (FTPFile ftpFile : ftpFiles){
String filename = path + "/" + ftpFile.getName();
if (ftpFile.getType() == FTPFile.FILE_TYPE) {
boolean deleted = ftpClient.deleteFile(filename);
logger.debug("Deleted {}? {}", filename, deleted);
} else {
recursiveDeleteDirectory(ftpClient, filename);
}
}
boolean dirDeleted = ftpClient.deleteFile(path);
logger.debug("Directory {} deleted: {}", path, dirDeleted);
} | java | static public void recursiveDeleteDirectory(FTPClient ftpClient, String path) throws IOException {
logger.info("Delete directory: {}", path);
FTPFile[] ftpFiles = ftpClient.listFiles(path);
logger.debug("Number of files that will be deleted: {}", ftpFiles.length);
for (FTPFile ftpFile : ftpFiles){
String filename = path + "/" + ftpFile.getName();
if (ftpFile.getType() == FTPFile.FILE_TYPE) {
boolean deleted = ftpClient.deleteFile(filename);
logger.debug("Deleted {}? {}", filename, deleted);
} else {
recursiveDeleteDirectory(ftpClient, filename);
}
}
boolean dirDeleted = ftpClient.deleteFile(path);
logger.debug("Directory {} deleted: {}", path, dirDeleted);
} | [
"static",
"public",
"void",
"recursiveDeleteDirectory",
"(",
"FTPClient",
"ftpClient",
",",
"String",
"path",
")",
"throws",
"IOException",
"{",
"logger",
".",
"info",
"(",
"\"Delete directory: {}\"",
",",
"path",
")",
";",
"FTPFile",
"[",
"]",
"ftpFiles",
"=",
"ftpClient",
".",
"listFiles",
"(",
"path",
")",
";",
"logger",
".",
"debug",
"(",
"\"Number of files that will be deleted: {}\"",
",",
"ftpFiles",
".",
"length",
")",
";",
"for",
"(",
"FTPFile",
"ftpFile",
":",
"ftpFiles",
")",
"{",
"String",
"filename",
"=",
"path",
"+",
"\"/\"",
"+",
"ftpFile",
".",
"getName",
"(",
")",
";",
"if",
"(",
"ftpFile",
".",
"getType",
"(",
")",
"==",
"FTPFile",
".",
"FILE_TYPE",
")",
"{",
"boolean",
"deleted",
"=",
"ftpClient",
".",
"deleteFile",
"(",
"filename",
")",
";",
"logger",
".",
"debug",
"(",
"\"Deleted {}? {}\"",
",",
"filename",
",",
"deleted",
")",
";",
"}",
"else",
"{",
"recursiveDeleteDirectory",
"(",
"ftpClient",
",",
"filename",
")",
";",
"}",
"}",
"boolean",
"dirDeleted",
"=",
"ftpClient",
".",
"deleteFile",
"(",
"path",
")",
";",
"logger",
".",
"debug",
"(",
"\"Directory {} deleted: {}\"",
",",
"path",
",",
"dirDeleted",
")",
";",
"}"
] | Deletes a directory with all its files and sub-directories.
@param ftpClient
@param path
@throws IOException | [
"Deletes",
"a",
"directory",
"with",
"all",
"its",
"files",
"and",
"sub",
"-",
"directories",
"."
] | train | https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/commons/components/commons-mule/src/main/java/org/soitoolkit/commons/mule/ftp/FtpUtil.java#L144-L163 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ArrayELResolver.java | ArrayELResolver.getValue | @Override
public Object getValue(ELContext context, Object base, Object property) {
"""
If the base object is a Java language array, returns the value at the given index. The index
is specified by the property argument, and coerced into an integer. If the coercion could not
be performed, an IllegalArgumentException is thrown. If the index is out of bounds, null is
returned. If the base is a Java language array, the propertyResolved property of the
ELContext object must be set to true by this resolver, before returning. If this property is
not true after this method is called, the caller should ignore the return value.
@param context
The context of this evaluation.
@param base
The array to analyze. Only bases that are a Java language array are handled by
this resolver.
@param property
The index of the element in the array to return the acceptable type for. Will be
coerced into an integer, but otherwise ignored by this resolver.
@return If the propertyResolved property of ELContext was set to true, then the value at the
given index or null if the index was out of bounds. Otherwise, undefined.
@throws PropertyNotFoundException
if the given index is out of bounds for this array.
@throws NullPointerException
if context is null
@throws ELException
if an exception was thrown while performing the property or variable resolution.
The thrown exception must be included as the cause property of this exception, if
available.
"""
if (context == null) {
throw new NullPointerException("context is null");
}
Object result = null;
if (isResolvable(base)) {
int index = toIndex(null, property);
result = index < 0 || index >= Array.getLength(base) ? null : Array.get(base, index);
context.setPropertyResolved(true);
}
return result;
} | java | @Override
public Object getValue(ELContext context, Object base, Object property) {
if (context == null) {
throw new NullPointerException("context is null");
}
Object result = null;
if (isResolvable(base)) {
int index = toIndex(null, property);
result = index < 0 || index >= Array.getLength(base) ? null : Array.get(base, index);
context.setPropertyResolved(true);
}
return result;
} | [
"@",
"Override",
"public",
"Object",
"getValue",
"(",
"ELContext",
"context",
",",
"Object",
"base",
",",
"Object",
"property",
")",
"{",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"context is null\"",
")",
";",
"}",
"Object",
"result",
"=",
"null",
";",
"if",
"(",
"isResolvable",
"(",
"base",
")",
")",
"{",
"int",
"index",
"=",
"toIndex",
"(",
"null",
",",
"property",
")",
";",
"result",
"=",
"index",
"<",
"0",
"||",
"index",
">=",
"Array",
".",
"getLength",
"(",
"base",
")",
"?",
"null",
":",
"Array",
".",
"get",
"(",
"base",
",",
"index",
")",
";",
"context",
".",
"setPropertyResolved",
"(",
"true",
")",
";",
"}",
"return",
"result",
";",
"}"
] | If the base object is a Java language array, returns the value at the given index. The index
is specified by the property argument, and coerced into an integer. If the coercion could not
be performed, an IllegalArgumentException is thrown. If the index is out of bounds, null is
returned. If the base is a Java language array, the propertyResolved property of the
ELContext object must be set to true by this resolver, before returning. If this property is
not true after this method is called, the caller should ignore the return value.
@param context
The context of this evaluation.
@param base
The array to analyze. Only bases that are a Java language array are handled by
this resolver.
@param property
The index of the element in the array to return the acceptable type for. Will be
coerced into an integer, but otherwise ignored by this resolver.
@return If the propertyResolved property of ELContext was set to true, then the value at the
given index or null if the index was out of bounds. Otherwise, undefined.
@throws PropertyNotFoundException
if the given index is out of bounds for this array.
@throws NullPointerException
if context is null
@throws ELException
if an exception was thrown while performing the property or variable resolution.
The thrown exception must be included as the cause property of this exception, if
available. | [
"If",
"the",
"base",
"object",
"is",
"a",
"Java",
"language",
"array",
"returns",
"the",
"value",
"at",
"the",
"given",
"index",
".",
"The",
"index",
"is",
"specified",
"by",
"the",
"property",
"argument",
"and",
"coerced",
"into",
"an",
"integer",
".",
"If",
"the",
"coercion",
"could",
"not",
"be",
"performed",
"an",
"IllegalArgumentException",
"is",
"thrown",
".",
"If",
"the",
"index",
"is",
"out",
"of",
"bounds",
"null",
"is",
"returned",
".",
"If",
"the",
"base",
"is",
"a",
"Java",
"language",
"array",
"the",
"propertyResolved",
"property",
"of",
"the",
"ELContext",
"object",
"must",
"be",
"set",
"to",
"true",
"by",
"this",
"resolver",
"before",
"returning",
".",
"If",
"this",
"property",
"is",
"not",
"true",
"after",
"this",
"method",
"is",
"called",
"the",
"caller",
"should",
"ignore",
"the",
"return",
"value",
"."
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ArrayELResolver.java#L155-L167 |
citrusframework/citrus | modules/citrus-docker/src/main/java/com/consol/citrus/docker/command/ContainerCreate.java | ContainerCreate.getPortBindings | private Ports getPortBindings(String portSpecs, ExposedPort[] exposedPorts, TestContext context) {
"""
Construct set of port bindings from comma delimited list of ports.
@param portSpecs
@param exposedPorts
@param context
@return
"""
String[] ports = StringUtils.commaDelimitedListToStringArray(portSpecs);
Ports portsBindings = new Ports();
for (String portSpec : ports) {
String[] binding = context.replaceDynamicContentInString(portSpec).split(":");
if (binding.length == 2) {
Integer hostPort = Integer.valueOf(binding[0]);
Integer port = Integer.valueOf(binding[1]);
portsBindings.bind(Stream.of(exposedPorts).filter(exposed -> port.equals(exposed.getPort())).findAny().orElse(ExposedPort.tcp(port)), Ports.Binding.bindPort(hostPort));
}
}
Stream.of(exposedPorts).filter(exposed -> !portsBindings.getBindings().keySet().contains(exposed)).forEach(exposed -> portsBindings.bind(exposed, Ports.Binding.empty()));
return portsBindings;
} | java | private Ports getPortBindings(String portSpecs, ExposedPort[] exposedPorts, TestContext context) {
String[] ports = StringUtils.commaDelimitedListToStringArray(portSpecs);
Ports portsBindings = new Ports();
for (String portSpec : ports) {
String[] binding = context.replaceDynamicContentInString(portSpec).split(":");
if (binding.length == 2) {
Integer hostPort = Integer.valueOf(binding[0]);
Integer port = Integer.valueOf(binding[1]);
portsBindings.bind(Stream.of(exposedPorts).filter(exposed -> port.equals(exposed.getPort())).findAny().orElse(ExposedPort.tcp(port)), Ports.Binding.bindPort(hostPort));
}
}
Stream.of(exposedPorts).filter(exposed -> !portsBindings.getBindings().keySet().contains(exposed)).forEach(exposed -> portsBindings.bind(exposed, Ports.Binding.empty()));
return portsBindings;
} | [
"private",
"Ports",
"getPortBindings",
"(",
"String",
"portSpecs",
",",
"ExposedPort",
"[",
"]",
"exposedPorts",
",",
"TestContext",
"context",
")",
"{",
"String",
"[",
"]",
"ports",
"=",
"StringUtils",
".",
"commaDelimitedListToStringArray",
"(",
"portSpecs",
")",
";",
"Ports",
"portsBindings",
"=",
"new",
"Ports",
"(",
")",
";",
"for",
"(",
"String",
"portSpec",
":",
"ports",
")",
"{",
"String",
"[",
"]",
"binding",
"=",
"context",
".",
"replaceDynamicContentInString",
"(",
"portSpec",
")",
".",
"split",
"(",
"\":\"",
")",
";",
"if",
"(",
"binding",
".",
"length",
"==",
"2",
")",
"{",
"Integer",
"hostPort",
"=",
"Integer",
".",
"valueOf",
"(",
"binding",
"[",
"0",
"]",
")",
";",
"Integer",
"port",
"=",
"Integer",
".",
"valueOf",
"(",
"binding",
"[",
"1",
"]",
")",
";",
"portsBindings",
".",
"bind",
"(",
"Stream",
".",
"of",
"(",
"exposedPorts",
")",
".",
"filter",
"(",
"exposed",
"->",
"port",
".",
"equals",
"(",
"exposed",
".",
"getPort",
"(",
")",
")",
")",
".",
"findAny",
"(",
")",
".",
"orElse",
"(",
"ExposedPort",
".",
"tcp",
"(",
"port",
")",
")",
",",
"Ports",
".",
"Binding",
".",
"bindPort",
"(",
"hostPort",
")",
")",
";",
"}",
"}",
"Stream",
".",
"of",
"(",
"exposedPorts",
")",
".",
"filter",
"(",
"exposed",
"->",
"!",
"portsBindings",
".",
"getBindings",
"(",
")",
".",
"keySet",
"(",
")",
".",
"contains",
"(",
"exposed",
")",
")",
".",
"forEach",
"(",
"exposed",
"->",
"portsBindings",
".",
"bind",
"(",
"exposed",
",",
"Ports",
".",
"Binding",
".",
"empty",
"(",
")",
")",
")",
";",
"return",
"portsBindings",
";",
"}"
] | Construct set of port bindings from comma delimited list of ports.
@param portSpecs
@param exposedPorts
@param context
@return | [
"Construct",
"set",
"of",
"port",
"bindings",
"from",
"comma",
"delimited",
"list",
"of",
"ports",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-docker/src/main/java/com/consol/citrus/docker/command/ContainerCreate.java#L222-L239 |
CodeNarc/CodeNarc | src/main/java/org/codenarc/util/AstUtil.java | AstUtil.isFinalVariable | public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {
"""
Return true if the DeclarationExpression represents a 'final' variable declaration.
NOTE: THIS IS A WORKAROUND.
There does not seem to be an easy way to determine whether the 'final' modifier has been
specified for a variable declaration. Return true if the 'final' is present before the variable name.
"""
if (isFromGeneratedSourceCode(declarationExpression)) {
return false;
}
List<Expression> variableExpressions = getVariableExpressions(declarationExpression);
if (!variableExpressions.isEmpty()) {
Expression variableExpression = variableExpressions.get(0);
int startOfDeclaration = declarationExpression.getColumnNumber();
int startOfVariableName = variableExpression.getColumnNumber();
int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);
String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);
String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?
sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : "";
return modifiers.contains("final");
}
return false;
} | java | public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {
if (isFromGeneratedSourceCode(declarationExpression)) {
return false;
}
List<Expression> variableExpressions = getVariableExpressions(declarationExpression);
if (!variableExpressions.isEmpty()) {
Expression variableExpression = variableExpressions.get(0);
int startOfDeclaration = declarationExpression.getColumnNumber();
int startOfVariableName = variableExpression.getColumnNumber();
int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);
String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);
String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?
sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : "";
return modifiers.contains("final");
}
return false;
} | [
"public",
"static",
"boolean",
"isFinalVariable",
"(",
"DeclarationExpression",
"declarationExpression",
",",
"SourceCode",
"sourceCode",
")",
"{",
"if",
"(",
"isFromGeneratedSourceCode",
"(",
"declarationExpression",
")",
")",
"{",
"return",
"false",
";",
"}",
"List",
"<",
"Expression",
">",
"variableExpressions",
"=",
"getVariableExpressions",
"(",
"declarationExpression",
")",
";",
"if",
"(",
"!",
"variableExpressions",
".",
"isEmpty",
"(",
")",
")",
"{",
"Expression",
"variableExpression",
"=",
"variableExpressions",
".",
"get",
"(",
"0",
")",
";",
"int",
"startOfDeclaration",
"=",
"declarationExpression",
".",
"getColumnNumber",
"(",
")",
";",
"int",
"startOfVariableName",
"=",
"variableExpression",
".",
"getColumnNumber",
"(",
")",
";",
"int",
"sourceLineNumber",
"=",
"findFirstNonAnnotationLine",
"(",
"declarationExpression",
",",
"sourceCode",
")",
";",
"String",
"sourceLine",
"=",
"sourceCode",
".",
"getLines",
"(",
")",
".",
"get",
"(",
"sourceLineNumber",
"-",
"1",
")",
";",
"String",
"modifiers",
"=",
"(",
"startOfDeclaration",
">=",
"0",
"&&",
"startOfVariableName",
">=",
"0",
"&&",
"sourceLine",
".",
"length",
"(",
")",
">=",
"startOfVariableName",
")",
"?",
"sourceLine",
".",
"substring",
"(",
"startOfDeclaration",
"-",
"1",
",",
"startOfVariableName",
"-",
"1",
")",
":",
"\"\"",
";",
"return",
"modifiers",
".",
"contains",
"(",
"\"final\"",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Return true if the DeclarationExpression represents a 'final' variable declaration.
NOTE: THIS IS A WORKAROUND.
There does not seem to be an easy way to determine whether the 'final' modifier has been
specified for a variable declaration. Return true if the 'final' is present before the variable name. | [
"Return",
"true",
"if",
"the",
"DeclarationExpression",
"represents",
"a",
"final",
"variable",
"declaration",
"."
] | train | https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L541-L558 |
RestExpress/PluginExpress | cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java | CorsHeaderPlugin.addPreflightOptionsRequestSupport | private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController) {
"""
Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request.
@param server a RestExpress server instance.
"""
RouteBuilder rb;
for (String pattern : methodsByPattern.keySet())
{
rb = server.uri(pattern, corsOptionsController)
.action("options", HttpMethod.OPTIONS)
.noSerialization()
// Disable both authentication and authorization which are usually use header such as X-Authorization.
// When browser does CORS preflight with OPTIONS request, such headers are not included.
.flag(Flags.Auth.PUBLIC_ROUTE)
.flag(Flags.Auth.NO_AUTHORIZATION);
for (String flag : flags)
{
rb.flag(flag);
}
for (Entry<String, Object> entry : parameters.entrySet())
{
rb.parameter(entry.getKey(), entry.getValue());
}
routeBuilders.add(rb);
}
} | java | private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController)
{
RouteBuilder rb;
for (String pattern : methodsByPattern.keySet())
{
rb = server.uri(pattern, corsOptionsController)
.action("options", HttpMethod.OPTIONS)
.noSerialization()
// Disable both authentication and authorization which are usually use header such as X-Authorization.
// When browser does CORS preflight with OPTIONS request, such headers are not included.
.flag(Flags.Auth.PUBLIC_ROUTE)
.flag(Flags.Auth.NO_AUTHORIZATION);
for (String flag : flags)
{
rb.flag(flag);
}
for (Entry<String, Object> entry : parameters.entrySet())
{
rb.parameter(entry.getKey(), entry.getValue());
}
routeBuilders.add(rb);
}
} | [
"private",
"void",
"addPreflightOptionsRequestSupport",
"(",
"RestExpress",
"server",
",",
"CorsOptionsController",
"corsOptionsController",
")",
"{",
"RouteBuilder",
"rb",
";",
"for",
"(",
"String",
"pattern",
":",
"methodsByPattern",
".",
"keySet",
"(",
")",
")",
"{",
"rb",
"=",
"server",
".",
"uri",
"(",
"pattern",
",",
"corsOptionsController",
")",
".",
"action",
"(",
"\"options\"",
",",
"HttpMethod",
".",
"OPTIONS",
")",
".",
"noSerialization",
"(",
")",
"// Disable both authentication and authorization which are usually use header such as X-Authorization.",
"// When browser does CORS preflight with OPTIONS request, such headers are not included.",
".",
"flag",
"(",
"Flags",
".",
"Auth",
".",
"PUBLIC_ROUTE",
")",
".",
"flag",
"(",
"Flags",
".",
"Auth",
".",
"NO_AUTHORIZATION",
")",
";",
"for",
"(",
"String",
"flag",
":",
"flags",
")",
"{",
"rb",
".",
"flag",
"(",
"flag",
")",
";",
"}",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"parameters",
".",
"entrySet",
"(",
")",
")",
"{",
"rb",
".",
"parameter",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"routeBuilders",
".",
"add",
"(",
"rb",
")",
";",
"}",
"}"
] | Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request.
@param server a RestExpress server instance. | [
"Add",
"an",
"OPTIONS",
"method",
"supported",
"on",
"all",
"routes",
"for",
"the",
"pre",
"-",
"flight",
"CORS",
"request",
"."
] | train | https://github.com/RestExpress/PluginExpress/blob/aeb13907c23bf31ef2b2b17ae4c0ca4a6f5bee69/cors/src/main/java/com/strategicgains/restexpress/plugin/cors/CorsHeaderPlugin.java#L230-L256 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java | JBBPUtils.arrayEndsWith | public static boolean arrayEndsWith(final byte[] array, final byte[] str) {
"""
Check that a byte array ends with some byte values.
@param array array to be checked, must not be null
@param str a byte string which will be checked as the end sequence of the
array, must not be null
@return true if the string is the end sequence of the array, false
otherwise
@throws NullPointerException if any argument is null
@since 1.1
"""
boolean result = false;
if (array.length >= str.length) {
result = true;
int index = str.length;
int arrindex = array.length;
while (--index >= 0) {
if (array[--arrindex] != str[index]) {
result = false;
break;
}
}
}
return result;
} | java | public static boolean arrayEndsWith(final byte[] array, final byte[] str) {
boolean result = false;
if (array.length >= str.length) {
result = true;
int index = str.length;
int arrindex = array.length;
while (--index >= 0) {
if (array[--arrindex] != str[index]) {
result = false;
break;
}
}
}
return result;
} | [
"public",
"static",
"boolean",
"arrayEndsWith",
"(",
"final",
"byte",
"[",
"]",
"array",
",",
"final",
"byte",
"[",
"]",
"str",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"if",
"(",
"array",
".",
"length",
">=",
"str",
".",
"length",
")",
"{",
"result",
"=",
"true",
";",
"int",
"index",
"=",
"str",
".",
"length",
";",
"int",
"arrindex",
"=",
"array",
".",
"length",
";",
"while",
"(",
"--",
"index",
">=",
"0",
")",
"{",
"if",
"(",
"array",
"[",
"--",
"arrindex",
"]",
"!=",
"str",
"[",
"index",
"]",
")",
"{",
"result",
"=",
"false",
";",
"break",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] | Check that a byte array ends with some byte values.
@param array array to be checked, must not be null
@param str a byte string which will be checked as the end sequence of the
array, must not be null
@return true if the string is the end sequence of the array, false
otherwise
@throws NullPointerException if any argument is null
@since 1.1 | [
"Check",
"that",
"a",
"byte",
"array",
"ends",
"with",
"some",
"byte",
"values",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPUtils.java#L941-L955 |
hypercube1024/firefly | firefly/src/main/java/com/firefly/client/http2/SimpleHTTPClient.java | SimpleHTTPClient.getConnectionPoolSize | public int getConnectionPoolSize(String host, int port) {
"""
Get the HTTP connection pool size.
@param host The host name.
@param port The target port.
@return The HTTP connection pool size.
"""
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
return _getPoolSize(req);
} | java | public int getConnectionPoolSize(String host, int port) {
RequestBuilder req = new RequestBuilder();
req.host = host;
req.port = port;
return _getPoolSize(req);
} | [
"public",
"int",
"getConnectionPoolSize",
"(",
"String",
"host",
",",
"int",
"port",
")",
"{",
"RequestBuilder",
"req",
"=",
"new",
"RequestBuilder",
"(",
")",
";",
"req",
".",
"host",
"=",
"host",
";",
"req",
".",
"port",
"=",
"port",
";",
"return",
"_getPoolSize",
"(",
"req",
")",
";",
"}"
] | Get the HTTP connection pool size.
@param host The host name.
@param port The target port.
@return The HTTP connection pool size. | [
"Get",
"the",
"HTTP",
"connection",
"pool",
"size",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/client/http2/SimpleHTTPClient.java#L744-L749 |
gallandarakhneorg/afc | core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java | XMLUtil.writeXML | public static void writeXML(Document xmldocument, String file) throws ParserConfigurationException, IOException {
"""
Write the given node tree into a XML file.
@param xmldocument is the object that contains the node tree
@param file is the file name.
@throws IOException if the stream cannot be read.
@throws ParserConfigurationException if the parser cannot be configured.
"""
assert file != null : AssertMessages.notNullParameter();
try (FileOutputStream fos = new FileOutputStream(file)) {
writeNode(xmldocument, fos);
}
} | java | public static void writeXML(Document xmldocument, String file) throws ParserConfigurationException, IOException {
assert file != null : AssertMessages.notNullParameter();
try (FileOutputStream fos = new FileOutputStream(file)) {
writeNode(xmldocument, fos);
}
} | [
"public",
"static",
"void",
"writeXML",
"(",
"Document",
"xmldocument",
",",
"String",
"file",
")",
"throws",
"ParserConfigurationException",
",",
"IOException",
"{",
"assert",
"file",
"!=",
"null",
":",
"AssertMessages",
".",
"notNullParameter",
"(",
")",
";",
"try",
"(",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"{",
"writeNode",
"(",
"xmldocument",
",",
"fos",
")",
";",
"}",
"}"
] | Write the given node tree into a XML file.
@param xmldocument is the object that contains the node tree
@param file is the file name.
@throws IOException if the stream cannot be read.
@throws ParserConfigurationException if the parser cannot be configured. | [
"Write",
"the",
"given",
"node",
"tree",
"into",
"a",
"XML",
"file",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L2377-L2382 |
RestComm/sip-servlets | containers/sip-servlets-catalina-8/src/main/java/org/mobicents/servlet/sip/catalina/NodeCreateRule.java | NodeCreateRule.begin | @Override
public void begin(String namespaceURI, String name, Attributes attributes)
throws Exception {
"""
Implemented to replace the content handler currently in use by a
NodeBuilder.
@param namespaceURI the namespace URI of the matching element, or an
empty string if the parser is not namespace aware or the element has
no namespace
@param name the local name if the parser is namespace aware, or just
the element name otherwise
@param attributes The attribute list of this element
@throws Exception indicates a JAXP configuration problem
"""
XMLReader xmlReader = getDigester().getXMLReader();
Document doc = documentBuilder.newDocument();
NodeBuilder builder = null;
if (nodeType == Node.ELEMENT_NODE) {
Element element = null;
if (getDigester().getNamespaceAware()) {
element =
doc.createElementNS(namespaceURI, name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttributeNS(attributes.getURI(i),
attributes.getLocalName(i),
attributes.getValue(i));
}
} else {
element = doc.createElement(name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttribute(attributes.getQName(i),
attributes.getValue(i));
}
}
builder = new NodeBuilder(doc, element);
} else {
builder = new NodeBuilder(doc, doc.createDocumentFragment());
}
xmlReader.setContentHandler(builder);
} | java | @Override
public void begin(String namespaceURI, String name, Attributes attributes)
throws Exception {
XMLReader xmlReader = getDigester().getXMLReader();
Document doc = documentBuilder.newDocument();
NodeBuilder builder = null;
if (nodeType == Node.ELEMENT_NODE) {
Element element = null;
if (getDigester().getNamespaceAware()) {
element =
doc.createElementNS(namespaceURI, name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttributeNS(attributes.getURI(i),
attributes.getLocalName(i),
attributes.getValue(i));
}
} else {
element = doc.createElement(name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttribute(attributes.getQName(i),
attributes.getValue(i));
}
}
builder = new NodeBuilder(doc, element);
} else {
builder = new NodeBuilder(doc, doc.createDocumentFragment());
}
xmlReader.setContentHandler(builder);
} | [
"@",
"Override",
"public",
"void",
"begin",
"(",
"String",
"namespaceURI",
",",
"String",
"name",
",",
"Attributes",
"attributes",
")",
"throws",
"Exception",
"{",
"XMLReader",
"xmlReader",
"=",
"getDigester",
"(",
")",
".",
"getXMLReader",
"(",
")",
";",
"Document",
"doc",
"=",
"documentBuilder",
".",
"newDocument",
"(",
")",
";",
"NodeBuilder",
"builder",
"=",
"null",
";",
"if",
"(",
"nodeType",
"==",
"Node",
".",
"ELEMENT_NODE",
")",
"{",
"Element",
"element",
"=",
"null",
";",
"if",
"(",
"getDigester",
"(",
")",
".",
"getNamespaceAware",
"(",
")",
")",
"{",
"element",
"=",
"doc",
".",
"createElementNS",
"(",
"namespaceURI",
",",
"name",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attributes",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"element",
".",
"setAttributeNS",
"(",
"attributes",
".",
"getURI",
"(",
"i",
")",
",",
"attributes",
".",
"getLocalName",
"(",
"i",
")",
",",
"attributes",
".",
"getValue",
"(",
"i",
")",
")",
";",
"}",
"}",
"else",
"{",
"element",
"=",
"doc",
".",
"createElement",
"(",
"name",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attributes",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"element",
".",
"setAttribute",
"(",
"attributes",
".",
"getQName",
"(",
"i",
")",
",",
"attributes",
".",
"getValue",
"(",
"i",
")",
")",
";",
"}",
"}",
"builder",
"=",
"new",
"NodeBuilder",
"(",
"doc",
",",
"element",
")",
";",
"}",
"else",
"{",
"builder",
"=",
"new",
"NodeBuilder",
"(",
"doc",
",",
"doc",
".",
"createDocumentFragment",
"(",
")",
")",
";",
"}",
"xmlReader",
".",
"setContentHandler",
"(",
"builder",
")",
";",
"}"
] | Implemented to replace the content handler currently in use by a
NodeBuilder.
@param namespaceURI the namespace URI of the matching element, or an
empty string if the parser is not namespace aware or the element has
no namespace
@param name the local name if the parser is namespace aware, or just
the element name otherwise
@param attributes The attribute list of this element
@throws Exception indicates a JAXP configuration problem | [
"Implemented",
"to",
"replace",
"the",
"content",
"handler",
"currently",
"in",
"use",
"by",
"a",
"NodeBuilder",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/containers/sip-servlets-catalina-8/src/main/java/org/mobicents/servlet/sip/catalina/NodeCreateRule.java#L394-L424 |
apereo/cas | support/cas-server-support-wsfederation-webflow/src/main/java/org/apereo/cas/web/flow/WsFederationAction.java | WsFederationAction.doExecute | @Override
protected Event doExecute(final RequestContext context) {
"""
Executes the webflow action.
@param context the context
@return the event
"""
try {
val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
val wa = request.getParameter(WA);
if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
wsFederationResponseValidator.validateWsFederationAuthenticationRequest(context);
return super.doExecute(context);
}
return wsFederationRequestBuilder.buildAuthenticationRequestEvent(context);
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, ex.getMessage());
}
} | java | @Override
protected Event doExecute(final RequestContext context) {
try {
val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
val wa = request.getParameter(WA);
if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
wsFederationResponseValidator.validateWsFederationAuthenticationRequest(context);
return super.doExecute(context);
}
return wsFederationRequestBuilder.buildAuthenticationRequestEvent(context);
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, ex.getMessage());
}
} | [
"@",
"Override",
"protected",
"Event",
"doExecute",
"(",
"final",
"RequestContext",
"context",
")",
"{",
"try",
"{",
"val",
"request",
"=",
"WebUtils",
".",
"getHttpServletRequestFromExternalWebflowContext",
"(",
"context",
")",
";",
"val",
"wa",
"=",
"request",
".",
"getParameter",
"(",
"WA",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"wa",
")",
"&&",
"wa",
".",
"equalsIgnoreCase",
"(",
"WSIGNIN",
")",
")",
"{",
"wsFederationResponseValidator",
".",
"validateWsFederationAuthenticationRequest",
"(",
"context",
")",
";",
"return",
"super",
".",
"doExecute",
"(",
"context",
")",
";",
"}",
"return",
"wsFederationRequestBuilder",
".",
"buildAuthenticationRequestEvent",
"(",
"context",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"throw",
"new",
"UnauthorizedServiceException",
"(",
"UnauthorizedServiceException",
".",
"CODE_UNAUTHZ_SERVICE",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Executes the webflow action.
@param context the context
@return the event | [
"Executes",
"the",
"webflow",
"action",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-wsfederation-webflow/src/main/java/org/apereo/cas/web/flow/WsFederationAction.java#L51-L65 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CfCodeGen.java | CfCodeGen.writeClassBody | @Override
public void writeClassBody(Definition def, Writer out) throws IOException {
"""
Output class code
@param def definition
@param out Writer
@throws IOException ioException
"""
out.write("public class " + getClassName(def) + " implements " +
def.getMcfDefs().get(getNumOfMcf()).getCfInterfaceClass());
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeWithIndent(out, indent, "/** The serial version UID */\n");
writeWithIndent(out, indent, "private static final long serialVersionUID = 1L;\n\n");
writeWithIndent(out, indent, "/** The logger */\n");
writeWithIndent(out, indent, "private static Logger log = Logger.getLogger(" + getSelfClassName(def) + ");\n\n");
writeWithIndent(out, indent, "/** Reference */\n");
writeWithIndent(out, indent, "private Reference reference;\n\n");
writeWithIndent(out, indent, "/** ManagedConnectionFactory */\n");
writeWithIndent(out, indent, "private " + def.getMcfDefs().get(getNumOfMcf()).getMcfClass() + " mcf;\n\n");
writeWithIndent(out, indent, "/** ConnectionManager */\n");
writeWithIndent(out, indent, "private ConnectionManager connectionManager;\n\n");
writeDefaultConstructor(def, out, indent);
//constructor
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Default constructor\n");
writeWithIndent(out, indent, " * @param mcf ManagedConnectionFactory\n");
writeWithIndent(out, indent, " * @param cxManager ConnectionManager\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent,
"public " + getClassName(def) + "(" + def.getMcfDefs().get(getNumOfMcf()).getMcfClass() +
" mcf, ConnectionManager cxManager)");
writeLeftCurlyBracket(out, indent);
writeWithIndent(out, indent + 1, "this.mcf = mcf;\n");
writeWithIndent(out, indent + 1, "this.connectionManager = cxManager;");
writeRightCurlyBracket(out, indent);
writeEol(out);
writeConnection(def, out, indent);
writeReference(def, out, indent);
writeRightCurlyBracket(out, 0);
} | java | @Override
public void writeClassBody(Definition def, Writer out) throws IOException
{
out.write("public class " + getClassName(def) + " implements " +
def.getMcfDefs().get(getNumOfMcf()).getCfInterfaceClass());
writeLeftCurlyBracket(out, 0);
int indent = 1;
writeWithIndent(out, indent, "/** The serial version UID */\n");
writeWithIndent(out, indent, "private static final long serialVersionUID = 1L;\n\n");
writeWithIndent(out, indent, "/** The logger */\n");
writeWithIndent(out, indent, "private static Logger log = Logger.getLogger(" + getSelfClassName(def) + ");\n\n");
writeWithIndent(out, indent, "/** Reference */\n");
writeWithIndent(out, indent, "private Reference reference;\n\n");
writeWithIndent(out, indent, "/** ManagedConnectionFactory */\n");
writeWithIndent(out, indent, "private " + def.getMcfDefs().get(getNumOfMcf()).getMcfClass() + " mcf;\n\n");
writeWithIndent(out, indent, "/** ConnectionManager */\n");
writeWithIndent(out, indent, "private ConnectionManager connectionManager;\n\n");
writeDefaultConstructor(def, out, indent);
//constructor
writeWithIndent(out, indent, "/**\n");
writeWithIndent(out, indent, " * Default constructor\n");
writeWithIndent(out, indent, " * @param mcf ManagedConnectionFactory\n");
writeWithIndent(out, indent, " * @param cxManager ConnectionManager\n");
writeWithIndent(out, indent, " */\n");
writeWithIndent(out, indent,
"public " + getClassName(def) + "(" + def.getMcfDefs().get(getNumOfMcf()).getMcfClass() +
" mcf, ConnectionManager cxManager)");
writeLeftCurlyBracket(out, indent);
writeWithIndent(out, indent + 1, "this.mcf = mcf;\n");
writeWithIndent(out, indent + 1, "this.connectionManager = cxManager;");
writeRightCurlyBracket(out, indent);
writeEol(out);
writeConnection(def, out, indent);
writeReference(def, out, indent);
writeRightCurlyBracket(out, 0);
} | [
"@",
"Override",
"public",
"void",
"writeClassBody",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"\"public class \"",
"+",
"getClassName",
"(",
"def",
")",
"+",
"\" implements \"",
"+",
"def",
".",
"getMcfDefs",
"(",
")",
".",
"get",
"(",
"getNumOfMcf",
"(",
")",
")",
".",
"getCfInterfaceClass",
"(",
")",
")",
";",
"writeLeftCurlyBracket",
"(",
"out",
",",
"0",
")",
";",
"int",
"indent",
"=",
"1",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/** The serial version UID */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"private static final long serialVersionUID = 1L;\\n\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/** The logger */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"private static Logger log = Logger.getLogger(\"",
"+",
"getSelfClassName",
"(",
"def",
")",
"+",
"\");\\n\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/** Reference */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"private Reference reference;\\n\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/** ManagedConnectionFactory */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"private \"",
"+",
"def",
".",
"getMcfDefs",
"(",
")",
".",
"get",
"(",
"getNumOfMcf",
"(",
")",
")",
".",
"getMcfClass",
"(",
")",
"+",
"\" mcf;\\n\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/** ConnectionManager */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"private ConnectionManager connectionManager;\\n\\n\"",
")",
";",
"writeDefaultConstructor",
"(",
"def",
",",
"out",
",",
"indent",
")",
";",
"//constructor",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"/**\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * Default constructor\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * @param mcf ManagedConnectionFactory\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" * @param cxManager ConnectionManager\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\" */\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
",",
"\"public \"",
"+",
"getClassName",
"(",
"def",
")",
"+",
"\"(\"",
"+",
"def",
".",
"getMcfDefs",
"(",
")",
".",
"get",
"(",
"getNumOfMcf",
"(",
")",
")",
".",
"getMcfClass",
"(",
")",
"+",
"\" mcf, ConnectionManager cxManager)\"",
")",
";",
"writeLeftCurlyBracket",
"(",
"out",
",",
"indent",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
"+",
"1",
",",
"\"this.mcf = mcf;\\n\"",
")",
";",
"writeWithIndent",
"(",
"out",
",",
"indent",
"+",
"1",
",",
"\"this.connectionManager = cxManager;\"",
")",
";",
"writeRightCurlyBracket",
"(",
"out",
",",
"indent",
")",
";",
"writeEol",
"(",
"out",
")",
";",
"writeConnection",
"(",
"def",
",",
"out",
",",
"indent",
")",
";",
"writeReference",
"(",
"def",
",",
"out",
",",
"indent",
")",
";",
"writeRightCurlyBracket",
"(",
"out",
",",
"0",
")",
";",
"}"
] | Output class code
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"class",
"code"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/CfCodeGen.java#L43-L88 |
httl/httl | httl/src/main/java/httl/spi/codecs/json/JSONArray.java | JSONArray.getLong | public long getLong(int index, long def) {
"""
get long value.
@param index index.
@param def default value.
@return value or default value.
"""
Object tmp = mArray.get(index);
return tmp != null && tmp instanceof Number ? ((Number) tmp)
.longValue() : def;
} | java | public long getLong(int index, long def) {
Object tmp = mArray.get(index);
return tmp != null && tmp instanceof Number ? ((Number) tmp)
.longValue() : def;
} | [
"public",
"long",
"getLong",
"(",
"int",
"index",
",",
"long",
"def",
")",
"{",
"Object",
"tmp",
"=",
"mArray",
".",
"get",
"(",
"index",
")",
";",
"return",
"tmp",
"!=",
"null",
"&&",
"tmp",
"instanceof",
"Number",
"?",
"(",
"(",
"Number",
")",
"tmp",
")",
".",
"longValue",
"(",
")",
":",
"def",
";",
"}"
] | get long value.
@param index index.
@param def default value.
@return value or default value. | [
"get",
"long",
"value",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/spi/codecs/json/JSONArray.java#L75-L79 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java | CoverageUtilities.createWritableRasterFromArray | public static WritableRaster createWritableRasterFromArray( int width, int height, int[] pixels ) {
"""
Create a {@link WritableRaster} from a int array.
@param width the width of the raster to create.
@param height the height of the raster to create.
@param pixels the array of data.
@return the produced raster.
"""
WritableRaster writableRaster = createWritableRaster(width, height, null, null, null);
int index = 0;
for( int y = 0; y < height; y++ ) {
for( int x = 0; x < width; x++ ) {
double value = (double) pixels[index];
if (value == 0) {
value = doubleNovalue;
}
writableRaster.setSample(x, y, 0, value);
index++;
}
}
return writableRaster;
} | java | public static WritableRaster createWritableRasterFromArray( int width, int height, int[] pixels ) {
WritableRaster writableRaster = createWritableRaster(width, height, null, null, null);
int index = 0;
for( int y = 0; y < height; y++ ) {
for( int x = 0; x < width; x++ ) {
double value = (double) pixels[index];
if (value == 0) {
value = doubleNovalue;
}
writableRaster.setSample(x, y, 0, value);
index++;
}
}
return writableRaster;
} | [
"public",
"static",
"WritableRaster",
"createWritableRasterFromArray",
"(",
"int",
"width",
",",
"int",
"height",
",",
"int",
"[",
"]",
"pixels",
")",
"{",
"WritableRaster",
"writableRaster",
"=",
"createWritableRaster",
"(",
"width",
",",
"height",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"height",
";",
"y",
"++",
")",
"{",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
")",
"{",
"double",
"value",
"=",
"(",
"double",
")",
"pixels",
"[",
"index",
"]",
";",
"if",
"(",
"value",
"==",
"0",
")",
"{",
"value",
"=",
"doubleNovalue",
";",
"}",
"writableRaster",
".",
"setSample",
"(",
"x",
",",
"y",
",",
"0",
",",
"value",
")",
";",
"index",
"++",
";",
"}",
"}",
"return",
"writableRaster",
";",
"}"
] | Create a {@link WritableRaster} from a int array.
@param width the width of the raster to create.
@param height the height of the raster to create.
@param pixels the array of data.
@return the produced raster. | [
"Create",
"a",
"{",
"@link",
"WritableRaster",
"}",
"from",
"a",
"int",
"array",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java#L799-L813 |
lucee/Lucee | core/src/main/java/lucee/runtime/crypt/BinConverter.java | BinConverter.longToByteArray | public static void longToByteArray(long lValue, byte[] buffer, int nStartIndex) {
"""
converts a long o bytes which are put into a given array
@param lValue the 64bit integer to convert
@param buffer the target buffer
@param nStartIndex where to place the bytes in the buffer
"""
buffer[nStartIndex] = (byte) (lValue >>> 56);
buffer[nStartIndex + 1] = (byte) ((lValue >>> 48) & 0x0ff);
buffer[nStartIndex + 2] = (byte) ((lValue >>> 40) & 0x0ff);
buffer[nStartIndex + 3] = (byte) ((lValue >>> 32) & 0x0ff);
buffer[nStartIndex + 4] = (byte) ((lValue >>> 24) & 0x0ff);
buffer[nStartIndex + 5] = (byte) ((lValue >>> 16) & 0x0ff);
buffer[nStartIndex + 6] = (byte) ((lValue >>> 8) & 0x0ff);
buffer[nStartIndex + 7] = (byte) lValue;
} | java | public static void longToByteArray(long lValue, byte[] buffer, int nStartIndex) {
buffer[nStartIndex] = (byte) (lValue >>> 56);
buffer[nStartIndex + 1] = (byte) ((lValue >>> 48) & 0x0ff);
buffer[nStartIndex + 2] = (byte) ((lValue >>> 40) & 0x0ff);
buffer[nStartIndex + 3] = (byte) ((lValue >>> 32) & 0x0ff);
buffer[nStartIndex + 4] = (byte) ((lValue >>> 24) & 0x0ff);
buffer[nStartIndex + 5] = (byte) ((lValue >>> 16) & 0x0ff);
buffer[nStartIndex + 6] = (byte) ((lValue >>> 8) & 0x0ff);
buffer[nStartIndex + 7] = (byte) lValue;
} | [
"public",
"static",
"void",
"longToByteArray",
"(",
"long",
"lValue",
",",
"byte",
"[",
"]",
"buffer",
",",
"int",
"nStartIndex",
")",
"{",
"buffer",
"[",
"nStartIndex",
"]",
"=",
"(",
"byte",
")",
"(",
"lValue",
">>>",
"56",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"1",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"48",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"2",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"40",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"3",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"32",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"4",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"24",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"5",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"16",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"6",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"lValue",
">>>",
"8",
")",
"&",
"0x0ff",
")",
";",
"buffer",
"[",
"nStartIndex",
"+",
"7",
"]",
"=",
"(",
"byte",
")",
"lValue",
";",
"}"
] | converts a long o bytes which are put into a given array
@param lValue the 64bit integer to convert
@param buffer the target buffer
@param nStartIndex where to place the bytes in the buffer | [
"converts",
"a",
"long",
"o",
"bytes",
"which",
"are",
"put",
"into",
"a",
"given",
"array"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/crypt/BinConverter.java#L45-L54 |
JavaMoney/jsr354-ri-bp | src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java | MonetaryFunctions.sortValiableDesc | @Deprecated
public static Comparator<? super MonetaryAmount> sortValiableDesc(
final ExchangeRateProvider provider) {
"""
Descending order of
{@link MonetaryFunctions#sortValuable(ExchangeRateProvider)}
@param provider the rate provider to be used.
@return the Descending order of
{@link MonetaryFunctions#sortValuable(ExchangeRateProvider)}
@deprecated Use #sortValiableDesc instead of.
"""
return new Comparator<MonetaryAmount>() {
@Override
public int compare(MonetaryAmount o1, MonetaryAmount o2) {
return sortValuable(provider).compare(o1, o2) * -1;
}
};
} | java | @Deprecated
public static Comparator<? super MonetaryAmount> sortValiableDesc(
final ExchangeRateProvider provider) {
return new Comparator<MonetaryAmount>() {
@Override
public int compare(MonetaryAmount o1, MonetaryAmount o2) {
return sortValuable(provider).compare(o1, o2) * -1;
}
};
} | [
"@",
"Deprecated",
"public",
"static",
"Comparator",
"<",
"?",
"super",
"MonetaryAmount",
">",
"sortValiableDesc",
"(",
"final",
"ExchangeRateProvider",
"provider",
")",
"{",
"return",
"new",
"Comparator",
"<",
"MonetaryAmount",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"MonetaryAmount",
"o1",
",",
"MonetaryAmount",
"o2",
")",
"{",
"return",
"sortValuable",
"(",
"provider",
")",
".",
"compare",
"(",
"o1",
",",
"o2",
")",
"*",
"-",
"1",
";",
"}",
"}",
";",
"}"
] | Descending order of
{@link MonetaryFunctions#sortValuable(ExchangeRateProvider)}
@param provider the rate provider to be used.
@return the Descending order of
{@link MonetaryFunctions#sortValuable(ExchangeRateProvider)}
@deprecated Use #sortValiableDesc instead of. | [
"Descending",
"order",
"of",
"{"
] | train | https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java#L116-L125 |
OpenLiberty/open-liberty | dev/com.ibm.ws.tx.embeddable/src/com/ibm/tx/jta/embeddable/impl/EmbeddableTransactionImpl.java | EmbeddableTransactionImpl.enlistAsyncResource | @Override
public void enlistAsyncResource(String xaResFactoryFilter, Serializable xaResInfo, Xid xid) throws SystemException // @LIDB1922-5C {
"""
Enlist an asynchronous resource with the target TransactionImpl object.
A WSATParticipantWrapper is typically a representation of a downstream WSAT
subordinate server.
@param asyncResource the remote WSATParticipantWrapper
"""
if (tc.isEntryEnabled())
Tr.entry(tc, "enlistAsyncResource (SPI): args: ", new Object[] { xaResFactoryFilter, xaResInfo, xid });
try {
final WSATAsyncResource res = new WSATAsyncResource(xaResFactoryFilter, xaResInfo, xid);
final WSATParticipantWrapper wrapper = new WSATParticipantWrapper(res);
getResources().addAsyncResource(wrapper);
} finally {
if (tc.isEntryEnabled())
Tr.exit(tc, "enlistAsyncResource (SPI)");
}
} | java | @Override
public void enlistAsyncResource(String xaResFactoryFilter, Serializable xaResInfo, Xid xid) throws SystemException // @LIDB1922-5C
{
if (tc.isEntryEnabled())
Tr.entry(tc, "enlistAsyncResource (SPI): args: ", new Object[] { xaResFactoryFilter, xaResInfo, xid });
try {
final WSATAsyncResource res = new WSATAsyncResource(xaResFactoryFilter, xaResInfo, xid);
final WSATParticipantWrapper wrapper = new WSATParticipantWrapper(res);
getResources().addAsyncResource(wrapper);
} finally {
if (tc.isEntryEnabled())
Tr.exit(tc, "enlistAsyncResource (SPI)");
}
} | [
"@",
"Override",
"public",
"void",
"enlistAsyncResource",
"(",
"String",
"xaResFactoryFilter",
",",
"Serializable",
"xaResInfo",
",",
"Xid",
"xid",
")",
"throws",
"SystemException",
"// @LIDB1922-5C",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"enlistAsyncResource (SPI): args: \"",
",",
"new",
"Object",
"[",
"]",
"{",
"xaResFactoryFilter",
",",
"xaResInfo",
",",
"xid",
"}",
")",
";",
"try",
"{",
"final",
"WSATAsyncResource",
"res",
"=",
"new",
"WSATAsyncResource",
"(",
"xaResFactoryFilter",
",",
"xaResInfo",
",",
"xid",
")",
";",
"final",
"WSATParticipantWrapper",
"wrapper",
"=",
"new",
"WSATParticipantWrapper",
"(",
"res",
")",
";",
"getResources",
"(",
")",
".",
"addAsyncResource",
"(",
"wrapper",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"enlistAsyncResource (SPI)\"",
")",
";",
"}",
"}"
] | Enlist an asynchronous resource with the target TransactionImpl object.
A WSATParticipantWrapper is typically a representation of a downstream WSAT
subordinate server.
@param asyncResource the remote WSATParticipantWrapper | [
"Enlist",
"an",
"asynchronous",
"resource",
"with",
"the",
"target",
"TransactionImpl",
"object",
".",
"A",
"WSATParticipantWrapper",
"is",
"typically",
"a",
"representation",
"of",
"a",
"downstream",
"WSAT",
"subordinate",
"server",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.tx.embeddable/src/com/ibm/tx/jta/embeddable/impl/EmbeddableTransactionImpl.java#L573-L586 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/multithreading/AbstractDataBinder.java | AbstractDataBinder.cacheData | private void cacheData(@NonNull final KeyType key, @NonNull final DataType data) {
"""
Adds the data, which corresponds to a specific key, to the cache, if caching is enabled.
@param key
The key of the data, which should be added to the cache, as an instance of the
generic type KeyType. The key may not be null
@param data
The data, which should be added to the cache, as an instance of the generic type
DataType. The data may not be null
"""
synchronized (cache) {
if (useCache) {
cache.put(key, data);
}
}
} | java | private void cacheData(@NonNull final KeyType key, @NonNull final DataType data) {
synchronized (cache) {
if (useCache) {
cache.put(key, data);
}
}
} | [
"private",
"void",
"cacheData",
"(",
"@",
"NonNull",
"final",
"KeyType",
"key",
",",
"@",
"NonNull",
"final",
"DataType",
"data",
")",
"{",
"synchronized",
"(",
"cache",
")",
"{",
"if",
"(",
"useCache",
")",
"{",
"cache",
".",
"put",
"(",
"key",
",",
"data",
")",
";",
"}",
"}",
"}"
] | Adds the data, which corresponds to a specific key, to the cache, if caching is enabled.
@param key
The key of the data, which should be added to the cache, as an instance of the
generic type KeyType. The key may not be null
@param data
The data, which should be added to the cache, as an instance of the generic type
DataType. The data may not be null | [
"Adds",
"the",
"data",
"which",
"corresponds",
"to",
"a",
"specific",
"key",
"to",
"the",
"cache",
"if",
"caching",
"is",
"enabled",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/multithreading/AbstractDataBinder.java#L334-L340 |
DiUS/pact-jvm | pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java | PactDslJsonArray.stringMatcher | public PactDslJsonArray stringMatcher(String regex, String value) {
"""
Element that must match the regular expression
@param regex regular expression
@param value example value to use for generated bodies
"""
if (!value.matches(regex)) {
throw new InvalidMatcherException(EXAMPLE + value + "\" does not match regular expression \"" +
regex + "\"");
}
body.put(value);
matchers.addRule(rootPath + appendArrayIndex(0), regexp(regex));
return this;
} | java | public PactDslJsonArray stringMatcher(String regex, String value) {
if (!value.matches(regex)) {
throw new InvalidMatcherException(EXAMPLE + value + "\" does not match regular expression \"" +
regex + "\"");
}
body.put(value);
matchers.addRule(rootPath + appendArrayIndex(0), regexp(regex));
return this;
} | [
"public",
"PactDslJsonArray",
"stringMatcher",
"(",
"String",
"regex",
",",
"String",
"value",
")",
"{",
"if",
"(",
"!",
"value",
".",
"matches",
"(",
"regex",
")",
")",
"{",
"throw",
"new",
"InvalidMatcherException",
"(",
"EXAMPLE",
"+",
"value",
"+",
"\"\\\" does not match regular expression \\\"\"",
"+",
"regex",
"+",
"\"\\\"\"",
")",
";",
"}",
"body",
".",
"put",
"(",
"value",
")",
";",
"matchers",
".",
"addRule",
"(",
"rootPath",
"+",
"appendArrayIndex",
"(",
"0",
")",
",",
"regexp",
"(",
"regex",
")",
")",
";",
"return",
"this",
";",
"}"
] | Element that must match the regular expression
@param regex regular expression
@param value example value to use for generated bodies | [
"Element",
"that",
"must",
"match",
"the",
"regular",
"expression"
] | train | https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L419-L427 |
graphql-java/java-dataloader | src/main/java/org/dataloader/DataLoader.java | DataLoader.newDataLoaderWithTry | public static <K, V> DataLoader<K, V> newDataLoaderWithTry(BatchLoader<K, Try<V>> batchLoadFunction) {
"""
Creates new DataLoader with the specified batch loader function and default options
(batching, caching and unlimited batch size) where the batch loader function returns a list of
{@link org.dataloader.Try} objects.
<p>
If its important you to know the exact status of each item in a batch call and whether it threw exceptions then
you can use this form to create the data loader.
<p>
Using Try objects allows you to capture a value returned or an exception that might
have occurred trying to get a value. .
@param batchLoadFunction the batch load function to use that uses {@link org.dataloader.Try} objects
@param <K> the key type
@param <V> the value type
@return a new DataLoader
"""
return newDataLoaderWithTry(batchLoadFunction, null);
} | java | public static <K, V> DataLoader<K, V> newDataLoaderWithTry(BatchLoader<K, Try<V>> batchLoadFunction) {
return newDataLoaderWithTry(batchLoadFunction, null);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"DataLoader",
"<",
"K",
",",
"V",
">",
"newDataLoaderWithTry",
"(",
"BatchLoader",
"<",
"K",
",",
"Try",
"<",
"V",
">",
">",
"batchLoadFunction",
")",
"{",
"return",
"newDataLoaderWithTry",
"(",
"batchLoadFunction",
",",
"null",
")",
";",
"}"
] | Creates new DataLoader with the specified batch loader function and default options
(batching, caching and unlimited batch size) where the batch loader function returns a list of
{@link org.dataloader.Try} objects.
<p>
If its important you to know the exact status of each item in a batch call and whether it threw exceptions then
you can use this form to create the data loader.
<p>
Using Try objects allows you to capture a value returned or an exception that might
have occurred trying to get a value. .
@param batchLoadFunction the batch load function to use that uses {@link org.dataloader.Try} objects
@param <K> the key type
@param <V> the value type
@return a new DataLoader | [
"Creates",
"new",
"DataLoader",
"with",
"the",
"specified",
"batch",
"loader",
"function",
"and",
"default",
"options",
"(",
"batching",
"caching",
"and",
"unlimited",
"batch",
"size",
")",
"where",
"the",
"batch",
"loader",
"function",
"returns",
"a",
"list",
"of",
"{",
"@link",
"org",
".",
"dataloader",
".",
"Try",
"}",
"objects",
".",
"<p",
">",
"If",
"its",
"important",
"you",
"to",
"know",
"the",
"exact",
"status",
"of",
"each",
"item",
"in",
"a",
"batch",
"call",
"and",
"whether",
"it",
"threw",
"exceptions",
"then",
"you",
"can",
"use",
"this",
"form",
"to",
"create",
"the",
"data",
"loader",
".",
"<p",
">",
"Using",
"Try",
"objects",
"allows",
"you",
"to",
"capture",
"a",
"value",
"returned",
"or",
"an",
"exception",
"that",
"might",
"have",
"occurred",
"trying",
"to",
"get",
"a",
"value",
".",
"."
] | train | https://github.com/graphql-java/java-dataloader/blob/dfdc8133ead10aa723f896b4a1fa4a1cec9a6fbc/src/main/java/org/dataloader/DataLoader.java#L109-L111 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/db/InstanceQuery.java | InstanceQuery.executeOneCompleteStmt | protected boolean executeOneCompleteStmt(final String _complStmt)
throws EFapsException {
"""
Execute the actual statement against the database.
@param _complStmt Statment to be executed
@return true if executed with success
@throws EFapsException on error
"""
final boolean ret = false;
ConnectionResource con = null;
try {
con = Context.getThreadContext().getConnectionResource();
AbstractObjectQuery.LOG.debug("Executing SQL: {}", _complStmt);
final Statement stmt = con.createStatement();
final ResultSet rs = stmt.executeQuery(_complStmt.toString());
final List<Object[]> values = new ArrayList<>();
while (rs.next()) {
final long id = rs.getLong(1);
Long typeId = null;
if (getBaseType().getMainTable().getSqlColType() != null) {
typeId = rs.getLong(2);
}
values.add(new Object[]{id, typeId});
}
rs.close();
stmt.close();
for (final Object[] row: values) {
final Long id = (Long) row[0];
final Long typeId = (Long) row[1];
getValues().add(Instance.get(typeId == null ? getBaseType() : Type.get(typeId), id));
}
} catch (final SQLException e) {
throw new EFapsException(InstanceQuery.class, "executeOneCompleteStmt", e);
}
return ret;
} | java | protected boolean executeOneCompleteStmt(final String _complStmt)
throws EFapsException
{
final boolean ret = false;
ConnectionResource con = null;
try {
con = Context.getThreadContext().getConnectionResource();
AbstractObjectQuery.LOG.debug("Executing SQL: {}", _complStmt);
final Statement stmt = con.createStatement();
final ResultSet rs = stmt.executeQuery(_complStmt.toString());
final List<Object[]> values = new ArrayList<>();
while (rs.next()) {
final long id = rs.getLong(1);
Long typeId = null;
if (getBaseType().getMainTable().getSqlColType() != null) {
typeId = rs.getLong(2);
}
values.add(new Object[]{id, typeId});
}
rs.close();
stmt.close();
for (final Object[] row: values) {
final Long id = (Long) row[0];
final Long typeId = (Long) row[1];
getValues().add(Instance.get(typeId == null ? getBaseType() : Type.get(typeId), id));
}
} catch (final SQLException e) {
throw new EFapsException(InstanceQuery.class, "executeOneCompleteStmt", e);
}
return ret;
} | [
"protected",
"boolean",
"executeOneCompleteStmt",
"(",
"final",
"String",
"_complStmt",
")",
"throws",
"EFapsException",
"{",
"final",
"boolean",
"ret",
"=",
"false",
";",
"ConnectionResource",
"con",
"=",
"null",
";",
"try",
"{",
"con",
"=",
"Context",
".",
"getThreadContext",
"(",
")",
".",
"getConnectionResource",
"(",
")",
";",
"AbstractObjectQuery",
".",
"LOG",
".",
"debug",
"(",
"\"Executing SQL: {}\"",
",",
"_complStmt",
")",
";",
"final",
"Statement",
"stmt",
"=",
"con",
".",
"createStatement",
"(",
")",
";",
"final",
"ResultSet",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"_complStmt",
".",
"toString",
"(",
")",
")",
";",
"final",
"List",
"<",
"Object",
"[",
"]",
">",
"values",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"final",
"long",
"id",
"=",
"rs",
".",
"getLong",
"(",
"1",
")",
";",
"Long",
"typeId",
"=",
"null",
";",
"if",
"(",
"getBaseType",
"(",
")",
".",
"getMainTable",
"(",
")",
".",
"getSqlColType",
"(",
")",
"!=",
"null",
")",
"{",
"typeId",
"=",
"rs",
".",
"getLong",
"(",
"2",
")",
";",
"}",
"values",
".",
"add",
"(",
"new",
"Object",
"[",
"]",
"{",
"id",
",",
"typeId",
"}",
")",
";",
"}",
"rs",
".",
"close",
"(",
")",
";",
"stmt",
".",
"close",
"(",
")",
";",
"for",
"(",
"final",
"Object",
"[",
"]",
"row",
":",
"values",
")",
"{",
"final",
"Long",
"id",
"=",
"(",
"Long",
")",
"row",
"[",
"0",
"]",
";",
"final",
"Long",
"typeId",
"=",
"(",
"Long",
")",
"row",
"[",
"1",
"]",
";",
"getValues",
"(",
")",
".",
"add",
"(",
"Instance",
".",
"get",
"(",
"typeId",
"==",
"null",
"?",
"getBaseType",
"(",
")",
":",
"Type",
".",
"get",
"(",
"typeId",
")",
",",
"id",
")",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"EFapsException",
"(",
"InstanceQuery",
".",
"class",
",",
"\"executeOneCompleteStmt\"",
",",
"e",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Execute the actual statement against the database.
@param _complStmt Statment to be executed
@return true if executed with success
@throws EFapsException on error | [
"Execute",
"the",
"actual",
"statement",
"against",
"the",
"database",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/InstanceQuery.java#L131-L164 |
spring-projects/spring-plugin | core/src/main/java/org/springframework/plugin/core/support/AbstractTypeAwareSupport.java | AbstractTypeAwareSupport.getBeans | @SuppressWarnings("unchecked")
protected List<T> getBeans() {
"""
Returns all beans from the {@link ApplicationContext} that match the given type.
@return
"""
TargetSource targetSource = this.targetSource;
if (targetSource == null) {
throw new IllegalStateException("Traget source not initialized!");
}
ProxyFactory factory = new ProxyFactory(List.class, targetSource);
return (List<T>) factory.getProxy();
} | java | @SuppressWarnings("unchecked")
protected List<T> getBeans() {
TargetSource targetSource = this.targetSource;
if (targetSource == null) {
throw new IllegalStateException("Traget source not initialized!");
}
ProxyFactory factory = new ProxyFactory(List.class, targetSource);
return (List<T>) factory.getProxy();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"List",
"<",
"T",
">",
"getBeans",
"(",
")",
"{",
"TargetSource",
"targetSource",
"=",
"this",
".",
"targetSource",
";",
"if",
"(",
"targetSource",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Traget source not initialized!\"",
")",
";",
"}",
"ProxyFactory",
"factory",
"=",
"new",
"ProxyFactory",
"(",
"List",
".",
"class",
",",
"targetSource",
")",
";",
"return",
"(",
"List",
"<",
"T",
">",
")",
"factory",
".",
"getProxy",
"(",
")",
";",
"}"
] | Returns all beans from the {@link ApplicationContext} that match the given type.
@return | [
"Returns",
"all",
"beans",
"from",
"the",
"{",
"@link",
"ApplicationContext",
"}",
"that",
"match",
"the",
"given",
"type",
"."
] | train | https://github.com/spring-projects/spring-plugin/blob/953d2ce12f05f26444fbb3bf21011f538f729868/core/src/main/java/org/springframework/plugin/core/support/AbstractTypeAwareSupport.java#L83-L95 |
CloudSlang/cs-actions | cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java | VmService.listVMsAndTemplates | public Map<String, String> listVMsAndTemplates(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
"""
Method used to connect to data center to retrieve a list with all the virtual machines and templates within.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted data center
@param delimiter String that represents the delimiter needed in the result list
@return Map with String as key and value that contains returnCode of the operation, a list that contains all the
virtual machines and templates within the data center or failure message and the exception if there is one
@throws Exception
"""
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
Map<String, ManagedObjectReference> virtualMachinesMorMap = new MorObjectHandler()
.getSpecificObjectsMap(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue());
Set<String> virtualMachineNamesList = virtualMachinesMorMap.keySet();
if (virtualMachineNamesList.size() > 0) {
return ResponseUtils.getResultsMap(ResponseUtils
.getResponseStringFromCollection(virtualMachineNamesList, delimiter), Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("No VM found in datacenter.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | java | public Map<String, String> listVMsAndTemplates(HttpInputs httpInputs, VmInputs vmInputs, String delimiter) throws Exception {
ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
try {
Map<String, ManagedObjectReference> virtualMachinesMorMap = new MorObjectHandler()
.getSpecificObjectsMap(connectionResources, ManagedObjectType.VIRTUAL_MACHINE.getValue());
Set<String> virtualMachineNamesList = virtualMachinesMorMap.keySet();
if (virtualMachineNamesList.size() > 0) {
return ResponseUtils.getResultsMap(ResponseUtils
.getResponseStringFromCollection(virtualMachineNamesList, delimiter), Outputs.RETURN_CODE_SUCCESS);
} else {
return ResponseUtils.getResultsMap("No VM found in datacenter.", Outputs.RETURN_CODE_FAILURE);
}
} catch (Exception ex) {
return ResponseUtils.getResultsMap(ex.toString(), Outputs.RETURN_CODE_FAILURE);
} finally {
if (httpInputs.isCloseSession()) {
connectionResources.getConnection().disconnect();
clearConnectionFromContext(httpInputs.getGlobalSessionObject());
}
}
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"listVMsAndTemplates",
"(",
"HttpInputs",
"httpInputs",
",",
"VmInputs",
"vmInputs",
",",
"String",
"delimiter",
")",
"throws",
"Exception",
"{",
"ConnectionResources",
"connectionResources",
"=",
"new",
"ConnectionResources",
"(",
"httpInputs",
",",
"vmInputs",
")",
";",
"try",
"{",
"Map",
"<",
"String",
",",
"ManagedObjectReference",
">",
"virtualMachinesMorMap",
"=",
"new",
"MorObjectHandler",
"(",
")",
".",
"getSpecificObjectsMap",
"(",
"connectionResources",
",",
"ManagedObjectType",
".",
"VIRTUAL_MACHINE",
".",
"getValue",
"(",
")",
")",
";",
"Set",
"<",
"String",
">",
"virtualMachineNamesList",
"=",
"virtualMachinesMorMap",
".",
"keySet",
"(",
")",
";",
"if",
"(",
"virtualMachineNamesList",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"return",
"ResponseUtils",
".",
"getResultsMap",
"(",
"ResponseUtils",
".",
"getResponseStringFromCollection",
"(",
"virtualMachineNamesList",
",",
"delimiter",
")",
",",
"Outputs",
".",
"RETURN_CODE_SUCCESS",
")",
";",
"}",
"else",
"{",
"return",
"ResponseUtils",
".",
"getResultsMap",
"(",
"\"No VM found in datacenter.\"",
",",
"Outputs",
".",
"RETURN_CODE_FAILURE",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"return",
"ResponseUtils",
".",
"getResultsMap",
"(",
"ex",
".",
"toString",
"(",
")",
",",
"Outputs",
".",
"RETURN_CODE_FAILURE",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"httpInputs",
".",
"isCloseSession",
"(",
")",
")",
"{",
"connectionResources",
".",
"getConnection",
"(",
")",
".",
"disconnect",
"(",
")",
";",
"clearConnectionFromContext",
"(",
"httpInputs",
".",
"getGlobalSessionObject",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Method used to connect to data center to retrieve a list with all the virtual machines and templates within.
@param httpInputs Object that has all the inputs necessary to made a connection to data center
@param vmInputs Object that has all the specific inputs necessary to identify the targeted data center
@param delimiter String that represents the delimiter needed in the result list
@return Map with String as key and value that contains returnCode of the operation, a list that contains all the
virtual machines and templates within the data center or failure message and the exception if there is one
@throws Exception | [
"Method",
"used",
"to",
"connect",
"to",
"data",
"center",
"to",
"retrieve",
"a",
"list",
"with",
"all",
"the",
"virtual",
"machines",
"and",
"templates",
"within",
"."
] | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/services/VmService.java#L218-L239 |
loadimpact/loadimpact-sdk-java | src/main/java/com/loadimpact/ApiTokenClient.java | ApiTokenClient.setDebug | public ApiTokenClient setDebug(boolean debug, int maxEntitySize, Logger log) {
"""
Enables REQ/RES debug logging. This method re-configures the web-target, via {@link #configure(String, boolean,
java.util.logging.Logger, int)}.
@param debug true for logging
@param maxEntitySize max number of chars for dumping the content of an entity (e.g. response body)
@param log non-standard log stream
@return itself (for chaining)
"""
wsBase = configure(apiToken, debug, log, maxEntitySize);
return this;
} | java | public ApiTokenClient setDebug(boolean debug, int maxEntitySize, Logger log) {
wsBase = configure(apiToken, debug, log, maxEntitySize);
return this;
} | [
"public",
"ApiTokenClient",
"setDebug",
"(",
"boolean",
"debug",
",",
"int",
"maxEntitySize",
",",
"Logger",
"log",
")",
"{",
"wsBase",
"=",
"configure",
"(",
"apiToken",
",",
"debug",
",",
"log",
",",
"maxEntitySize",
")",
";",
"return",
"this",
";",
"}"
] | Enables REQ/RES debug logging. This method re-configures the web-target, via {@link #configure(String, boolean,
java.util.logging.Logger, int)}.
@param debug true for logging
@param maxEntitySize max number of chars for dumping the content of an entity (e.g. response body)
@param log non-standard log stream
@return itself (for chaining) | [
"Enables",
"REQ",
"/",
"RES",
"debug",
"logging",
".",
"This",
"method",
"re",
"-",
"configures",
"the",
"web",
"-",
"target",
"via",
"{",
"@link",
"#configure",
"(",
"String",
"boolean",
"java",
".",
"util",
".",
"logging",
".",
"Logger",
"int",
")",
"}",
"."
] | train | https://github.com/loadimpact/loadimpact-sdk-java/blob/49af80b768c5453266414108b0d30a0fc01b8cef/src/main/java/com/loadimpact/ApiTokenClient.java#L173-L176 |
amzn/ion-java | src/com/amazon/ion/util/IonStreamUtils.java | IonStreamUtils.writeFloatList | public static void writeFloatList(IonWriter writer, float[] values)
throws IOException {
"""
writes an IonList with a series of IonFloat values. This
starts a List, writes the values (without any annoations)
and closes the list. For text and tree writers this is
just a convienience, but for the binary writer it can be
optimized internally. Note that since, currently, IonFloat
is a 64 bit float this is a helper that simply casts
the passed in floats to double before writing them.
@param values 32 bit float values to populate the lists IonFloat's with
"""
if (writer instanceof _Private_ListWriter) {
((_Private_ListWriter)writer).writeFloatList(values);
return;
}
writer.stepIn(IonType.LIST);
for (int ii=0; ii<values.length; ii++) {
writer.writeFloat(values[ii]);
}
writer.stepOut();
} | java | public static void writeFloatList(IonWriter writer, float[] values)
throws IOException
{
if (writer instanceof _Private_ListWriter) {
((_Private_ListWriter)writer).writeFloatList(values);
return;
}
writer.stepIn(IonType.LIST);
for (int ii=0; ii<values.length; ii++) {
writer.writeFloat(values[ii]);
}
writer.stepOut();
} | [
"public",
"static",
"void",
"writeFloatList",
"(",
"IonWriter",
"writer",
",",
"float",
"[",
"]",
"values",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"instanceof",
"_Private_ListWriter",
")",
"{",
"(",
"(",
"_Private_ListWriter",
")",
"writer",
")",
".",
"writeFloatList",
"(",
"values",
")",
";",
"return",
";",
"}",
"writer",
".",
"stepIn",
"(",
"IonType",
".",
"LIST",
")",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"values",
".",
"length",
";",
"ii",
"++",
")",
"{",
"writer",
".",
"writeFloat",
"(",
"values",
"[",
"ii",
"]",
")",
";",
"}",
"writer",
".",
"stepOut",
"(",
")",
";",
"}"
] | writes an IonList with a series of IonFloat values. This
starts a List, writes the values (without any annoations)
and closes the list. For text and tree writers this is
just a convienience, but for the binary writer it can be
optimized internally. Note that since, currently, IonFloat
is a 64 bit float this is a helper that simply casts
the passed in floats to double before writing them.
@param values 32 bit float values to populate the lists IonFloat's with | [
"writes",
"an",
"IonList",
"with",
"a",
"series",
"of",
"IonFloat",
"values",
".",
"This",
"starts",
"a",
"List",
"writes",
"the",
"values",
"(",
"without",
"any",
"annoations",
")",
"and",
"closes",
"the",
"list",
".",
"For",
"text",
"and",
"tree",
"writers",
"this",
"is",
"just",
"a",
"convienience",
"but",
"for",
"the",
"binary",
"writer",
"it",
"can",
"be",
"optimized",
"internally",
".",
"Note",
"that",
"since",
"currently",
"IonFloat",
"is",
"a",
"64",
"bit",
"float",
"this",
"is",
"a",
"helper",
"that",
"simply",
"casts",
"the",
"passed",
"in",
"floats",
"to",
"double",
"before",
"writing",
"them",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonStreamUtils.java#L163-L176 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java | CommerceSubscriptionEntryPersistenceImpl.fetchByUUID_G | @Override
public CommerceSubscriptionEntry fetchByUUID_G(String uuid, long groupId) {
"""
Returns the commerce subscription entry where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce subscription entry, or <code>null</code> if a matching commerce subscription entry could not be found
"""
return fetchByUUID_G(uuid, groupId, true);
} | java | @Override
public CommerceSubscriptionEntry fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | [
"@",
"Override",
"public",
"CommerceSubscriptionEntry",
"fetchByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"{",
"return",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
",",
"true",
")",
";",
"}"
] | Returns the commerce subscription entry where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching commerce subscription entry, or <code>null</code> if a matching commerce subscription entry could not be found | [
"Returns",
"the",
"commerce",
"subscription",
"entry",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
"finder",
"cache",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java#L711-L714 |
axibase/atsd-api-java | src/main/java/com/axibase/tsd/client/MetaDataService.java | MetaDataService.deleteGroupEntities | public boolean deleteGroupEntities(String entityGroupName, Entity... entities) {
"""
Delete entities from entity group.
@param entityGroupName Entity group name.
@param entities Entities to replace. @return {@code true} if entities added.
@return is success
@throws AtsdClientException raised if there is any client problem
@throws AtsdServerException raised if there is any server problem
"""
checkEntityGroupIsEmpty(entityGroupName);
List<String> entitiesNames = new ArrayList<>();
for (Entity entity : entities) {
entitiesNames.add(entity.getName());
}
QueryPart<Entity> query = new Query<Entity>("entity-groups")
.path(entityGroupName, true)
.path("entities/delete");
return httpClientManager.updateMetaData(query, post(entitiesNames));
} | java | public boolean deleteGroupEntities(String entityGroupName, Entity... entities) {
checkEntityGroupIsEmpty(entityGroupName);
List<String> entitiesNames = new ArrayList<>();
for (Entity entity : entities) {
entitiesNames.add(entity.getName());
}
QueryPart<Entity> query = new Query<Entity>("entity-groups")
.path(entityGroupName, true)
.path("entities/delete");
return httpClientManager.updateMetaData(query, post(entitiesNames));
} | [
"public",
"boolean",
"deleteGroupEntities",
"(",
"String",
"entityGroupName",
",",
"Entity",
"...",
"entities",
")",
"{",
"checkEntityGroupIsEmpty",
"(",
"entityGroupName",
")",
";",
"List",
"<",
"String",
">",
"entitiesNames",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Entity",
"entity",
":",
"entities",
")",
"{",
"entitiesNames",
".",
"add",
"(",
"entity",
".",
"getName",
"(",
")",
")",
";",
"}",
"QueryPart",
"<",
"Entity",
">",
"query",
"=",
"new",
"Query",
"<",
"Entity",
">",
"(",
"\"entity-groups\"",
")",
".",
"path",
"(",
"entityGroupName",
",",
"true",
")",
".",
"path",
"(",
"\"entities/delete\"",
")",
";",
"return",
"httpClientManager",
".",
"updateMetaData",
"(",
"query",
",",
"post",
"(",
"entitiesNames",
")",
")",
";",
"}"
] | Delete entities from entity group.
@param entityGroupName Entity group name.
@param entities Entities to replace. @return {@code true} if entities added.
@return is success
@throws AtsdClientException raised if there is any client problem
@throws AtsdServerException raised if there is any server problem | [
"Delete",
"entities",
"from",
"entity",
"group",
"."
] | train | https://github.com/axibase/atsd-api-java/blob/63a0767d08b202dad2ebef4372ff947d6fba0246/src/main/java/com/axibase/tsd/client/MetaDataService.java#L555-L565 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/WebElementCreator.java | WebElementCreator.setLocation | private void setLocation(WebElement webElement, WebView webView, int x, int y, int width, int height ) {
"""
Sets the location of a {@code WebElement}
@param webElement the {@code TextView} object to set location
@param webView the {@code WebView} the text is shown in
@param x the x location to set
@param y the y location to set
@param width the width to set
@param height the height to set
"""
float scale = webView.getScale();
int[] locationOfWebViewXY = new int[2];
webView.getLocationOnScreen(locationOfWebViewXY);
int locationX = (int) (locationOfWebViewXY[0] + (x + (Math.floor(width / 2))) * scale);
int locationY = (int) (locationOfWebViewXY[1] + (y + (Math.floor(height / 2))) * scale);
webElement.setLocationX(locationX);
webElement.setLocationY(locationY);
} | java | private void setLocation(WebElement webElement, WebView webView, int x, int y, int width, int height ){
float scale = webView.getScale();
int[] locationOfWebViewXY = new int[2];
webView.getLocationOnScreen(locationOfWebViewXY);
int locationX = (int) (locationOfWebViewXY[0] + (x + (Math.floor(width / 2))) * scale);
int locationY = (int) (locationOfWebViewXY[1] + (y + (Math.floor(height / 2))) * scale);
webElement.setLocationX(locationX);
webElement.setLocationY(locationY);
} | [
"private",
"void",
"setLocation",
"(",
"WebElement",
"webElement",
",",
"WebView",
"webView",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"float",
"scale",
"=",
"webView",
".",
"getScale",
"(",
")",
";",
"int",
"[",
"]",
"locationOfWebViewXY",
"=",
"new",
"int",
"[",
"2",
"]",
";",
"webView",
".",
"getLocationOnScreen",
"(",
"locationOfWebViewXY",
")",
";",
"int",
"locationX",
"=",
"(",
"int",
")",
"(",
"locationOfWebViewXY",
"[",
"0",
"]",
"+",
"(",
"x",
"+",
"(",
"Math",
".",
"floor",
"(",
"width",
"/",
"2",
")",
")",
")",
"*",
"scale",
")",
";",
"int",
"locationY",
"=",
"(",
"int",
")",
"(",
"locationOfWebViewXY",
"[",
"1",
"]",
"+",
"(",
"y",
"+",
"(",
"Math",
".",
"floor",
"(",
"height",
"/",
"2",
")",
")",
")",
"*",
"scale",
")",
";",
"webElement",
".",
"setLocationX",
"(",
"locationX",
")",
";",
"webElement",
".",
"setLocationY",
"(",
"locationY",
")",
";",
"}"
] | Sets the location of a {@code WebElement}
@param webElement the {@code TextView} object to set location
@param webView the {@code WebView} the text is shown in
@param x the x location to set
@param y the y location to set
@param width the width to set
@param height the height to set | [
"Sets",
"the",
"location",
"of",
"a",
"{",
"@code",
"WebElement",
"}"
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/WebElementCreator.java#L103-L113 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.3/src/com/ibm/ws/microprofile/config13/sources/OSGiConfigUtils.java | OSGiConfigUtils.getApplicationPID | public static String getApplicationPID(BundleContext bundleContext, String applicationName) {
"""
Get the internal OSGi identifier for the Application with the given name
@param bundleContext The context to use to find the Application reference
@param applicationName The application name to look for
@return The application pid
"""
String applicationPID = null;
if (FrameworkState.isValid()) {
ServiceReference<?> appRef = getApplicationServiceRef(bundleContext, applicationName);
if (appRef != null) {
//not actually sure what the difference is between service.pid and ibm.extends.source.pid but this is the way it is done everywhere else!
applicationPID = (String) appRef.getProperty(Constants.SERVICE_PID);
String sourcePid = (String) appRef.getProperty("ibm.extends.source.pid");
if (sourcePid != null) {
applicationPID = sourcePid;
}
}
}
return applicationPID;
} | java | public static String getApplicationPID(BundleContext bundleContext, String applicationName) {
String applicationPID = null;
if (FrameworkState.isValid()) {
ServiceReference<?> appRef = getApplicationServiceRef(bundleContext, applicationName);
if (appRef != null) {
//not actually sure what the difference is between service.pid and ibm.extends.source.pid but this is the way it is done everywhere else!
applicationPID = (String) appRef.getProperty(Constants.SERVICE_PID);
String sourcePid = (String) appRef.getProperty("ibm.extends.source.pid");
if (sourcePid != null) {
applicationPID = sourcePid;
}
}
}
return applicationPID;
} | [
"public",
"static",
"String",
"getApplicationPID",
"(",
"BundleContext",
"bundleContext",
",",
"String",
"applicationName",
")",
"{",
"String",
"applicationPID",
"=",
"null",
";",
"if",
"(",
"FrameworkState",
".",
"isValid",
"(",
")",
")",
"{",
"ServiceReference",
"<",
"?",
">",
"appRef",
"=",
"getApplicationServiceRef",
"(",
"bundleContext",
",",
"applicationName",
")",
";",
"if",
"(",
"appRef",
"!=",
"null",
")",
"{",
"//not actually sure what the difference is between service.pid and ibm.extends.source.pid but this is the way it is done everywhere else!",
"applicationPID",
"=",
"(",
"String",
")",
"appRef",
".",
"getProperty",
"(",
"Constants",
".",
"SERVICE_PID",
")",
";",
"String",
"sourcePid",
"=",
"(",
"String",
")",
"appRef",
".",
"getProperty",
"(",
"\"ibm.extends.source.pid\"",
")",
";",
"if",
"(",
"sourcePid",
"!=",
"null",
")",
"{",
"applicationPID",
"=",
"sourcePid",
";",
"}",
"}",
"}",
"return",
"applicationPID",
";",
"}"
] | Get the internal OSGi identifier for the Application with the given name
@param bundleContext The context to use to find the Application reference
@param applicationName The application name to look for
@return The application pid | [
"Get",
"the",
"internal",
"OSGi",
"identifier",
"for",
"the",
"Application",
"with",
"the",
"given",
"name"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.3/src/com/ibm/ws/microprofile/config13/sources/OSGiConfigUtils.java#L192-L208 |
lisicnu/droidUtil | src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java | ShellUtils.execCommand | public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
"""
execute shell command
@param command command
@param isRoot whether need to run with root
@param isNeedResultMsg whether need result msg
@return
@see ShellUtils#execCommand(String[], boolean, boolean)
"""
return execCommand(new String[]{command}, isRoot, isNeedResultMsg);
} | java | public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
return execCommand(new String[]{command}, isRoot, isNeedResultMsg);
} | [
"public",
"static",
"CommandResult",
"execCommand",
"(",
"String",
"command",
",",
"boolean",
"isRoot",
",",
"boolean",
"isNeedResultMsg",
")",
"{",
"return",
"execCommand",
"(",
"new",
"String",
"[",
"]",
"{",
"command",
"}",
",",
"isRoot",
",",
"isNeedResultMsg",
")",
";",
"}"
] | execute shell command
@param command command
@param isRoot whether need to run with root
@param isNeedResultMsg whether need result msg
@return
@see ShellUtils#execCommand(String[], boolean, boolean) | [
"execute",
"shell",
"command"
] | train | https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java#L81-L83 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/BandwidthClient.java | BandwidthClient.buildMethod | protected HttpUriRequest buildMethod(final String method, final String path, final String params) {
"""
Helper method that builds the request to the server.
Only POST is supported currently since we have cases in the API
like token creation that accepts empty string payload "", instead of {}
@param method the method.
@param path the path.
@param params json string.
@return the request.
"""
if (StringUtils.equalsIgnoreCase(method, HttpPost.METHOD_NAME)) {
return generatePostRequest(path, params);
} else {
throw new RuntimeException(String.format("Method %s not supported.", method));
}
} | java | protected HttpUriRequest buildMethod(final String method, final String path, final String params) {
if (StringUtils.equalsIgnoreCase(method, HttpPost.METHOD_NAME)) {
return generatePostRequest(path, params);
} else {
throw new RuntimeException(String.format("Method %s not supported.", method));
}
} | [
"protected",
"HttpUriRequest",
"buildMethod",
"(",
"final",
"String",
"method",
",",
"final",
"String",
"path",
",",
"final",
"String",
"params",
")",
"{",
"if",
"(",
"StringUtils",
".",
"equalsIgnoreCase",
"(",
"method",
",",
"HttpPost",
".",
"METHOD_NAME",
")",
")",
"{",
"return",
"generatePostRequest",
"(",
"path",
",",
"params",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"Method %s not supported.\"",
",",
"method",
")",
")",
";",
"}",
"}"
] | Helper method that builds the request to the server.
Only POST is supported currently since we have cases in the API
like token creation that accepts empty string payload "", instead of {}
@param method the method.
@param path the path.
@param params json string.
@return the request. | [
"Helper",
"method",
"that",
"builds",
"the",
"request",
"to",
"the",
"server",
".",
"Only",
"POST",
"is",
"supported",
"currently",
"since",
"we",
"have",
"cases",
"in",
"the",
"API",
"like",
"token",
"creation",
"that",
"accepts",
"empty",
"string",
"payload",
"instead",
"of",
"{}"
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/BandwidthClient.java#L595-L601 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java | FileWriter.writeMap | public File writeMap(Map<?, ?> map, String kvSeparator, boolean isAppend) throws IORuntimeException {
"""
将Map写入文件,每个键值对为一行,一行中键与值之间使用kvSeparator分隔
@param map Map
@param kvSeparator 键和值之间的分隔符,如果传入null使用默认分隔符" = "
@param isAppend 是否追加
@return 目标文件
@throws IORuntimeException IO异常
@since 4.0.5
"""
return writeMap(map, null, kvSeparator, isAppend);
} | java | public File writeMap(Map<?, ?> map, String kvSeparator, boolean isAppend) throws IORuntimeException {
return writeMap(map, null, kvSeparator, isAppend);
} | [
"public",
"File",
"writeMap",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"map",
",",
"String",
"kvSeparator",
",",
"boolean",
"isAppend",
")",
"throws",
"IORuntimeException",
"{",
"return",
"writeMap",
"(",
"map",
",",
"null",
",",
"kvSeparator",
",",
"isAppend",
")",
";",
"}"
] | 将Map写入文件,每个键值对为一行,一行中键与值之间使用kvSeparator分隔
@param map Map
@param kvSeparator 键和值之间的分隔符,如果传入null使用默认分隔符" = "
@param isAppend 是否追加
@return 目标文件
@throws IORuntimeException IO异常
@since 4.0.5 | [
"将Map写入文件,每个键值对为一行,一行中键与值之间使用kvSeparator分隔"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java#L220-L222 |
jaliss/securesocial | module-code/app/securesocial/core/java/BaseUserService.java | BaseUserService.findByEmailAndProvider | @Override
public Future<Option<BasicProfile>> findByEmailAndProvider(String email, String providerId) {
"""
Finds an Identity by email and provider id.
Note: If you do not plan to use the UsernamePassword provider just provide en empty
implementation.
@param email - the user email
@param providerId - the provider id
@return
"""
return toScala(doFindByEmailAndProvider(email, providerId).thenApply(Scala::Option));
} | java | @Override
public Future<Option<BasicProfile>> findByEmailAndProvider(String email, String providerId) {
return toScala(doFindByEmailAndProvider(email, providerId).thenApply(Scala::Option));
} | [
"@",
"Override",
"public",
"Future",
"<",
"Option",
"<",
"BasicProfile",
">",
">",
"findByEmailAndProvider",
"(",
"String",
"email",
",",
"String",
"providerId",
")",
"{",
"return",
"toScala",
"(",
"doFindByEmailAndProvider",
"(",
"email",
",",
"providerId",
")",
".",
"thenApply",
"(",
"Scala",
"::",
"Option",
")",
")",
";",
"}"
] | Finds an Identity by email and provider id.
Note: If you do not plan to use the UsernamePassword provider just provide en empty
implementation.
@param email - the user email
@param providerId - the provider id
@return | [
"Finds",
"an",
"Identity",
"by",
"email",
"and",
"provider",
"id",
"."
] | train | https://github.com/jaliss/securesocial/blob/0f9710325724da34a46c5ecefb439121fce837b7/module-code/app/securesocial/core/java/BaseUserService.java#L60-L63 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java | UserAttrs.setIntAttribute | public static final void setIntAttribute(Path path, String attribute, int value, LinkOption... options) throws IOException {
"""
Set user-defined-attribute
@param path
@param attribute user:attribute name. user: can be omitted.. user: can be omitted.
@param value
@param options
@throws IOException
"""
attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute;
Files.setAttribute(path, attribute, Primitives.writeInt(value), options);
} | java | public static final void setIntAttribute(Path path, String attribute, int value, LinkOption... options) throws IOException
{
attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute;
Files.setAttribute(path, attribute, Primitives.writeInt(value), options);
} | [
"public",
"static",
"final",
"void",
"setIntAttribute",
"(",
"Path",
"path",
",",
"String",
"attribute",
",",
"int",
"value",
",",
"LinkOption",
"...",
"options",
")",
"throws",
"IOException",
"{",
"attribute",
"=",
"attribute",
".",
"startsWith",
"(",
"\"user:\"",
")",
"?",
"attribute",
":",
"\"user:\"",
"+",
"attribute",
";",
"Files",
".",
"setAttribute",
"(",
"path",
",",
"attribute",
",",
"Primitives",
".",
"writeInt",
"(",
"value",
")",
",",
"options",
")",
";",
"}"
] | Set user-defined-attribute
@param path
@param attribute user:attribute name. user: can be omitted.. user: can be omitted.
@param value
@param options
@throws IOException | [
"Set",
"user",
"-",
"defined",
"-",
"attribute"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java#L53-L57 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndexUtil.java | ClassReflectionIndexUtil.findRequiredMethod | public static Method findRequiredMethod(final DeploymentReflectionIndex deploymentReflectionIndex, final Class<?> clazz, final MethodIdentifier methodIdentifier) throws DeploymentUnitProcessingException {
"""
Finds and returns a method corresponding to the passed <code>methodIdentifier</code>.
The passed <code>classReflectionIndex</code> will be used to traverse the class hierarchy while finding the method.
<p/>
Throws {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} if no such method is found.
@param deploymentReflectionIndex The deployment reflection index
@param clazz The class to search
@param methodIdentifier The method identifier of the method being searched for
@return
@throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
If no such method is found
"""
Method method = findMethod(deploymentReflectionIndex, clazz, methodIdentifier);
if (method == null) {
throw ServerLogger.ROOT_LOGGER.noMethodFound(methodIdentifier, clazz);
}
return method;
} | java | public static Method findRequiredMethod(final DeploymentReflectionIndex deploymentReflectionIndex, final Class<?> clazz, final MethodIdentifier methodIdentifier) throws DeploymentUnitProcessingException {
Method method = findMethod(deploymentReflectionIndex, clazz, methodIdentifier);
if (method == null) {
throw ServerLogger.ROOT_LOGGER.noMethodFound(methodIdentifier, clazz);
}
return method;
} | [
"public",
"static",
"Method",
"findRequiredMethod",
"(",
"final",
"DeploymentReflectionIndex",
"deploymentReflectionIndex",
",",
"final",
"Class",
"<",
"?",
">",
"clazz",
",",
"final",
"MethodIdentifier",
"methodIdentifier",
")",
"throws",
"DeploymentUnitProcessingException",
"{",
"Method",
"method",
"=",
"findMethod",
"(",
"deploymentReflectionIndex",
",",
"clazz",
",",
"methodIdentifier",
")",
";",
"if",
"(",
"method",
"==",
"null",
")",
"{",
"throw",
"ServerLogger",
".",
"ROOT_LOGGER",
".",
"noMethodFound",
"(",
"methodIdentifier",
",",
"clazz",
")",
";",
"}",
"return",
"method",
";",
"}"
] | Finds and returns a method corresponding to the passed <code>methodIdentifier</code>.
The passed <code>classReflectionIndex</code> will be used to traverse the class hierarchy while finding the method.
<p/>
Throws {@link org.jboss.as.server.deployment.DeploymentUnitProcessingException} if no such method is found.
@param deploymentReflectionIndex The deployment reflection index
@param clazz The class to search
@param methodIdentifier The method identifier of the method being searched for
@return
@throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
If no such method is found | [
"Finds",
"and",
"returns",
"a",
"method",
"corresponding",
"to",
"the",
"passed",
"<code",
">",
"methodIdentifier<",
"/",
"code",
">",
".",
"The",
"passed",
"<code",
">",
"classReflectionIndex<",
"/",
"code",
">",
"will",
"be",
"used",
"to",
"traverse",
"the",
"class",
"hierarchy",
"while",
"finding",
"the",
"method",
".",
"<p",
"/",
">",
"Throws",
"{",
"@link",
"org",
".",
"jboss",
".",
"as",
".",
"server",
".",
"deployment",
".",
"DeploymentUnitProcessingException",
"}",
"if",
"no",
"such",
"method",
"is",
"found",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndexUtil.java#L97-L103 |
audit4j/audit4j-core | src/main/java/org/audit4j/core/handler/file/archive/AbstractArchiveJob.java | AbstractArchiveJob.fileCreatedDate | private Date fileCreatedDate(String fileName) {
"""
File created date.
@param fileName the file name
@return the date
"""
String[] splittedWithoutExtention = fileName.split(".");
String fileNameWithoutExtention = splittedWithoutExtention[0];
String[] splittedWithoutPrefix = fileNameWithoutExtention.split("-");
String fileNameDateInStr = splittedWithoutPrefix[1];
try {
return AuditUtil.stringTodate(fileNameDateInStr, "yyyy-MM-dd");
} catch (ParseException e) {
throw new Audit4jRuntimeException("Exception occured parsing the date.", e);
}
} | java | private Date fileCreatedDate(String fileName) {
String[] splittedWithoutExtention = fileName.split(".");
String fileNameWithoutExtention = splittedWithoutExtention[0];
String[] splittedWithoutPrefix = fileNameWithoutExtention.split("-");
String fileNameDateInStr = splittedWithoutPrefix[1];
try {
return AuditUtil.stringTodate(fileNameDateInStr, "yyyy-MM-dd");
} catch (ParseException e) {
throw new Audit4jRuntimeException("Exception occured parsing the date.", e);
}
} | [
"private",
"Date",
"fileCreatedDate",
"(",
"String",
"fileName",
")",
"{",
"String",
"[",
"]",
"splittedWithoutExtention",
"=",
"fileName",
".",
"split",
"(",
"\".\"",
")",
";",
"String",
"fileNameWithoutExtention",
"=",
"splittedWithoutExtention",
"[",
"0",
"]",
";",
"String",
"[",
"]",
"splittedWithoutPrefix",
"=",
"fileNameWithoutExtention",
".",
"split",
"(",
"\"-\"",
")",
";",
"String",
"fileNameDateInStr",
"=",
"splittedWithoutPrefix",
"[",
"1",
"]",
";",
"try",
"{",
"return",
"AuditUtil",
".",
"stringTodate",
"(",
"fileNameDateInStr",
",",
"\"yyyy-MM-dd\"",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"throw",
"new",
"Audit4jRuntimeException",
"(",
"\"Exception occured parsing the date.\"",
",",
"e",
")",
";",
"}",
"}"
] | File created date.
@param fileName the file name
@return the date | [
"File",
"created",
"date",
"."
] | train | https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/handler/file/archive/AbstractArchiveJob.java#L87-L97 |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getNavImageURL | public String getNavImageURL(WebSiteRequest req, HttpServletResponse resp, Object params) throws IOException, SQLException {
"""
Gets the URL associated with a nav image.
@see #getNavImageAlt
@see #getNavImageSuffix
"""
return resp.encodeURL(req.getContextPath()+req.getURL(this, params));
} | java | public String getNavImageURL(WebSiteRequest req, HttpServletResponse resp, Object params) throws IOException, SQLException {
return resp.encodeURL(req.getContextPath()+req.getURL(this, params));
} | [
"public",
"String",
"getNavImageURL",
"(",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"Object",
"params",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"return",
"resp",
".",
"encodeURL",
"(",
"req",
".",
"getContextPath",
"(",
")",
"+",
"req",
".",
"getURL",
"(",
"this",
",",
"params",
")",
")",
";",
"}"
] | Gets the URL associated with a nav image.
@see #getNavImageAlt
@see #getNavImageSuffix | [
"Gets",
"the",
"URL",
"associated",
"with",
"a",
"nav",
"image",
"."
] | train | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L674-L676 |
MTDdk/jawn | jawn-core/src/main/java/net/javapla/jawn/core/Controller.java | Controller.outputStream | public OutputStream outputStream(String contentType, Map<String, String> headers, int status) {
"""
Use to send raw data to HTTP client.
@param contentType content type
@param headers set of headers.
@param status status.
@return instance of output stream to send raw data directly to HTTP client.
"""
Result result = ResultBuilder.noBody(status).contentType(contentType);
headers.entrySet().forEach(header -> result.addHeader(header.getKey(), header.getValue()));
setControllerResult(result);
try {
//return context.responseOutputStream(); //TODO not possible, is it?
return context.responseOutputStream(result);
} catch(Exception e) {
throw new ControllerException(e);
}
} | java | public OutputStream outputStream(String contentType, Map<String, String> headers, int status) {
Result result = ResultBuilder.noBody(status).contentType(contentType);
headers.entrySet().forEach(header -> result.addHeader(header.getKey(), header.getValue()));
setControllerResult(result);
try {
//return context.responseOutputStream(); //TODO not possible, is it?
return context.responseOutputStream(result);
} catch(Exception e) {
throw new ControllerException(e);
}
} | [
"public",
"OutputStream",
"outputStream",
"(",
"String",
"contentType",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
",",
"int",
"status",
")",
"{",
"Result",
"result",
"=",
"ResultBuilder",
".",
"noBody",
"(",
"status",
")",
".",
"contentType",
"(",
"contentType",
")",
";",
"headers",
".",
"entrySet",
"(",
")",
".",
"forEach",
"(",
"header",
"->",
"result",
".",
"addHeader",
"(",
"header",
".",
"getKey",
"(",
")",
",",
"header",
".",
"getValue",
"(",
")",
")",
")",
";",
"setControllerResult",
"(",
"result",
")",
";",
"try",
"{",
"//return context.responseOutputStream(); //TODO not possible, is it?",
"return",
"context",
".",
"responseOutputStream",
"(",
"result",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ControllerException",
"(",
"e",
")",
";",
"}",
"}"
] | Use to send raw data to HTTP client.
@param contentType content type
@param headers set of headers.
@param status status.
@return instance of output stream to send raw data directly to HTTP client. | [
"Use",
"to",
"send",
"raw",
"data",
"to",
"HTTP",
"client",
"."
] | train | https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core/src/main/java/net/javapla/jawn/core/Controller.java#L1522-L1533 |
digipost/sdp-shared | api-commons/src/main/java/no/digipost/api/xml/MessagingMarshalling.java | MessagingMarshalling.getMessaging | public static Messaging getMessaging(final Jaxb2Marshaller jaxb2Marshaller, final WebServiceMessage message) {
"""
Enten returnerer denne et Messaging objekt, eller så kaster den en RuntimeException
"""
SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();
if (soapHeader == null) {
throw new RuntimeException("The ebMS header is missing (no SOAP header found in SOAP request)");
}
Iterator<SoapHeaderElement> soapHeaderElementIterator = soapHeader.examineHeaderElements(MESSAGING_QNAME);
if (!soapHeaderElementIterator.hasNext()) {
throw new RuntimeException("The ebMS header is missing in SOAP header");
}
SoapHeaderElement incomingSoapHeaderElement = soapHeaderElementIterator.next();
try {
return (Messaging) jaxb2Marshaller.unmarshal(incomingSoapHeaderElement.getSource());
} catch (Exception e) {
throw new RuntimeException("The ebMs header failed to unmarshall");
}
} | java | public static Messaging getMessaging(final Jaxb2Marshaller jaxb2Marshaller, final WebServiceMessage message) {
SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();
if (soapHeader == null) {
throw new RuntimeException("The ebMS header is missing (no SOAP header found in SOAP request)");
}
Iterator<SoapHeaderElement> soapHeaderElementIterator = soapHeader.examineHeaderElements(MESSAGING_QNAME);
if (!soapHeaderElementIterator.hasNext()) {
throw new RuntimeException("The ebMS header is missing in SOAP header");
}
SoapHeaderElement incomingSoapHeaderElement = soapHeaderElementIterator.next();
try {
return (Messaging) jaxb2Marshaller.unmarshal(incomingSoapHeaderElement.getSource());
} catch (Exception e) {
throw new RuntimeException("The ebMs header failed to unmarshall");
}
} | [
"public",
"static",
"Messaging",
"getMessaging",
"(",
"final",
"Jaxb2Marshaller",
"jaxb2Marshaller",
",",
"final",
"WebServiceMessage",
"message",
")",
"{",
"SoapHeader",
"soapHeader",
"=",
"(",
"(",
"SoapMessage",
")",
"message",
")",
".",
"getSoapHeader",
"(",
")",
";",
"if",
"(",
"soapHeader",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The ebMS header is missing (no SOAP header found in SOAP request)\"",
")",
";",
"}",
"Iterator",
"<",
"SoapHeaderElement",
">",
"soapHeaderElementIterator",
"=",
"soapHeader",
".",
"examineHeaderElements",
"(",
"MESSAGING_QNAME",
")",
";",
"if",
"(",
"!",
"soapHeaderElementIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The ebMS header is missing in SOAP header\"",
")",
";",
"}",
"SoapHeaderElement",
"incomingSoapHeaderElement",
"=",
"soapHeaderElementIterator",
".",
"next",
"(",
")",
";",
"try",
"{",
"return",
"(",
"Messaging",
")",
"jaxb2Marshaller",
".",
"unmarshal",
"(",
"incomingSoapHeaderElement",
".",
"getSource",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The ebMs header failed to unmarshall\"",
")",
";",
"}",
"}"
] | Enten returnerer denne et Messaging objekt, eller så kaster den en RuntimeException | [
"Enten",
"returnerer",
"denne",
"et",
"Messaging",
"objekt",
"eller",
"så",
"kaster",
"den",
"en",
"RuntimeException"
] | train | https://github.com/digipost/sdp-shared/blob/c34920a993b65ff0908dab9d9c92140ded7312bc/api-commons/src/main/java/no/digipost/api/xml/MessagingMarshalling.java#L19-L38 |
Erudika/para | para-server/src/main/java/com/erudika/para/rest/RestUtils.java | RestUtils.returnStatusResponse | public static void returnStatusResponse(HttpServletResponse response, int status, String message) {
"""
A generic JSON response handler. Returns a message and response code.
@param response the response to write to
@param status status code
@param message error message
"""
if (response == null) {
return;
}
PrintWriter out = null;
try {
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON);
out = response.getWriter();
ParaObjectUtils.getJsonWriter().writeValue(out, getStatusResponse(Response.Status.
fromStatusCode(status), message).getEntity());
} catch (Exception ex) {
logger.error(null, ex);
} finally {
if (out != null) {
out.close();
}
}
} | java | public static void returnStatusResponse(HttpServletResponse response, int status, String message) {
if (response == null) {
return;
}
PrintWriter out = null;
try {
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON);
out = response.getWriter();
ParaObjectUtils.getJsonWriter().writeValue(out, getStatusResponse(Response.Status.
fromStatusCode(status), message).getEntity());
} catch (Exception ex) {
logger.error(null, ex);
} finally {
if (out != null) {
out.close();
}
}
} | [
"public",
"static",
"void",
"returnStatusResponse",
"(",
"HttpServletResponse",
"response",
",",
"int",
"status",
",",
"String",
"message",
")",
"{",
"if",
"(",
"response",
"==",
"null",
")",
"{",
"return",
";",
"}",
"PrintWriter",
"out",
"=",
"null",
";",
"try",
"{",
"response",
".",
"setStatus",
"(",
"status",
")",
";",
"response",
".",
"setContentType",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
";",
"out",
"=",
"response",
".",
"getWriter",
"(",
")",
";",
"ParaObjectUtils",
".",
"getJsonWriter",
"(",
")",
".",
"writeValue",
"(",
"out",
",",
"getStatusResponse",
"(",
"Response",
".",
"Status",
".",
"fromStatusCode",
"(",
"status",
")",
",",
"message",
")",
".",
"getEntity",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"null",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"out",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | A generic JSON response handler. Returns a message and response code.
@param response the response to write to
@param status status code
@param message error message | [
"A",
"generic",
"JSON",
"response",
"handler",
".",
"Returns",
"a",
"message",
"and",
"response",
"code",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L942-L960 |
cdk/cdk | base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/UniqueBondMatches.java | UniqueBondMatches.toEdgeSet | private Set<Tuple> toEdgeSet(int[] mapping) {
"""
Convert a mapping to a bitset.
@param mapping an atom mapping
@return a bit set of the mapped vertices (values in array)
"""
Set<Tuple> edges = new HashSet<Tuple>(mapping.length * 2);
for (int u = 0; u < g.length; u++) {
for (int v : g[u]) {
edges.add(new Tuple(mapping[u], mapping[v]));
}
}
return edges;
} | java | private Set<Tuple> toEdgeSet(int[] mapping) {
Set<Tuple> edges = new HashSet<Tuple>(mapping.length * 2);
for (int u = 0; u < g.length; u++) {
for (int v : g[u]) {
edges.add(new Tuple(mapping[u], mapping[v]));
}
}
return edges;
} | [
"private",
"Set",
"<",
"Tuple",
">",
"toEdgeSet",
"(",
"int",
"[",
"]",
"mapping",
")",
"{",
"Set",
"<",
"Tuple",
">",
"edges",
"=",
"new",
"HashSet",
"<",
"Tuple",
">",
"(",
"mapping",
".",
"length",
"*",
"2",
")",
";",
"for",
"(",
"int",
"u",
"=",
"0",
";",
"u",
"<",
"g",
".",
"length",
";",
"u",
"++",
")",
"{",
"for",
"(",
"int",
"v",
":",
"g",
"[",
"u",
"]",
")",
"{",
"edges",
".",
"add",
"(",
"new",
"Tuple",
"(",
"mapping",
"[",
"u",
"]",
",",
"mapping",
"[",
"v",
"]",
")",
")",
";",
"}",
"}",
"return",
"edges",
";",
"}"
] | Convert a mapping to a bitset.
@param mapping an atom mapping
@return a bit set of the mapped vertices (values in array) | [
"Convert",
"a",
"mapping",
"to",
"a",
"bitset",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/UniqueBondMatches.java#L83-L91 |
google/closure-compiler | src/com/google/javascript/jscomp/TypeValidator.java | TypeValidator.expectNumber | void expectNumber(Node n, JSType type, String msg) {
"""
Expect the type to be a number, or a type convertible to number. If the expectation is not met,
issue a warning at the provided node's source code position.
"""
if (!type.matchesNumberContext()) {
mismatch(n, msg, type, NUMBER_TYPE);
} else {
expectNumberStrict(n, type, msg);
}
} | java | void expectNumber(Node n, JSType type, String msg) {
if (!type.matchesNumberContext()) {
mismatch(n, msg, type, NUMBER_TYPE);
} else {
expectNumberStrict(n, type, msg);
}
} | [
"void",
"expectNumber",
"(",
"Node",
"n",
",",
"JSType",
"type",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"!",
"type",
".",
"matchesNumberContext",
"(",
")",
")",
"{",
"mismatch",
"(",
"n",
",",
"msg",
",",
"type",
",",
"NUMBER_TYPE",
")",
";",
"}",
"else",
"{",
"expectNumberStrict",
"(",
"n",
",",
"type",
",",
"msg",
")",
";",
"}",
"}"
] | Expect the type to be a number, or a type convertible to number. If the expectation is not met,
issue a warning at the provided node's source code position. | [
"Expect",
"the",
"type",
"to",
"be",
"a",
"number",
"or",
"a",
"type",
"convertible",
"to",
"number",
".",
"If",
"the",
"expectation",
"is",
"not",
"met",
"issue",
"a",
"warning",
"at",
"the",
"provided",
"node",
"s",
"source",
"code",
"position",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeValidator.java#L373-L379 |
apache/incubator-shardingsphere | sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/update/UpdateParserFactory.java | UpdateParserFactory.newInstance | public static AbstractUpdateParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine) {
"""
Create update parser instance.
@param dbType database type
@param shardingRule databases and tables sharding rule
@param lexerEngine lexical analysis engine.
@return Update parser instance
"""
switch (dbType) {
case H2:
case MySQL:
return new MySQLUpdateParser(shardingRule, lexerEngine);
case Oracle:
return new OracleUpdateParser(shardingRule, lexerEngine);
case SQLServer:
return new SQLServerUpdateParser(shardingRule, lexerEngine);
case PostgreSQL:
return new PostgreSQLUpdateParser(shardingRule, lexerEngine);
default:
throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType));
}
} | java | public static AbstractUpdateParser newInstance(final DatabaseType dbType, final ShardingRule shardingRule, final LexerEngine lexerEngine) {
switch (dbType) {
case H2:
case MySQL:
return new MySQLUpdateParser(shardingRule, lexerEngine);
case Oracle:
return new OracleUpdateParser(shardingRule, lexerEngine);
case SQLServer:
return new SQLServerUpdateParser(shardingRule, lexerEngine);
case PostgreSQL:
return new PostgreSQLUpdateParser(shardingRule, lexerEngine);
default:
throw new UnsupportedOperationException(String.format("Cannot support database [%s].", dbType));
}
} | [
"public",
"static",
"AbstractUpdateParser",
"newInstance",
"(",
"final",
"DatabaseType",
"dbType",
",",
"final",
"ShardingRule",
"shardingRule",
",",
"final",
"LexerEngine",
"lexerEngine",
")",
"{",
"switch",
"(",
"dbType",
")",
"{",
"case",
"H2",
":",
"case",
"MySQL",
":",
"return",
"new",
"MySQLUpdateParser",
"(",
"shardingRule",
",",
"lexerEngine",
")",
";",
"case",
"Oracle",
":",
"return",
"new",
"OracleUpdateParser",
"(",
"shardingRule",
",",
"lexerEngine",
")",
";",
"case",
"SQLServer",
":",
"return",
"new",
"SQLServerUpdateParser",
"(",
"shardingRule",
",",
"lexerEngine",
")",
";",
"case",
"PostgreSQL",
":",
"return",
"new",
"PostgreSQLUpdateParser",
"(",
"shardingRule",
",",
"lexerEngine",
")",
";",
"default",
":",
"throw",
"new",
"UnsupportedOperationException",
"(",
"String",
".",
"format",
"(",
"\"Cannot support database [%s].\"",
",",
"dbType",
")",
")",
";",
"}",
"}"
] | Create update parser instance.
@param dbType database type
@param shardingRule databases and tables sharding rule
@param lexerEngine lexical analysis engine.
@return Update parser instance | [
"Create",
"update",
"parser",
"instance",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/old/parser/sql/dml/update/UpdateParserFactory.java#L46-L60 |
umeding/fuzzer | src/main/java/com/uwemeding/fuzzer/Program.java | Program.addHedge | public Hedge addHedge(String name, String arg, String expression) {
"""
Add a hedge by name.
<p>
@param name name of the hedge
@param arg argument
@param expression the expression
@return the hedge
"""
return addHedge(new Hedge(name, arg, expression));
} | java | public Hedge addHedge(String name, String arg, String expression) {
return addHedge(new Hedge(name, arg, expression));
} | [
"public",
"Hedge",
"addHedge",
"(",
"String",
"name",
",",
"String",
"arg",
",",
"String",
"expression",
")",
"{",
"return",
"addHedge",
"(",
"new",
"Hedge",
"(",
"name",
",",
"arg",
",",
"expression",
")",
")",
";",
"}"
] | Add a hedge by name.
<p>
@param name name of the hedge
@param arg argument
@param expression the expression
@return the hedge | [
"Add",
"a",
"hedge",
"by",
"name",
".",
"<p",
">"
] | train | https://github.com/umeding/fuzzer/blob/e8aa46313bb1d1328865f26f99455124aede828c/src/main/java/com/uwemeding/fuzzer/Program.java#L199-L201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.