repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
dbracewell/mango | src/main/java/com/davidbracewell/conversion/Val.java | Val.asOrElse | public <T> T asOrElse(Class<T> clazz, @NonNull Supplier<T> supplier) {
if (isNull()) {
return supplier.get();
}
T value = as(clazz);
if (value == null) {
return supplier.get();
}
return value;
} | java | public <T> T asOrElse(Class<T> clazz, @NonNull Supplier<T> supplier) {
if (isNull()) {
return supplier.get();
}
T value = as(clazz);
if (value == null) {
return supplier.get();
}
return value;
} | [
"public",
"<",
"T",
">",
"T",
"asOrElse",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"@",
"NonNull",
"Supplier",
"<",
"T",
">",
"supplier",
")",
"{",
"if",
"(",
"isNull",
"(",
")",
")",
"{",
"return",
"supplier",
".",
"get",
"(",
")",
";",
"}",... | Converts the underlying object to the given class type.
@param <T> the type parameter
@param clazz The class to convert to
@param supplier The supplier to use to generate a default value
@return This object as the given type or null if the wrapped object is null | [
"Converts",
"the",
"underlying",
"object",
"to",
"the",
"given",
"class",
"type",
"."
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/conversion/Val.java#L242-L251 |
Azure/azure-sdk-for-java | edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/TriggersInner.java | TriggersInner.getAsync | public Observable<TriggerInner> getAsync(String deviceName, String name, String resourceGroupName) {
return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<TriggerInner>, TriggerInner>() {
@Override
public TriggerInner call(ServiceResponse<TriggerInner> response) {
return response.body();
}
});
} | java | public Observable<TriggerInner> getAsync(String deviceName, String name, String resourceGroupName) {
return getWithServiceResponseAsync(deviceName, name, resourceGroupName).map(new Func1<ServiceResponse<TriggerInner>, TriggerInner>() {
@Override
public TriggerInner call(ServiceResponse<TriggerInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"TriggerInner",
">",
"getAsync",
"(",
"String",
"deviceName",
",",
"String",
"name",
",",
"String",
"resourceGroupName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"deviceName",
",",
"name",
",",
"resourceGroupName",
")",
... | Get a specific trigger by name.
@param deviceName The device name.
@param name The trigger name.
@param resourceGroupName The resource group name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the TriggerInner object | [
"Get",
"a",
"specific",
"trigger",
"by",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/TriggersInner.java#L377-L384 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/ComponentExposedTypeGenerator.java | ComponentExposedTypeGenerator.addFieldsForComputedMethod | private void addFieldsForComputedMethod(TypeElement component, Set<String> alreadyDone) {
getMethodsWithAnnotation(component, Computed.class).forEach(method -> {
String propertyName = computedPropertyNameToFieldName(getComputedPropertyName(method));
if (alreadyDone.contains(propertyName)) {
return;
}
TypeMirror propertyType = getComputedPropertyTypeFromMethod(method);
componentExposedTypeBuilder
.addField(FieldSpec
.builder(TypeName.get(propertyType),
propertyName,
Modifier.PROTECTED)
.addAnnotation(JsProperty.class)
.build());
alreadyDone.add(propertyName);
});
getSuperComponentType(component)
.ifPresent(superComponent -> addFieldsForComputedMethod(superComponent, alreadyDone));
} | java | private void addFieldsForComputedMethod(TypeElement component, Set<String> alreadyDone) {
getMethodsWithAnnotation(component, Computed.class).forEach(method -> {
String propertyName = computedPropertyNameToFieldName(getComputedPropertyName(method));
if (alreadyDone.contains(propertyName)) {
return;
}
TypeMirror propertyType = getComputedPropertyTypeFromMethod(method);
componentExposedTypeBuilder
.addField(FieldSpec
.builder(TypeName.get(propertyType),
propertyName,
Modifier.PROTECTED)
.addAnnotation(JsProperty.class)
.build());
alreadyDone.add(propertyName);
});
getSuperComponentType(component)
.ifPresent(superComponent -> addFieldsForComputedMethod(superComponent, alreadyDone));
} | [
"private",
"void",
"addFieldsForComputedMethod",
"(",
"TypeElement",
"component",
",",
"Set",
"<",
"String",
">",
"alreadyDone",
")",
"{",
"getMethodsWithAnnotation",
"(",
"component",
",",
"Computed",
".",
"class",
")",
".",
"forEach",
"(",
"method",
"->",
"{",... | Add fields for computed methods so they are visible in the template
@param component Component we are currently processing
@param alreadyDone Already processed computed properties (in case there is a getter and a | [
"Add",
"fields",
"for",
"computed",
"methods",
"so",
"they",
"are",
"visible",
"in",
"the",
"template"
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/ComponentExposedTypeGenerator.java#L415-L436 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java | ExpressRoutePortsInner.getByResourceGroup | public ExpressRoutePortInner getByResourceGroup(String resourceGroupName, String expressRoutePortName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().single().body();
} | java | public ExpressRoutePortInner getByResourceGroup(String resourceGroupName, String expressRoutePortName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, expressRoutePortName).toBlocking().single().body();
} | [
"public",
"ExpressRoutePortInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"expressRoutePortName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"expressRoutePortName",
")",
".",
"toBlocking",
... | Retrieves the requested ExpressRoutePort resource.
@param resourceGroupName The name of the resource group.
@param expressRoutePortName The name of ExpressRoutePort.
@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 ExpressRoutePortInner object if successful. | [
"Retrieves",
"the",
"requested",
"ExpressRoutePort",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java#L277-L279 |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java | ProxyUtil.createCompositeServiceProxy | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, boolean allowMultipleInheritance) {
return createCompositeServiceProxy(classLoader, services, null, allowMultipleInheritance);
} | java | public static Object createCompositeServiceProxy(ClassLoader classLoader, Object[] services, boolean allowMultipleInheritance) {
return createCompositeServiceProxy(classLoader, services, null, allowMultipleInheritance);
} | [
"public",
"static",
"Object",
"createCompositeServiceProxy",
"(",
"ClassLoader",
"classLoader",
",",
"Object",
"[",
"]",
"services",
",",
"boolean",
"allowMultipleInheritance",
")",
"{",
"return",
"createCompositeServiceProxy",
"(",
"classLoader",
",",
"services",
",",
... | Creates a composite service using all of the given
services.
@param classLoader the {@link ClassLoader}
@param services the service objects
@param allowMultipleInheritance whether or not to allow multiple inheritance
@return the object | [
"Creates",
"a",
"composite",
"service",
"using",
"all",
"of",
"the",
"given",
"services",
"."
] | train | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java#L37-L39 |
io7m/jcanephora | com.io7m.jcanephora.core/src/main/java/com/io7m/jcanephora/core/JCGLBufferUpdates.java | JCGLBufferUpdates.newUpdateReplacingAll | public static <T extends JCGLBufferWritableType> JCGLBufferUpdateType<T>
newUpdateReplacingAll(final T buffer)
{
NullCheck.notNull(buffer, "Buffer");
return newUpdateReplacingRange(buffer, buffer.byteRange());
} | java | public static <T extends JCGLBufferWritableType> JCGLBufferUpdateType<T>
newUpdateReplacingAll(final T buffer)
{
NullCheck.notNull(buffer, "Buffer");
return newUpdateReplacingRange(buffer, buffer.byteRange());
} | [
"public",
"static",
"<",
"T",
"extends",
"JCGLBufferWritableType",
">",
"JCGLBufferUpdateType",
"<",
"T",
">",
"newUpdateReplacingAll",
"(",
"final",
"T",
"buffer",
")",
"{",
"NullCheck",
".",
"notNull",
"(",
"buffer",
",",
"\"Buffer\"",
")",
";",
"return",
"n... | Construct an update that will replace all of the data in {@code buffer}.
@param buffer The buffer
@param <T> The precise type of buffer
@return An update | [
"Construct",
"an",
"update",
"that",
"will",
"replace",
"all",
"of",
"the",
"data",
"in",
"{",
"@code",
"buffer",
"}",
"."
] | train | https://github.com/io7m/jcanephora/blob/0004c1744b7f0969841d04cd4fa693f402b10980/com.io7m.jcanephora.core/src/main/java/com/io7m/jcanephora/core/JCGLBufferUpdates.java#L48-L53 |
osglworks/java-tool | src/main/java/org/osgl/Lang.java | F1.compose | public <X1, X2, X3, X4, X5> F5<X1, X2, X3, X4, X5, R>
compose(final Func5<? super X1, ? super X2, ? super X3, ? super X4, ? super X5, ? extends P1> before) {
final F1<P1, R> me = this;
return new F5<X1, X2, X3, X4, X5, R>() {
@Override
public R apply(X1 x1, X2 x2, X3 x3, X4 x4, X5 x5) {
return me.apply(before.apply(x1, x2, x3, x4, x5));
}
};
} | java | public <X1, X2, X3, X4, X5> F5<X1, X2, X3, X4, X5, R>
compose(final Func5<? super X1, ? super X2, ? super X3, ? super X4, ? super X5, ? extends P1> before) {
final F1<P1, R> me = this;
return new F5<X1, X2, X3, X4, X5, R>() {
@Override
public R apply(X1 x1, X2 x2, X3 x3, X4 x4, X5 x5) {
return me.apply(before.apply(x1, x2, x3, x4, x5));
}
};
} | [
"public",
"<",
"X1",
",",
"X2",
",",
"X3",
",",
"X4",
",",
"X5",
">",
"F5",
"<",
"X1",
",",
"X2",
",",
"X3",
",",
"X4",
",",
"X5",
",",
"R",
">",
"compose",
"(",
"final",
"Func5",
"<",
"?",
"super",
"X1",
",",
"?",
"super",
"X2",
",",
"?"... | Returns an {@code F3<X1, X2, X3, X4, X5, R>>} function by composing the specified
{@code Func3<X1, X2, X3, X4, X5, P1>} function with this function applied last
@param <X1>
the type of first param the new function applied to
@param <X2>
the type of second param the new function applied to
@param <X3>
the type of third param the new function applied to
@param <X4>
the type of fourth param the new function applied to
@param <X5>
the type of fifth param the new function applied to
@param before
the function to be applied first when applying the return function
@return an new function such that f(x1, x2, x3, x4, x5) == apply(f1(x1, x2, x3, x4, x5)) | [
"Returns",
"an",
"{",
"@code",
"F3<",
";",
"X1",
"X2",
"X3",
"X4",
"X5",
"R>",
";",
">",
"}",
"function",
"by",
"composing",
"the",
"specified",
"{",
"@code",
"Func3<X1",
"X2",
"X3",
"X4",
"X5",
"P1>",
";",
"}",
"function",
"with",
"this",
"f... | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/Lang.java#L757-L766 |
javagl/ND | nd-distance/src/main/java/de/javagl/nd/distance/tuples/j/LongTupleDistanceFunctions.java | LongTupleDistanceFunctions.byDistanceComparator | public static Comparator<LongTuple> byDistanceComparator(
LongTuple reference,
final ToDoubleBiFunction<? super LongTuple, ? super LongTuple>
distanceFunction)
{
final LongTuple fReference = LongTuples.copy(reference);
return new Comparator<LongTuple>()
{
@Override
public int compare(LongTuple t0, LongTuple t1)
{
double d0 = distanceFunction.applyAsDouble(fReference, t0);
double d1 = distanceFunction.applyAsDouble(fReference, t1);
return Double.compare(d0, d1);
}
};
} | java | public static Comparator<LongTuple> byDistanceComparator(
LongTuple reference,
final ToDoubleBiFunction<? super LongTuple, ? super LongTuple>
distanceFunction)
{
final LongTuple fReference = LongTuples.copy(reference);
return new Comparator<LongTuple>()
{
@Override
public int compare(LongTuple t0, LongTuple t1)
{
double d0 = distanceFunction.applyAsDouble(fReference, t0);
double d1 = distanceFunction.applyAsDouble(fReference, t1);
return Double.compare(d0, d1);
}
};
} | [
"public",
"static",
"Comparator",
"<",
"LongTuple",
">",
"byDistanceComparator",
"(",
"LongTuple",
"reference",
",",
"final",
"ToDoubleBiFunction",
"<",
"?",
"super",
"LongTuple",
",",
"?",
"super",
"LongTuple",
">",
"distanceFunction",
")",
"{",
"final",
"LongTup... | Returns a new comparator that compares {@link LongTuple} instances
by their distance to the given reference, according to the given
distance function.
A copy of the given reference point will be stored, so that changes
in the given point will not affect the returned comparator.
@param reference The reference point
@param distanceFunction The distance function
@return The comparator | [
"Returns",
"a",
"new",
"comparator",
"that",
"compares",
"{",
"@link",
"LongTuple",
"}",
"instances",
"by",
"their",
"distance",
"to",
"the",
"given",
"reference",
"according",
"to",
"the",
"given",
"distance",
"function",
".",
"A",
"copy",
"of",
"the",
"giv... | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-distance/src/main/java/de/javagl/nd/distance/tuples/j/LongTupleDistanceFunctions.java#L54-L70 |
JavaMoney/jsr354-api | src/main/java/javax/money/Monetary.java | Monetary.getRounding | public static MonetaryRounding getRounding(CurrencyUnit currencyUnit, String... providers) {
return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(
() -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available."))
.getRounding(currencyUnit, providers);
} | java | public static MonetaryRounding getRounding(CurrencyUnit currencyUnit, String... providers) {
return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(
() -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available."))
.getRounding(currencyUnit, providers);
} | [
"public",
"static",
"MonetaryRounding",
"getRounding",
"(",
"CurrencyUnit",
"currencyUnit",
",",
"String",
"...",
"providers",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"monetaryRoundingsSingletonSpi",
"(",
")",
")",
".",
"orElseThrow",
"(",
"(",
")"... | Creates an {@link MonetaryOperator} for rounding {@link MonetaryAmount}
instances given a currency.
@param currencyUnit The currency, which determines the required scale. As
{@link java.math.RoundingMode}, by default, {@link java.math.RoundingMode#HALF_UP}
is used.
@param providers the providers and ordering to be used. By default providers and ordering as defined in
#getDefaultProviders is used.
@return a new instance {@link MonetaryOperator} implementing the
rounding, never {@code null}. | [
"Creates",
"an",
"{",
"@link",
"MonetaryOperator",
"}",
"for",
"rounding",
"{",
"@link",
"MonetaryAmount",
"}",
"instances",
"given",
"a",
"currency",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/Monetary.java#L153-L157 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/RecurrenceUtility.java | RecurrenceUtility.getDurationValue | public static Integer getDurationValue(ProjectProperties properties, Duration duration)
{
Integer result;
if (duration == null)
{
result = null;
}
else
{
if (duration.getUnits() != TimeUnit.MINUTES)
{
duration = duration.convertUnits(TimeUnit.MINUTES, properties);
}
result = Integer.valueOf((int) duration.getDuration());
}
return (result);
} | java | public static Integer getDurationValue(ProjectProperties properties, Duration duration)
{
Integer result;
if (duration == null)
{
result = null;
}
else
{
if (duration.getUnits() != TimeUnit.MINUTES)
{
duration = duration.convertUnits(TimeUnit.MINUTES, properties);
}
result = Integer.valueOf((int) duration.getDuration());
}
return (result);
} | [
"public",
"static",
"Integer",
"getDurationValue",
"(",
"ProjectProperties",
"properties",
",",
"Duration",
"duration",
")",
"{",
"Integer",
"result",
";",
"if",
"(",
"duration",
"==",
"null",
")",
"{",
"result",
"=",
"null",
";",
"}",
"else",
"{",
"if",
"... | Convert an MPXJ Duration instance into an integer duration in minutes
ready to be written to an MPX file.
@param properties project properties, used for duration units conversion
@param duration Duration instance
@return integer duration in minutes | [
"Convert",
"an",
"MPXJ",
"Duration",
"instance",
"into",
"an",
"integer",
"duration",
"in",
"minutes",
"ready",
"to",
"be",
"written",
"to",
"an",
"MPX",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/RecurrenceUtility.java#L90-L106 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java | ApiOvhDedicatednasha.serviceName_partition_partitionName_options_GET | public OvhOptions serviceName_partition_partitionName_options_GET(String serviceName, String partitionName) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/options";
StringBuilder sb = path(qPath, serviceName, partitionName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOptions.class);
} | java | public OvhOptions serviceName_partition_partitionName_options_GET(String serviceName, String partitionName) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/options";
StringBuilder sb = path(qPath, serviceName, partitionName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOptions.class);
} | [
"public",
"OvhOptions",
"serviceName_partition_partitionName_options_GET",
"(",
"String",
"serviceName",
",",
"String",
"partitionName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/nasha/{serviceName}/partition/{partitionName}/options\"",
";",
"String... | Get this object properties
REST: GET /dedicated/nasha/{serviceName}/partition/{partitionName}/options
@param serviceName [required] The internal name of your storage
@param partitionName [required] the given name of partition | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java#L111-L116 |
GoogleCloudPlatform/appengine-pipelines | java/src/main/java/com/google/appengine/tools/pipeline/impl/PipelineManager.java | PipelineManager.queryJobOrAbandonTask | private static JobRecord queryJobOrAbandonTask(Key key, JobRecord.InflationType inflationType) {
try {
return backEnd.queryJob(key, inflationType);
} catch (NoSuchObjectException e) {
logger.log(
Level.WARNING, "Cannot find some part of the job: " + key + ". Ignoring the task.", e);
throw new AbandonTaskException();
}
} | java | private static JobRecord queryJobOrAbandonTask(Key key, JobRecord.InflationType inflationType) {
try {
return backEnd.queryJob(key, inflationType);
} catch (NoSuchObjectException e) {
logger.log(
Level.WARNING, "Cannot find some part of the job: " + key + ". Ignoring the task.", e);
throw new AbandonTaskException();
}
} | [
"private",
"static",
"JobRecord",
"queryJobOrAbandonTask",
"(",
"Key",
"key",
",",
"JobRecord",
".",
"InflationType",
"inflationType",
")",
"{",
"try",
"{",
"return",
"backEnd",
".",
"queryJob",
"(",
"key",
",",
"inflationType",
")",
";",
"}",
"catch",
"(",
... | Queries for the job with the given key from the data store and if the job
is not found then throws an {@link AbandonTaskException}.
@param key The key of the JobRecord to be fetched
@param inflationType Specifies the manner in which the returned JobRecord
should be inflated.
@return A {@code JobRecord}, possibly with a partially-inflated associated
graph of objects.
@throws AbandonTaskException If Either the JobRecord or any of the
associated Slots or Barriers are not found in the data store. | [
"Queries",
"for",
"the",
"job",
"with",
"the",
"given",
"key",
"from",
"the",
"data",
"store",
"and",
"if",
"the",
"job",
"is",
"not",
"found",
"then",
"throws",
"an",
"{",
"@link",
"AbandonTaskException",
"}",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/java/src/main/java/com/google/appengine/tools/pipeline/impl/PipelineManager.java#L1186-L1194 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/servlet/RendererRequestUtils.java | RendererRequestUtils.refreshConfigIfNeeded | public static boolean refreshConfigIfNeeded(HttpServletRequest request, JawrConfig jawrConfig) {
boolean refreshed = false;
if (request.getAttribute(JawrConstant.JAWR_BUNDLE_REFRESH_CHECK) == null) {
request.setAttribute(JawrConstant.JAWR_BUNDLE_REFRESH_CHECK, Boolean.TRUE);
if (jawrConfig.getRefreshKey().length() > 0 && null != request.getParameter(JawrConstant.REFRESH_KEY_PARAM)
&& jawrConfig.getRefreshKey().equals(request.getParameter(JawrConstant.REFRESH_KEY_PARAM))) {
JawrApplicationConfigManager appConfigMgr = (JawrApplicationConfigManager) request.getSession()
.getServletContext().getAttribute(JawrConstant.JAWR_APPLICATION_CONFIG_MANAGER);
if (appConfigMgr == null) {
throw new IllegalStateException(
"JawrApplicationConfigManager is not present in servlet context. Initialization of Jawr either failed or never occurred.");
}
appConfigMgr.refreshConfig();
refreshed = true;
}
}
return refreshed;
} | java | public static boolean refreshConfigIfNeeded(HttpServletRequest request, JawrConfig jawrConfig) {
boolean refreshed = false;
if (request.getAttribute(JawrConstant.JAWR_BUNDLE_REFRESH_CHECK) == null) {
request.setAttribute(JawrConstant.JAWR_BUNDLE_REFRESH_CHECK, Boolean.TRUE);
if (jawrConfig.getRefreshKey().length() > 0 && null != request.getParameter(JawrConstant.REFRESH_KEY_PARAM)
&& jawrConfig.getRefreshKey().equals(request.getParameter(JawrConstant.REFRESH_KEY_PARAM))) {
JawrApplicationConfigManager appConfigMgr = (JawrApplicationConfigManager) request.getSession()
.getServletContext().getAttribute(JawrConstant.JAWR_APPLICATION_CONFIG_MANAGER);
if (appConfigMgr == null) {
throw new IllegalStateException(
"JawrApplicationConfigManager is not present in servlet context. Initialization of Jawr either failed or never occurred.");
}
appConfigMgr.refreshConfig();
refreshed = true;
}
}
return refreshed;
} | [
"public",
"static",
"boolean",
"refreshConfigIfNeeded",
"(",
"HttpServletRequest",
"request",
",",
"JawrConfig",
"jawrConfig",
")",
"{",
"boolean",
"refreshed",
"=",
"false",
";",
"if",
"(",
"request",
".",
"getAttribute",
"(",
"JawrConstant",
".",
"JAWR_BUNDLE_REFR... | Refresh the Jawr config if a manual reload has been ask using the refresh
key parameter from the URL
@param request
the request
@param jawrConfig
the Jawr config
@return true if the config has been refreshed | [
"Refresh",
"the",
"Jawr",
"config",
"if",
"a",
"manual",
"reload",
"has",
"been",
"ask",
"using",
"the",
"refresh",
"key",
"parameter",
"from",
"the",
"URL"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/RendererRequestUtils.java#L382-L403 |
google/error-prone-javac | src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java | ElementFilter.packagesIn | public static List<PackageElement>
packagesIn(Iterable<? extends Element> elements) {
return listFilter(elements, PACKAGE_KIND, PackageElement.class);
} | java | public static List<PackageElement>
packagesIn(Iterable<? extends Element> elements) {
return listFilter(elements, PACKAGE_KIND, PackageElement.class);
} | [
"public",
"static",
"List",
"<",
"PackageElement",
">",
"packagesIn",
"(",
"Iterable",
"<",
"?",
"extends",
"Element",
">",
"elements",
")",
"{",
"return",
"listFilter",
"(",
"elements",
",",
"PACKAGE_KIND",
",",
"PackageElement",
".",
"class",
")",
";",
"}"... | Returns a list of packages in {@code elements}.
@return a list of packages in {@code elements}
@param elements the elements to filter | [
"Returns",
"a",
"list",
"of",
"packages",
"in",
"{"
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java#L172-L175 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/db/ConnectionUtility.java | ConnectionUtility.createDataSource | public static DataSource createDataSource(String source, String type, String... configs){
String config = StringUtils.join(configs, " ");
return createDataSource(source, type, config);
} | java | public static DataSource createDataSource(String source, String type, String... configs){
String config = StringUtils.join(configs, " ");
return createDataSource(source, type, config);
} | [
"public",
"static",
"DataSource",
"createDataSource",
"(",
"String",
"source",
",",
"String",
"type",
",",
"String",
"...",
"configs",
")",
"{",
"String",
"config",
"=",
"StringUtils",
".",
"join",
"(",
"configs",
",",
"\" \"",
")",
";",
"return",
"createDat... | Create a data source
@param source name of the data source, can be anything
@param type type of the data source
@param configs configurations, normally paths to configuration files
@return the newly created data source | [
"Create",
"a",
"data",
"source"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L203-L206 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/opengl/ImageIOImageData.java | ImageIOImageData.copyArea | private void copyArea(BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.drawImage(image.getSubimage(x, y, width, height),x+dx,y+dy,null);
} | java | private void copyArea(BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.drawImage(image.getSubimage(x, y, width, height),x+dx,y+dy,null);
} | [
"private",
"void",
"copyArea",
"(",
"BufferedImage",
"image",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"width",
",",
"int",
"height",
",",
"int",
"dx",
",",
"int",
"dy",
")",
"{",
"Graphics2D",
"g",
"=",
"(",
"Graphics2D",
")",
"image",
".",
"... | Implement of transform copy area for 1.4
@param image The image to copy
@param x The x position to copy to
@param y The y position to copy to
@param width The width of the image
@param height The height of the image
@param dx The transform on the x axis
@param dy The transform on the y axis | [
"Implement",
"of",
"transform",
"copy",
"area",
"for",
"1",
".",
"4"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/opengl/ImageIOImageData.java#L232-L236 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUResourceBundle.java | ICUResourceBundle.getStringWithFallback | public String getStringWithFallback(String path) throws MissingResourceException {
// Optimized form of getWithFallback(path).getString();
ICUResourceBundle actualBundle = this;
String result = findStringWithFallback(path, actualBundle, null);
if (result == null) {
throw new MissingResourceException(
"Can't find resource for bundle "
+ this.getClass().getName() + ", key " + getType(),
path, getKey());
}
if (result.equals(NO_INHERITANCE_MARKER)) {
throw new MissingResourceException("Encountered NO_INHERITANCE_MARKER", path, getKey());
}
return result;
} | java | public String getStringWithFallback(String path) throws MissingResourceException {
// Optimized form of getWithFallback(path).getString();
ICUResourceBundle actualBundle = this;
String result = findStringWithFallback(path, actualBundle, null);
if (result == null) {
throw new MissingResourceException(
"Can't find resource for bundle "
+ this.getClass().getName() + ", key " + getType(),
path, getKey());
}
if (result.equals(NO_INHERITANCE_MARKER)) {
throw new MissingResourceException("Encountered NO_INHERITANCE_MARKER", path, getKey());
}
return result;
} | [
"public",
"String",
"getStringWithFallback",
"(",
"String",
"path",
")",
"throws",
"MissingResourceException",
"{",
"// Optimized form of getWithFallback(path).getString();",
"ICUResourceBundle",
"actualBundle",
"=",
"this",
";",
"String",
"result",
"=",
"findStringWithFallback... | will throw type mismatch exception if the resource is not a string | [
"will",
"throw",
"type",
"mismatch",
"exception",
"if",
"the",
"resource",
"is",
"not",
"a",
"string"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUResourceBundle.java#L353-L369 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java | ListManagementTermsImpl.deleteAllTermsAsync | public Observable<String> deleteAllTermsAsync(String listId, String language) {
return deleteAllTermsWithServiceResponseAsync(listId, language).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
} | java | public Observable<String> deleteAllTermsAsync(String listId, String language) {
return deleteAllTermsWithServiceResponseAsync(listId, language).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"String",
">",
"deleteAllTermsAsync",
"(",
"String",
"listId",
",",
"String",
"language",
")",
"{",
"return",
"deleteAllTermsWithServiceResponseAsync",
"(",
"listId",
",",
"language",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"Servi... | Deletes all terms from the list with list Id equal to the list Id passed.
@param listId List Id of the image list.
@param language Language of the terms.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the String object | [
"Deletes",
"all",
"terms",
"from",
"the",
"list",
"with",
"list",
"Id",
"equal",
"to",
"the",
"list",
"Id",
"passed",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java#L473-L480 |
lucee/Lucee | core/src/main/java/lucee/runtime/type/util/CollectionUtil.java | CollectionUtil.getKeyList | public static String getKeyList(Iterator<Key> it, String delimiter) {
StringBuilder sb = new StringBuilder(it.next().getString());
if (delimiter.length() == 1) {
char c = delimiter.charAt(0);
while (it.hasNext()) {
sb.append(c);
sb.append(it.next().getString());
}
}
else {
while (it.hasNext()) {
sb.append(delimiter);
sb.append(it.next().getString());
}
}
return sb.toString();
} | java | public static String getKeyList(Iterator<Key> it, String delimiter) {
StringBuilder sb = new StringBuilder(it.next().getString());
if (delimiter.length() == 1) {
char c = delimiter.charAt(0);
while (it.hasNext()) {
sb.append(c);
sb.append(it.next().getString());
}
}
else {
while (it.hasNext()) {
sb.append(delimiter);
sb.append(it.next().getString());
}
}
return sb.toString();
} | [
"public",
"static",
"String",
"getKeyList",
"(",
"Iterator",
"<",
"Key",
">",
"it",
",",
"String",
"delimiter",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"it",
".",
"next",
"(",
")",
".",
"getString",
"(",
")",
")",
";",
"if",
... | /*
public static String[] toStringArray(Key[] keys) { if(keys==null) return null; String[] arr=new
String[keys.length]; for(int i=0;i<keys.length;i++){ arr[i]=keys[i].getString(); } return arr; } | [
"/",
"*",
"public",
"static",
"String",
"[]",
"toStringArray",
"(",
"Key",
"[]",
"keys",
")",
"{",
"if",
"(",
"keys",
"==",
"null",
")",
"return",
"null",
";",
"String",
"[]",
"arr",
"=",
"new",
"String",
"[",
"keys",
".",
"length",
"]",
";",
"for"... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/CollectionUtil.java#L57-L73 |
deeplearning4j/deeplearning4j | datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java | ArrowConverter.getFieldForColumn | public static Field getFieldForColumn(String name,ColumnType columnType) {
switch(columnType) {
case Long: return field(name,new ArrowType.Int(64,false));
case Integer: return field(name,new ArrowType.Int(32,false));
case Double: return field(name,new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE));
case Float: return field(name,new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE));
case Boolean: return field(name, new ArrowType.Bool());
case Categorical: return field(name,new ArrowType.Utf8());
case Time: return field(name,new ArrowType.Date(DateUnit.MILLISECOND));
case Bytes: return field(name,new ArrowType.Binary());
case NDArray: return field(name,new ArrowType.Binary());
case String: return field(name,new ArrowType.Utf8());
default: throw new IllegalArgumentException("Column type invalid " + columnType);
}
} | java | public static Field getFieldForColumn(String name,ColumnType columnType) {
switch(columnType) {
case Long: return field(name,new ArrowType.Int(64,false));
case Integer: return field(name,new ArrowType.Int(32,false));
case Double: return field(name,new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE));
case Float: return field(name,new ArrowType.FloatingPoint(FloatingPointPrecision.SINGLE));
case Boolean: return field(name, new ArrowType.Bool());
case Categorical: return field(name,new ArrowType.Utf8());
case Time: return field(name,new ArrowType.Date(DateUnit.MILLISECOND));
case Bytes: return field(name,new ArrowType.Binary());
case NDArray: return field(name,new ArrowType.Binary());
case String: return field(name,new ArrowType.Utf8());
default: throw new IllegalArgumentException("Column type invalid " + columnType);
}
} | [
"public",
"static",
"Field",
"getFieldForColumn",
"(",
"String",
"name",
",",
"ColumnType",
"columnType",
")",
"{",
"switch",
"(",
"columnType",
")",
"{",
"case",
"Long",
":",
"return",
"field",
"(",
"name",
",",
"new",
"ArrowType",
".",
"Int",
"(",
"64",
... | Create a field given the input {@link ColumnType}
and name
@param name the name of the field
@param columnType the column type to add
@return | [
"Create",
"a",
"field",
"given",
"the",
"input",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java#L471-L486 |
jbundle/jbundle | base/message/trx/src/main/java/org/jbundle/base/message/trx/transport/soap/SOAPMessageTransport.java | SOAPMessageTransport.createExternalMessage | public ExternalMessage createExternalMessage(BaseMessage message, Object rawData)
{
ExternalMessage externalTrxMessageOut = super.createExternalMessage(message, rawData);
if (externalTrxMessageOut == null)
{
if (MessageTypeModel.MESSAGE_IN.equalsIgnoreCase((String)message.get(TrxMessageHeader.MESSAGE_PROCESS_TYPE)))
externalTrxMessageOut = new SoapTrxMessageIn(message, rawData);
else
externalTrxMessageOut = new SoapTrxMessageOut(message, rawData);
}
return externalTrxMessageOut;
} | java | public ExternalMessage createExternalMessage(BaseMessage message, Object rawData)
{
ExternalMessage externalTrxMessageOut = super.createExternalMessage(message, rawData);
if (externalTrxMessageOut == null)
{
if (MessageTypeModel.MESSAGE_IN.equalsIgnoreCase((String)message.get(TrxMessageHeader.MESSAGE_PROCESS_TYPE)))
externalTrxMessageOut = new SoapTrxMessageIn(message, rawData);
else
externalTrxMessageOut = new SoapTrxMessageOut(message, rawData);
}
return externalTrxMessageOut;
} | [
"public",
"ExternalMessage",
"createExternalMessage",
"(",
"BaseMessage",
"message",
",",
"Object",
"rawData",
")",
"{",
"ExternalMessage",
"externalTrxMessageOut",
"=",
"super",
".",
"createExternalMessage",
"(",
"message",
",",
"rawData",
")",
";",
"if",
"(",
"ext... | Get the external message container for this Internal message.
Typically, the overriding class supplies a default format for the transport type.
<br/>NOTE: The message header from the internal message is copies, but not the message itself.
@param The internalTrxMessage that I will convert to this external format.
@return The (empty) External message. | [
"Get",
"the",
"external",
"message",
"container",
"for",
"this",
"Internal",
"message",
".",
"Typically",
"the",
"overriding",
"class",
"supplies",
"a",
"default",
"format",
"for",
"the",
"transport",
"type",
".",
"<br",
"/",
">",
"NOTE",
":",
"The",
"messag... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/transport/soap/SOAPMessageTransport.java#L132-L143 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/SelectListUtil.java | SelectListUtil.isLegacyMatch | @Deprecated
private static boolean isLegacyMatch(final Object option, final Object data) {
// Support legacy matching, which supported setSelected using String representations...
String optionAsString = String.valueOf(option);
String matchAsString = String.valueOf(data);
boolean equal = Util.equals(optionAsString, matchAsString);
return equal;
} | java | @Deprecated
private static boolean isLegacyMatch(final Object option, final Object data) {
// Support legacy matching, which supported setSelected using String representations...
String optionAsString = String.valueOf(option);
String matchAsString = String.valueOf(data);
boolean equal = Util.equals(optionAsString, matchAsString);
return equal;
} | [
"@",
"Deprecated",
"private",
"static",
"boolean",
"isLegacyMatch",
"(",
"final",
"Object",
"option",
",",
"final",
"Object",
"data",
")",
"{",
"// Support legacy matching, which supported setSelected using String representations...",
"String",
"optionAsString",
"=",
"String"... | Check for legacy matching, which supported setSelected using String representations.
@param option the option to test for a match
@param data the test data value
@return true if the option is a legacy match
@deprecated Support for legacy matching will be removed | [
"Check",
"for",
"legacy",
"matching",
"which",
"supported",
"setSelected",
"using",
"String",
"representations",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/SelectListUtil.java#L175-L182 |
exoplatform/jcr | exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/common/SessionProvider.java | SessionProvider.getSession | public synchronized Session getSession(String workspaceName, ManageableRepository repository) throws LoginException,
NoSuchWorkspaceException, RepositoryException
{
if (closed)
{
throw new IllegalStateException("Session provider already closed");
}
if (workspaceName == null)
{
throw new IllegalArgumentException("Workspace Name is null");
}
ExtendedSession session = cache.get(key(repository, workspaceName));
// create and cache new session
if (session == null)
{
if (conversationState != null)
{
session =
(ExtendedSession) repository.getDynamicSession(workspaceName, conversationState.getIdentity()
.getMemberships());
}
else if (!isSystem)
{
session = (ExtendedSession)repository.login(workspaceName);
}
else
{
session = (ExtendedSession)repository.getSystemSession(workspaceName);
}
session.registerLifecycleListener(this);
cache.put(key(repository, workspaceName), session);
}
return session;
} | java | public synchronized Session getSession(String workspaceName, ManageableRepository repository) throws LoginException,
NoSuchWorkspaceException, RepositoryException
{
if (closed)
{
throw new IllegalStateException("Session provider already closed");
}
if (workspaceName == null)
{
throw new IllegalArgumentException("Workspace Name is null");
}
ExtendedSession session = cache.get(key(repository, workspaceName));
// create and cache new session
if (session == null)
{
if (conversationState != null)
{
session =
(ExtendedSession) repository.getDynamicSession(workspaceName, conversationState.getIdentity()
.getMemberships());
}
else if (!isSystem)
{
session = (ExtendedSession)repository.login(workspaceName);
}
else
{
session = (ExtendedSession)repository.getSystemSession(workspaceName);
}
session.registerLifecycleListener(this);
cache.put(key(repository, workspaceName), session);
}
return session;
} | [
"public",
"synchronized",
"Session",
"getSession",
"(",
"String",
"workspaceName",
",",
"ManageableRepository",
"repository",
")",
"throws",
"LoginException",
",",
"NoSuchWorkspaceException",
",",
"RepositoryException",
"{",
"if",
"(",
"closed",
")",
"{",
"throw",
"ne... | Gets the session from an internal cache if a similar session has already been used
or creates a new session and puts it into the internal cache.
@param workspaceName the workspace name
@param repository the repository instance
@return a session corresponding to the given repository and workspace
@throws LoginException if an error occurs while trying to login to the workspace
@throws NoSuchWorkspaceException if the requested workspace doesn't exist
@throws RepositoryException if any error occurs | [
"Gets",
"the",
"session",
"from",
"an",
"internal",
"cache",
"if",
"a",
"similar",
"session",
"has",
"already",
"been",
"used",
"or",
"creates",
"a",
"new",
"session",
"and",
"puts",
"it",
"into",
"the",
"internal",
"cache",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/common/SessionProvider.java#L171-L211 |
javalite/activejdbc | javalite-common/src/main/java/org/javalite/common/Util.java | Util.saveTo | public static void saveTo(String path, InputStream in) {
if (in == null) {
throw new IllegalArgumentException("input stream cannot be null");
}
if (path == null) {
throw new IllegalArgumentException("path cannot be null");
}
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int len;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
closeQuietly(out);
}
} | java | public static void saveTo(String path, InputStream in) {
if (in == null) {
throw new IllegalArgumentException("input stream cannot be null");
}
if (path == null) {
throw new IllegalArgumentException("path cannot be null");
}
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int len;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
closeQuietly(out);
}
} | [
"public",
"static",
"void",
"saveTo",
"(",
"String",
"path",
",",
"InputStream",
"in",
")",
"{",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"input stream cannot be null\"",
")",
";",
"}",
"if",
"(",
"path",
... | Saves content read from input stream into a file.
@param path path to file.
@param in input stream to read content from. | [
"Saves",
"content",
"read",
"from",
"input",
"stream",
"into",
"a",
"file",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Util.java#L403-L425 |
apache/incubator-gobblin | gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java | Batch.tryAppend | public Future<RecordMetadata> tryAppend(D record, WriteCallback callback, LargeMessagePolicy largeMessagePolicy)
throws RecordTooLargeException {
if (!hasRoom(record, largeMessagePolicy)) {
LOG.debug ("Cannot add {} to previous batch because the batch already has {} bytes",
record.toString(), getCurrentSizeInByte());
if (largeMessagePolicy == LargeMessagePolicy.FAIL) {
throw new RecordTooLargeException();
}
return null;
}
this.append(record);
thunks.add(new Thunk(callback, getRecordSizeInByte(record)));
RecordFuture future = new RecordFuture(latch, recordCount);
recordCount++;
return future;
} | java | public Future<RecordMetadata> tryAppend(D record, WriteCallback callback, LargeMessagePolicy largeMessagePolicy)
throws RecordTooLargeException {
if (!hasRoom(record, largeMessagePolicy)) {
LOG.debug ("Cannot add {} to previous batch because the batch already has {} bytes",
record.toString(), getCurrentSizeInByte());
if (largeMessagePolicy == LargeMessagePolicy.FAIL) {
throw new RecordTooLargeException();
}
return null;
}
this.append(record);
thunks.add(new Thunk(callback, getRecordSizeInByte(record)));
RecordFuture future = new RecordFuture(latch, recordCount);
recordCount++;
return future;
} | [
"public",
"Future",
"<",
"RecordMetadata",
">",
"tryAppend",
"(",
"D",
"record",
",",
"WriteCallback",
"callback",
",",
"LargeMessagePolicy",
"largeMessagePolicy",
")",
"throws",
"RecordTooLargeException",
"{",
"if",
"(",
"!",
"hasRoom",
"(",
"record",
",",
"large... | Try to add a record to this batch
<p>
This method first check room space if a give record can be added
If there is no space for new record, a null is returned; otherwise {@link Batch#append(Object)}
is invoked and {@link RecordFuture} object is returned. User can call get() method on this object
which will block current thread until the batch s fully completed (sent and received acknowledgement).
The future object also contains meta information where this new record is located, usually an offset inside this batch.
</p>
@param record : record needs to be added
@param callback : A callback which will be invoked when the whole batch gets sent and acknowledged
@param largeMessagePolicy : the {@link LargeMessagePolicy} that is in effect for this batch
@return A future object which contains {@link RecordMetadata} | [
"Try",
"to",
"add",
"a",
"record",
"to",
"this",
"batch",
"<p",
">",
"This",
"method",
"first",
"check",
"room",
"space",
"if",
"a",
"give",
"record",
"can",
"be",
"added",
"If",
"there",
"is",
"no",
"space",
"for",
"new",
"record",
"a",
"null",
"is"... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java#L169-L184 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/writer/ThrottleWriter.java | ThrottleWriter.writeEnvelope | @Override
public void writeEnvelope(RecordEnvelope<D> record) throws IOException {
try {
if (ThrottleType.QPS.equals(type)) {
acquirePermits(1L);
}
long beforeWrittenBytes = writer.bytesWritten();
writer.writeEnvelope(record);
if (ThrottleType.Bytes.equals(type)) {
long delta = writer.bytesWritten() - beforeWrittenBytes;
if (delta < 0) {
throw new UnsupportedOperationException("Cannot throttle on bytes because "
+ writer.getClass().getSimpleName() + " does not supports bytesWritten");
}
if (delta > 0) {
acquirePermits(delta);
}
}
} catch (InterruptedException e) {
throw new IOException("Failed while acquiring permits.",e);
}
} | java | @Override
public void writeEnvelope(RecordEnvelope<D> record) throws IOException {
try {
if (ThrottleType.QPS.equals(type)) {
acquirePermits(1L);
}
long beforeWrittenBytes = writer.bytesWritten();
writer.writeEnvelope(record);
if (ThrottleType.Bytes.equals(type)) {
long delta = writer.bytesWritten() - beforeWrittenBytes;
if (delta < 0) {
throw new UnsupportedOperationException("Cannot throttle on bytes because "
+ writer.getClass().getSimpleName() + " does not supports bytesWritten");
}
if (delta > 0) {
acquirePermits(delta);
}
}
} catch (InterruptedException e) {
throw new IOException("Failed while acquiring permits.",e);
}
} | [
"@",
"Override",
"public",
"void",
"writeEnvelope",
"(",
"RecordEnvelope",
"<",
"D",
">",
"record",
")",
"throws",
"IOException",
"{",
"try",
"{",
"if",
"(",
"ThrottleType",
".",
"QPS",
".",
"equals",
"(",
"type",
")",
")",
"{",
"acquirePermits",
"(",
"1... | Calls inner writer with self throttling.
If the throttle type is byte, it applies throttle after write happens.
This is because it can figure out written bytes after it's written. It's not ideal but throttling after write should be sufficient for most cases.
{@inheritDoc}
@see org.apache.gobblin.writer.DataWriter#write(java.lang.Object) | [
"Calls",
"inner",
"writer",
"with",
"self",
"throttling",
".",
"If",
"the",
"throttle",
"type",
"is",
"byte",
"it",
"applies",
"throttle",
"after",
"write",
"happens",
".",
"This",
"is",
"because",
"it",
"can",
"figure",
"out",
"written",
"bytes",
"after",
... | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/writer/ThrottleWriter.java#L124-L147 |
Talend/tesb-rt-se | sam/sam-agent/src/main/java/org/talend/esb/sam/agent/flowidprocessor/FlowIdProducerOut.java | FlowIdProducerOut.handleINEvent | protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {
Message inMsg = exchange.getInMessage();
EventProducerInterceptor epi = null;
FlowIdHelper.setFlowId(inMsg, reqFid);
ListIterator<Interceptor<? extends Message>> interceptors = inMsg
.getInterceptorChain().getIterator();
while (interceptors.hasNext() && epi == null) {
Interceptor<? extends Message> interceptor = interceptors.next();
if (interceptor instanceof EventProducerInterceptor) {
epi = (EventProducerInterceptor) interceptor;
epi.handleMessage(inMsg);
}
}
} | java | protected void handleINEvent(Exchange exchange, String reqFid) throws Fault {
Message inMsg = exchange.getInMessage();
EventProducerInterceptor epi = null;
FlowIdHelper.setFlowId(inMsg, reqFid);
ListIterator<Interceptor<? extends Message>> interceptors = inMsg
.getInterceptorChain().getIterator();
while (interceptors.hasNext() && epi == null) {
Interceptor<? extends Message> interceptor = interceptors.next();
if (interceptor instanceof EventProducerInterceptor) {
epi = (EventProducerInterceptor) interceptor;
epi.handleMessage(inMsg);
}
}
} | [
"protected",
"void",
"handleINEvent",
"(",
"Exchange",
"exchange",
",",
"String",
"reqFid",
")",
"throws",
"Fault",
"{",
"Message",
"inMsg",
"=",
"exchange",
".",
"getInMessage",
"(",
")",
";",
"EventProducerInterceptor",
"epi",
"=",
"null",
";",
"FlowIdHelper",... | Calling EventProducerInterceptor in case of logging faults.
@param exchange
the message exchange
@param reqFid
the FlowId
@throws Fault
the fault | [
"Calling",
"EventProducerInterceptor",
"in",
"case",
"of",
"logging",
"faults",
"."
] | train | https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/sam/sam-agent/src/main/java/org/talend/esb/sam/agent/flowidprocessor/FlowIdProducerOut.java#L211-L228 |
Impetus/Kundera | src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBSchemaManager.java | CouchDBSchemaManager.checkForDBExistence | private boolean checkForDBExistence() throws ClientProtocolException, IOException, URISyntaxException
{
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
HttpGet get = new HttpGet(uri);
HttpResponse getRes = null;
try
{
// creating database.
getRes = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
if (getRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return true;
}
return false;
}
finally
{
CouchDBUtils.closeContent(getRes);
}
} | java | private boolean checkForDBExistence() throws ClientProtocolException, IOException, URISyntaxException
{
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
HttpGet get = new HttpGet(uri);
HttpResponse getRes = null;
try
{
// creating database.
getRes = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
if (getRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return true;
}
return false;
}
finally
{
CouchDBUtils.closeContent(getRes);
}
} | [
"private",
"boolean",
"checkForDBExistence",
"(",
")",
"throws",
"ClientProtocolException",
",",
"IOException",
",",
"URISyntaxException",
"{",
"URI",
"uri",
"=",
"new",
"URI",
"(",
"CouchDBConstants",
".",
"PROTOCOL",
",",
"null",
",",
"httpHost",
".",
"getHostNa... | Check for db existence.
@return true, if successful
@throws ClientProtocolException
the client protocol exception
@throws IOException
Signals that an I/O exception has occurred.
@throws URISyntaxException
the URI syntax exception | [
"Check",
"for",
"db",
"existence",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBSchemaManager.java#L716-L737 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/common/struct/ScheduledService.java | ScheduledService.start | public synchronized ScheduledService start() {
if (started) {
return this;
}
if (scheduledExecutorService == null) {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new NamedThreadFactory(threadName, true));
}
ScheduledFuture future = null;
switch (mode) {
case MODE_FIXEDRATE:
future = scheduledExecutorService.scheduleAtFixedRate(runnable, initialDelay,
period,
unit);
break;
case MODE_FIXEDDELAY:
future = scheduledExecutorService.scheduleWithFixedDelay(runnable, initialDelay, period,
unit);
break;
default:
break;
}
if (future != null) {
this.future = future;
// 缓存一下
SCHEDULED_SERVICE_MAP.put(this, System.currentTimeMillis());
started = true;
} else {
started = false;
}
return this;
} | java | public synchronized ScheduledService start() {
if (started) {
return this;
}
if (scheduledExecutorService == null) {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
new NamedThreadFactory(threadName, true));
}
ScheduledFuture future = null;
switch (mode) {
case MODE_FIXEDRATE:
future = scheduledExecutorService.scheduleAtFixedRate(runnable, initialDelay,
period,
unit);
break;
case MODE_FIXEDDELAY:
future = scheduledExecutorService.scheduleWithFixedDelay(runnable, initialDelay, period,
unit);
break;
default:
break;
}
if (future != null) {
this.future = future;
// 缓存一下
SCHEDULED_SERVICE_MAP.put(this, System.currentTimeMillis());
started = true;
} else {
started = false;
}
return this;
} | [
"public",
"synchronized",
"ScheduledService",
"start",
"(",
")",
"{",
"if",
"(",
"started",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"scheduledExecutorService",
"==",
"null",
")",
"{",
"scheduledExecutorService",
"=",
"new",
"ScheduledThreadPoolExecutor",
... | 开始执行定时任务
@return the boolean
@see ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)
@see ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit) | [
"开始执行定时任务"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/struct/ScheduledService.java#L127-L158 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java | CeCPMain.postProcessAlignment | public static AFPChain postProcessAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2m,CECalculator calculator, CECPParameters param ) throws StructureException{
// remove bottom half of the matrix
Matrix doubledMatrix = afpChain.getDistanceMatrix();
// the matrix can be null if the alignment is too short.
if ( doubledMatrix != null ) {
assert(doubledMatrix.getRowDimension() == ca1.length);
assert(doubledMatrix.getColumnDimension() == ca2m.length);
Matrix singleMatrix = doubledMatrix.getMatrix(0, ca1.length-1, 0, (ca2m.length/2)-1);
assert(singleMatrix.getRowDimension() == ca1.length);
assert(singleMatrix.getColumnDimension() == (ca2m.length/2));
afpChain.setDistanceMatrix(singleMatrix);
}
// Check for circular permutations
int alignLen = afpChain.getOptLength();
if ( alignLen > 0) {
afpChain = filterDuplicateAFPs(afpChain,calculator,ca1,ca2m,param);
}
return afpChain;
} | java | public static AFPChain postProcessAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2m,CECalculator calculator, CECPParameters param ) throws StructureException{
// remove bottom half of the matrix
Matrix doubledMatrix = afpChain.getDistanceMatrix();
// the matrix can be null if the alignment is too short.
if ( doubledMatrix != null ) {
assert(doubledMatrix.getRowDimension() == ca1.length);
assert(doubledMatrix.getColumnDimension() == ca2m.length);
Matrix singleMatrix = doubledMatrix.getMatrix(0, ca1.length-1, 0, (ca2m.length/2)-1);
assert(singleMatrix.getRowDimension() == ca1.length);
assert(singleMatrix.getColumnDimension() == (ca2m.length/2));
afpChain.setDistanceMatrix(singleMatrix);
}
// Check for circular permutations
int alignLen = afpChain.getOptLength();
if ( alignLen > 0) {
afpChain = filterDuplicateAFPs(afpChain,calculator,ca1,ca2m,param);
}
return afpChain;
} | [
"public",
"static",
"AFPChain",
"postProcessAlignment",
"(",
"AFPChain",
"afpChain",
",",
"Atom",
"[",
"]",
"ca1",
",",
"Atom",
"[",
"]",
"ca2m",
",",
"CECalculator",
"calculator",
",",
"CECPParameters",
"param",
")",
"throws",
"StructureException",
"{",
"// rem... | Circular permutation specific code to be run after the standard CE alignment
@param afpChain The finished alignment
@param ca1 CA atoms of the first protein
@param ca2m A duplicated copy of the second protein
@param calculator The CECalculator used to create afpChain
@param param Parameters
@throws StructureException | [
"Circular",
"permutation",
"specific",
"code",
"to",
"be",
"run",
"after",
"the",
"standard",
"CE",
"alignment"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java#L204-L226 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfStamper.java | PdfStamper.replacePage | public void replacePage(PdfReader r, int pageImported, int pageReplaced) {
stamper.replacePage(r, pageImported, pageReplaced);
} | java | public void replacePage(PdfReader r, int pageImported, int pageReplaced) {
stamper.replacePage(r, pageImported, pageReplaced);
} | [
"public",
"void",
"replacePage",
"(",
"PdfReader",
"r",
",",
"int",
"pageImported",
",",
"int",
"pageReplaced",
")",
"{",
"stamper",
".",
"replacePage",
"(",
"r",
",",
"pageImported",
",",
"pageReplaced",
")",
";",
"}"
] | Replaces a page from this document with a page from other document. Only the content
is replaced not the fields and annotations. This method must be called before
getOverContent() or getUndercontent() are called for the same page.
@param r the <CODE>PdfReader</CODE> from where the new page will be imported
@param pageImported the page number of the imported page
@param pageReplaced the page to replace in this document
@since iText 2.1.1 | [
"Replaces",
"a",
"page",
"from",
"this",
"document",
"with",
"a",
"page",
"from",
"other",
"document",
".",
"Only",
"the",
"content",
"is",
"replaced",
"not",
"the",
"fields",
"and",
"annotations",
".",
"This",
"method",
"must",
"be",
"called",
"before",
"... | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStamper.java#L157-L159 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/factory/AbstractObjectFactory.java | AbstractObjectFactory.resolveCompatibleConstructor | @SuppressWarnings("unchecked")
protected Constructor resolveCompatibleConstructor(final Class<?> objectType, final Class<?>[] parameterTypes) {
for (Constructor constructor : objectType.getConstructors()) {
Class[] constructorParameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == constructorParameterTypes.length) {
boolean match = true;
for (int index = 0; index < constructorParameterTypes.length; index++) {
match &= constructorParameterTypes[index].isAssignableFrom(parameterTypes[index]);
}
if (match) {
return constructor;
}
}
}
return null;
} | java | @SuppressWarnings("unchecked")
protected Constructor resolveCompatibleConstructor(final Class<?> objectType, final Class<?>[] parameterTypes) {
for (Constructor constructor : objectType.getConstructors()) {
Class[] constructorParameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == constructorParameterTypes.length) {
boolean match = true;
for (int index = 0; index < constructorParameterTypes.length; index++) {
match &= constructorParameterTypes[index].isAssignableFrom(parameterTypes[index]);
}
if (match) {
return constructor;
}
}
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"Constructor",
"resolveCompatibleConstructor",
"(",
"final",
"Class",
"<",
"?",
">",
"objectType",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
")",
"{",
"for",
"(",
"Constru... | Resolves the matching constructor for the specified Class type who's actual public constructor argument types
are assignment compatible with the expected parameter types.
@param objectType the Class from which the constructor is resolved.
@param parameterTypes the array of Class types determining the resolved constructor's signature.
@return a matching constructor from the specified Class type who's actual public constructor argument types
are assignment compatible with the expected parameter types.
@throws NullPointerException if either the objectType or parameterTypes are null.
@see #resolveConstructor(Class, Class[])
@see java.lang.Class
@see java.lang.reflect.Constructor | [
"Resolves",
"the",
"matching",
"constructor",
"for",
"the",
"specified",
"Class",
"type",
"who",
"s",
"actual",
"public",
"constructor",
"argument",
"types",
"are",
"assignment",
"compatible",
"with",
"the",
"expected",
"parameter",
"types",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/factory/AbstractObjectFactory.java#L166-L185 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java | SnowflakeResultChunk.getCell | public final Object getCell(int rowIdx, int colIdx)
{
if (resultData != null)
{
return extractCell(resultData, rowIdx, colIdx);
}
return data.get(colCount * rowIdx + colIdx);
} | java | public final Object getCell(int rowIdx, int colIdx)
{
if (resultData != null)
{
return extractCell(resultData, rowIdx, colIdx);
}
return data.get(colCount * rowIdx + colIdx);
} | [
"public",
"final",
"Object",
"getCell",
"(",
"int",
"rowIdx",
",",
"int",
"colIdx",
")",
"{",
"if",
"(",
"resultData",
"!=",
"null",
")",
"{",
"return",
"extractCell",
"(",
"resultData",
",",
"rowIdx",
",",
"colIdx",
")",
";",
"}",
"return",
"data",
".... | Creates a String object for the given cell
@param rowIdx zero based row
@param colIdx zero based column
@return String | [
"Creates",
"a",
"String",
"object",
"for",
"the",
"given",
"cell"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java#L140-L147 |
phax/ph-css | ph-css/src/main/java/com/helger/css/handler/CSSHandler.java | CSSHandler.readDeclarationListFromNode | @Nonnull
public static CSSDeclarationList readDeclarationListFromNode (@Nonnull final ECSSVersion eVersion,
@Nonnull final CSSNode aNode,
@Nonnull final ICSSInterpretErrorHandler aErrorHandler)
{
ValueEnforcer.notNull (eVersion, "Version");
ValueEnforcer.notNull (aNode, "Node");
if (!ECSSNodeType.STYLEDECLARATIONLIST.isNode (aNode, eVersion))
throw new CSSHandlingException (aNode, "Passed node is not a style declaration node!");
ValueEnforcer.notNull (aErrorHandler, "ErrorHandler");
return new CSSNodeToDomainObject (eVersion, aErrorHandler).createDeclarationListFromNode (aNode);
} | java | @Nonnull
public static CSSDeclarationList readDeclarationListFromNode (@Nonnull final ECSSVersion eVersion,
@Nonnull final CSSNode aNode,
@Nonnull final ICSSInterpretErrorHandler aErrorHandler)
{
ValueEnforcer.notNull (eVersion, "Version");
ValueEnforcer.notNull (aNode, "Node");
if (!ECSSNodeType.STYLEDECLARATIONLIST.isNode (aNode, eVersion))
throw new CSSHandlingException (aNode, "Passed node is not a style declaration node!");
ValueEnforcer.notNull (aErrorHandler, "ErrorHandler");
return new CSSNodeToDomainObject (eVersion, aErrorHandler).createDeclarationListFromNode (aNode);
} | [
"@",
"Nonnull",
"public",
"static",
"CSSDeclarationList",
"readDeclarationListFromNode",
"(",
"@",
"Nonnull",
"final",
"ECSSVersion",
"eVersion",
",",
"@",
"Nonnull",
"final",
"CSSNode",
"aNode",
",",
"@",
"Nonnull",
"final",
"ICSSInterpretErrorHandler",
"aErrorHandler"... | Create a {@link CSSDeclarationList} object from a parsed object.
@param eVersion
The CSS version to use. May not be <code>null</code>.
@param aNode
The parsed CSS object to read. May not be <code>null</code>.
@param aErrorHandler
The error handler to be used. May not be <code>null</code>.
@return Never <code>null</code>.
@since 5.0.2 | [
"Create",
"a",
"{",
"@link",
"CSSDeclarationList",
"}",
"object",
"from",
"a",
"parsed",
"object",
"."
] | train | https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/handler/CSSHandler.java#L118-L130 |
wildfly/wildfly-core | patching/src/main/java/org/jboss/as/patching/installation/InstallationManagerImpl.java | InstallationManagerImpl.getInstalledIdentities | @Override
public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {
List<InstalledIdentity> installedIdentities;
final File metadataDir = installedImage.getInstallationMetadata();
if(!metadataDir.exists()) {
installedIdentities = Collections.singletonList(defaultIdentity);
} else {
final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;
final File[] identityConfs = metadataDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() &&
pathname.getName().endsWith(Constants.DOT_CONF) &&
!pathname.getName().equals(defaultConf);
}
});
if(identityConfs == null || identityConfs.length == 0) {
installedIdentities = Collections.singletonList(defaultIdentity);
} else {
installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);
installedIdentities.add(defaultIdentity);
for(File conf : identityConfs) {
final Properties props = loadProductConf(conf);
String productName = conf.getName();
productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());
final String productVersion = props.getProperty(Constants.CURRENT_VERSION);
InstalledIdentity identity;
try {
identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);
} catch (IOException e) {
throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);
}
installedIdentities.add(identity);
}
}
}
return installedIdentities;
} | java | @Override
public List<InstalledIdentity> getInstalledIdentities() throws PatchingException {
List<InstalledIdentity> installedIdentities;
final File metadataDir = installedImage.getInstallationMetadata();
if(!metadataDir.exists()) {
installedIdentities = Collections.singletonList(defaultIdentity);
} else {
final String defaultConf = defaultIdentity.getIdentity().getName() + Constants.DOT_CONF;
final File[] identityConfs = metadataDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() &&
pathname.getName().endsWith(Constants.DOT_CONF) &&
!pathname.getName().equals(defaultConf);
}
});
if(identityConfs == null || identityConfs.length == 0) {
installedIdentities = Collections.singletonList(defaultIdentity);
} else {
installedIdentities = new ArrayList<InstalledIdentity>(identityConfs.length + 1);
installedIdentities.add(defaultIdentity);
for(File conf : identityConfs) {
final Properties props = loadProductConf(conf);
String productName = conf.getName();
productName = productName.substring(0, productName.length() - Constants.DOT_CONF.length());
final String productVersion = props.getProperty(Constants.CURRENT_VERSION);
InstalledIdentity identity;
try {
identity = LayersFactory.load(installedImage, new ProductConfig(productName, productVersion, null), moduleRoots, bundleRoots);
} catch (IOException e) {
throw new PatchingException(PatchLogger.ROOT_LOGGER.failedToLoadInfo(productName), e);
}
installedIdentities.add(identity);
}
}
}
return installedIdentities;
} | [
"@",
"Override",
"public",
"List",
"<",
"InstalledIdentity",
">",
"getInstalledIdentities",
"(",
")",
"throws",
"PatchingException",
"{",
"List",
"<",
"InstalledIdentity",
">",
"installedIdentities",
";",
"final",
"File",
"metadataDir",
"=",
"installedImage",
".",
"... | This method will return a list of installed identities for which
the corresponding .conf file exists under .installation directory.
The list will also include the default identity even if the .conf
file has not been created for it. | [
"This",
"method",
"will",
"return",
"a",
"list",
"of",
"installed",
"identities",
"for",
"which",
"the",
"corresponding",
".",
"conf",
"file",
"exists",
"under",
".",
"installation",
"directory",
".",
"The",
"list",
"will",
"also",
"include",
"the",
"default",... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/installation/InstallationManagerImpl.java#L148-L188 |
apereo/cas | core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/spring/boot/AbstractCasBanner.java | AbstractCasBanner.collectEnvironmentInfo | private String collectEnvironmentInfo(final Environment environment, final Class<?> sourceClass) {
val properties = System.getProperties();
if (properties.containsKey("CAS_BANNER_SKIP")) {
try (val formatter = new Formatter()) {
formatter.format("CAS Version: %s%n", CasVersion.getVersion());
return formatter.toString();
}
}
try (val formatter = new Formatter()) {
val sysInfo = SystemUtils.getSystemInfo();
sysInfo.forEach((k, v) -> {
if (k.startsWith(SEPARATOR_CHAR)) {
formatter.format("%s%n", LINE_SEPARATOR);
} else {
formatter.format("%s: %s%n", k, v);
}
});
formatter.format("%s%n", LINE_SEPARATOR);
injectEnvironmentInfoIntoBanner(formatter, environment, sourceClass);
return formatter.toString();
}
} | java | private String collectEnvironmentInfo(final Environment environment, final Class<?> sourceClass) {
val properties = System.getProperties();
if (properties.containsKey("CAS_BANNER_SKIP")) {
try (val formatter = new Formatter()) {
formatter.format("CAS Version: %s%n", CasVersion.getVersion());
return formatter.toString();
}
}
try (val formatter = new Formatter()) {
val sysInfo = SystemUtils.getSystemInfo();
sysInfo.forEach((k, v) -> {
if (k.startsWith(SEPARATOR_CHAR)) {
formatter.format("%s%n", LINE_SEPARATOR);
} else {
formatter.format("%s: %s%n", k, v);
}
});
formatter.format("%s%n", LINE_SEPARATOR);
injectEnvironmentInfoIntoBanner(formatter, environment, sourceClass);
return formatter.toString();
}
} | [
"private",
"String",
"collectEnvironmentInfo",
"(",
"final",
"Environment",
"environment",
",",
"final",
"Class",
"<",
"?",
">",
"sourceClass",
")",
"{",
"val",
"properties",
"=",
"System",
".",
"getProperties",
"(",
")",
";",
"if",
"(",
"properties",
".",
"... | Collect environment info with
details on the java and os deployment
versions.
@param environment the environment
@param sourceClass the source class
@return environment info | [
"Collect",
"environment",
"info",
"with",
"details",
"on",
"the",
"java",
"and",
"os",
"deployment",
"versions",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/spring/boot/AbstractCasBanner.java#L51-L73 |
apache/reef | lang/java/reef-runtime-yarn/src/main/java/org/apache/reef/runtime/yarn/client/YarnSubmissionHelper.java | YarnSubmissionHelper.setDriverResources | public YarnSubmissionHelper setDriverResources(final int memoryinMegabytes, final int numberOfCores) {
applicationSubmissionContext.setResource(Resource.newInstance(getMemory(memoryinMegabytes), numberOfCores));
return this;
} | java | public YarnSubmissionHelper setDriverResources(final int memoryinMegabytes, final int numberOfCores) {
applicationSubmissionContext.setResource(Resource.newInstance(getMemory(memoryinMegabytes), numberOfCores));
return this;
} | [
"public",
"YarnSubmissionHelper",
"setDriverResources",
"(",
"final",
"int",
"memoryinMegabytes",
",",
"final",
"int",
"numberOfCores",
")",
"{",
"applicationSubmissionContext",
".",
"setResource",
"(",
"Resource",
".",
"newInstance",
"(",
"getMemory",
"(",
"memoryinMeg... | Set the resources (memory and number of cores) for the Driver.
@param memoryinMegabytes memory to be allocated for the Driver, in MegaBytes.
@param numberOfCores Number of cores to allocate for the Driver.
@return this. | [
"Set",
"the",
"resources",
"(",
"memory",
"and",
"number",
"of",
"cores",
")",
"for",
"the",
"Driver",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-yarn/src/main/java/org/apache/reef/runtime/yarn/client/YarnSubmissionHelper.java#L150-L153 |
lightbend/config | config/src/main/java/com/typesafe/config/parser/ConfigDocumentFactory.java | ConfigDocumentFactory.parseString | public static ConfigDocument parseString(String s, ConfigParseOptions options) {
return Parseable.newString(s, options).parseConfigDocument();
} | java | public static ConfigDocument parseString(String s, ConfigParseOptions options) {
return Parseable.newString(s, options).parseConfigDocument();
} | [
"public",
"static",
"ConfigDocument",
"parseString",
"(",
"String",
"s",
",",
"ConfigParseOptions",
"options",
")",
"{",
"return",
"Parseable",
".",
"newString",
"(",
"s",
",",
"options",
")",
".",
"parseConfigDocument",
"(",
")",
";",
"}"
] | Parses a string which should be valid HOCON or JSON.
@param s string to parse
@param options parse options
@return the parsed configuration | [
"Parses",
"a",
"string",
"which",
"should",
"be",
"valid",
"HOCON",
"or",
"JSON",
"."
] | train | https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/parser/ConfigDocumentFactory.java#L79-L81 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/SheetCrossSheetReferenceResourcesImpl.java | SheetCrossSheetReferenceResourcesImpl.createCrossSheetReference | public CrossSheetReference createCrossSheetReference(long sheetId, CrossSheetReference crossSheetReference) throws SmartsheetException
{
return this.createResource("sheets/" + sheetId + "/crosssheetreferences", CrossSheetReference.class, crossSheetReference);
} | java | public CrossSheetReference createCrossSheetReference(long sheetId, CrossSheetReference crossSheetReference) throws SmartsheetException
{
return this.createResource("sheets/" + sheetId + "/crosssheetreferences", CrossSheetReference.class, crossSheetReference);
} | [
"public",
"CrossSheetReference",
"createCrossSheetReference",
"(",
"long",
"sheetId",
",",
"CrossSheetReference",
"crossSheetReference",
")",
"throws",
"SmartsheetException",
"{",
"return",
"this",
".",
"createResource",
"(",
"\"sheets/\"",
"+",
"sheetId",
"+",
"\"/crosss... | <p>Create a cross sheet reference in the given sheet.</p>
<p>It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/crosssheetreferences</p>
@param sheetId the sheet id
@param crossSheetReference the cross sheet reference to create
@return the created cross sheet reference
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | [
"<p",
">",
"Create",
"a",
"cross",
"sheet",
"reference",
"in",
"the",
"given",
"sheet",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetCrossSheetReferenceResourcesImpl.java#L109-L112 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/PCAResult.java | PCAResult.processDecomposition | private static EigenPair[] processDecomposition(EigenvalueDecomposition evd) {
double[] eigenvalues = evd.getRealEigenvalues();
double[][] eigenvectors = evd.getV();
EigenPair[] eigenPairs = new EigenPair[eigenvalues.length];
for(int i = 0; i < eigenvalues.length; i++) {
double e = Math.abs(eigenvalues[i]);
double[] v = VMath.getCol(eigenvectors, i);
eigenPairs[i] = new EigenPair(v, e);
}
Arrays.sort(eigenPairs, Comparator.reverseOrder());
return eigenPairs;
} | java | private static EigenPair[] processDecomposition(EigenvalueDecomposition evd) {
double[] eigenvalues = evd.getRealEigenvalues();
double[][] eigenvectors = evd.getV();
EigenPair[] eigenPairs = new EigenPair[eigenvalues.length];
for(int i = 0; i < eigenvalues.length; i++) {
double e = Math.abs(eigenvalues[i]);
double[] v = VMath.getCol(eigenvectors, i);
eigenPairs[i] = new EigenPair(v, e);
}
Arrays.sort(eigenPairs, Comparator.reverseOrder());
return eigenPairs;
} | [
"private",
"static",
"EigenPair",
"[",
"]",
"processDecomposition",
"(",
"EigenvalueDecomposition",
"evd",
")",
"{",
"double",
"[",
"]",
"eigenvalues",
"=",
"evd",
".",
"getRealEigenvalues",
"(",
")",
";",
"double",
"[",
"]",
"[",
"]",
"eigenvectors",
"=",
"... | Convert an eigenvalue decomposition into EigenPair objects.
@param evd Eigenvalue decomposition
@return Eigenpairs | [
"Convert",
"an",
"eigenvalue",
"decomposition",
"into",
"EigenPair",
"objects",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/pca/PCAResult.java#L85-L97 |
VoltDB/voltdb | src/frontend/org/voltdb/client/ReconnectStatusListener.java | ReconnectStatusListener.connectToOneServerWithRetry | private void connectToOneServerWithRetry(String hostname, int port) {
long sleep = m_initialRetryIntervalMS;
while (m_shouldContinue.get()) {
try {
m_client.createConnection(hostname, port);
LOG.info(String.format("Connected to VoltDB node at %s:%d.", hostname, port));
break;
} catch (Exception e) {
LOG.warn(String.format("Connection to VoltDB node at %s:%d failed - retrying in %d second(s).",
hostname, port, TimeUnit.MILLISECONDS.toSeconds(sleep)));
try {
Thread.sleep(sleep);
} catch (Exception ignored) {
}
if (sleep < m_maxRetryIntervalMS) {
sleep = Math.min(sleep + sleep, m_maxRetryIntervalMS);
}
}
}
} | java | private void connectToOneServerWithRetry(String hostname, int port) {
long sleep = m_initialRetryIntervalMS;
while (m_shouldContinue.get()) {
try {
m_client.createConnection(hostname, port);
LOG.info(String.format("Connected to VoltDB node at %s:%d.", hostname, port));
break;
} catch (Exception e) {
LOG.warn(String.format("Connection to VoltDB node at %s:%d failed - retrying in %d second(s).",
hostname, port, TimeUnit.MILLISECONDS.toSeconds(sleep)));
try {
Thread.sleep(sleep);
} catch (Exception ignored) {
}
if (sleep < m_maxRetryIntervalMS) {
sleep = Math.min(sleep + sleep, m_maxRetryIntervalMS);
}
}
}
} | [
"private",
"void",
"connectToOneServerWithRetry",
"(",
"String",
"hostname",
",",
"int",
"port",
")",
"{",
"long",
"sleep",
"=",
"m_initialRetryIntervalMS",
";",
"while",
"(",
"m_shouldContinue",
".",
"get",
"(",
")",
")",
"{",
"try",
"{",
"m_client",
".",
"... | Connect to a single server with retry. Limited exponential backoff.
No timeout. This will run until the process is killed or interrupted/closed
if it's not able to connect.
@param hostname host name
@param port port | [
"Connect",
"to",
"a",
"single",
"server",
"with",
"retry",
".",
"Limited",
"exponential",
"backoff",
".",
"No",
"timeout",
".",
"This",
"will",
"run",
"until",
"the",
"process",
"is",
"killed",
"or",
"interrupted",
"/",
"closed",
"if",
"it",
"s",
"not",
... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ReconnectStatusListener.java#L98-L117 |
beangle/beangle3 | ioc/spring/src/main/java/org/beangle/inject/spring/config/BeanDefinitionParser.java | BeanDefinitionParser.parseMetaElements | public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
} | java | public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
} | [
"public",
"void",
"parseMetaElements",
"(",
"Element",
"ele",
",",
"BeanMetadataAttributeAccessor",
"attributeAccessor",
")",
"{",
"NodeList",
"nl",
"=",
"ele",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nl",
"."... | <p>
parseMetaElements.
</p>
@param ele a {@link org.w3c.dom.Element} object.
@param attributeAccessor a {@link org.springframework.beans.BeanMetadataAttributeAccessor}
object. | [
"<p",
">",
"parseMetaElements",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/ioc/spring/src/main/java/org/beangle/inject/spring/config/BeanDefinitionParser.java#L334-L347 |
prestodb/presto-hadoop-apache2 | src/main/java/org/apache/hadoop/util/LineReader.java | LineReader.readLine | public int readLine(Text str, int maxLineLength,
int maxBytesToConsume)
throws IOException
{
maxLineLength = Math.min(maxLineLength, MAX_ARRAY_SIZE);
maxBytesToConsume = Math.min(maxBytesToConsume, MAX_ARRAY_SIZE);
if (this.recordDelimiterBytes != null) {
return readCustomLine(str, maxLineLength, maxBytesToConsume);
}
else {
return readDefaultLine(str, maxLineLength, maxBytesToConsume);
}
} | java | public int readLine(Text str, int maxLineLength,
int maxBytesToConsume)
throws IOException
{
maxLineLength = Math.min(maxLineLength, MAX_ARRAY_SIZE);
maxBytesToConsume = Math.min(maxBytesToConsume, MAX_ARRAY_SIZE);
if (this.recordDelimiterBytes != null) {
return readCustomLine(str, maxLineLength, maxBytesToConsume);
}
else {
return readDefaultLine(str, maxLineLength, maxBytesToConsume);
}
} | [
"public",
"int",
"readLine",
"(",
"Text",
"str",
",",
"int",
"maxLineLength",
",",
"int",
"maxBytesToConsume",
")",
"throws",
"IOException",
"{",
"maxLineLength",
"=",
"Math",
".",
"min",
"(",
"maxLineLength",
",",
"MAX_ARRAY_SIZE",
")",
";",
"maxBytesToConsume"... | Read one line from the InputStream into the given Text.
@param str the object to store the given line (without newline)
@param maxLineLength the maximum number of bytes to store into str;
the rest of the line is silently discarded.
@param maxBytesToConsume the maximum number of bytes to consume
in this call. This is only a hint, because if the line cross
this threshold, we allow it to happen. It can overshoot
potentially by as much as one buffer length.
@return the number of bytes read including the (longest) newline
found.
@throws IOException if the underlying stream throws | [
"Read",
"one",
"line",
"from",
"the",
"InputStream",
"into",
"the",
"given",
"Text",
"."
] | train | https://github.com/prestodb/presto-hadoop-apache2/blob/6c848073a47b777f47561255e467c954ec24e2f9/src/main/java/org/apache/hadoop/util/LineReader.java#L183-L195 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_RemoveRepeatedPoints.java | ST_RemoveRepeatedPoints.removeDuplicateCoordinates | public static GeometryCollection removeDuplicateCoordinates(GeometryCollection geometryCollection, double tolerance) throws SQLException {
ArrayList<Geometry> geoms = new ArrayList<>();
for (int i = 0; i < geometryCollection.getNumGeometries(); i++) {
Geometry geom = geometryCollection.getGeometryN(i);
geoms.add(removeDuplicateCoordinates(geom, tolerance));
}
return FACTORY.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
} | java | public static GeometryCollection removeDuplicateCoordinates(GeometryCollection geometryCollection, double tolerance) throws SQLException {
ArrayList<Geometry> geoms = new ArrayList<>();
for (int i = 0; i < geometryCollection.getNumGeometries(); i++) {
Geometry geom = geometryCollection.getGeometryN(i);
geoms.add(removeDuplicateCoordinates(geom, tolerance));
}
return FACTORY.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
} | [
"public",
"static",
"GeometryCollection",
"removeDuplicateCoordinates",
"(",
"GeometryCollection",
"geometryCollection",
",",
"double",
"tolerance",
")",
"throws",
"SQLException",
"{",
"ArrayList",
"<",
"Geometry",
">",
"geoms",
"=",
"new",
"ArrayList",
"<>",
"(",
")"... | Removes duplicated coordinates within a GeometryCollection
@param geometryCollection
@param tolerance to delete the coordinates
@return
@throws java.sql.SQLException | [
"Removes",
"duplicated",
"coordinates",
"within",
"a",
"GeometryCollection"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_RemoveRepeatedPoints.java#L196-L203 |
lightblueseas/file-worker | src/main/java/de/alpharogroup/file/checksum/ChecksumExtensions.java | ChecksumExtensions.getChecksum | public static String getChecksum(final File file, final Algorithm algorithm)
throws NoSuchAlgorithmException, IOException
{
return getChecksum(file, algorithm.getAlgorithm());
} | java | public static String getChecksum(final File file, final Algorithm algorithm)
throws NoSuchAlgorithmException, IOException
{
return getChecksum(file, algorithm.getAlgorithm());
} | [
"public",
"static",
"String",
"getChecksum",
"(",
"final",
"File",
"file",
",",
"final",
"Algorithm",
"algorithm",
")",
"throws",
"NoSuchAlgorithmException",
",",
"IOException",
"{",
"return",
"getChecksum",
"(",
"file",
",",
"algorithm",
".",
"getAlgorithm",
"(",... | Gets the checksum from the given file with an instance of the given algorithm.
@param file
the file.
@param algorithm
the algorithm to get the checksum. This could be for instance "MD4", "MD5",
"SHA-1", "SHA-256", "SHA-384" or "SHA-512".
@return The checksum from the file as a String object.
@throws NoSuchAlgorithmException
Is thrown if the algorithm is not supported or does not exists.
{@link java.security.MessageDigest} object.
@throws IOException
Signals that an I/O exception has occurred. | [
"Gets",
"the",
"checksum",
"from",
"the",
"given",
"file",
"with",
"an",
"instance",
"of",
"the",
"given",
"algorithm",
"."
] | train | https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/checksum/ChecksumExtensions.java#L196-L200 |
Mangopay/mangopay2-java-sdk | src/main/java/com/mangopay/core/RestTool.java | RestTool.addRequestHttpHeader | public void addRequestHttpHeader(Map<String, String> httpHeader) {
if (this.requestHttpHeaders == null)
this.requestHttpHeaders = new HashMap<>();
this.requestHttpHeaders.putAll(httpHeader);
} | java | public void addRequestHttpHeader(Map<String, String> httpHeader) {
if (this.requestHttpHeaders == null)
this.requestHttpHeaders = new HashMap<>();
this.requestHttpHeaders.putAll(httpHeader);
} | [
"public",
"void",
"addRequestHttpHeader",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"httpHeader",
")",
"{",
"if",
"(",
"this",
".",
"requestHttpHeaders",
"==",
"null",
")",
"this",
".",
"requestHttpHeaders",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",... | Adds HTTP headers as name/value pairs into the request.
@param httpHeader Collection of headers name/value pairs. | [
"Adds",
"HTTP",
"headers",
"as",
"name",
"/",
"value",
"pairs",
"into",
"the",
"request",
"."
] | train | https://github.com/Mangopay/mangopay2-java-sdk/blob/037cecb44ea62def63b507817fd9961649151157/src/main/java/com/mangopay/core/RestTool.java#L74-L80 |
thrau/jarchivelib | src/main/java/org/rauschig/jarchivelib/CommonsStreamFactory.java | CommonsStreamFactory.createCompressorOutputStream | static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getCompressionType(), destination);
} | java | static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getCompressionType(), destination);
} | [
"static",
"CompressorOutputStream",
"createCompressorOutputStream",
"(",
"CommonsCompressor",
"compressor",
",",
"File",
"destination",
")",
"throws",
"IOException",
",",
"CompressorException",
"{",
"return",
"createCompressorOutputStream",
"(",
"compressor",
".",
"getCompres... | Uses the {@link CompressorStreamFactory} and the name of the given compressor to create a new
{@link CompressorOutputStream} for the given destination {@link File}.
@param compressor the invoking compressor
@param destination the file to create the {@link CompressorOutputStream} for
@return a new {@link CompressorOutputStream}
@throws IOException if an I/O error occurs
@throws CompressorException if the compressor name is not known | [
"Uses",
"the",
"{",
"@link",
"CompressorStreamFactory",
"}",
"and",
"the",
"name",
"of",
"the",
"given",
"compressor",
"to",
"create",
"a",
"new",
"{",
"@link",
"CompressorOutputStream",
"}",
"for",
"the",
"given",
"destination",
"{",
"@link",
"File",
"}",
"... | train | https://github.com/thrau/jarchivelib/blob/8afee5124c588f589306796985b722d63572bbfa/src/main/java/org/rauschig/jarchivelib/CommonsStreamFactory.java#L180-L183 |
icode/ameba | src/main/java/ameba/core/Application.java | Application.readAppConfig | public static URL readAppConfig(Properties properties, String confFile) {
Enumeration<URL> urls = IOUtils.getResources(confFile);
URL url = null;
if (urls.hasMoreElements()) {
InputStream in = null;
Set<URL> urlSet = Sets.newHashSet(Iterators.forEnumeration(urls));
if (urlSet.size() > 1) {
String errorMsg = Messages.get("info.load.config.multi.error",
StringUtils.join(urlSet.stream().map(Application::toExternalForm), LINE_SEPARATOR));
logger.error(errorMsg);
throw new ConfigErrorException(errorMsg);
}
url = urlSet.iterator().next();
try {
logger.trace(Messages.get("info.load", toExternalForm(url)));
in = url.openStream();
} catch (IOException e) {
logger.error(Messages.get("info.load.error", toExternalForm(url)));
}
loadProperties(in, properties, url);
} else {
logger.warn(Messages.get("info.load.error.not.found", confFile));
}
return url;
} | java | public static URL readAppConfig(Properties properties, String confFile) {
Enumeration<URL> urls = IOUtils.getResources(confFile);
URL url = null;
if (urls.hasMoreElements()) {
InputStream in = null;
Set<URL> urlSet = Sets.newHashSet(Iterators.forEnumeration(urls));
if (urlSet.size() > 1) {
String errorMsg = Messages.get("info.load.config.multi.error",
StringUtils.join(urlSet.stream().map(Application::toExternalForm), LINE_SEPARATOR));
logger.error(errorMsg);
throw new ConfigErrorException(errorMsg);
}
url = urlSet.iterator().next();
try {
logger.trace(Messages.get("info.load", toExternalForm(url)));
in = url.openStream();
} catch (IOException e) {
logger.error(Messages.get("info.load.error", toExternalForm(url)));
}
loadProperties(in, properties, url);
} else {
logger.warn(Messages.get("info.load.error.not.found", confFile));
}
return url;
} | [
"public",
"static",
"URL",
"readAppConfig",
"(",
"Properties",
"properties",
",",
"String",
"confFile",
")",
"{",
"Enumeration",
"<",
"URL",
">",
"urls",
"=",
"IOUtils",
".",
"getResources",
"(",
"confFile",
")",
";",
"URL",
"url",
"=",
"null",
";",
"if",
... | <p>readAppConfig.</p>
@param properties a {@link java.util.Properties} object.
@param confFile a {@link java.lang.String} object.
@return a {@link java.net.URL} object. | [
"<p",
">",
"readAppConfig",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/core/Application.java#L313-L340 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarZooKeeperClient.java | AvatarZooKeeperClient.getPrimaryAvatarAddress | public String getPrimaryAvatarAddress(String address, Stat stat, boolean retry)
throws IOException, KeeperException, InterruptedException {
return getPrimaryAvatarAddress(address, stat, retry, false);
} | java | public String getPrimaryAvatarAddress(String address, Stat stat, boolean retry)
throws IOException, KeeperException, InterruptedException {
return getPrimaryAvatarAddress(address, stat, retry, false);
} | [
"public",
"String",
"getPrimaryAvatarAddress",
"(",
"String",
"address",
",",
"Stat",
"stat",
",",
"boolean",
"retry",
")",
"throws",
"IOException",
",",
"KeeperException",
",",
"InterruptedException",
"{",
"return",
"getPrimaryAvatarAddress",
"(",
"address",
",",
"... | Retrieves the primary address for the cluster, this does not perform a
sync before it reads the znode. | [
"Retrieves",
"the",
"primary",
"address",
"for",
"the",
"cluster",
"this",
"does",
"not",
"perform",
"a",
"sync",
"before",
"it",
"reads",
"the",
"znode",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarZooKeeperClient.java#L367-L370 |
line/armeria | core/src/main/java/com/linecorp/armeria/server/file/HttpFileBuilder.java | HttpFileBuilder.ofResource | public static HttpFileBuilder ofResource(ClassLoader classLoader, String path) {
requireNonNull(classLoader, "classLoader");
requireNonNull(path, "path");
// Strip the leading slash.
if (path.startsWith("/")) {
path = path.substring(1);
}
// Retrieve the resource URL.
final URL url = classLoader.getResource(path);
if (url == null || url.getPath().endsWith("/")) {
// Non-existent resource.
return new NonExistentHttpFileBuilder();
}
// Convert to a real file if possible.
if ("file".equals(url.getProtocol())) {
File f;
try {
f = new File(url.toURI());
} catch (URISyntaxException ignored) {
f = new File(url.getPath());
}
return of(f);
}
return new ClassPathHttpFileBuilder(url);
} | java | public static HttpFileBuilder ofResource(ClassLoader classLoader, String path) {
requireNonNull(classLoader, "classLoader");
requireNonNull(path, "path");
// Strip the leading slash.
if (path.startsWith("/")) {
path = path.substring(1);
}
// Retrieve the resource URL.
final URL url = classLoader.getResource(path);
if (url == null || url.getPath().endsWith("/")) {
// Non-existent resource.
return new NonExistentHttpFileBuilder();
}
// Convert to a real file if possible.
if ("file".equals(url.getProtocol())) {
File f;
try {
f = new File(url.toURI());
} catch (URISyntaxException ignored) {
f = new File(url.getPath());
}
return of(f);
}
return new ClassPathHttpFileBuilder(url);
} | [
"public",
"static",
"HttpFileBuilder",
"ofResource",
"(",
"ClassLoader",
"classLoader",
",",
"String",
"path",
")",
"{",
"requireNonNull",
"(",
"classLoader",
",",
"\"classLoader\"",
")",
";",
"requireNonNull",
"(",
"path",
",",
"\"path\"",
")",
";",
"// Strip the... | Returns a new {@link HttpFileBuilder} that builds an {@link HttpFile} from the classpath resource
at the specified {@code path} using the specified {@link ClassLoader}. | [
"Returns",
"a",
"new",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/file/HttpFileBuilder.java#L111-L140 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2ConnectionSettings.java | H2ConnectionSettings.processUpgradeHeaderSettings | protected void processUpgradeHeaderSettings(String settings) throws Http2Exception {
if (settings != null) {
byte[] decoded = decode(settings);
if (decoded != null) {
FrameSettings settingsFrame = new FrameSettings(0, decoded.length, (byte) 0x0, false, FrameDirection.READ);
settingsFrame.processPayload(decoded);
updateSettings(settingsFrame);
}
}
} | java | protected void processUpgradeHeaderSettings(String settings) throws Http2Exception {
if (settings != null) {
byte[] decoded = decode(settings);
if (decoded != null) {
FrameSettings settingsFrame = new FrameSettings(0, decoded.length, (byte) 0x0, false, FrameDirection.READ);
settingsFrame.processPayload(decoded);
updateSettings(settingsFrame);
}
}
} | [
"protected",
"void",
"processUpgradeHeaderSettings",
"(",
"String",
"settings",
")",
"throws",
"Http2Exception",
"{",
"if",
"(",
"settings",
"!=",
"null",
")",
"{",
"byte",
"[",
"]",
"decoded",
"=",
"decode",
"(",
"settings",
")",
";",
"if",
"(",
"decoded",
... | A settings frame can be encoded as a base-64 string and passed as a header on the initial upgrade request.
This method decodes that base-64 string and applies the encoded settings to this http2 connection. | [
"A",
"settings",
"frame",
"can",
"be",
"encoded",
"as",
"a",
"base",
"-",
"64",
"string",
"and",
"passed",
"as",
"a",
"header",
"on",
"the",
"initial",
"upgrade",
"request",
".",
"This",
"method",
"decodes",
"that",
"base",
"-",
"64",
"string",
"and",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2ConnectionSettings.java#L33-L43 |
knightliao/disconf | disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/dao/GenericDao.java | GenericDao.count | public int count(String column, Object value) {
return count(Operators.match(column, value));
} | java | public int count(String column, Object value) {
return count(Operators.match(column, value));
} | [
"public",
"int",
"count",
"(",
"String",
"column",
",",
"Object",
"value",
")",
"{",
"return",
"count",
"(",
"Operators",
".",
"match",
"(",
"column",
",",
"value",
")",
")",
";",
"}"
] | 查询符合条件的结果计数
@param column 条件字段
@param value 条件字段的值。支持集合对象,支持数组,会按照in 操作来组装条件
@return | [
"查询符合条件的结果计数"
] | train | https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-web/src/main/java/com/baidu/unbiz/common/genericdao/dao/GenericDao.java#L178-L180 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/productpackageservice/GetAllProductPackages.java | GetAllProductPackages.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ProductPackageService.
ProductPackageServiceInterface productPackageService =
adManagerServices.get(session, ProductPackageServiceInterface.class);
// Create a statement to select all product packages.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get product packages by statement.
ProductPackagePage page =
productPackageService.getProductPackagesByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ProductPackage productPackage : page.getResults()) {
System.out.printf(
"%d) Product package with ID %d and name '%s' was found.%n",
i++, productPackage.getId(), productPackage.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ProductPackageService.
ProductPackageServiceInterface productPackageService =
adManagerServices.get(session, ProductPackageServiceInterface.class);
// Create a statement to select all product packages.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get product packages by statement.
ProductPackagePage page =
productPackageService.getProductPackagesByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ProductPackage productPackage : page.getResults()) {
System.out.printf(
"%d) Product package with ID %d and name '%s' was found.%n",
i++, productPackage.getId(), productPackage.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the ProductPackageService.",
"ProductPackageServiceInterface",
"productPackageService",
"=",
"adManagerServi... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/productpackageservice/GetAllProductPackages.java#L53-L87 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.suppressField | @Deprecated
public static synchronized void suppressField(Class<?> clazz, String... fieldNames) {
SuppressCode.suppressField(clazz, fieldNames);
} | java | @Deprecated
public static synchronized void suppressField(Class<?> clazz, String... fieldNames) {
SuppressCode.suppressField(clazz, fieldNames);
} | [
"@",
"Deprecated",
"public",
"static",
"synchronized",
"void",
"suppressField",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"...",
"fieldNames",
")",
"{",
"SuppressCode",
".",
"suppressField",
"(",
"clazz",
",",
"fieldNames",
")",
";",
"}"
] | Suppress multiple methods for a class.
@param clazz The class whose methods will be suppressed.
@param fieldNames The names of the methods that'll be suppressed. If field names
are empty, <i>all</i> fields in the supplied class will be
suppressed.
@deprecated Use {@link #suppress(Field)} instead. | [
"Suppress",
"multiple",
"methods",
"for",
"a",
"class",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L1830-L1833 |
xiancloud/xian | xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java | ZKPaths.makePath | public static String makePath(String parent, String firstChild, String... restChildren)
{
StringBuilder path = new StringBuilder();
joinPath(path, parent, firstChild);
if ( restChildren == null )
{
return path.toString();
}
else
{
for ( String child : restChildren )
{
joinPath(path, "", child);
}
return path.toString();
}
} | java | public static String makePath(String parent, String firstChild, String... restChildren)
{
StringBuilder path = new StringBuilder();
joinPath(path, parent, firstChild);
if ( restChildren == null )
{
return path.toString();
}
else
{
for ( String child : restChildren )
{
joinPath(path, "", child);
}
return path.toString();
}
} | [
"public",
"static",
"String",
"makePath",
"(",
"String",
"parent",
",",
"String",
"firstChild",
",",
"String",
"...",
"restChildren",
")",
"{",
"StringBuilder",
"path",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"joinPath",
"(",
"path",
",",
"parent",
",",
... | Given a parent path and a list of children nodes, create a combined full path
@param parent the parent
@param firstChild the first children in the path
@param restChildren the rest of the children in the path
@return full path | [
"Given",
"a",
"parent",
"path",
"and",
"a",
"list",
"of",
"children",
"nodes",
"create",
"a",
"combined",
"full",
"path"
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java#L382-L401 |
alkacon/opencms-core | src-modules/org/opencms/workplace/commons/CmsLock.java | CmsLock.buildLockDialog | public static String buildLockDialog(CmsDialog dialog) throws CmsException {
return buildLockDialog(dialog, null, null, 2000, false);
} | java | public static String buildLockDialog(CmsDialog dialog) throws CmsException {
return buildLockDialog(dialog, null, null, 2000, false);
} | [
"public",
"static",
"String",
"buildLockDialog",
"(",
"CmsDialog",
"dialog",
")",
"throws",
"CmsException",
"{",
"return",
"buildLockDialog",
"(",
"dialog",
",",
"null",
",",
"null",
",",
"2000",
",",
"false",
")",
";",
"}"
] | Returns the html code to build the lock dialog.<p>
@return html code
@throws CmsException if something goes wrong | [
"Returns",
"the",
"html",
"code",
"to",
"build",
"the",
"lock",
"dialog",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsLock.java#L205-L208 |
alkacon/opencms-core | src/org/opencms/file/collectors/CmsPriorityResourceCollector.java | CmsPriorityResourceCollector.allMappedToUriPriorityDate | protected List<CmsResource> allMappedToUriPriorityDate(CmsObject cms, String param, boolean asc, int numResults)
throws CmsException {
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, true);
List<CmsResource> mapped = new ArrayList<CmsResource>();
// sort out the resources mapped to the current page
Iterator<CmsResource> i = result.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
// read all properties - reason: comparator will do this later anyway, so we just prefill the cache
CmsProperty prop = cms.readPropertyObject(res, PROPERTY_CHANNEL, false);
if (!prop.isNullProperty()) {
if (CmsProject.isInsideProject(
prop.getValueList(),
cms.getRequestContext().getSiteRoot() + cms.getRequestContext().getUri())) {
mapped.add(res);
}
}
}
if (mapped.isEmpty()) {
// nothing was mapped, no need for further processing
return mapped;
}
// create priority comparator to use to sort the resources
CmsPriorityDateResourceComparator comparator = new CmsPriorityDateResourceComparator(cms, asc);
Collections.sort(mapped, comparator);
return shrinkToFit(mapped, data.getCount(), numResults);
} | java | protected List<CmsResource> allMappedToUriPriorityDate(CmsObject cms, String param, boolean asc, int numResults)
throws CmsException {
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, true);
List<CmsResource> mapped = new ArrayList<CmsResource>();
// sort out the resources mapped to the current page
Iterator<CmsResource> i = result.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
// read all properties - reason: comparator will do this later anyway, so we just prefill the cache
CmsProperty prop = cms.readPropertyObject(res, PROPERTY_CHANNEL, false);
if (!prop.isNullProperty()) {
if (CmsProject.isInsideProject(
prop.getValueList(),
cms.getRequestContext().getSiteRoot() + cms.getRequestContext().getUri())) {
mapped.add(res);
}
}
}
if (mapped.isEmpty()) {
// nothing was mapped, no need for further processing
return mapped;
}
// create priority comparator to use to sort the resources
CmsPriorityDateResourceComparator comparator = new CmsPriorityDateResourceComparator(cms, asc);
Collections.sort(mapped, comparator);
return shrinkToFit(mapped, data.getCount(), numResults);
} | [
"protected",
"List",
"<",
"CmsResource",
">",
"allMappedToUriPriorityDate",
"(",
"CmsObject",
"cms",
",",
"String",
"param",
",",
"boolean",
"asc",
",",
"int",
"numResults",
")",
"throws",
"CmsException",
"{",
"CmsCollectorData",
"data",
"=",
"new",
"CmsCollectorD... | Returns a list of all resource from specified folder that have been mapped to
the currently requested uri, sorted by priority, then date ascending or descending.<p>
@param cms the current OpenCms user context
@param param the folder name to use
@param asc if true, the date sort order is ascending, otherwise descending
@param numResults the number of results
@return all resources in the folder matching the given criteria
@throws CmsException if something goes wrong | [
"Returns",
"a",
"list",
"of",
"all",
"resource",
"from",
"specified",
"folder",
"that",
"have",
"been",
"mapped",
"to",
"the",
"currently",
"requested",
"uri",
"sorted",
"by",
"priority",
"then",
"date",
"ascending",
"or",
"descending",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/collectors/CmsPriorityResourceCollector.java#L295-L336 |
redisson/redisson | redisson/src/main/java/org/redisson/spring/cache/CacheConfig.java | CacheConfig.toJSON | public static String toJSON(Map<String, ? extends CacheConfig> config) throws IOException {
return new CacheConfigSupport().toJSON(config);
} | java | public static String toJSON(Map<String, ? extends CacheConfig> config) throws IOException {
return new CacheConfigSupport().toJSON(config);
} | [
"public",
"static",
"String",
"toJSON",
"(",
"Map",
"<",
"String",
",",
"?",
"extends",
"CacheConfig",
">",
"config",
")",
"throws",
"IOException",
"{",
"return",
"new",
"CacheConfigSupport",
"(",
")",
".",
"toJSON",
"(",
"config",
")",
";",
"}"
] | Convert current configuration to JSON format
@param config object
@return json string
@throws IOException error | [
"Convert",
"current",
"configuration",
"to",
"JSON",
"format"
] | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/spring/cache/CacheConfig.java#L168-L170 |
igniterealtime/REST-API-Client | src/main/java/org/igniterealtime/restclient/RestApiClient.java | RestApiClient.deleteUserFromGroup | public Response deleteUserFromGroup(String username, String groupName) {
return restClient.delete("users/" + username + "/groups/" + groupName,
new HashMap<String, String>());
} | java | public Response deleteUserFromGroup(String username, String groupName) {
return restClient.delete("users/" + username + "/groups/" + groupName,
new HashMap<String, String>());
} | [
"public",
"Response",
"deleteUserFromGroup",
"(",
"String",
"username",
",",
"String",
"groupName",
")",
"{",
"return",
"restClient",
".",
"delete",
"(",
"\"users/\"",
"+",
"username",
"+",
"\"/groups/\"",
"+",
"groupName",
",",
"new",
"HashMap",
"<",
"String",
... | Delete user from group.
@param username the username
@param groupName the group name
@return the response | [
"Delete",
"user",
"from",
"group",
"."
] | train | https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L535-L538 |
Credntia/MVBarcodeReader | mvbarcodereader/src/main/java/devliving/online/mvbarcodereader/BarcodeCaptureFragment.java | BarcodeCaptureFragment.onRequestPermissionsResult | @Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != RC_HANDLE_CAMERA_PERM) {
Log.d("BARCODE-SCANNER", "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("BARCODE-SCANNER", "Camera permission granted - initialize the camera source");
// we have permission, so create the camerasource
initiateCamera();
return;
}
Log.e("BARCODE-SCANNER", "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
if (mListener != null) mListener.onBarcodeScanningFailed("Camera permission denied");
else {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Camera Permission Denied")
.setMessage(R.string.no_camera_permission)
.setPositiveButton(R.string.ok, listener)
.show();
}
} | java | @Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != RC_HANDLE_CAMERA_PERM) {
Log.d("BARCODE-SCANNER", "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("BARCODE-SCANNER", "Camera permission granted - initialize the camera source");
// we have permission, so create the camerasource
initiateCamera();
return;
}
Log.e("BARCODE-SCANNER", "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
if (mListener != null) mListener.onBarcodeScanningFailed("Camera permission denied");
else {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().finish();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Camera Permission Denied")
.setMessage(R.string.no_camera_permission)
.setPositiveButton(R.string.ok, listener)
.show();
}
} | [
"@",
"Override",
"public",
"void",
"onRequestPermissionsResult",
"(",
"int",
"requestCode",
",",
"@",
"NonNull",
"String",
"[",
"]",
"permissions",
",",
"@",
"NonNull",
"int",
"[",
"]",
"grantResults",
")",
"{",
"if",
"(",
"requestCode",
"!=",
"RC_HANDLE_CAMER... | Callback for the result from requesting permissions. This method
is invoked for every call on {@link #requestPermissions(String[], int)}.
<p>
<strong>Note:</strong> It is possible that the permissions request interaction
with the user is interrupted. In this case you will receive empty permissions
and results arrays which should be treated as a cancellation.
</p>
@param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
@param permissions The requested permissions. Never null.
@param grantResults The grant results for the corresponding permissions
which is either {@link PackageManager#PERMISSION_GRANTED}
or {@link PackageManager#PERMISSION_DENIED}. Never null.
@see #requestPermissions(String[], int) | [
"Callback",
"for",
"the",
"result",
"from",
"requesting",
"permissions",
".",
"This",
"method",
"is",
"invoked",
"for",
"every",
"call",
"on",
"{",
"@link",
"#requestPermissions",
"(",
"String",
"[]",
"int",
")",
"}",
".",
"<p",
">",
"<strong",
">",
"Note"... | train | https://github.com/Credntia/MVBarcodeReader/blob/2a2561f1c3b4d4e3c046a341fbf23a31eabfda8d/mvbarcodereader/src/main/java/devliving/online/mvbarcodereader/BarcodeCaptureFragment.java#L224-L259 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/RepositoryException.java | RepositoryException.toPersistException | public final PersistException toPersistException(final String message) {
Throwable cause;
if (this instanceof PersistException) {
cause = this;
} else {
cause = getCause();
}
if (cause == null) {
cause = this;
} else if (cause instanceof PersistException && message == null) {
return (PersistException) cause;
}
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = message;
} else if (message != null) {
causeMessage = message + " : " + causeMessage;
}
return makePersistException(causeMessage, cause);
} | java | public final PersistException toPersistException(final String message) {
Throwable cause;
if (this instanceof PersistException) {
cause = this;
} else {
cause = getCause();
}
if (cause == null) {
cause = this;
} else if (cause instanceof PersistException && message == null) {
return (PersistException) cause;
}
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = message;
} else if (message != null) {
causeMessage = message + " : " + causeMessage;
}
return makePersistException(causeMessage, cause);
} | [
"public",
"final",
"PersistException",
"toPersistException",
"(",
"final",
"String",
"message",
")",
"{",
"Throwable",
"cause",
";",
"if",
"(",
"this",
"instanceof",
"PersistException",
")",
"{",
"cause",
"=",
"this",
";",
"}",
"else",
"{",
"cause",
"=",
"ge... | Converts RepositoryException into an appropriate PersistException, prepending
the specified message. If message is null, original exception message is
preserved.
@param message message to prepend, which may be null | [
"Converts",
"RepositoryException",
"into",
"an",
"appropriate",
"PersistException",
"prepending",
"the",
"specified",
"message",
".",
"If",
"message",
"is",
"null",
"original",
"exception",
"message",
"is",
"preserved",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/RepositoryException.java#L139-L161 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.zip | public static Map zip(Object[] keys, Object[] values) {
return zip(java.util.Arrays.asList(keys), java.util.Arrays.asList(values), false);
} | java | public static Map zip(Object[] keys, Object[] values) {
return zip(java.util.Arrays.asList(keys), java.util.Arrays.asList(values), false);
} | [
"public",
"static",
"Map",
"zip",
"(",
"Object",
"[",
"]",
"keys",
",",
"Object",
"[",
"]",
"values",
")",
"{",
"return",
"zip",
"(",
"java",
".",
"util",
".",
"Arrays",
".",
"asList",
"(",
"keys",
")",
",",
"java",
".",
"util",
".",
"Arrays",
".... | Creates a map where the object at index N from the first Iterator is the key for the object at index N of the
second Iterator. <br> By default discards both key and value if either one is null.
@param keys array of keys
@param values array of values
@return map | [
"Creates",
"a",
"map",
"where",
"the",
"object",
"at",
"index",
"N",
"from",
"the",
"first",
"Iterator",
"is",
"the",
"key",
"for",
"the",
"object",
"at",
"index",
"N",
"of",
"the",
"second",
"Iterator",
".",
"<br",
">",
"By",
"default",
"discards",
"b... | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L204-L206 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/ArrayLabelSetterFactory.java | ArrayLabelSetterFactory.createMapField | private Optional<ArrayLabelSetter> createMapField(final Class<?> beanClass, final String fieldName) {
final Field labelsField;
try {
labelsField = beanClass.getDeclaredField("labels");
labelsField.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
// フィールドが見つからない場合は、何もしない。
return Optional.empty();
}
if(!Map.class.isAssignableFrom(labelsField.getType())) {
return Optional.empty();
}
final ParameterizedType type = (ParameterizedType) labelsField.getGenericType();
final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0];
final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1];
if(keyType.equals(String.class) && valueType.equals(String.class)) {
return Optional.of(new ArrayLabelSetter() {
@SuppressWarnings("unchecked")
@Override
public void set(final Object beanObj, final String label, final int index) {
ArgUtils.notNull(beanObj, "beanObj");
ArgUtils.notEmpty(label, "label");
try {
Map<String, String> labelsMapObj = (Map<String, String>) labelsField.get(beanObj);
if(labelsMapObj == null) {
labelsMapObj = new LinkedHashMap<>();
labelsField.set(beanObj, labelsMapObj);
}
final String mapKey = createMapKey(fieldName, index);
labelsMapObj.put(mapKey, label);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("fail access labels field.", e);
}
}
});
} else {
// タイプが一致しない場合
log.warn("not match generics type of labels. key type:{}, value type:{}.", keyType.getName(), valueType.getName());
return Optional.empty();
}
} | java | private Optional<ArrayLabelSetter> createMapField(final Class<?> beanClass, final String fieldName) {
final Field labelsField;
try {
labelsField = beanClass.getDeclaredField("labels");
labelsField.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
// フィールドが見つからない場合は、何もしない。
return Optional.empty();
}
if(!Map.class.isAssignableFrom(labelsField.getType())) {
return Optional.empty();
}
final ParameterizedType type = (ParameterizedType) labelsField.getGenericType();
final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0];
final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1];
if(keyType.equals(String.class) && valueType.equals(String.class)) {
return Optional.of(new ArrayLabelSetter() {
@SuppressWarnings("unchecked")
@Override
public void set(final Object beanObj, final String label, final int index) {
ArgUtils.notNull(beanObj, "beanObj");
ArgUtils.notEmpty(label, "label");
try {
Map<String, String> labelsMapObj = (Map<String, String>) labelsField.get(beanObj);
if(labelsMapObj == null) {
labelsMapObj = new LinkedHashMap<>();
labelsField.set(beanObj, labelsMapObj);
}
final String mapKey = createMapKey(fieldName, index);
labelsMapObj.put(mapKey, label);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("fail access labels field.", e);
}
}
});
} else {
// タイプが一致しない場合
log.warn("not match generics type of labels. key type:{}, value type:{}.", keyType.getName(), valueType.getName());
return Optional.empty();
}
} | [
"private",
"Optional",
"<",
"ArrayLabelSetter",
">",
"createMapField",
"(",
"final",
"Class",
"<",
"?",
">",
"beanClass",
",",
"final",
"String",
"fieldName",
")",
"{",
"final",
"Field",
"labelsField",
";",
"try",
"{",
"labelsField",
"=",
"beanClass",
".",
"... | {@link Map}フィールドにラベル情報が格納されている場合。
<p>キーはフィールド名。</p>
@param beanClass フィールドが定義してあるクラスのインスタンス
@param fieldName フィールド名
@return ラベル情報の設定用クラス | [
"{",
"@link",
"Map",
"}",
"フィールドにラベル情報が格納されている場合。",
"<p",
">",
"キーはフィールド名。<",
"/",
"p",
">"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/ArrayLabelSetterFactory.java#L77-L129 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbStatement.java | MariaDbStatement.executeLargeUpdate | @Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
return executeLargeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
} | java | @Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
return executeLargeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
} | [
"@",
"Override",
"public",
"long",
"executeLargeUpdate",
"(",
"String",
"sql",
",",
"int",
"[",
"]",
"columnIndexes",
")",
"throws",
"SQLException",
"{",
"return",
"executeLargeUpdate",
"(",
"sql",
",",
"Statement",
".",
"RETURN_GENERATED_KEYS",
")",
";",
"}"
] | Identical to executeLargeUpdate(String sql, int autoGeneratedKeys) with autoGeneratedKeys =
Statement.RETURN_GENERATED_KEYS set.
@param sql sql command
@param columnIndexes column Indexes
@return update counts
@throws SQLException if any error occur during execution | [
"Identical",
"to",
"executeLargeUpdate",
"(",
"String",
"sql",
"int",
"autoGeneratedKeys",
")",
"with",
"autoGeneratedKeys",
"=",
"Statement",
".",
"RETURN_GENERATED_KEYS",
"set",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L656-L659 |
aws/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/CreateAppRequest.java | CreateAppRequest.withAttributes | public CreateAppRequest withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | java | public CreateAppRequest withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} | [
"public",
"CreateAppRequest",
"withAttributes",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"attributes",
")",
"{",
"setAttributes",
"(",
"attributes",
")",
";",
"return",
"this",
";",
"}"
] | <p>
One or more user-defined key/value pairs to be added to the stack attributes.
</p>
@param attributes
One or more user-defined key/value pairs to be added to the stack attributes.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"One",
"or",
"more",
"user",
"-",
"defined",
"key",
"/",
"value",
"pairs",
"to",
"be",
"added",
"to",
"the",
"stack",
"attributes",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/CreateAppRequest.java#L708-L711 |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java | BndUtils.throwAsMalformedURLException | private static void throwAsMalformedURLException( final String message, final Exception cause )
throws MalformedURLException
{
final MalformedURLException exception = new MalformedURLException( message );
exception.initCause( cause );
throw exception;
} | java | private static void throwAsMalformedURLException( final String message, final Exception cause )
throws MalformedURLException
{
final MalformedURLException exception = new MalformedURLException( message );
exception.initCause( cause );
throw exception;
} | [
"private",
"static",
"void",
"throwAsMalformedURLException",
"(",
"final",
"String",
"message",
",",
"final",
"Exception",
"cause",
")",
"throws",
"MalformedURLException",
"{",
"final",
"MalformedURLException",
"exception",
"=",
"new",
"MalformedURLException",
"(",
"mes... | Creates an MalformedURLException with a message and a cause.
@param message exception message
@param cause exception cause
@throws MalformedURLException the created MalformedURLException | [
"Creates",
"an",
"MalformedURLException",
"with",
"a",
"message",
"and",
"a",
"cause",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L350-L356 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/HTODDependencyTable.java | HTODDependencyTable.removeEntry | public Result removeEntry(Object dependency, Object entry) {
Result result = this.htod.getFromResultPool();
ValueSet valueSet = (ValueSet) dependencyToEntryTable.get(dependency);
if (valueSet == null) {
return result;
}
result.bExist = HTODDynacache.EXIST;
valueSet.remove(entry);
dependencyNotUpdatedTable.remove(dependency);
if (valueSet.isEmpty()) {
dependencyToEntryTable.remove(dependency);
if (this.type == DEP_ID_TABLE) {
result.returnCode = this.htod.delValueSet(HTODDynacache.DEP_ID_DATA, dependency);
} else {
result.returnCode = this.htod.delValueSet(HTODDynacache.TEMPLATE_ID_DATA, dependency);
}
}
return result;
} | java | public Result removeEntry(Object dependency, Object entry) {
Result result = this.htod.getFromResultPool();
ValueSet valueSet = (ValueSet) dependencyToEntryTable.get(dependency);
if (valueSet == null) {
return result;
}
result.bExist = HTODDynacache.EXIST;
valueSet.remove(entry);
dependencyNotUpdatedTable.remove(dependency);
if (valueSet.isEmpty()) {
dependencyToEntryTable.remove(dependency);
if (this.type == DEP_ID_TABLE) {
result.returnCode = this.htod.delValueSet(HTODDynacache.DEP_ID_DATA, dependency);
} else {
result.returnCode = this.htod.delValueSet(HTODDynacache.TEMPLATE_ID_DATA, dependency);
}
}
return result;
} | [
"public",
"Result",
"removeEntry",
"(",
"Object",
"dependency",
",",
"Object",
"entry",
")",
"{",
"Result",
"result",
"=",
"this",
".",
"htod",
".",
"getFromResultPool",
"(",
")",
";",
"ValueSet",
"valueSet",
"=",
"(",
"ValueSet",
")",
"dependencyToEntryTable"... | This removes the specified entry from the specified dependency.
@param dependency The dependency.
@param result | [
"This",
"removes",
"the",
"specified",
"entry",
"from",
"the",
"specified",
"dependency",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/HTODDependencyTable.java#L179-L199 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java | MSPDIWriter.writeAssignmentTimephasedData | private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)
{
for (TimephasedWork mpx : data)
{
TimephasedDataType xml = m_factory.createTimephasedDataType();
list.add(xml);
xml.setStart(mpx.getStart());
xml.setFinish(mpx.getFinish());
xml.setType(BigInteger.valueOf(type));
xml.setUID(assignmentID);
xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));
xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));
}
} | java | private void writeAssignmentTimephasedData(BigInteger assignmentID, List<TimephasedDataType> list, List<TimephasedWork> data, int type)
{
for (TimephasedWork mpx : data)
{
TimephasedDataType xml = m_factory.createTimephasedDataType();
list.add(xml);
xml.setStart(mpx.getStart());
xml.setFinish(mpx.getFinish());
xml.setType(BigInteger.valueOf(type));
xml.setUID(assignmentID);
xml.setUnit(DatatypeConverter.printDurationTimeUnits(mpx.getTotalAmount(), false));
xml.setValue(DatatypeConverter.printDuration(this, mpx.getTotalAmount()));
}
} | [
"private",
"void",
"writeAssignmentTimephasedData",
"(",
"BigInteger",
"assignmentID",
",",
"List",
"<",
"TimephasedDataType",
">",
"list",
",",
"List",
"<",
"TimephasedWork",
">",
"data",
",",
"int",
"type",
")",
"{",
"for",
"(",
"TimephasedWork",
"mpx",
":",
... | Writes a list of timephased data to the MSPDI file.
@param assignmentID current assignment ID
@param list output list of timephased data items
@param data input list of timephased data
@param type list type (planned or completed) | [
"Writes",
"a",
"list",
"of",
"timephased",
"data",
"to",
"the",
"MSPDI",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIWriter.java#L1894-L1908 |
cdk/cdk | display/renderawt/src/main/java/org/openscience/cdk/renderer/visitor/AbstractAWTDrawVisitor.java | AbstractAWTDrawVisitor.getTextBounds | protected Rectangle2D getTextBounds(String text, Graphics2D g2) {
return new TextLayout(text, g2.getFont(), g2.getFontRenderContext()).getBounds();
} | java | protected Rectangle2D getTextBounds(String text, Graphics2D g2) {
return new TextLayout(text, g2.getFont(), g2.getFontRenderContext()).getBounds();
} | [
"protected",
"Rectangle2D",
"getTextBounds",
"(",
"String",
"text",
",",
"Graphics2D",
"g2",
")",
"{",
"return",
"new",
"TextLayout",
"(",
"text",
",",
"g2",
".",
"getFont",
"(",
")",
",",
"g2",
".",
"getFontRenderContext",
"(",
")",
")",
".",
"getBounds",... | Obtain the exact bounding box of the {@code text} in the provided
graphics environment.
@param text the text to obtain the bounds of
@param g2 the graphic environment
@return bounds of the text
@see TextLayout | [
"Obtain",
"the",
"exact",
"bounding",
"box",
"of",
"the",
"{",
"@code",
"text",
"}",
"in",
"the",
"provided",
"graphics",
"environment",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderawt/src/main/java/org/openscience/cdk/renderer/visitor/AbstractAWTDrawVisitor.java#L120-L122 |
jcustenborder/connect-utils | connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/validators/Validators.java | Validators.validHostAndPort | public static Validator validHostAndPort(Integer defaultPort, boolean requireBracketsForIPv6, boolean portRequired) {
return ValidHostAndPort.of(defaultPort, requireBracketsForIPv6, portRequired);
} | java | public static Validator validHostAndPort(Integer defaultPort, boolean requireBracketsForIPv6, boolean portRequired) {
return ValidHostAndPort.of(defaultPort, requireBracketsForIPv6, portRequired);
} | [
"public",
"static",
"Validator",
"validHostAndPort",
"(",
"Integer",
"defaultPort",
",",
"boolean",
"requireBracketsForIPv6",
",",
"boolean",
"portRequired",
")",
"{",
"return",
"ValidHostAndPort",
".",
"of",
"(",
"defaultPort",
",",
"requireBracketsForIPv6",
",",
"po... | Validator to ensure that a configuration setting is a hostname and port.
@param defaultPort
@param requireBracketsForIPv6
@param portRequired
@return validator | [
"Validator",
"to",
"ensure",
"that",
"a",
"configuration",
"setting",
"is",
"a",
"hostname",
"and",
"port",
"."
] | train | https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/validators/Validators.java#L182-L184 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsSqlManager.java | CmsSqlManager.getPreparedStatement | public PreparedStatement getPreparedStatement(Connection con, CmsProject project, String queryKey)
throws SQLException {
return getPreparedStatement(con, project.getUuid(), queryKey);
} | java | public PreparedStatement getPreparedStatement(Connection con, CmsProject project, String queryKey)
throws SQLException {
return getPreparedStatement(con, project.getUuid(), queryKey);
} | [
"public",
"PreparedStatement",
"getPreparedStatement",
"(",
"Connection",
"con",
",",
"CmsProject",
"project",
",",
"String",
"queryKey",
")",
"throws",
"SQLException",
"{",
"return",
"getPreparedStatement",
"(",
"con",
",",
"project",
".",
"getUuid",
"(",
")",
",... | Returns a PreparedStatement for a JDBC connection specified by the key of a SQL query
and the CmsProject.<p>
@param con the JDBC connection
@param project the specified CmsProject
@param queryKey the key of the SQL query
@return PreparedStatement a new PreparedStatement containing the pre-compiled SQL statement
@throws SQLException if a database access error occurs | [
"Returns",
"a",
"PreparedStatement",
"for",
"a",
"JDBC",
"connection",
"specified",
"by",
"the",
"key",
"of",
"a",
"SQL",
"query",
"and",
"the",
"CmsProject",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSqlManager.java#L239-L243 |
OpenTSDB/opentsdb | src/core/TSDB.java | TSDB.addPoint | public Deferred<Object> addPoint(final String metric,
final long timestamp,
final long value,
final Map<String, String> tags) {
final byte[] v;
if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) {
v = new byte[] { (byte) value };
} else if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) {
v = Bytes.fromShort((short) value);
} else if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) {
v = Bytes.fromInt((int) value);
} else {
v = Bytes.fromLong(value);
}
final short flags = (short) (v.length - 1); // Just the length.
return addPointInternal(metric, timestamp, v, tags, flags);
} | java | public Deferred<Object> addPoint(final String metric,
final long timestamp,
final long value,
final Map<String, String> tags) {
final byte[] v;
if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) {
v = new byte[] { (byte) value };
} else if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) {
v = Bytes.fromShort((short) value);
} else if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) {
v = Bytes.fromInt((int) value);
} else {
v = Bytes.fromLong(value);
}
final short flags = (short) (v.length - 1); // Just the length.
return addPointInternal(metric, timestamp, v, tags, flags);
} | [
"public",
"Deferred",
"<",
"Object",
">",
"addPoint",
"(",
"final",
"String",
"metric",
",",
"final",
"long",
"timestamp",
",",
"final",
"long",
"value",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"final",
"byte",
"[",
"]... | Adds a single integer value data point in the TSDB.
<p>
WARNING: The tags map may be modified by this method without a lock. Give
the method a copy if you plan to use it elsewhere.
<p>
@param metric A non-empty string.
@param timestamp The timestamp associated with the value.
@param value The value of the data point.
@param tags The tags on this series. This map must be non-empty.
@return A deferred object that indicates the completion of the request.
The {@link Object} has not special meaning and can be {@code null} (think
of it as {@code Deferred<Void>}). But you probably want to attach at
least an errback to this {@code Deferred} to handle failures.
@throws IllegalArgumentException if the timestamp is less than or equal
to the previous timestamp added or 0 for the first timestamp, or if the
difference with the previous timestamp is too large.
@throws IllegalArgumentException if the metric name is empty or contains
illegal characters.
@throws IllegalArgumentException if the tags list is empty or one of the
elements contains illegal characters.
@throws HBaseException (deferred) if there was a problem while persisting
data. | [
"Adds",
"a",
"single",
"integer",
"value",
"data",
"point",
"in",
"the",
"TSDB",
".",
"<p",
">",
"WARNING",
":",
"The",
"tags",
"map",
"may",
"be",
"modified",
"by",
"this",
"method",
"without",
"a",
"lock",
".",
"Give",
"the",
"method",
"a",
"copy",
... | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/TSDB.java#L1004-L1021 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.toAsync | public static <T1, T2, R> Func2<T1, T2, Observable<R>> toAsync(Func2<? super T1, ? super T2, ? extends R> func) {
return toAsync(func, Schedulers.computation());
} | java | public static <T1, T2, R> Func2<T1, T2, Observable<R>> toAsync(Func2<? super T1, ? super T2, ? extends R> func) {
return toAsync(func, Schedulers.computation());
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"R",
">",
"Func2",
"<",
"T1",
",",
"T2",
",",
"Observable",
"<",
"R",
">",
">",
"toAsync",
"(",
"Func2",
"<",
"?",
"super",
"T1",
",",
"?",
"super",
"T2",
",",
"?",
"extends",
"R",
">",
"func",
"... | Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.png" alt="">
@param <T1> the first parameter type
@param <T2> the second parameter type
@param <R> the result type
@param func the function to convert
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229851.aspx">MSDN: Observable.ToAsync</a> | [
"Convert",
"a",
"synchronous",
"function",
"call",
"into",
"an",
"asynchronous",
"function",
"call",
"through",
"an",
"Observable",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki"... | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L256-L258 |
morfologik/morfologik-stemming | morfologik-stemming/src/main/java/morfologik/stemming/BufferUtils.java | BufferUtils.sharedPrefixLength | static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
int i = 0;
final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
aStart += a.position();
bStart += b.position();
while (i < max && a.get(aStart++) == b.get(bStart++)) {
i++;
}
return i;
} | java | static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
int i = 0;
final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
aStart += a.position();
bStart += b.position();
while (i < max && a.get(aStart++) == b.get(bStart++)) {
i++;
}
return i;
} | [
"static",
"int",
"sharedPrefixLength",
"(",
"ByteBuffer",
"a",
",",
"int",
"aStart",
",",
"ByteBuffer",
"b",
",",
"int",
"bStart",
")",
"{",
"int",
"i",
"=",
"0",
";",
"final",
"int",
"max",
"=",
"Math",
".",
"min",
"(",
"a",
".",
"remaining",
"(",
... | Compute the length of the shared prefix between two byte sequences. | [
"Compute",
"the",
"length",
"of",
"the",
"shared",
"prefix",
"between",
"two",
"byte",
"sequences",
"."
] | train | https://github.com/morfologik/morfologik-stemming/blob/9d9099cc5ec4155a0eb8dfecdc23d01cbd734f6e/morfologik-stemming/src/main/java/morfologik/stemming/BufferUtils.java#L99-L108 |
js-lib-com/commons | src/main/java/js/util/Strings.java | Strings.replaceAll | public static String replaceAll(String source, Pattern pattern, Handler<String, String> handler)
{
Matcher matcher = pattern.matcher(source);
StringBuilder builder = new StringBuilder();
int start = 0;
while(matcher.find(start)) {
builder.append(source.substring(start, matcher.start()));
if(matcher.groupCount() == 0) {
builder.append(handler.handle(source.substring(matcher.start(), matcher.end())));
}
else {
for(int i = 0; i < matcher.groupCount(); ++i) {
builder.append(handler.handle(matcher.group(i + 1)));
}
}
start = matcher.end();
}
builder.append(source.substring(start));
return builder.toString();
} | java | public static String replaceAll(String source, Pattern pattern, Handler<String, String> handler)
{
Matcher matcher = pattern.matcher(source);
StringBuilder builder = new StringBuilder();
int start = 0;
while(matcher.find(start)) {
builder.append(source.substring(start, matcher.start()));
if(matcher.groupCount() == 0) {
builder.append(handler.handle(source.substring(matcher.start(), matcher.end())));
}
else {
for(int i = 0; i < matcher.groupCount(); ++i) {
builder.append(handler.handle(matcher.group(i + 1)));
}
}
start = matcher.end();
}
builder.append(source.substring(start));
return builder.toString();
} | [
"public",
"static",
"String",
"replaceAll",
"(",
"String",
"source",
",",
"Pattern",
"pattern",
",",
"Handler",
"<",
"String",
",",
"String",
">",
"handler",
")",
"{",
"Matcher",
"matcher",
"=",
"pattern",
".",
"matcher",
"(",
"source",
")",
";",
"StringBu... | Replace all pattern occurrences using match transformer. This method is the standard replace all but allows for
matched pattern transformation via caller code handler. Common usage is to supply match transformer as anonymous
instance of {@link Handler} interface. If {@link Handler#handle(Object)} method returns given <code>match</code>
value replace all degrade to standard behavior, and of course there is no need to use it.
<pre>
Pattern pattern = Pattern.compile("i");
String text = Strings.replaceAll("This is a text", pattern, new Handler<String, String>()
{
public String handle(String match)
{
return "<em>" + match + "</em>";
}
});
</pre>
In above sample code, after replace all, <code>text</code> will be <em>Th<em>i</em>s
<em>i</em>s a text</em>.
@param source source string,
@param pattern pattern to look for,
@param handler match transformer.
@return new string with pattern replaced. | [
"Replace",
"all",
"pattern",
"occurrences",
"using",
"match",
"transformer",
".",
"This",
"method",
"is",
"the",
"standard",
"replace",
"all",
"but",
"allows",
"for",
"matched",
"pattern",
"transformation",
"via",
"caller",
"code",
"handler",
".",
"Common",
"usa... | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Strings.java#L1169-L1188 |
gitblit/fathom | fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java | SwaggerBuilder.translate | protected String translate(String messageKey, String defaultMessage) {
if (messages == null || Strings.isNullOrEmpty(messageKey)) {
return Strings.emptyToNull(defaultMessage);
}
return Strings.emptyToNull(messages.getWithDefault(messageKey, defaultMessage, defaultLanguage));
} | java | protected String translate(String messageKey, String defaultMessage) {
if (messages == null || Strings.isNullOrEmpty(messageKey)) {
return Strings.emptyToNull(defaultMessage);
}
return Strings.emptyToNull(messages.getWithDefault(messageKey, defaultMessage, defaultLanguage));
} | [
"protected",
"String",
"translate",
"(",
"String",
"messageKey",
",",
"String",
"defaultMessage",
")",
"{",
"if",
"(",
"messages",
"==",
"null",
"||",
"Strings",
".",
"isNullOrEmpty",
"(",
"messageKey",
")",
")",
"{",
"return",
"Strings",
".",
"emptyToNull",
... | Attempts to provide a localized message.
@param messageKey
@param defaultMessage
@return the default message or a localized message or null | [
"Attempts",
"to",
"provide",
"a",
"localized",
"message",
"."
] | train | https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L1083-L1088 |
lessthanoptimal/BoofCV | examples/src/main/java/boofcv/examples/imageprocessing/ExampleFourierTransform.java | ExampleFourierTransform.applyBoxFilter | public static void applyBoxFilter( GrayF32 input ) {
// declare storage
GrayF32 boxImage = new GrayF32(input.width, input.height);
InterleavedF32 boxTransform = new InterleavedF32(input.width,input.height,2);
InterleavedF32 transform = new InterleavedF32(input.width,input.height,2);
GrayF32 blurredImage = new GrayF32(input.width, input.height);
GrayF32 spatialBlur = new GrayF32(input.width, input.height);
DiscreteFourierTransform<GrayF32,InterleavedF32> dft =
DiscreteFourierTransformOps.createTransformF32();
// Make the image scaled from 0 to 1 to reduce overflow issues
PixelMath.divide(input,255.0f,input);
// compute the Fourier Transform
dft.forward(input,transform);
// create the box filter which is centered around the pixel. Note that the filter gets wrapped around
// the image edges
for( int y = 0; y < 15; y++ ) {
int yy = y-7 < 0 ? boxImage.height+(y-7) : y - 7;
for( int x = 0; x < 15; x++ ) {
int xx = x-7 < 0 ? boxImage.width+(x-7) : x - 7;
// Set the value such that it doesn't change the image intensity
boxImage.set(xx,yy,1.0f/(15*15));
}
}
// compute the DFT for the box filter
dft.forward(boxImage,boxTransform);
// Visualize the Fourier Transform for the input image and the box filter
displayTransform(transform,"Input Image");
displayTransform(boxTransform,"Box Filter");
// apply the filter. convolution in spacial domain is the same as multiplication in the frequency domain
DiscreteFourierTransformOps.multiplyComplex(transform,boxTransform,transform);
// convert the image back and display the results
dft.inverse(transform,blurredImage);
// undo change of scale
PixelMath.multiply(blurredImage,255.0f,blurredImage);
PixelMath.multiply(input,255.0f,input);
// For sake of comparison, let's compute the box blur filter in the spatial domain
// NOTE: The image border will be different since the frequency domain wraps around and this implementation
// of the spacial domain adapts the kernel size
BlurImageOps.mean(input,spatialBlur,7,null,null);
// Convert to BufferedImage for output
BufferedImage originOut = ConvertBufferedImage.convertTo(input, null);
BufferedImage spacialOut = ConvertBufferedImage.convertTo(spatialBlur, null);
BufferedImage blurredOut = ConvertBufferedImage.convertTo(blurredImage, null);
ListDisplayPanel listPanel = new ListDisplayPanel();
listPanel.addImage(originOut,"Original Image");
listPanel.addImage(spacialOut,"Spacial Domain Box");
listPanel.addImage(blurredOut,"Frequency Domain Box");
ShowImages.showWindow(listPanel,"Box Blur in Spacial and Frequency Domain of Input Image");
} | java | public static void applyBoxFilter( GrayF32 input ) {
// declare storage
GrayF32 boxImage = new GrayF32(input.width, input.height);
InterleavedF32 boxTransform = new InterleavedF32(input.width,input.height,2);
InterleavedF32 transform = new InterleavedF32(input.width,input.height,2);
GrayF32 blurredImage = new GrayF32(input.width, input.height);
GrayF32 spatialBlur = new GrayF32(input.width, input.height);
DiscreteFourierTransform<GrayF32,InterleavedF32> dft =
DiscreteFourierTransformOps.createTransformF32();
// Make the image scaled from 0 to 1 to reduce overflow issues
PixelMath.divide(input,255.0f,input);
// compute the Fourier Transform
dft.forward(input,transform);
// create the box filter which is centered around the pixel. Note that the filter gets wrapped around
// the image edges
for( int y = 0; y < 15; y++ ) {
int yy = y-7 < 0 ? boxImage.height+(y-7) : y - 7;
for( int x = 0; x < 15; x++ ) {
int xx = x-7 < 0 ? boxImage.width+(x-7) : x - 7;
// Set the value such that it doesn't change the image intensity
boxImage.set(xx,yy,1.0f/(15*15));
}
}
// compute the DFT for the box filter
dft.forward(boxImage,boxTransform);
// Visualize the Fourier Transform for the input image and the box filter
displayTransform(transform,"Input Image");
displayTransform(boxTransform,"Box Filter");
// apply the filter. convolution in spacial domain is the same as multiplication in the frequency domain
DiscreteFourierTransformOps.multiplyComplex(transform,boxTransform,transform);
// convert the image back and display the results
dft.inverse(transform,blurredImage);
// undo change of scale
PixelMath.multiply(blurredImage,255.0f,blurredImage);
PixelMath.multiply(input,255.0f,input);
// For sake of comparison, let's compute the box blur filter in the spatial domain
// NOTE: The image border will be different since the frequency domain wraps around and this implementation
// of the spacial domain adapts the kernel size
BlurImageOps.mean(input,spatialBlur,7,null,null);
// Convert to BufferedImage for output
BufferedImage originOut = ConvertBufferedImage.convertTo(input, null);
BufferedImage spacialOut = ConvertBufferedImage.convertTo(spatialBlur, null);
BufferedImage blurredOut = ConvertBufferedImage.convertTo(blurredImage, null);
ListDisplayPanel listPanel = new ListDisplayPanel();
listPanel.addImage(originOut,"Original Image");
listPanel.addImage(spacialOut,"Spacial Domain Box");
listPanel.addImage(blurredOut,"Frequency Domain Box");
ShowImages.showWindow(listPanel,"Box Blur in Spacial and Frequency Domain of Input Image");
} | [
"public",
"static",
"void",
"applyBoxFilter",
"(",
"GrayF32",
"input",
")",
"{",
"// declare storage",
"GrayF32",
"boxImage",
"=",
"new",
"GrayF32",
"(",
"input",
".",
"width",
",",
"input",
".",
"height",
")",
";",
"InterleavedF32",
"boxTransform",
"=",
"new"... | Demonstration of how to apply a box filter in the frequency domain and compares the results
to a box filter which has been applied in the spatial domain | [
"Demonstration",
"of",
"how",
"to",
"apply",
"a",
"box",
"filter",
"in",
"the",
"frequency",
"domain",
"and",
"compares",
"the",
"results",
"to",
"a",
"box",
"filter",
"which",
"has",
"been",
"applied",
"in",
"the",
"spatial",
"domain"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/imageprocessing/ExampleFourierTransform.java#L49-L111 |
gallandarakhneorg/afc | core/maths/mathstochastic/src/main/java/org/arakhne/afc/math/stochastic/StochasticLaw.java | StochasticLaw.paramBoolean | @Pure
protected static boolean paramBoolean(String paramName, Map<String, String> parameters)
throws LawParameterNotFoundException {
final String svalue = parameters.get(paramName);
if (svalue != null && !"".equals(svalue)) { //$NON-NLS-1$
try {
return Boolean.parseBoolean(svalue);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
//
}
}
throw new LawParameterNotFoundException(paramName);
} | java | @Pure
protected static boolean paramBoolean(String paramName, Map<String, String> parameters)
throws LawParameterNotFoundException {
final String svalue = parameters.get(paramName);
if (svalue != null && !"".equals(svalue)) { //$NON-NLS-1$
try {
return Boolean.parseBoolean(svalue);
} catch (AssertionError e) {
throw e;
} catch (Throwable e) {
//
}
}
throw new LawParameterNotFoundException(paramName);
} | [
"@",
"Pure",
"protected",
"static",
"boolean",
"paramBoolean",
"(",
"String",
"paramName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"throws",
"LawParameterNotFoundException",
"{",
"final",
"String",
"svalue",
"=",
"parameters",
".",
"get... | Extract a parameter value from a map of parameters.
@param paramName is the nameof the parameter to extract.
@param parameters is the map of available parameters
@return the extract value
@throws LawParameterNotFoundException if the parameter was not found or the value is not a double. | [
"Extract",
"a",
"parameter",
"value",
"from",
"a",
"map",
"of",
"parameters",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathstochastic/src/main/java/org/arakhne/afc/math/stochastic/StochasticLaw.java#L76-L90 |
threerings/narya | core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java | ChatChannelManager.bodyRemovedFromChannel | @AnyThread
public void bodyRemovedFromChannel (ChatChannel channel, final int bodyId)
{
_peerMan.invokeNodeAction(new ChannelAction(channel) {
@Override protected void execute () {
ChannelInfo info = _channelMan._channels.get(_channel);
if (info != null) {
info.participants.remove(bodyId);
} else if (_channelMan._resolving.containsKey(_channel)) {
log.warning("Oh for fuck's sake, distributed systems are complicated",
"channel", _channel);
}
}
});
} | java | @AnyThread
public void bodyRemovedFromChannel (ChatChannel channel, final int bodyId)
{
_peerMan.invokeNodeAction(new ChannelAction(channel) {
@Override protected void execute () {
ChannelInfo info = _channelMan._channels.get(_channel);
if (info != null) {
info.participants.remove(bodyId);
} else if (_channelMan._resolving.containsKey(_channel)) {
log.warning("Oh for fuck's sake, distributed systems are complicated",
"channel", _channel);
}
}
});
} | [
"@",
"AnyThread",
"public",
"void",
"bodyRemovedFromChannel",
"(",
"ChatChannel",
"channel",
",",
"final",
"int",
"bodyId",
")",
"{",
"_peerMan",
".",
"invokeNodeAction",
"(",
"new",
"ChannelAction",
"(",
"channel",
")",
"{",
"@",
"Override",
"protected",
"void"... | When a body loses channel membership, this method should be called so that any server that
happens to be hosting that channel can be told that the body in question is now a
participant. | [
"When",
"a",
"body",
"loses",
"channel",
"membership",
"this",
"method",
"should",
"be",
"called",
"so",
"that",
"any",
"server",
"that",
"happens",
"to",
"be",
"hosting",
"that",
"channel",
"can",
"be",
"told",
"that",
"the",
"body",
"in",
"question",
"is... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/server/ChatChannelManager.java#L114-L128 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPUtility.java | MPPUtility.getColor | public static final Color getColor(byte[] data, int offset)
{
Color result = null;
if (getByte(data, offset + 3) == 0)
{
int r = getByte(data, offset);
int g = getByte(data, offset + 1);
int b = getByte(data, offset + 2);
result = new Color(r, g, b);
}
return result;
} | java | public static final Color getColor(byte[] data, int offset)
{
Color result = null;
if (getByte(data, offset + 3) == 0)
{
int r = getByte(data, offset);
int g = getByte(data, offset + 1);
int b = getByte(data, offset + 2);
result = new Color(r, g, b);
}
return result;
} | [
"public",
"static",
"final",
"Color",
"getColor",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"{",
"Color",
"result",
"=",
"null",
";",
"if",
"(",
"getByte",
"(",
"data",
",",
"offset",
"+",
"3",
")",
"==",
"0",
")",
"{",
"int",
"r"... | Reads a color value represented by three bytes, for R, G, and B
components, plus a flag byte indicating if this is an automatic color.
Returns null if the color type is "Automatic".
@param data byte array of data
@param offset offset into array
@return new Color instance | [
"Reads",
"a",
"color",
"value",
"represented",
"by",
"three",
"bytes",
"for",
"R",
"G",
"and",
"B",
"components",
"plus",
"a",
"flag",
"byte",
"indicating",
"if",
"this",
"is",
"an",
"automatic",
"color",
".",
"Returns",
"null",
"if",
"the",
"color",
"ty... | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L534-L547 |
redkale/redkale | src/org/redkale/asm/ModuleVisitor.java | ModuleVisitor.visitExport | public void visitExport(String packaze, int access, String... modules) {
if (mv != null) {
mv.visitExport(packaze, access, modules);
}
} | java | public void visitExport(String packaze, int access, String... modules) {
if (mv != null) {
mv.visitExport(packaze, access, modules);
}
} | [
"public",
"void",
"visitExport",
"(",
"String",
"packaze",
",",
"int",
"access",
",",
"String",
"...",
"modules",
")",
"{",
"if",
"(",
"mv",
"!=",
"null",
")",
"{",
"mv",
".",
"visitExport",
"(",
"packaze",
",",
"access",
",",
"modules",
")",
";",
"}... | Visit an exported package of the current module.
@param packaze the qualified name of the exported package.
@param access the access flag of the exported package,
valid values are among {@code ACC_SYNTHETIC} and
{@code ACC_MANDATED}.
@param modules the qualified names of the modules that can access to
the public classes of the exported package or
<tt>null</tt>. | [
"Visit",
"an",
"exported",
"package",
"of",
"the",
"current",
"module",
"."
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/asm/ModuleVisitor.java#L162-L166 |
maguro/aunit | junit/src/main/java/com/toolazydogs/aunit/internal/Util.java | Util.validateVoid | @SuppressWarnings({"ThrowableInstanceNeverThrown"})
public static void validateVoid(Method method, List<Throwable> errors)
{
if (method.getReturnType() != Void.TYPE)
{
errors.add(new Exception("Method " + method.getName() + "() should be void"));
}
} | java | @SuppressWarnings({"ThrowableInstanceNeverThrown"})
public static void validateVoid(Method method, List<Throwable> errors)
{
if (method.getReturnType() != Void.TYPE)
{
errors.add(new Exception("Method " + method.getName() + "() should be void"));
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"ThrowableInstanceNeverThrown\"",
"}",
")",
"public",
"static",
"void",
"validateVoid",
"(",
"Method",
"method",
",",
"List",
"<",
"Throwable",
">",
"errors",
")",
"{",
"if",
"(",
"method",
".",
"getReturnType",
"(",
")",
... | Validate that a method returns no value.
@param method the method to be tested
@param errors a list to place the errors | [
"Validate",
"that",
"a",
"method",
"returns",
"no",
"value",
"."
] | train | https://github.com/maguro/aunit/blob/1f972e35b28327e5e2e7881befc928df0546d74c/junit/src/main/java/com/toolazydogs/aunit/internal/Util.java#L54-L61 |
roboconf/roboconf-platform | miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/DebugWsDelegate.java | DebugWsDelegate.diagnoseInstance | public Diagnostic diagnoseInstance( String applicationName, String instancePath )
throws DebugWsException {
this.logger.finer( "Diagnosing instance " + instancePath + " in application " + applicationName );
WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "diagnose-instance" );
path = path.queryParam( "application-name", applicationName );
path = path.queryParam( "instance-path", instancePath );
ClientResponse response = this.wsClient.createBuilder( path )
.accept( MediaType.APPLICATION_JSON )
.get( ClientResponse.class );
if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
String value = response.getEntity( String.class );
this.logger.finer( response.getStatusInfo() + ": " + value );
throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
}
this.logger.finer( String.valueOf( response.getStatusInfo()));
return response.getEntity( Diagnostic.class );
} | java | public Diagnostic diagnoseInstance( String applicationName, String instancePath )
throws DebugWsException {
this.logger.finer( "Diagnosing instance " + instancePath + " in application " + applicationName );
WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "diagnose-instance" );
path = path.queryParam( "application-name", applicationName );
path = path.queryParam( "instance-path", instancePath );
ClientResponse response = this.wsClient.createBuilder( path )
.accept( MediaType.APPLICATION_JSON )
.get( ClientResponse.class );
if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
String value = response.getEntity( String.class );
this.logger.finer( response.getStatusInfo() + ": " + value );
throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
}
this.logger.finer( String.valueOf( response.getStatusInfo()));
return response.getEntity( Diagnostic.class );
} | [
"public",
"Diagnostic",
"diagnoseInstance",
"(",
"String",
"applicationName",
",",
"String",
"instancePath",
")",
"throws",
"DebugWsException",
"{",
"this",
".",
"logger",
".",
"finer",
"(",
"\"Diagnosing instance \"",
"+",
"instancePath",
"+",
"\" in application \"",
... | Runs a diagnostic for a given instance.
@return the instance
@throws DebugWsException | [
"Runs",
"a",
"diagnostic",
"for",
"a",
"given",
"instance",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/DebugWsDelegate.java#L128-L149 |
HeidelTime/heideltime | src/jvntextpro/util/StringUtils.java | StringUtils.findLastOf | public static int findLastOf (String container, String charSeq, int begin){
//find the last occurrence of one of characters in charSeq from begin backward
for (int i = begin; i < container.length() && i >= 0; --i){
if (charSeq.contains("" + container.charAt(i)))
return i;
}
return -1;
} | java | public static int findLastOf (String container, String charSeq, int begin){
//find the last occurrence of one of characters in charSeq from begin backward
for (int i = begin; i < container.length() && i >= 0; --i){
if (charSeq.contains("" + container.charAt(i)))
return i;
}
return -1;
} | [
"public",
"static",
"int",
"findLastOf",
"(",
"String",
"container",
",",
"String",
"charSeq",
",",
"int",
"begin",
")",
"{",
"//find the last occurrence of one of characters in charSeq from begin backward\r",
"for",
"(",
"int",
"i",
"=",
"begin",
";",
"i",
"<",
"co... | Find the last occurrence.
@param container the string on which we search
@param charSeq the string which we search for the occurrence
@param begin the start position in container to search from
@return the position where charSeq occurs for the last time in container (from right to left). | [
"Find",
"the",
"last",
"occurrence",
"."
] | train | https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/jvntextpro/util/StringUtils.java#L69-L76 |
wnameless/rubycollect4j | src/main/java/net/sf/rubycollect4j/RubyObject.java | RubyObject.send | public static <E> E send(Object o, String methodName, Byte arg) {
return send(o, methodName, (Object) arg);
} | java | public static <E> E send(Object o, String methodName, Byte arg) {
return send(o, methodName, (Object) arg);
} | [
"public",
"static",
"<",
"E",
">",
"E",
"send",
"(",
"Object",
"o",
",",
"String",
"methodName",
",",
"Byte",
"arg",
")",
"{",
"return",
"send",
"(",
"o",
",",
"methodName",
",",
"(",
"Object",
")",
"arg",
")",
";",
"}"
] | Executes a method of any Object by Java reflection.
@param o
an Object
@param methodName
name of the method
@param arg
a Byte
@return the result of the method called | [
"Executes",
"a",
"method",
"of",
"any",
"Object",
"by",
"Java",
"reflection",
"."
] | train | https://github.com/wnameless/rubycollect4j/blob/b8b8d8eccaca2254a3d09b91745882fb7a0d5add/src/main/java/net/sf/rubycollect4j/RubyObject.java#L111-L113 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog2/lookup/adapters/DnsLookupDataAdapter.java | DnsLookupDataAdapter.assignMinimumTTL | private void assignMinimumTTL(List<? extends DnsAnswer> dnsAnswers, LookupResult.Builder builder) {
if (config.hasOverrideTTL()) {
builder.cacheTTL(config.getCacheTTLOverrideMillis());
} else {
// Deduce minimum TTL on all TXT records. A TTL will always be returned by DNS server.
builder.cacheTTL(dnsAnswers.stream()
.map(DnsAnswer::dnsTTL)
.min(Comparator.comparing(Long::valueOf)).get() * 1000);
}
} | java | private void assignMinimumTTL(List<? extends DnsAnswer> dnsAnswers, LookupResult.Builder builder) {
if (config.hasOverrideTTL()) {
builder.cacheTTL(config.getCacheTTLOverrideMillis());
} else {
// Deduce minimum TTL on all TXT records. A TTL will always be returned by DNS server.
builder.cacheTTL(dnsAnswers.stream()
.map(DnsAnswer::dnsTTL)
.min(Comparator.comparing(Long::valueOf)).get() * 1000);
}
} | [
"private",
"void",
"assignMinimumTTL",
"(",
"List",
"<",
"?",
"extends",
"DnsAnswer",
">",
"dnsAnswers",
",",
"LookupResult",
".",
"Builder",
"builder",
")",
"{",
"if",
"(",
"config",
".",
"hasOverrideTTL",
"(",
")",
")",
"{",
"builder",
".",
"cacheTTL",
"... | Assigns the minimum TTL found in the supplied DnsAnswers. The minimum makes sense, because this is the least
amount of time that at least one of the records is valid for. | [
"Assigns",
"the",
"minimum",
"TTL",
"found",
"in",
"the",
"supplied",
"DnsAnswers",
".",
"The",
"minimum",
"makes",
"sense",
"because",
"this",
"is",
"the",
"least",
"amount",
"of",
"time",
"that",
"at",
"least",
"one",
"of",
"the",
"records",
"is",
"valid... | train | https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog2/lookup/adapters/DnsLookupDataAdapter.java#L373-L383 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObject.java | JsiiObject.jsiiAsyncCall | @Nullable
protected final <T> T jsiiAsyncCall(final String method, final Class<T> returnType, @Nullable final Object... args) {
JsiiClient client = engine.getClient();
JsiiPromise promise = client.beginAsyncMethod(this.objRef, method, JsiiObjectMapper.valueToTree(args));
engine.processAllPendingCallbacks();
return JsiiObjectMapper.treeToValue(client.endAsyncMethod(promise), returnType);
} | java | @Nullable
protected final <T> T jsiiAsyncCall(final String method, final Class<T> returnType, @Nullable final Object... args) {
JsiiClient client = engine.getClient();
JsiiPromise promise = client.beginAsyncMethod(this.objRef, method, JsiiObjectMapper.valueToTree(args));
engine.processAllPendingCallbacks();
return JsiiObjectMapper.treeToValue(client.endAsyncMethod(promise), returnType);
} | [
"@",
"Nullable",
"protected",
"final",
"<",
"T",
">",
"T",
"jsiiAsyncCall",
"(",
"final",
"String",
"method",
",",
"final",
"Class",
"<",
"T",
">",
"returnType",
",",
"@",
"Nullable",
"final",
"Object",
"...",
"args",
")",
"{",
"JsiiClient",
"client",
"=... | Calls an async method on the object.
@param method The name of the method.
@param returnType The return type.
@param args Method arguments.
@param <T> Java type for the return value.
@return A ereturn value. | [
"Calls",
"an",
"async",
"method",
"on",
"the",
"object",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObject.java#L88-L96 |
samskivert/samskivert | src/main/java/com/samskivert/util/MethodFinder.java | MethodFinder.findMethod | public Method findMethod (String methodName, Class<?>[] parameterTypes)
throws NoSuchMethodException
{
// make sure the constructor list is loaded
maybeLoadMethods();
List<Member> methodList = _methodMap.get(methodName);
if (methodList == null) {
throw new NoSuchMethodException(
"No method named " + _clazz.getName() + "." + methodName);
}
if (parameterTypes == null) {
parameterTypes = new Class<?>[0];
}
return (Method)findMemberIn(methodList, parameterTypes);
} | java | public Method findMethod (String methodName, Class<?>[] parameterTypes)
throws NoSuchMethodException
{
// make sure the constructor list is loaded
maybeLoadMethods();
List<Member> methodList = _methodMap.get(methodName);
if (methodList == null) {
throw new NoSuchMethodException(
"No method named " + _clazz.getName() + "." + methodName);
}
if (parameterTypes == null) {
parameterTypes = new Class<?>[0];
}
return (Method)findMemberIn(methodList, parameterTypes);
} | [
"public",
"Method",
"findMethod",
"(",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
")",
"throws",
"NoSuchMethodException",
"{",
"// make sure the constructor list is loaded",
"maybeLoadMethods",
"(",
")",
";",
"List",
"<",
"Membe... | Returns the most specific public method in my target class that has the given name and
accepts the number and type of parameters in the given Class array in a reflective
invocation.
<p> A null value or Void.TYPE in parameterTypes will match a corresponding Object or array
reference in a method's formal parameter list, but not a primitive formal parameter.
@param methodName name of the method to search for.
@param parameterTypes array representing the number and types of parameters to look for in
the method's signature. A null array is treated as a zero-length array.
@return Method object satisfying the conditions.
@exception NoSuchMethodException if no methods match the criteria, or if the reflective call
is ambiguous based on the parameter types, or if methodName is null. | [
"Returns",
"the",
"most",
"specific",
"public",
"method",
"in",
"my",
"target",
"class",
"that",
"has",
"the",
"given",
"name",
"and",
"accepts",
"the",
"number",
"and",
"type",
"of",
"parameters",
"in",
"the",
"given",
"Class",
"array",
"in",
"a",
"reflec... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/MethodFinder.java#L110-L127 |
alkacon/opencms-core | src/org/opencms/ui/CmsVaadinUtils.java | CmsVaadinUtils.getOUComboBox | public static ComboBox getOUComboBox(CmsObject cms, String baseOu, Log log, boolean includeWebOU) {
ComboBox combo = null;
try {
IndexedContainer container = new IndexedContainer();
container.addContainerProperty("desc", String.class, "");
for (String ou : CmsOUHandler.getManagableOUs(cms)) {
if (includeWebOU | !OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, ou).hasFlagWebuser()) {
Item item = container.addItem(ou);
if (ou == "") {
CmsOrganizationalUnit root = OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, "");
item.getItemProperty("desc").setValue(root.getDisplayName(A_CmsUI.get().getLocale()));
} else {
item.getItemProperty("desc").setValue(
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, ou).getDisplayName(
A_CmsUI.get().getLocale()));
}
}
}
combo = new ComboBox(null, container);
combo.setTextInputAllowed(true);
combo.setNullSelectionAllowed(false);
combo.setWidth("379px");
combo.setInputPrompt(
Messages.get().getBundle(UI.getCurrent().getLocale()).key(Messages.GUI_EXPLORER_CLICK_TO_EDIT_0));
combo.setItemCaptionPropertyId("desc");
combo.setFilteringMode(FilteringMode.CONTAINS);
combo.select(baseOu);
} catch (CmsException e) {
if (log != null) {
log.error("Unable to read OU", e);
}
}
return combo;
} | java | public static ComboBox getOUComboBox(CmsObject cms, String baseOu, Log log, boolean includeWebOU) {
ComboBox combo = null;
try {
IndexedContainer container = new IndexedContainer();
container.addContainerProperty("desc", String.class, "");
for (String ou : CmsOUHandler.getManagableOUs(cms)) {
if (includeWebOU | !OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, ou).hasFlagWebuser()) {
Item item = container.addItem(ou);
if (ou == "") {
CmsOrganizationalUnit root = OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, "");
item.getItemProperty("desc").setValue(root.getDisplayName(A_CmsUI.get().getLocale()));
} else {
item.getItemProperty("desc").setValue(
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, ou).getDisplayName(
A_CmsUI.get().getLocale()));
}
}
}
combo = new ComboBox(null, container);
combo.setTextInputAllowed(true);
combo.setNullSelectionAllowed(false);
combo.setWidth("379px");
combo.setInputPrompt(
Messages.get().getBundle(UI.getCurrent().getLocale()).key(Messages.GUI_EXPLORER_CLICK_TO_EDIT_0));
combo.setItemCaptionPropertyId("desc");
combo.setFilteringMode(FilteringMode.CONTAINS);
combo.select(baseOu);
} catch (CmsException e) {
if (log != null) {
log.error("Unable to read OU", e);
}
}
return combo;
} | [
"public",
"static",
"ComboBox",
"getOUComboBox",
"(",
"CmsObject",
"cms",
",",
"String",
"baseOu",
",",
"Log",
"log",
",",
"boolean",
"includeWebOU",
")",
"{",
"ComboBox",
"combo",
"=",
"null",
";",
"try",
"{",
"IndexedContainer",
"container",
"=",
"new",
"I... | Creates the ComboBox for OU selection.<p>
@param cms CmsObject
@param baseOu OU
@param log Logger object
@param includeWebOU include webou?
@return ComboBox | [
"Creates",
"the",
"ComboBox",
"for",
"OU",
"selection",
".",
"<p",
">",
"@param",
"cms",
"CmsObject",
"@param",
"baseOu",
"OU",
"@param",
"log",
"Logger",
"object",
"@param",
"includeWebOU",
"include",
"webou?"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L671-L708 |
VoltDB/voltdb | src/frontend/org/voltdb/StatsProcInputTable.java | StatsProcInputTable.calculateAverage | static long calculateAverage(long currAvg, long currInvoc, long rowAvg, long rowInvoc)
{
long currTtl = currAvg * currInvoc;
long rowTtl = rowAvg * rowInvoc;
// If both are 0, then currTtl, rowTtl are also 0.
if ((currInvoc + rowInvoc) == 0L) {
return 0L;
} else {
return (currTtl + rowTtl) / (currInvoc + rowInvoc);
}
} | java | static long calculateAverage(long currAvg, long currInvoc, long rowAvg, long rowInvoc)
{
long currTtl = currAvg * currInvoc;
long rowTtl = rowAvg * rowInvoc;
// If both are 0, then currTtl, rowTtl are also 0.
if ((currInvoc + rowInvoc) == 0L) {
return 0L;
} else {
return (currTtl + rowTtl) / (currInvoc + rowInvoc);
}
} | [
"static",
"long",
"calculateAverage",
"(",
"long",
"currAvg",
",",
"long",
"currInvoc",
",",
"long",
"rowAvg",
",",
"long",
"rowInvoc",
")",
"{",
"long",
"currTtl",
"=",
"currAvg",
"*",
"currInvoc",
";",
"long",
"rowTtl",
"=",
"rowAvg",
"*",
"rowInvoc",
";... | Given a running average and the running invocation total as well as a new
row's average and invocation total, return a new running average | [
"Given",
"a",
"running",
"average",
"and",
"the",
"running",
"invocation",
"total",
"as",
"well",
"as",
"a",
"new",
"row",
"s",
"average",
"and",
"invocation",
"total",
"return",
"a",
"new",
"running",
"average"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/StatsProcInputTable.java#L97-L108 |
aws/aws-sdk-java | aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/LinuxParameters.java | LinuxParameters.getTmpfs | public java.util.List<Tmpfs> getTmpfs() {
if (tmpfs == null) {
tmpfs = new com.amazonaws.internal.SdkInternalList<Tmpfs>();
}
return tmpfs;
} | java | public java.util.List<Tmpfs> getTmpfs() {
if (tmpfs == null) {
tmpfs = new com.amazonaws.internal.SdkInternalList<Tmpfs>();
}
return tmpfs;
} | [
"public",
"java",
".",
"util",
".",
"List",
"<",
"Tmpfs",
">",
"getTmpfs",
"(",
")",
"{",
"if",
"(",
"tmpfs",
"==",
"null",
")",
"{",
"tmpfs",
"=",
"new",
"com",
".",
"amazonaws",
".",
"internal",
".",
"SdkInternalList",
"<",
"Tmpfs",
">",
"(",
")"... | <p>
The container path, mount options, and size (in MiB) of the tmpfs mount. This parameter maps to the
<code>--tmpfs</code> option to <a href="https://docs.docker.com/engine/reference/run/">docker run</a>.
</p>
<note>
<p>
If you are using tasks that use the Fargate launch type, the <code>tmpfs</code> parameter is not supported.
</p>
</note>
@return The container path, mount options, and size (in MiB) of the tmpfs mount. This parameter maps to the
<code>--tmpfs</code> option to <a href="https://docs.docker.com/engine/reference/run/">docker
run</a>.</p> <note>
<p>
If you are using tasks that use the Fargate launch type, the <code>tmpfs</code> parameter is not
supported.
</p> | [
"<p",
">",
"The",
"container",
"path",
"mount",
"options",
"and",
"size",
"(",
"in",
"MiB",
")",
"of",
"the",
"tmpfs",
"mount",
".",
"This",
"parameter",
"maps",
"to",
"the",
"<code",
">",
"--",
"tmpfs<",
"/",
"code",
">",
"option",
"to",
"<a",
"href... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/LinuxParameters.java#L494-L499 |
ironjacamar/ironjacamar | common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java | AbstractParser.elementAsInteger | protected Integer elementAsInteger(XMLStreamReader reader, String key, Map<String, String> expressions)
throws XMLStreamException, ParserException
{
Integer integerValue = null;
String elementtext = rawElementText(reader);
if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1)
expressions.put(key, elementtext);
try
{
integerValue = Integer.valueOf(getSubstitutionValue(elementtext));
}
catch (NumberFormatException nfe)
{
throw new ParserException(bundle.notValidNumber(elementtext, reader.getLocalName()));
}
return integerValue;
} | java | protected Integer elementAsInteger(XMLStreamReader reader, String key, Map<String, String> expressions)
throws XMLStreamException, ParserException
{
Integer integerValue = null;
String elementtext = rawElementText(reader);
if (key != null && expressions != null && elementtext != null && elementtext.indexOf("${") != -1)
expressions.put(key, elementtext);
try
{
integerValue = Integer.valueOf(getSubstitutionValue(elementtext));
}
catch (NumberFormatException nfe)
{
throw new ParserException(bundle.notValidNumber(elementtext, reader.getLocalName()));
}
return integerValue;
} | [
"protected",
"Integer",
"elementAsInteger",
"(",
"XMLStreamReader",
"reader",
",",
"String",
"key",
",",
"Map",
"<",
"String",
",",
"String",
">",
"expressions",
")",
"throws",
"XMLStreamException",
",",
"ParserException",
"{",
"Integer",
"integerValue",
"=",
"nul... | convert an xml element in Integer value
@param reader the StAX reader
@param key The key
@param expressions The expressions
@return the integer representing element
@throws XMLStreamException StAX exception
@throws ParserException in case it isn't a number | [
"convert",
"an",
"xml",
"element",
"in",
"Integer",
"value"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java#L256-L274 |
hibernate/hibernate-ogm | infinispan-remote/src/main/java/org/hibernate/ogm/datastore/infinispanremote/configuration/impl/InfinispanRemoteConfiguration.java | InfinispanRemoteConfiguration.loadResourceFile | private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {
if ( configurationResourceUrl != null ) {
try ( InputStream openStream = configurationResourceUrl.openStream() ) {
hotRodConfiguration.load( openStream );
}
catch (IOException e) {
throw log.failedLoadingHotRodConfigurationProperties( e );
}
}
} | java | private void loadResourceFile(URL configurationResourceUrl, Properties hotRodConfiguration) {
if ( configurationResourceUrl != null ) {
try ( InputStream openStream = configurationResourceUrl.openStream() ) {
hotRodConfiguration.load( openStream );
}
catch (IOException e) {
throw log.failedLoadingHotRodConfigurationProperties( e );
}
}
} | [
"private",
"void",
"loadResourceFile",
"(",
"URL",
"configurationResourceUrl",
",",
"Properties",
"hotRodConfiguration",
")",
"{",
"if",
"(",
"configurationResourceUrl",
"!=",
"null",
")",
"{",
"try",
"(",
"InputStream",
"openStream",
"=",
"configurationResourceUrl",
... | Load the properties from the resource file if one is specified | [
"Load",
"the",
"properties",
"from",
"the",
"resource",
"file",
"if",
"one",
"is",
"specified"
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/infinispan-remote/src/main/java/org/hibernate/ogm/datastore/infinispanremote/configuration/impl/InfinispanRemoteConfiguration.java#L276-L285 |
alkacon/opencms-core | src/org/opencms/ui/dialogs/CmsRestoreDeletedDialog.java | CmsRestoreDeletedDialog.initDeletedResources | private void initDeletedResources(CmsObject cms, List<I_CmsHistoryResource> deletedResources) throws CmsException {
Collections.sort(deletedResources, new Comparator<I_CmsHistoryResource>() {
public int compare(I_CmsHistoryResource first, I_CmsHistoryResource second) {
return first.getRootPath().compareTo(second.getRootPath());
}
});
m_deletedResourceContainer.removeAllComponents();
m_selectionContainer = new IndexedContainer();
m_selectionContainer.addContainerProperty(PROP_SELECTED, Boolean.class, Boolean.FALSE);
m_okButton.setEnabled(!deletedResources.isEmpty());
if (deletedResources.isEmpty()) {
m_deletedResourceContainer.addComponent(
new Label(CmsVaadinUtils.getMessageText(org.opencms.workplace.list.Messages.GUI_LIST_EMPTY_0)));
}
for (I_CmsHistoryResource deleted : deletedResources) {
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(deleted.getTypeId());
String typeName = resType.getTypeName();
CmsExplorerTypeSettings explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(typeName);
String title = cms.getRequestContext().removeSiteRoot(deleted.getRootPath());
String subtitle = CmsVaadinUtils.getMessageText(
org.opencms.ui.Messages.GUI_RESTOREDELETED_DATE_VERSION_2,
CmsVfsService.formatDateTime(cms, deleted.getDateLastModified()),
"" + deleted.getVersion());
if (explorerType == null) {
explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
deleted.isFile()
? CmsResourceTypeUnknownFile.RESOURCE_TYPE_NAME
: CmsResourceTypeUnknownFolder.RESOURCE_TYPE_NAME);
}
CmsResourceInfo info = new CmsResourceInfo(
title,
subtitle,
CmsResourceUtil.getBigIconResource(explorerType, deleted.getName()));
info.setWidth("100%");
HorizontalLayout hl = new HorizontalLayout();
hl.setWidth("100%");
CheckBox checkbox = new CheckBox();
hl.addComponent(checkbox);
hl.addComponent(info);
hl.setExpandRatio(info, 1);
hl.setComponentAlignment(checkbox, Alignment.MIDDLE_LEFT);
m_selectionContainer.addItem(deleted.getStructureId());
checkbox.setPropertyDataSource(
m_selectionContainer.getItem(deleted.getStructureId()).getItemProperty(PROP_SELECTED));
m_deletedResourceContainer.addComponent(hl);
}
} | java | private void initDeletedResources(CmsObject cms, List<I_CmsHistoryResource> deletedResources) throws CmsException {
Collections.sort(deletedResources, new Comparator<I_CmsHistoryResource>() {
public int compare(I_CmsHistoryResource first, I_CmsHistoryResource second) {
return first.getRootPath().compareTo(second.getRootPath());
}
});
m_deletedResourceContainer.removeAllComponents();
m_selectionContainer = new IndexedContainer();
m_selectionContainer.addContainerProperty(PROP_SELECTED, Boolean.class, Boolean.FALSE);
m_okButton.setEnabled(!deletedResources.isEmpty());
if (deletedResources.isEmpty()) {
m_deletedResourceContainer.addComponent(
new Label(CmsVaadinUtils.getMessageText(org.opencms.workplace.list.Messages.GUI_LIST_EMPTY_0)));
}
for (I_CmsHistoryResource deleted : deletedResources) {
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(deleted.getTypeId());
String typeName = resType.getTypeName();
CmsExplorerTypeSettings explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(typeName);
String title = cms.getRequestContext().removeSiteRoot(deleted.getRootPath());
String subtitle = CmsVaadinUtils.getMessageText(
org.opencms.ui.Messages.GUI_RESTOREDELETED_DATE_VERSION_2,
CmsVfsService.formatDateTime(cms, deleted.getDateLastModified()),
"" + deleted.getVersion());
if (explorerType == null) {
explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
deleted.isFile()
? CmsResourceTypeUnknownFile.RESOURCE_TYPE_NAME
: CmsResourceTypeUnknownFolder.RESOURCE_TYPE_NAME);
}
CmsResourceInfo info = new CmsResourceInfo(
title,
subtitle,
CmsResourceUtil.getBigIconResource(explorerType, deleted.getName()));
info.setWidth("100%");
HorizontalLayout hl = new HorizontalLayout();
hl.setWidth("100%");
CheckBox checkbox = new CheckBox();
hl.addComponent(checkbox);
hl.addComponent(info);
hl.setExpandRatio(info, 1);
hl.setComponentAlignment(checkbox, Alignment.MIDDLE_LEFT);
m_selectionContainer.addItem(deleted.getStructureId());
checkbox.setPropertyDataSource(
m_selectionContainer.getItem(deleted.getStructureId()).getItemProperty(PROP_SELECTED));
m_deletedResourceContainer.addComponent(hl);
}
} | [
"private",
"void",
"initDeletedResources",
"(",
"CmsObject",
"cms",
",",
"List",
"<",
"I_CmsHistoryResource",
">",
"deletedResources",
")",
"throws",
"CmsException",
"{",
"Collections",
".",
"sort",
"(",
"deletedResources",
",",
"new",
"Comparator",
"<",
"I_CmsHisto... | Fills the list of resources to select from.<p>
@param cms the cms context
@param deletedResources the deleted resources
@throws CmsException if something goes wrong | [
"Fills",
"the",
"list",
"of",
"resources",
"to",
"select",
"from",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/CmsRestoreDeletedDialog.java#L257-L309 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/script/ScriptAPI.java | ScriptAPI.getAndValidateScriptName | private String getAndValidateScriptName(JSONObject params) throws ApiException {
String scriptName = params.getString(ACTION_PARAM_SCRIPT_NAME);
if (extension.getScript(scriptName) == null) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
}
return scriptName;
} | java | private String getAndValidateScriptName(JSONObject params) throws ApiException {
String scriptName = params.getString(ACTION_PARAM_SCRIPT_NAME);
if (extension.getScript(scriptName) == null) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, ACTION_PARAM_SCRIPT_NAME);
}
return scriptName;
} | [
"private",
"String",
"getAndValidateScriptName",
"(",
"JSONObject",
"params",
")",
"throws",
"ApiException",
"{",
"String",
"scriptName",
"=",
"params",
".",
"getString",
"(",
"ACTION_PARAM_SCRIPT_NAME",
")",
";",
"if",
"(",
"extension",
".",
"getScript",
"(",
"sc... | Gets and validates that the parameter named {@value #ACTION_PARAM_SCRIPT_NAME}, in {@code parameters}, represents an
existing script name.
<p>
The parameter must exist, that is, it should be a mandatory parameter, otherwise a runtime exception is thrown.
@param params the parameters of the API request.
@return the name of a existing script.
@throws ApiException if the no script exists with the given name. | [
"Gets",
"and",
"validates",
"that",
"the",
"parameter",
"named",
"{",
"@value",
"#ACTION_PARAM_SCRIPT_NAME",
"}",
"in",
"{",
"@code",
"parameters",
"}",
"represents",
"an",
"existing",
"script",
"name",
".",
"<p",
">",
"The",
"parameter",
"must",
"exist",
"tha... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/script/ScriptAPI.java#L193-L199 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus.java | NumberNumberMinus.minus | public static Number minus(Number left, Number right) {
return NumberMath.subtract(left, right);
} | java | public static Number minus(Number left, Number right) {
return NumberMath.subtract(left, right);
} | [
"public",
"static",
"Number",
"minus",
"(",
"Number",
"left",
",",
"Number",
"right",
")",
"{",
"return",
"NumberMath",
".",
"subtract",
"(",
"left",
",",
"right",
")",
";",
"}"
] | Subtraction of two Numbers.
@param left a Number
@param right another Number to subtract to the first one
@return the subtraction | [
"Subtraction",
"of",
"two",
"Numbers",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/dgmimpl/NumberNumberMinus.java#L42-L44 |
softindex/datakernel | cloud-fs/src/main/java/io/datakernel/remotefs/RemoteFsClusterClient.java | RemoteFsClusterClient.markDead | public boolean markDead(Object partitionId, @Nullable Throwable e) {
FsClient client = aliveClients.remove(partitionId);
if (client != null) {
logger.warn("marking " + partitionId + " as dead (" + e + ')');
deadClients.put(partitionId, client);
return true;
}
return false;
} | java | public boolean markDead(Object partitionId, @Nullable Throwable e) {
FsClient client = aliveClients.remove(partitionId);
if (client != null) {
logger.warn("marking " + partitionId + " as dead (" + e + ')');
deadClients.put(partitionId, client);
return true;
}
return false;
} | [
"public",
"boolean",
"markDead",
"(",
"Object",
"partitionId",
",",
"@",
"Nullable",
"Throwable",
"e",
")",
"{",
"FsClient",
"client",
"=",
"aliveClients",
".",
"remove",
"(",
"partitionId",
")",
";",
"if",
"(",
"client",
"!=",
"null",
")",
"{",
"logger",
... | Mark partition as dead. It means that no operations will use it and it would not be given to the server selector.
Next call of {@link #checkDeadPartitions()} or {@link #checkAllPartitions()} will ping this partition and possibly
mark it as alive again.
@param partitionId id of the partition to be marked
@param e optional exception for logging
@return <code>true</code> if partition was alive and <code>false</code> otherwise | [
"Mark",
"partition",
"as",
"dead",
".",
"It",
"means",
"that",
"no",
"operations",
"will",
"use",
"it",
"and",
"it",
"would",
"not",
"be",
"given",
"to",
"the",
"server",
"selector",
".",
"Next",
"call",
"of",
"{",
"@link",
"#checkDeadPartitions",
"()",
... | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/cloud-fs/src/main/java/io/datakernel/remotefs/RemoteFsClusterClient.java#L210-L218 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/ActorSDKLauncher.java | ActorSDKLauncher.startProfileActivity | public static void startProfileActivity(Context context, int uid) {
// Ignore call if context is empty, simple work-around when fragment was disconnected from
// activity
if (context == null) {
return;
}
Bundle b = new Bundle();
b.putInt(Intents.EXTRA_UID, uid);
startActivity(context, b, ProfileActivity.class);
} | java | public static void startProfileActivity(Context context, int uid) {
// Ignore call if context is empty, simple work-around when fragment was disconnected from
// activity
if (context == null) {
return;
}
Bundle b = new Bundle();
b.putInt(Intents.EXTRA_UID, uid);
startActivity(context, b, ProfileActivity.class);
} | [
"public",
"static",
"void",
"startProfileActivity",
"(",
"Context",
"context",
",",
"int",
"uid",
")",
"{",
"// Ignore call if context is empty, simple work-around when fragment was disconnected from",
"// activity",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"return",
... | Launch User Profile Activity
@param context current context
@param uid user id | [
"Launch",
"User",
"Profile",
"Activity"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/ActorSDKLauncher.java#L19-L29 |
line/armeria | core/src/main/java/com/linecorp/armeria/internal/ArmeriaHttpUtil.java | ArmeriaHttpUtil.toArmeria | public static HttpHeaders toArmeria(HttpRequest in) throws URISyntaxException {
final URI requestTargetUri = toUri(in);
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final HttpHeaders out = new DefaultHttpHeaders(true, inHeaders.size());
out.path(toHttp2Path(requestTargetUri));
out.method(HttpMethod.valueOf(in.method().name()));
setHttp2Scheme(inHeaders, requestTargetUri, out);
if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) {
// Attempt to take from HOST header before taking from the request-line
final String host = inHeaders.getAsString(HttpHeaderNames.HOST);
setHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out);
}
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out;
} | java | public static HttpHeaders toArmeria(HttpRequest in) throws URISyntaxException {
final URI requestTargetUri = toUri(in);
final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers();
final HttpHeaders out = new DefaultHttpHeaders(true, inHeaders.size());
out.path(toHttp2Path(requestTargetUri));
out.method(HttpMethod.valueOf(in.method().name()));
setHttp2Scheme(inHeaders, requestTargetUri, out);
if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) {
// Attempt to take from HOST header before taking from the request-line
final String host = inHeaders.getAsString(HttpHeaderNames.HOST);
setHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out);
}
// Add the HTTP headers which have not been consumed above
toArmeria(inHeaders, out);
return out;
} | [
"public",
"static",
"HttpHeaders",
"toArmeria",
"(",
"HttpRequest",
"in",
")",
"throws",
"URISyntaxException",
"{",
"final",
"URI",
"requestTargetUri",
"=",
"toUri",
"(",
"in",
")",
";",
"final",
"io",
".",
"netty",
".",
"handler",
".",
"codec",
".",
"http",... | Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers.
The following headers are only used if they can not be found in the {@code HOST} header or the
{@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
<ul>
<li>{@link ExtensionHeaderNames#SCHEME}</li>
</ul>
{@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}. | [
"Converts",
"the",
"headers",
"of",
"the",
"given",
"Netty",
"HTTP",
"/",
"1",
".",
"x",
"request",
"into",
"Armeria",
"HTTP",
"/",
"2",
"headers",
".",
"The",
"following",
"headers",
"are",
"only",
"used",
"if",
"they",
"can",
"not",
"be",
"found",
"i... | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/internal/ArmeriaHttpUtil.java#L527-L546 |
casbin/jcasbin | src/main/java/org/casbin/jcasbin/main/Enforcer.java | Enforcer.addPermissionForUser | public boolean addPermissionForUser(String user, String... permission) {
List<String> params = new ArrayList<>();
params.add(user);
Collections.addAll(params, permission);
return addPolicy(params);
} | java | public boolean addPermissionForUser(String user, String... permission) {
List<String> params = new ArrayList<>();
params.add(user);
Collections.addAll(params, permission);
return addPolicy(params);
} | [
"public",
"boolean",
"addPermissionForUser",
"(",
"String",
"user",
",",
"String",
"...",
"permission",
")",
"{",
"List",
"<",
"String",
">",
"params",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"params",
".",
"add",
"(",
"user",
")",
";",
"Collection... | addPermissionForUser adds a permission for a user or role.
Returns false if the user or role already has the permission (aka not affected).
@param user the user.
@param permission the permission, usually be (obj, act). It is actually the rule without the subject.
@return succeeds or not. | [
"addPermissionForUser",
"adds",
"a",
"permission",
"for",
"a",
"user",
"or",
"role",
".",
"Returns",
"false",
"if",
"the",
"user",
"or",
"role",
"already",
"has",
"the",
"permission",
"(",
"aka",
"not",
"affected",
")",
"."
] | train | https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L251-L258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.