repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
Netflix/Hystrix
|
hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java
|
HystrixCommandExecutionHook.onComplete
|
@Deprecated
public <T> T onComplete(HystrixInvokable<T> commandInstance, T response) {
"""
DEPRECATED: Change usages of this to {@link #onEmit} if you want to write a hook that handles each emitted command value
or to {@link #onSuccess} if you want to write a hook that handles success of the command
Invoked after completion of {@link HystrixCommand} execution that results in a response.
<p>
The response can come either from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
@param commandInstance
The executing HystrixCommand instance.
@param response
from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
@return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
@since 1.2
"""
// pass-thru by default
return response;
}
|
java
|
@Deprecated
public <T> T onComplete(HystrixInvokable<T> commandInstance, T response) {
// pass-thru by default
return response;
}
|
[
"@",
"Deprecated",
"public",
"<",
"T",
">",
"T",
"onComplete",
"(",
"HystrixInvokable",
"<",
"T",
">",
"commandInstance",
",",
"T",
"response",
")",
"{",
"// pass-thru by default",
"return",
"response",
";",
"}"
] |
DEPRECATED: Change usages of this to {@link #onEmit} if you want to write a hook that handles each emitted command value
or to {@link #onSuccess} if you want to write a hook that handles success of the command
Invoked after completion of {@link HystrixCommand} execution that results in a response.
<p>
The response can come either from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
@param commandInstance
The executing HystrixCommand instance.
@param response
from {@link HystrixCommand#run()} or {@link HystrixCommand#getFallback()}.
@return T response object that can be modified, decorated, replaced or just returned as a pass-thru.
@since 1.2
|
[
"DEPRECATED",
":",
"Change",
"usages",
"of",
"this",
"to",
"{",
"@link",
"#onEmit",
"}",
"if",
"you",
"want",
"to",
"write",
"a",
"hook",
"that",
"handles",
"each",
"emitted",
"command",
"value",
"or",
"to",
"{",
"@link",
"#onSuccess",
"}",
"if",
"you",
"want",
"to",
"write",
"a",
"hook",
"that",
"handles",
"success",
"of",
"the",
"command"
] |
train
|
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java#L469-L473
|
sculptor/sculptor
|
sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/util/FactoryHelper.java
|
FactoryHelper.newInstanceFromName
|
public static Object newInstanceFromName(String className, ClassLoader classLoader) {
"""
Creates an instance from a String class name.
@param className
full class name
@param classLoader
the class will be loaded with this ClassLoader
@return new instance of the class
@throws RuntimeException
if class not found or could not be instantiated
"""
try {
Class<?> clazz = Class.forName(className, true, classLoader);
return clazz.newInstance();
} catch (Exception e) {
String m = "Couldn't create instance from name " + className + " (" + e.getMessage() + ")";
LOG.error(m, e);
throw new RuntimeException(m);
}
}
|
java
|
public static Object newInstanceFromName(String className, ClassLoader classLoader) {
try {
Class<?> clazz = Class.forName(className, true, classLoader);
return clazz.newInstance();
} catch (Exception e) {
String m = "Couldn't create instance from name " + className + " (" + e.getMessage() + ")";
LOG.error(m, e);
throw new RuntimeException(m);
}
}
|
[
"public",
"static",
"Object",
"newInstanceFromName",
"(",
"String",
"className",
",",
"ClassLoader",
"classLoader",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"className",
",",
"true",
",",
"classLoader",
")",
";",
"return",
"clazz",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"m",
"=",
"\"Couldn't create instance from name \"",
"+",
"className",
"+",
"\" (\"",
"+",
"e",
".",
"getMessage",
"(",
")",
"+",
"\")\"",
";",
"LOG",
".",
"error",
"(",
"m",
",",
"e",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"m",
")",
";",
"}",
"}"
] |
Creates an instance from a String class name.
@param className
full class name
@param classLoader
the class will be loaded with this ClassLoader
@return new instance of the class
@throws RuntimeException
if class not found or could not be instantiated
|
[
"Creates",
"an",
"instance",
"from",
"a",
"String",
"class",
"name",
"."
] |
train
|
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/util/FactoryHelper.java#L61-L70
|
aws/aws-sdk-java
|
aws-java-sdk-cloudwatch/src/main/java/com/amazonaws/services/cloudwatch/model/Datapoint.java
|
Datapoint.withExtendedStatistics
|
public Datapoint withExtendedStatistics(java.util.Map<String, Double> extendedStatistics) {
"""
<p>
The percentile statistic for the data point.
</p>
@param extendedStatistics
The percentile statistic for the data point.
@return Returns a reference to this object so that method calls can be chained together.
"""
setExtendedStatistics(extendedStatistics);
return this;
}
|
java
|
public Datapoint withExtendedStatistics(java.util.Map<String, Double> extendedStatistics) {
setExtendedStatistics(extendedStatistics);
return this;
}
|
[
"public",
"Datapoint",
"withExtendedStatistics",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Double",
">",
"extendedStatistics",
")",
"{",
"setExtendedStatistics",
"(",
"extendedStatistics",
")",
";",
"return",
"this",
";",
"}"
] |
<p>
The percentile statistic for the data point.
</p>
@param extendedStatistics
The percentile statistic for the data point.
@return Returns a reference to this object so that method calls can be chained together.
|
[
"<p",
">",
"The",
"percentile",
"statistic",
"for",
"the",
"data",
"point",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cloudwatch/src/main/java/com/amazonaws/services/cloudwatch/model/Datapoint.java#L426-L429
|
netty/netty
|
codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionStatus.java
|
SpdySessionStatus.valueOf
|
public static SpdySessionStatus valueOf(int code) {
"""
Returns the {@link SpdySessionStatus} represented by the specified code.
If the specified code is a defined SPDY status code, a cached instance
will be returned. Otherwise, a new instance will be returned.
"""
switch (code) {
case 0:
return OK;
case 1:
return PROTOCOL_ERROR;
case 2:
return INTERNAL_ERROR;
}
return new SpdySessionStatus(code, "UNKNOWN (" + code + ')');
}
|
java
|
public static SpdySessionStatus valueOf(int code) {
switch (code) {
case 0:
return OK;
case 1:
return PROTOCOL_ERROR;
case 2:
return INTERNAL_ERROR;
}
return new SpdySessionStatus(code, "UNKNOWN (" + code + ')');
}
|
[
"public",
"static",
"SpdySessionStatus",
"valueOf",
"(",
"int",
"code",
")",
"{",
"switch",
"(",
"code",
")",
"{",
"case",
"0",
":",
"return",
"OK",
";",
"case",
"1",
":",
"return",
"PROTOCOL_ERROR",
";",
"case",
"2",
":",
"return",
"INTERNAL_ERROR",
";",
"}",
"return",
"new",
"SpdySessionStatus",
"(",
"code",
",",
"\"UNKNOWN (\"",
"+",
"code",
"+",
"'",
"'",
")",
";",
"}"
] |
Returns the {@link SpdySessionStatus} represented by the specified code.
If the specified code is a defined SPDY status code, a cached instance
will be returned. Otherwise, a new instance will be returned.
|
[
"Returns",
"the",
"{"
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdySessionStatus.java#L46-L57
|
Azure/azure-sdk-for-java
|
redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/LinkedServersInner.java
|
LinkedServersInner.beginCreateAsync
|
public Observable<RedisLinkedServerWithPropertiesInner> beginCreateAsync(String resourceGroupName, String name, String linkedServerName, RedisLinkedServerCreateParameters parameters) {
"""
Adds a linked server to the Redis cache (requires Premium SKU).
@param resourceGroupName The name of the resource group.
@param name The name of the Redis cache.
@param linkedServerName The name of the linked server that is being added to the Redis cache.
@param parameters Parameters supplied to the Create Linked server operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisLinkedServerWithPropertiesInner object
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, name, linkedServerName, parameters).map(new Func1<ServiceResponse<RedisLinkedServerWithPropertiesInner>, RedisLinkedServerWithPropertiesInner>() {
@Override
public RedisLinkedServerWithPropertiesInner call(ServiceResponse<RedisLinkedServerWithPropertiesInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<RedisLinkedServerWithPropertiesInner> beginCreateAsync(String resourceGroupName, String name, String linkedServerName, RedisLinkedServerCreateParameters parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, name, linkedServerName, parameters).map(new Func1<ServiceResponse<RedisLinkedServerWithPropertiesInner>, RedisLinkedServerWithPropertiesInner>() {
@Override
public RedisLinkedServerWithPropertiesInner call(ServiceResponse<RedisLinkedServerWithPropertiesInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"RedisLinkedServerWithPropertiesInner",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"linkedServerName",
",",
"RedisLinkedServerCreateParameters",
"parameters",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"linkedServerName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RedisLinkedServerWithPropertiesInner",
">",
",",
"RedisLinkedServerWithPropertiesInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RedisLinkedServerWithPropertiesInner",
"call",
"(",
"ServiceResponse",
"<",
"RedisLinkedServerWithPropertiesInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Adds a linked server to the Redis cache (requires Premium SKU).
@param resourceGroupName The name of the resource group.
@param name The name of the Redis cache.
@param linkedServerName The name of the linked server that is being added to the Redis cache.
@param parameters Parameters supplied to the Create Linked server operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisLinkedServerWithPropertiesInner object
|
[
"Adds",
"a",
"linked",
"server",
"to",
"the",
"Redis",
"cache",
"(",
"requires",
"Premium",
"SKU",
")",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/redis/v2018_03_01/implementation/LinkedServersInner.java#L216-L223
|
apptik/jus
|
android/jus-android/src/main/java/io/apptik/comm/jus/util/DefaultBitmapLruCache.java
|
DefaultBitmapLruCache.sizeOf
|
@Override
protected int sizeOf(String key, Bitmap value) {
"""
Measure item size in kilobytes rather than units which is more practical
for a bitmap cache
"""
final int bitmapSize = BitmapLruPool.getBitmapSize(value);
return bitmapSize == 0 ? 1 : bitmapSize;
}
|
java
|
@Override
protected int sizeOf(String key, Bitmap value) {
final int bitmapSize = BitmapLruPool.getBitmapSize(value);
return bitmapSize == 0 ? 1 : bitmapSize;
}
|
[
"@",
"Override",
"protected",
"int",
"sizeOf",
"(",
"String",
"key",
",",
"Bitmap",
"value",
")",
"{",
"final",
"int",
"bitmapSize",
"=",
"BitmapLruPool",
".",
"getBitmapSize",
"(",
"value",
")",
";",
"return",
"bitmapSize",
"==",
"0",
"?",
"1",
":",
"bitmapSize",
";",
"}"
] |
Measure item size in kilobytes rather than units which is more practical
for a bitmap cache
|
[
"Measure",
"item",
"size",
"in",
"kilobytes",
"rather",
"than",
"units",
"which",
"is",
"more",
"practical",
"for",
"a",
"bitmap",
"cache"
] |
train
|
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/util/DefaultBitmapLruCache.java#L80-L84
|
facebookarchive/hadoop-20
|
src/contrib/corona/src/java/org/apache/hadoop/corona/Schedulable.java
|
Schedulable.distributeShareFair
|
private static void distributeShareFair(
double total, final Collection<? extends Schedulable> schedulables) {
"""
Distribute the total share among the list of schedulables according to the
FAIR model.
Finds a way to distribute the share in such a way that all the
min and max reservations of the schedulables are satisfied
@param total the share to be distributed
@param schedulables the list of schedulables
"""
BinarySearcher searcher = new BinarySearcher() {
@Override
protected double targetFunction(double x) {
return totalShareWithRatio(schedulables, x);
}
};
double ratio = searcher.getSolution(total);
for (Schedulable schedulable : schedulables) {
schedulable.share = shareWithRatio(schedulable, ratio);
}
}
|
java
|
private static void distributeShareFair(
double total, final Collection<? extends Schedulable> schedulables) {
BinarySearcher searcher = new BinarySearcher() {
@Override
protected double targetFunction(double x) {
return totalShareWithRatio(schedulables, x);
}
};
double ratio = searcher.getSolution(total);
for (Schedulable schedulable : schedulables) {
schedulable.share = shareWithRatio(schedulable, ratio);
}
}
|
[
"private",
"static",
"void",
"distributeShareFair",
"(",
"double",
"total",
",",
"final",
"Collection",
"<",
"?",
"extends",
"Schedulable",
">",
"schedulables",
")",
"{",
"BinarySearcher",
"searcher",
"=",
"new",
"BinarySearcher",
"(",
")",
"{",
"@",
"Override",
"protected",
"double",
"targetFunction",
"(",
"double",
"x",
")",
"{",
"return",
"totalShareWithRatio",
"(",
"schedulables",
",",
"x",
")",
";",
"}",
"}",
";",
"double",
"ratio",
"=",
"searcher",
".",
"getSolution",
"(",
"total",
")",
";",
"for",
"(",
"Schedulable",
"schedulable",
":",
"schedulables",
")",
"{",
"schedulable",
".",
"share",
"=",
"shareWithRatio",
"(",
"schedulable",
",",
"ratio",
")",
";",
"}",
"}"
] |
Distribute the total share among the list of schedulables according to the
FAIR model.
Finds a way to distribute the share in such a way that all the
min and max reservations of the schedulables are satisfied
@param total the share to be distributed
@param schedulables the list of schedulables
|
[
"Distribute",
"the",
"total",
"share",
"among",
"the",
"list",
"of",
"schedulables",
"according",
"to",
"the",
"FAIR",
"model",
".",
"Finds",
"a",
"way",
"to",
"distribute",
"the",
"share",
"in",
"such",
"a",
"way",
"that",
"all",
"the",
"min",
"and",
"max",
"reservations",
"of",
"the",
"schedulables",
"are",
"satisfied"
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Schedulable.java#L223-L235
|
synchronoss/cpo-api
|
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
|
CassandraCpoAdapter.getCpoAttributes
|
@Override
public List<CpoAttribute> getCpoAttributes(String expression) throws CpoException {
"""
Get the cpo attributes for this expression
@param expression - A string expression
@return A List of CpoAttribute
@throws CpoException
"""
List<CpoAttribute> attributes = new ArrayList<>();
if (expression != null && !expression.isEmpty()) {
Session session;
ResultSet rs;
try {
session = getWriteSession();
rs = session.execute(expression);
ColumnDefinitions columnDefs = rs.getColumnDefinitions();
for (int i = 0; i < columnDefs.size(); i++) {
CpoAttribute attribute = new CassandraCpoAttribute();
attribute.setDataName(columnDefs.getName(i));
DataTypeMapEntry<?> dataTypeMapEntry = metaDescriptor.getDataTypeMapEntry(columnDefs.getType(i).getName().ordinal());
attribute.setDataType(dataTypeMapEntry.getDataTypeName());
attribute.setDataTypeInt(dataTypeMapEntry.getDataTypeInt());
attribute.setJavaType(dataTypeMapEntry.getJavaClass().getName());
attribute.setJavaName(dataTypeMapEntry.makeJavaName(columnDefs.getName(i)));
attributes.add(attribute);
}
} catch (Throwable t) {
logger.error(ExceptionHelper.getLocalizedMessage(t), t);
throw new CpoException("Error Generating Attributes", t);
}
}
return attributes;
}
|
java
|
@Override
public List<CpoAttribute> getCpoAttributes(String expression) throws CpoException {
List<CpoAttribute> attributes = new ArrayList<>();
if (expression != null && !expression.isEmpty()) {
Session session;
ResultSet rs;
try {
session = getWriteSession();
rs = session.execute(expression);
ColumnDefinitions columnDefs = rs.getColumnDefinitions();
for (int i = 0; i < columnDefs.size(); i++) {
CpoAttribute attribute = new CassandraCpoAttribute();
attribute.setDataName(columnDefs.getName(i));
DataTypeMapEntry<?> dataTypeMapEntry = metaDescriptor.getDataTypeMapEntry(columnDefs.getType(i).getName().ordinal());
attribute.setDataType(dataTypeMapEntry.getDataTypeName());
attribute.setDataTypeInt(dataTypeMapEntry.getDataTypeInt());
attribute.setJavaType(dataTypeMapEntry.getJavaClass().getName());
attribute.setJavaName(dataTypeMapEntry.makeJavaName(columnDefs.getName(i)));
attributes.add(attribute);
}
} catch (Throwable t) {
logger.error(ExceptionHelper.getLocalizedMessage(t), t);
throw new CpoException("Error Generating Attributes", t);
}
}
return attributes;
}
|
[
"@",
"Override",
"public",
"List",
"<",
"CpoAttribute",
">",
"getCpoAttributes",
"(",
"String",
"expression",
")",
"throws",
"CpoException",
"{",
"List",
"<",
"CpoAttribute",
">",
"attributes",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"expression",
"!=",
"null",
"&&",
"!",
"expression",
".",
"isEmpty",
"(",
")",
")",
"{",
"Session",
"session",
";",
"ResultSet",
"rs",
";",
"try",
"{",
"session",
"=",
"getWriteSession",
"(",
")",
";",
"rs",
"=",
"session",
".",
"execute",
"(",
"expression",
")",
";",
"ColumnDefinitions",
"columnDefs",
"=",
"rs",
".",
"getColumnDefinitions",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"columnDefs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"CpoAttribute",
"attribute",
"=",
"new",
"CassandraCpoAttribute",
"(",
")",
";",
"attribute",
".",
"setDataName",
"(",
"columnDefs",
".",
"getName",
"(",
"i",
")",
")",
";",
"DataTypeMapEntry",
"<",
"?",
">",
"dataTypeMapEntry",
"=",
"metaDescriptor",
".",
"getDataTypeMapEntry",
"(",
"columnDefs",
".",
"getType",
"(",
"i",
")",
".",
"getName",
"(",
")",
".",
"ordinal",
"(",
")",
")",
";",
"attribute",
".",
"setDataType",
"(",
"dataTypeMapEntry",
".",
"getDataTypeName",
"(",
")",
")",
";",
"attribute",
".",
"setDataTypeInt",
"(",
"dataTypeMapEntry",
".",
"getDataTypeInt",
"(",
")",
")",
";",
"attribute",
".",
"setJavaType",
"(",
"dataTypeMapEntry",
".",
"getJavaClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"attribute",
".",
"setJavaName",
"(",
"dataTypeMapEntry",
".",
"makeJavaName",
"(",
"columnDefs",
".",
"getName",
"(",
"i",
")",
")",
")",
";",
"attributes",
".",
"add",
"(",
"attribute",
")",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"logger",
".",
"error",
"(",
"ExceptionHelper",
".",
"getLocalizedMessage",
"(",
"t",
")",
",",
"t",
")",
";",
"throw",
"new",
"CpoException",
"(",
"\"Error Generating Attributes\"",
",",
"t",
")",
";",
"}",
"}",
"return",
"attributes",
";",
"}"
] |
Get the cpo attributes for this expression
@param expression - A string expression
@return A List of CpoAttribute
@throws CpoException
|
[
"Get",
"the",
"cpo",
"attributes",
"for",
"this",
"expression"
] |
train
|
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1975-L2004
|
kuali/ojb-1.0.4
|
src/java/org/apache/ojb/broker/metadata/JdbcTypesHelper.java
|
JdbcTypesHelper.getObjectFromColumn
|
private static Object getObjectFromColumn(ResultSet rs, CallableStatement stmt, Integer jdbcType, String columnName, int columnId)
throws SQLException {
"""
Returns an java object for the given jdbcType by extract from the given
CallableStatement or ResultSet.
NOTE: Exactly one of the arguments of type CallableStatement or ResultSet
have to be non-null.
If the 'columnId' argument is equals {@link JdbcType#MIN_INT}, then the given 'columnName'
argument is used to lookup column. Else the given 'columnId' is used as column index.
"""
return getJdbcTypeByTypesIndex(jdbcType).getObjectFromColumn(rs, stmt, columnName, columnId);
}
|
java
|
private static Object getObjectFromColumn(ResultSet rs, CallableStatement stmt, Integer jdbcType, String columnName, int columnId)
throws SQLException
{
return getJdbcTypeByTypesIndex(jdbcType).getObjectFromColumn(rs, stmt, columnName, columnId);
}
|
[
"private",
"static",
"Object",
"getObjectFromColumn",
"(",
"ResultSet",
"rs",
",",
"CallableStatement",
"stmt",
",",
"Integer",
"jdbcType",
",",
"String",
"columnName",
",",
"int",
"columnId",
")",
"throws",
"SQLException",
"{",
"return",
"getJdbcTypeByTypesIndex",
"(",
"jdbcType",
")",
".",
"getObjectFromColumn",
"(",
"rs",
",",
"stmt",
",",
"columnName",
",",
"columnId",
")",
";",
"}"
] |
Returns an java object for the given jdbcType by extract from the given
CallableStatement or ResultSet.
NOTE: Exactly one of the arguments of type CallableStatement or ResultSet
have to be non-null.
If the 'columnId' argument is equals {@link JdbcType#MIN_INT}, then the given 'columnName'
argument is used to lookup column. Else the given 'columnId' is used as column index.
|
[
"Returns",
"an",
"java",
"object",
"for",
"the",
"given",
"jdbcType",
"by",
"extract",
"from",
"the",
"given",
"CallableStatement",
"or",
"ResultSet",
".",
"NOTE",
":",
"Exactly",
"one",
"of",
"the",
"arguments",
"of",
"type",
"CallableStatement",
"or",
"ResultSet",
"have",
"to",
"be",
"non",
"-",
"null",
".",
"If",
"the",
"columnId",
"argument",
"is",
"equals",
"{"
] |
train
|
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/metadata/JdbcTypesHelper.java#L227-L231
|
BranchMetrics/android-branch-deep-linking
|
Branch-SDK/src/io/branch/referral/Branch.java
|
Branch.redeemRewards
|
public void redeemRewards(int count, BranchReferralStateChangedListener callback) {
"""
<p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
credits within it. If the number to redeem exceeds the number available in the bucket, all of
the available credits will be redeemed instead.</p>
@param count A {@link Integer} specifying the number of credits to attempt to redeem from
the bucket.
@param callback A {@link BranchReferralStateChangedListener} callback instance that will
trigger actions defined therein upon a executing redeem rewards.
"""
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback);
}
|
java
|
public void redeemRewards(int count, BranchReferralStateChangedListener callback) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback);
}
|
[
"public",
"void",
"redeemRewards",
"(",
"int",
"count",
",",
"BranchReferralStateChangedListener",
"callback",
")",
"{",
"redeemRewards",
"(",
"Defines",
".",
"Jsonkey",
".",
"DefaultBucket",
".",
"getKey",
"(",
")",
",",
"count",
",",
"callback",
")",
";",
"}"
] |
<p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
credits within it. If the number to redeem exceeds the number available in the bucket, all of
the available credits will be redeemed instead.</p>
@param count A {@link Integer} specifying the number of credits to attempt to redeem from
the bucket.
@param callback A {@link BranchReferralStateChangedListener} callback instance that will
trigger actions defined therein upon a executing redeem rewards.
|
[
"<p",
">",
"Redeems",
"the",
"specified",
"number",
"of",
"credits",
"from",
"the",
"default",
"bucket",
"if",
"there",
"are",
"sufficient",
"credits",
"within",
"it",
".",
"If",
"the",
"number",
"to",
"redeem",
"exceeds",
"the",
"number",
"available",
"in",
"the",
"bucket",
"all",
"of",
"the",
"available",
"credits",
"will",
"be",
"redeemed",
"instead",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/Branch.java#L1885-L1887
|
TheCoder4eu/BootsFaces-OSP
|
src/main/java/net/bootsfaces/component/selectOneMenu/SelectOneMenuRenderer.java
|
SelectOneMenuRenderer.renderJQueryAfterComponent
|
private void renderJQueryAfterComponent(ResponseWriter rw, String clientId, SelectOneMenu menu) throws IOException {
"""
render a jquery javascript block after the component if necessary
@param rw
@param clientId
@param menu
@throws IOException
"""
Boolean select2 = menu.isSelect2();
if (select2 != null && select2) {
rw.startElement("script", menu);
rw.writeAttribute("type", "text/javascript", "script");
StringBuilder buf = new StringBuilder("$(document).ready(function(){");
buf.append("\n");
// jquery selector for the ID of the select component
buf.append(" $(\"[id='").append(clientId).append("']\")");
// select2 command to enable filtering
buf.append(".select2();");
buf.append("\n");
buf.append("});");
rw.writeText(buf.toString(), "script");
rw.endElement("script");
}
}
|
java
|
private void renderJQueryAfterComponent(ResponseWriter rw, String clientId, SelectOneMenu menu) throws IOException {
Boolean select2 = menu.isSelect2();
if (select2 != null && select2) {
rw.startElement("script", menu);
rw.writeAttribute("type", "text/javascript", "script");
StringBuilder buf = new StringBuilder("$(document).ready(function(){");
buf.append("\n");
// jquery selector for the ID of the select component
buf.append(" $(\"[id='").append(clientId).append("']\")");
// select2 command to enable filtering
buf.append(".select2();");
buf.append("\n");
buf.append("});");
rw.writeText(buf.toString(), "script");
rw.endElement("script");
}
}
|
[
"private",
"void",
"renderJQueryAfterComponent",
"(",
"ResponseWriter",
"rw",
",",
"String",
"clientId",
",",
"SelectOneMenu",
"menu",
")",
"throws",
"IOException",
"{",
"Boolean",
"select2",
"=",
"menu",
".",
"isSelect2",
"(",
")",
";",
"if",
"(",
"select2",
"!=",
"null",
"&&",
"select2",
")",
"{",
"rw",
".",
"startElement",
"(",
"\"script\"",
",",
"menu",
")",
";",
"rw",
".",
"writeAttribute",
"(",
"\"type\"",
",",
"\"text/javascript\"",
",",
"\"script\"",
")",
";",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"\"$(document).ready(function(){\"",
")",
";",
"buf",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"// jquery selector for the ID of the select component",
"buf",
".",
"append",
"(",
"\" $(\\\"[id='\"",
")",
".",
"append",
"(",
"clientId",
")",
".",
"append",
"(",
"\"']\\\")\"",
")",
";",
"// select2 command to enable filtering",
"buf",
".",
"append",
"(",
"\".select2();\"",
")",
";",
"buf",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"buf",
".",
"append",
"(",
"\"});\"",
")",
";",
"rw",
".",
"writeText",
"(",
"buf",
".",
"toString",
"(",
")",
",",
"\"script\"",
")",
";",
"rw",
".",
"endElement",
"(",
"\"script\"",
")",
";",
"}",
"}"
] |
render a jquery javascript block after the component if necessary
@param rw
@param clientId
@param menu
@throws IOException
|
[
"render",
"a",
"jquery",
"javascript",
"block",
"after",
"the",
"component",
"if",
"necessary"
] |
train
|
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/selectOneMenu/SelectOneMenuRenderer.java#L290-L308
|
Azure/azure-sdk-for-java
|
sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/BackupShortTermRetentionPoliciesInner.java
|
BackupShortTermRetentionPoliciesInner.beginUpdateAsync
|
public Observable<BackupShortTermRetentionPolicyInner> beginUpdateAsync(String resourceGroupName, String serverName, String databaseName, Integer retentionDays) {
"""
Updates a database's short term retention policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@param retentionDays The backup retention period in days. This is how many days Point-in-Time Restore will be supported.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BackupShortTermRetentionPolicyInner object
"""
return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, retentionDays).map(new Func1<ServiceResponse<BackupShortTermRetentionPolicyInner>, BackupShortTermRetentionPolicyInner>() {
@Override
public BackupShortTermRetentionPolicyInner call(ServiceResponse<BackupShortTermRetentionPolicyInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<BackupShortTermRetentionPolicyInner> beginUpdateAsync(String resourceGroupName, String serverName, String databaseName, Integer retentionDays) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, retentionDays).map(new Func1<ServiceResponse<BackupShortTermRetentionPolicyInner>, BackupShortTermRetentionPolicyInner>() {
@Override
public BackupShortTermRetentionPolicyInner call(ServiceResponse<BackupShortTermRetentionPolicyInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"BackupShortTermRetentionPolicyInner",
">",
"beginUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"Integer",
"retentionDays",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName",
",",
"retentionDays",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"BackupShortTermRetentionPolicyInner",
">",
",",
"BackupShortTermRetentionPolicyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"BackupShortTermRetentionPolicyInner",
"call",
"(",
"ServiceResponse",
"<",
"BackupShortTermRetentionPolicyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates a database's short term retention policy.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database.
@param retentionDays The backup retention period in days. This is how many days Point-in-Time Restore will be supported.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BackupShortTermRetentionPolicyInner object
|
[
"Updates",
"a",
"database",
"s",
"short",
"term",
"retention",
"policy",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/BackupShortTermRetentionPoliciesInner.java#L833-L840
|
mebigfatguy/fb-contrib
|
src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java
|
ExceptionSoftening.updateEndPCsOnCatchRegScope
|
private void updateEndPCsOnCatchRegScope(List<CatchInfo> infos, int pc, int seen) {
"""
reduces the end pc based on the optional LocalVariableTable's exception
register scope
@param infos the list of active catch blocks
@param pc the current pc
@param seen the currently parsed opcode
"""
if (lvt != null) {
for (CatchInfo ci : infos) {
if ((ci.getStart() == pc) && OpcodeUtils.isAStore(seen)) {
int exReg = RegisterUtils.getAStoreReg(this, seen);
LocalVariable lv = lvt.getLocalVariable(exReg, pc + 1);
if (lv != null) {
ci.setFinish(lv.getStartPC() + lv.getLength());
}
break;
}
}
}
}
|
java
|
private void updateEndPCsOnCatchRegScope(List<CatchInfo> infos, int pc, int seen) {
if (lvt != null) {
for (CatchInfo ci : infos) {
if ((ci.getStart() == pc) && OpcodeUtils.isAStore(seen)) {
int exReg = RegisterUtils.getAStoreReg(this, seen);
LocalVariable lv = lvt.getLocalVariable(exReg, pc + 1);
if (lv != null) {
ci.setFinish(lv.getStartPC() + lv.getLength());
}
break;
}
}
}
}
|
[
"private",
"void",
"updateEndPCsOnCatchRegScope",
"(",
"List",
"<",
"CatchInfo",
">",
"infos",
",",
"int",
"pc",
",",
"int",
"seen",
")",
"{",
"if",
"(",
"lvt",
"!=",
"null",
")",
"{",
"for",
"(",
"CatchInfo",
"ci",
":",
"infos",
")",
"{",
"if",
"(",
"(",
"ci",
".",
"getStart",
"(",
")",
"==",
"pc",
")",
"&&",
"OpcodeUtils",
".",
"isAStore",
"(",
"seen",
")",
")",
"{",
"int",
"exReg",
"=",
"RegisterUtils",
".",
"getAStoreReg",
"(",
"this",
",",
"seen",
")",
";",
"LocalVariable",
"lv",
"=",
"lvt",
".",
"getLocalVariable",
"(",
"exReg",
",",
"pc",
"+",
"1",
")",
";",
"if",
"(",
"lv",
"!=",
"null",
")",
"{",
"ci",
".",
"setFinish",
"(",
"lv",
".",
"getStartPC",
"(",
")",
"+",
"lv",
".",
"getLength",
"(",
")",
")",
";",
"}",
"break",
";",
"}",
"}",
"}",
"}"
] |
reduces the end pc based on the optional LocalVariableTable's exception
register scope
@param infos the list of active catch blocks
@param pc the current pc
@param seen the currently parsed opcode
|
[
"reduces",
"the",
"end",
"pc",
"based",
"on",
"the",
"optional",
"LocalVariableTable",
"s",
"exception",
"register",
"scope"
] |
train
|
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java#L332-L345
|
op4j/op4j
|
src/main/java/org/op4j/functions/Call.java
|
Call.setOfString
|
public static Function<Object,Set<String>> setOfString(final String methodName, final Object... optionalParameters) {
"""
<p>
Abbreviation for {{@link #methodForSetOfString(String, Object...)}.
</p>
@since 1.1
@param methodName the name of the method
@param optionalParameters the (optional) parameters of the method.
@return the result of the method execution
"""
return methodForSetOfString(methodName, optionalParameters);
}
|
java
|
public static Function<Object,Set<String>> setOfString(final String methodName, final Object... optionalParameters) {
return methodForSetOfString(methodName, optionalParameters);
}
|
[
"public",
"static",
"Function",
"<",
"Object",
",",
"Set",
"<",
"String",
">",
">",
"setOfString",
"(",
"final",
"String",
"methodName",
",",
"final",
"Object",
"...",
"optionalParameters",
")",
"{",
"return",
"methodForSetOfString",
"(",
"methodName",
",",
"optionalParameters",
")",
";",
"}"
] |
<p>
Abbreviation for {{@link #methodForSetOfString(String, Object...)}.
</p>
@since 1.1
@param methodName the name of the method
@param optionalParameters the (optional) parameters of the method.
@return the result of the method execution
|
[
"<p",
">",
"Abbreviation",
"for",
"{{",
"@link",
"#methodForSetOfString",
"(",
"String",
"Object",
"...",
")",
"}",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/Call.java#L581-L583
|
deeplearning4j/deeplearning4j
|
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
|
WordVectorSerializer.writeWordVectors
|
public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, File file)
throws IOException {
"""
This method writes word vectors to the given file.
Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network.
@param lookupTable
@param file
@param <T>
"""
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
writeWordVectors(lookupTable, bos);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
java
|
public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, File file)
throws IOException {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
writeWordVectors(lookupTable, bos);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
[
"public",
"static",
"<",
"T",
"extends",
"SequenceElement",
">",
"void",
"writeWordVectors",
"(",
"WeightLookupTable",
"<",
"T",
">",
"lookupTable",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedOutputStream",
"bos",
"=",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
")",
"{",
"writeWordVectors",
"(",
"lookupTable",
",",
"bos",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
This method writes word vectors to the given file.
Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network.
@param lookupTable
@param file
@param <T>
|
[
"This",
"method",
"writes",
"word",
"vectors",
"to",
"the",
"given",
"file",
".",
"Please",
"note",
":",
"this",
"method",
"doesn",
"t",
"load",
"whole",
"vocab",
"/",
"lookupTable",
"into",
"memory",
"so",
"it",
"s",
"able",
"to",
"process",
"large",
"vocabularies",
"served",
"over",
"network",
"."
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L321-L328
|
infinispan/infinispan
|
server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
|
HotRodServer.toMillis
|
private static long toMillis(long duration, TimeUnitValue unit) {
"""
Transforms lifespan pass as seconds into milliseconds following this rule (inspired by Memcached):
<p>
If lifespan is bigger than number of seconds in 30 days, then it is considered unix time. After converting it to
milliseconds, we subtract the current time in and the result is returned.
<p>
Otherwise it's just considered number of seconds from now and it's returned in milliseconds unit.
"""
if (duration > 0) {
long milliseconds = unit.toTimeUnit().toMillis(duration);
if (milliseconds > MILLISECONDS_IN_30_DAYS) {
long unixTimeExpiry = milliseconds - System.currentTimeMillis();
return unixTimeExpiry < 0 ? 0 : unixTimeExpiry;
} else {
return milliseconds;
}
} else {
return duration;
}
}
|
java
|
private static long toMillis(long duration, TimeUnitValue unit) {
if (duration > 0) {
long milliseconds = unit.toTimeUnit().toMillis(duration);
if (milliseconds > MILLISECONDS_IN_30_DAYS) {
long unixTimeExpiry = milliseconds - System.currentTimeMillis();
return unixTimeExpiry < 0 ? 0 : unixTimeExpiry;
} else {
return milliseconds;
}
} else {
return duration;
}
}
|
[
"private",
"static",
"long",
"toMillis",
"(",
"long",
"duration",
",",
"TimeUnitValue",
"unit",
")",
"{",
"if",
"(",
"duration",
">",
"0",
")",
"{",
"long",
"milliseconds",
"=",
"unit",
".",
"toTimeUnit",
"(",
")",
".",
"toMillis",
"(",
"duration",
")",
";",
"if",
"(",
"milliseconds",
">",
"MILLISECONDS_IN_30_DAYS",
")",
"{",
"long",
"unixTimeExpiry",
"=",
"milliseconds",
"-",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"return",
"unixTimeExpiry",
"<",
"0",
"?",
"0",
":",
"unixTimeExpiry",
";",
"}",
"else",
"{",
"return",
"milliseconds",
";",
"}",
"}",
"else",
"{",
"return",
"duration",
";",
"}",
"}"
] |
Transforms lifespan pass as seconds into milliseconds following this rule (inspired by Memcached):
<p>
If lifespan is bigger than number of seconds in 30 days, then it is considered unix time. After converting it to
milliseconds, we subtract the current time in and the result is returned.
<p>
Otherwise it's just considered number of seconds from now and it's returned in milliseconds unit.
|
[
"Transforms",
"lifespan",
"pass",
"as",
"seconds",
"into",
"milliseconds",
"following",
"this",
"rule",
"(",
"inspired",
"by",
"Memcached",
")",
":",
"<p",
">",
"If",
"lifespan",
"is",
"bigger",
"than",
"number",
"of",
"seconds",
"in",
"30",
"days",
"then",
"it",
"is",
"considered",
"unix",
"time",
".",
"After",
"converting",
"it",
"to",
"milliseconds",
"we",
"subtract",
"the",
"current",
"time",
"in",
"and",
"the",
"result",
"is",
"returned",
".",
"<p",
">",
"Otherwise",
"it",
"s",
"just",
"considered",
"number",
"of",
"seconds",
"from",
"now",
"and",
"it",
"s",
"returned",
"in",
"milliseconds",
"unit",
"."
] |
train
|
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java#L607-L619
|
fuinorg/units4j
|
src/main/java/org/fuin/units4j/dependency/Dependencies.java
|
Dependencies.validate
|
public final void validate() throws InvalidDependenciesDefinitionException {
"""
Checks if the definition is valid - Especially if no package is in both lists.
@throws InvalidDependenciesDefinitionException
This instance is invalid.
"""
int errorCount = 0;
final StringBuilder sb = new StringBuilder("Duplicate package entries in 'allowed' and 'forbidden': ");
final List<Package<NotDependsOn>> list = getForbidden();
for (int i = 0; i < list.size(); i++) {
final String name = list.get(i).getName();
final Package<DependsOn> dep = new Package<DependsOn>(name);
if (getAllowed().indexOf(dep) > -1) {
if (errorCount > 0) {
sb.append(", ");
}
sb.append(name);
errorCount++;
}
}
if (errorCount > 0) {
throw new InvalidDependenciesDefinitionException(this, sb.toString());
}
}
|
java
|
public final void validate() throws InvalidDependenciesDefinitionException {
int errorCount = 0;
final StringBuilder sb = new StringBuilder("Duplicate package entries in 'allowed' and 'forbidden': ");
final List<Package<NotDependsOn>> list = getForbidden();
for (int i = 0; i < list.size(); i++) {
final String name = list.get(i).getName();
final Package<DependsOn> dep = new Package<DependsOn>(name);
if (getAllowed().indexOf(dep) > -1) {
if (errorCount > 0) {
sb.append(", ");
}
sb.append(name);
errorCount++;
}
}
if (errorCount > 0) {
throw new InvalidDependenciesDefinitionException(this, sb.toString());
}
}
|
[
"public",
"final",
"void",
"validate",
"(",
")",
"throws",
"InvalidDependenciesDefinitionException",
"{",
"int",
"errorCount",
"=",
"0",
";",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"Duplicate package entries in 'allowed' and 'forbidden': \"",
")",
";",
"final",
"List",
"<",
"Package",
"<",
"NotDependsOn",
">",
">",
"list",
"=",
"getForbidden",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"list",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"String",
"name",
"=",
"list",
".",
"get",
"(",
"i",
")",
".",
"getName",
"(",
")",
";",
"final",
"Package",
"<",
"DependsOn",
">",
"dep",
"=",
"new",
"Package",
"<",
"DependsOn",
">",
"(",
"name",
")",
";",
"if",
"(",
"getAllowed",
"(",
")",
".",
"indexOf",
"(",
"dep",
")",
">",
"-",
"1",
")",
"{",
"if",
"(",
"errorCount",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"name",
")",
";",
"errorCount",
"++",
";",
"}",
"}",
"if",
"(",
"errorCount",
">",
"0",
")",
"{",
"throw",
"new",
"InvalidDependenciesDefinitionException",
"(",
"this",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] |
Checks if the definition is valid - Especially if no package is in both lists.
@throws InvalidDependenciesDefinitionException
This instance is invalid.
|
[
"Checks",
"if",
"the",
"definition",
"is",
"valid",
"-",
"Especially",
"if",
"no",
"package",
"is",
"in",
"both",
"lists",
"."
] |
train
|
https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/dependency/Dependencies.java#L136-L155
|
facebook/fresco
|
imagepipeline-base/src/main/java/com/facebook/imagepipeline/common/BytesRange.java
|
BytesRange.fromContentRangeHeader
|
@Nullable
public static BytesRange fromContentRangeHeader(@Nullable String header)
throws IllegalArgumentException {
"""
Creates an instance of BytesRange by parsing the value of a returned HTTP "Content-Range"
header.
<p> If the range runs to the end of the available content, the end of the range will be set to
TO_END_OF_CONTENT.
<p> The header spec is at https://tools.ietf.org/html/rfc2616#section-14.16
@param header
@throws IllegalArgumentException if the header is non-null but fails to match the format per
the spec
@return the parsed range
"""
if (header == null) {
return null;
}
if (sHeaderParsingRegEx == null) {
sHeaderParsingRegEx = Pattern.compile("[-/ ]");
}
try {
final String[] headerParts = sHeaderParsingRegEx.split(header);
Preconditions.checkArgument(headerParts.length == 4);
Preconditions.checkArgument(headerParts[0].equals("bytes"));
final int from = Integer.parseInt(headerParts[1]);
final int to = Integer.parseInt(headerParts[2]);
final int length = Integer.parseInt(headerParts[3]);
Preconditions.checkArgument(to > from);
Preconditions.checkArgument(length > to);
if (to < length - 1) {
return new BytesRange(from, to);
} else {
return new BytesRange(from, TO_END_OF_CONTENT);
}
} catch (IllegalArgumentException x) {
throw new IllegalArgumentException(
String.format((Locale) null, "Invalid Content-Range header value: \"%s\"", header),
x);
}
}
|
java
|
@Nullable
public static BytesRange fromContentRangeHeader(@Nullable String header)
throws IllegalArgumentException {
if (header == null) {
return null;
}
if (sHeaderParsingRegEx == null) {
sHeaderParsingRegEx = Pattern.compile("[-/ ]");
}
try {
final String[] headerParts = sHeaderParsingRegEx.split(header);
Preconditions.checkArgument(headerParts.length == 4);
Preconditions.checkArgument(headerParts[0].equals("bytes"));
final int from = Integer.parseInt(headerParts[1]);
final int to = Integer.parseInt(headerParts[2]);
final int length = Integer.parseInt(headerParts[3]);
Preconditions.checkArgument(to > from);
Preconditions.checkArgument(length > to);
if (to < length - 1) {
return new BytesRange(from, to);
} else {
return new BytesRange(from, TO_END_OF_CONTENT);
}
} catch (IllegalArgumentException x) {
throw new IllegalArgumentException(
String.format((Locale) null, "Invalid Content-Range header value: \"%s\"", header),
x);
}
}
|
[
"@",
"Nullable",
"public",
"static",
"BytesRange",
"fromContentRangeHeader",
"(",
"@",
"Nullable",
"String",
"header",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"header",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"sHeaderParsingRegEx",
"==",
"null",
")",
"{",
"sHeaderParsingRegEx",
"=",
"Pattern",
".",
"compile",
"(",
"\"[-/ ]\"",
")",
";",
"}",
"try",
"{",
"final",
"String",
"[",
"]",
"headerParts",
"=",
"sHeaderParsingRegEx",
".",
"split",
"(",
"header",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"headerParts",
".",
"length",
"==",
"4",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"headerParts",
"[",
"0",
"]",
".",
"equals",
"(",
"\"bytes\"",
")",
")",
";",
"final",
"int",
"from",
"=",
"Integer",
".",
"parseInt",
"(",
"headerParts",
"[",
"1",
"]",
")",
";",
"final",
"int",
"to",
"=",
"Integer",
".",
"parseInt",
"(",
"headerParts",
"[",
"2",
"]",
")",
";",
"final",
"int",
"length",
"=",
"Integer",
".",
"parseInt",
"(",
"headerParts",
"[",
"3",
"]",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"to",
">",
"from",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"length",
">",
"to",
")",
";",
"if",
"(",
"to",
"<",
"length",
"-",
"1",
")",
"{",
"return",
"new",
"BytesRange",
"(",
"from",
",",
"to",
")",
";",
"}",
"else",
"{",
"return",
"new",
"BytesRange",
"(",
"from",
",",
"TO_END_OF_CONTENT",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalArgumentException",
"x",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"(",
"Locale",
")",
"null",
",",
"\"Invalid Content-Range header value: \\\"%s\\\"\"",
",",
"header",
")",
",",
"x",
")",
";",
"}",
"}"
] |
Creates an instance of BytesRange by parsing the value of a returned HTTP "Content-Range"
header.
<p> If the range runs to the end of the available content, the end of the range will be set to
TO_END_OF_CONTENT.
<p> The header spec is at https://tools.ietf.org/html/rfc2616#section-14.16
@param header
@throws IllegalArgumentException if the header is non-null but fails to match the format per
the spec
@return the parsed range
|
[
"Creates",
"an",
"instance",
"of",
"BytesRange",
"by",
"parsing",
"the",
"value",
"of",
"a",
"returned",
"HTTP",
"Content",
"-",
"Range",
"header",
"."
] |
train
|
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/common/BytesRange.java#L140-L172
|
apache/incubator-gobblin
|
gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java
|
AzkabanClient.createProject
|
public AzkabanClientStatus createProject(String projectName,
String description) throws AzkabanClientException {
"""
Creates a project.
@param projectName project name
@param description project description
@return A status object indicating if AJAX request is successful.
"""
AzkabanMultiCallables.CreateProjectCallable callable =
AzkabanMultiCallables.CreateProjectCallable.builder()
.client(this)
.projectName(projectName)
.description(description)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
}
|
java
|
public AzkabanClientStatus createProject(String projectName,
String description) throws AzkabanClientException {
AzkabanMultiCallables.CreateProjectCallable callable =
AzkabanMultiCallables.CreateProjectCallable.builder()
.client(this)
.projectName(projectName)
.description(description)
.build();
return runWithRetry(callable, AzkabanClientStatus.class);
}
|
[
"public",
"AzkabanClientStatus",
"createProject",
"(",
"String",
"projectName",
",",
"String",
"description",
")",
"throws",
"AzkabanClientException",
"{",
"AzkabanMultiCallables",
".",
"CreateProjectCallable",
"callable",
"=",
"AzkabanMultiCallables",
".",
"CreateProjectCallable",
".",
"builder",
"(",
")",
".",
"client",
"(",
"this",
")",
".",
"projectName",
"(",
"projectName",
")",
".",
"description",
"(",
"description",
")",
".",
"build",
"(",
")",
";",
"return",
"runWithRetry",
"(",
"callable",
",",
"AzkabanClientStatus",
".",
"class",
")",
";",
"}"
] |
Creates a project.
@param projectName project name
@param description project description
@return A status object indicating if AJAX request is successful.
|
[
"Creates",
"a",
"project",
"."
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/AzkabanClient.java#L278-L288
|
eurekaclinical/aiw-i2b2-etl
|
src/main/java/edu/emory/cci/aiw/i2b2etl/dest/metadata/conceptid/SimpleConceptId.java
|
SimpleConceptId.getInstance
|
public static ConceptId getInstance(String id, Metadata metadata) {
"""
Returns a concept propId with the given string identifier.
@param id a concept identifier {@link String}. Cannot be
<code>null</code>.
@return a {@link PropDefConceptId}.
"""
List<Object> key = new ArrayList<>(1);
key.add(id);
ConceptId result = metadata.getFromConceptIdCache(key);
if (result != null) {
return result;
} else {
result = new SimpleConceptId(id, metadata);
metadata.putInConceptIdCache(key, result);
return result;
}
}
|
java
|
public static ConceptId getInstance(String id, Metadata metadata) {
List<Object> key = new ArrayList<>(1);
key.add(id);
ConceptId result = metadata.getFromConceptIdCache(key);
if (result != null) {
return result;
} else {
result = new SimpleConceptId(id, metadata);
metadata.putInConceptIdCache(key, result);
return result;
}
}
|
[
"public",
"static",
"ConceptId",
"getInstance",
"(",
"String",
"id",
",",
"Metadata",
"metadata",
")",
"{",
"List",
"<",
"Object",
">",
"key",
"=",
"new",
"ArrayList",
"<>",
"(",
"1",
")",
";",
"key",
".",
"add",
"(",
"id",
")",
";",
"ConceptId",
"result",
"=",
"metadata",
".",
"getFromConceptIdCache",
"(",
"key",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"return",
"result",
";",
"}",
"else",
"{",
"result",
"=",
"new",
"SimpleConceptId",
"(",
"id",
",",
"metadata",
")",
";",
"metadata",
".",
"putInConceptIdCache",
"(",
"key",
",",
"result",
")",
";",
"return",
"result",
";",
"}",
"}"
] |
Returns a concept propId with the given string identifier.
@param id a concept identifier {@link String}. Cannot be
<code>null</code>.
@return a {@link PropDefConceptId}.
|
[
"Returns",
"a",
"concept",
"propId",
"with",
"the",
"given",
"string",
"identifier",
"."
] |
train
|
https://github.com/eurekaclinical/aiw-i2b2-etl/blob/3eed6bda7755919cb9466d2930723a0f4748341a/src/main/java/edu/emory/cci/aiw/i2b2etl/dest/metadata/conceptid/SimpleConceptId.java#L42-L53
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/ClientAsynchEventThreadPool.java
|
ClientAsynchEventThreadPool.dispatchDestinationListenerEvent
|
public void dispatchDestinationListenerEvent(SICoreConnection conn, SIDestinationAddress destinationAddress,
DestinationAvailability destinationAvailability, DestinationListener destinationListener) {
"""
Dispatches a thread which will call the destinationAvailable method on the destinationListener passing in the supplied parameters.
@param conn
@param destinationAddress
@param destinationAvailability
@param destinationListener
"""
if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dispatchDestinationListenerEvent",
new Object[]{conn, destinationAddress, destinationAvailability, destinationListener});
//Create a new DestinationListenerThread and dispatch it.
final DestinationListenerThread thread = new DestinationListenerThread(conn, destinationAddress, destinationAvailability, destinationListener);
dispatchThread(thread);
if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "dispatchDestinationListenerEvent");
}
|
java
|
public void dispatchDestinationListenerEvent(SICoreConnection conn, SIDestinationAddress destinationAddress,
DestinationAvailability destinationAvailability, DestinationListener destinationListener)
{
if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dispatchDestinationListenerEvent",
new Object[]{conn, destinationAddress, destinationAvailability, destinationListener});
//Create a new DestinationListenerThread and dispatch it.
final DestinationListenerThread thread = new DestinationListenerThread(conn, destinationAddress, destinationAvailability, destinationListener);
dispatchThread(thread);
if(TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "dispatchDestinationListenerEvent");
}
|
[
"public",
"void",
"dispatchDestinationListenerEvent",
"(",
"SICoreConnection",
"conn",
",",
"SIDestinationAddress",
"destinationAddress",
",",
"DestinationAvailability",
"destinationAvailability",
",",
"DestinationListener",
"destinationListener",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"entry",
"(",
"this",
",",
"tc",
",",
"\"dispatchDestinationListenerEvent\"",
",",
"new",
"Object",
"[",
"]",
"{",
"conn",
",",
"destinationAddress",
",",
"destinationAvailability",
",",
"destinationListener",
"}",
")",
";",
"//Create a new DestinationListenerThread and dispatch it.",
"final",
"DestinationListenerThread",
"thread",
"=",
"new",
"DestinationListenerThread",
"(",
"conn",
",",
"destinationAddress",
",",
"destinationAvailability",
",",
"destinationListener",
")",
";",
"dispatchThread",
"(",
"thread",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".",
"exit",
"(",
"this",
",",
"tc",
",",
"\"dispatchDestinationListenerEvent\"",
")",
";",
"}"
] |
Dispatches a thread which will call the destinationAvailable method on the destinationListener passing in the supplied parameters.
@param conn
@param destinationAddress
@param destinationAvailability
@param destinationListener
|
[
"Dispatches",
"a",
"thread",
"which",
"will",
"call",
"the",
"destinationAvailable",
"method",
"on",
"the",
"destinationListener",
"passing",
"in",
"the",
"supplied",
"parameters",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/client/ClientAsynchEventThreadPool.java#L189-L200
|
Jasig/resource-server
|
resource-server-utils/src/main/java/org/jasig/resourceserver/utils/filter/PathBasedCacheExpirationFilter.java
|
PathBasedCacheExpirationFilter.setCacheMaxAges
|
public void setCacheMaxAges(Map<String, ? extends Number> cacheMaxAges) {
"""
Specify map of ant paths to max-age times (in seconds). The default map is:
/**/*.aggr.min.js - 365 days
/**/*.aggr.min.css - 365 days
/**/*.min.js - 365 days
/**/*.min.css - 365 days
/rs/**/* - 365 days
"""
final Builder<String, Long> cacheMaxAgesBuilder = ImmutableMap.builder();
final Builder<Long, String> cachedControlStringsBuilder = ImmutableMap.builder();
final Set<Long> maxAgeLog = new HashSet<Long>();
for (final Map.Entry<String, ? extends Number> cacheMaxAgeEntry : cacheMaxAges.entrySet()) {
final Number maxAgeNum = cacheMaxAgeEntry.getValue();
final int maxAge = maxAgeNum.intValue();
final long maxAgeMillis = TimeUnit.SECONDS.toMillis(maxAge);
cacheMaxAgesBuilder.put(cacheMaxAgeEntry.getKey(), maxAgeMillis);
if (maxAgeLog.add(maxAgeMillis)) {
cachedControlStringsBuilder.put(maxAgeMillis, "public, max-age=" + maxAge);
}
}
this.cacheMaxAges = cacheMaxAgesBuilder.build();
this.cachedControlStrings = cachedControlStringsBuilder.build();
}
|
java
|
public void setCacheMaxAges(Map<String, ? extends Number> cacheMaxAges) {
final Builder<String, Long> cacheMaxAgesBuilder = ImmutableMap.builder();
final Builder<Long, String> cachedControlStringsBuilder = ImmutableMap.builder();
final Set<Long> maxAgeLog = new HashSet<Long>();
for (final Map.Entry<String, ? extends Number> cacheMaxAgeEntry : cacheMaxAges.entrySet()) {
final Number maxAgeNum = cacheMaxAgeEntry.getValue();
final int maxAge = maxAgeNum.intValue();
final long maxAgeMillis = TimeUnit.SECONDS.toMillis(maxAge);
cacheMaxAgesBuilder.put(cacheMaxAgeEntry.getKey(), maxAgeMillis);
if (maxAgeLog.add(maxAgeMillis)) {
cachedControlStringsBuilder.put(maxAgeMillis, "public, max-age=" + maxAge);
}
}
this.cacheMaxAges = cacheMaxAgesBuilder.build();
this.cachedControlStrings = cachedControlStringsBuilder.build();
}
|
[
"public",
"void",
"setCacheMaxAges",
"(",
"Map",
"<",
"String",
",",
"?",
"extends",
"Number",
">",
"cacheMaxAges",
")",
"{",
"final",
"Builder",
"<",
"String",
",",
"Long",
">",
"cacheMaxAgesBuilder",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"final",
"Builder",
"<",
"Long",
",",
"String",
">",
"cachedControlStringsBuilder",
"=",
"ImmutableMap",
".",
"builder",
"(",
")",
";",
"final",
"Set",
"<",
"Long",
">",
"maxAgeLog",
"=",
"new",
"HashSet",
"<",
"Long",
">",
"(",
")",
";",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"String",
",",
"?",
"extends",
"Number",
">",
"cacheMaxAgeEntry",
":",
"cacheMaxAges",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"Number",
"maxAgeNum",
"=",
"cacheMaxAgeEntry",
".",
"getValue",
"(",
")",
";",
"final",
"int",
"maxAge",
"=",
"maxAgeNum",
".",
"intValue",
"(",
")",
";",
"final",
"long",
"maxAgeMillis",
"=",
"TimeUnit",
".",
"SECONDS",
".",
"toMillis",
"(",
"maxAge",
")",
";",
"cacheMaxAgesBuilder",
".",
"put",
"(",
"cacheMaxAgeEntry",
".",
"getKey",
"(",
")",
",",
"maxAgeMillis",
")",
";",
"if",
"(",
"maxAgeLog",
".",
"add",
"(",
"maxAgeMillis",
")",
")",
"{",
"cachedControlStringsBuilder",
".",
"put",
"(",
"maxAgeMillis",
",",
"\"public, max-age=\"",
"+",
"maxAge",
")",
";",
"}",
"}",
"this",
".",
"cacheMaxAges",
"=",
"cacheMaxAgesBuilder",
".",
"build",
"(",
")",
";",
"this",
".",
"cachedControlStrings",
"=",
"cachedControlStringsBuilder",
".",
"build",
"(",
")",
";",
"}"
] |
Specify map of ant paths to max-age times (in seconds). The default map is:
/**/*.aggr.min.js - 365 days
/**/*.aggr.min.css - 365 days
/**/*.min.js - 365 days
/**/*.min.css - 365 days
/rs/**/* - 365 days
|
[
"Specify",
"map",
"of",
"ant",
"paths",
"to",
"max",
"-",
"age",
"times",
"(",
"in",
"seconds",
")",
".",
"The",
"default",
"map",
"is",
":"
] |
train
|
https://github.com/Jasig/resource-server/blob/13375f716777ec3c99ae9917f672881d4aa32df3/resource-server-utils/src/main/java/org/jasig/resourceserver/utils/filter/PathBasedCacheExpirationFilter.java#L84-L102
|
m-m-m/util
|
reflect/src/main/java/net/sf/mmm/util/reflect/base/AnnotationUtilImpl.java
|
AnnotationUtilImpl.getInterfacesAnnotation
|
private <A extends Annotation> A getInterfacesAnnotation(Class<?> annotatedType, Class<A> annotation) {
"""
This method gets the first {@link Class#getAnnotation(Class) annotation} of the type given by {@code annotation} in
the {@link Class#getInterfaces() hierarchy} of the given {@code annotatedInterface} . <br>
This method is only useful if the given {@code annotation} is a {@link #isRuntimeAnnotation(Class) runtime
annotation} that is {@link #isAnnotationForType(Class, ElementType) applicable} for {@link ElementType#TYPE
classes}.
@param <A> is the type of the requested annotation.
@param annotatedType is the type potentially implementing an interface annotated with the given {@code annotation}.
This should NOT be an {@link Class#isPrimitive() primitive}, {@link Class#isArray() array},
{@link Class#isEnum() enum}, or {@link Class#isAnnotation() annotation}.
@param annotation is the type of the requested annotation.
@return the requested annotation or {@code null} if neither the {@code annotatedInterface} nor one of its
{@link Class#getInterfaces() super-interfaces} are {@link Class#getAnnotation(Class) annotated} with the
given {@code annotation}.
"""
Class<?>[] interfaces = annotatedType.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
A result = interfaces[i].getAnnotation(annotation);
if (result != null) {
return result;
}
}
for (int i = 0; i < interfaces.length; i++) {
A result = getInterfacesAnnotation(interfaces[i], annotation);
if (result != null) {
return result;
}
}
return null;
}
|
java
|
private <A extends Annotation> A getInterfacesAnnotation(Class<?> annotatedType, Class<A> annotation) {
Class<?>[] interfaces = annotatedType.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
A result = interfaces[i].getAnnotation(annotation);
if (result != null) {
return result;
}
}
for (int i = 0; i < interfaces.length; i++) {
A result = getInterfacesAnnotation(interfaces[i], annotation);
if (result != null) {
return result;
}
}
return null;
}
|
[
"private",
"<",
"A",
"extends",
"Annotation",
">",
"A",
"getInterfacesAnnotation",
"(",
"Class",
"<",
"?",
">",
"annotatedType",
",",
"Class",
"<",
"A",
">",
"annotation",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"interfaces",
"=",
"annotatedType",
".",
"getInterfaces",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"interfaces",
".",
"length",
";",
"i",
"++",
")",
"{",
"A",
"result",
"=",
"interfaces",
"[",
"i",
"]",
".",
"getAnnotation",
"(",
"annotation",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"return",
"result",
";",
"}",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"interfaces",
".",
"length",
";",
"i",
"++",
")",
"{",
"A",
"result",
"=",
"getInterfacesAnnotation",
"(",
"interfaces",
"[",
"i",
"]",
",",
"annotation",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"return",
"result",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
This method gets the first {@link Class#getAnnotation(Class) annotation} of the type given by {@code annotation} in
the {@link Class#getInterfaces() hierarchy} of the given {@code annotatedInterface} . <br>
This method is only useful if the given {@code annotation} is a {@link #isRuntimeAnnotation(Class) runtime
annotation} that is {@link #isAnnotationForType(Class, ElementType) applicable} for {@link ElementType#TYPE
classes}.
@param <A> is the type of the requested annotation.
@param annotatedType is the type potentially implementing an interface annotated with the given {@code annotation}.
This should NOT be an {@link Class#isPrimitive() primitive}, {@link Class#isArray() array},
{@link Class#isEnum() enum}, or {@link Class#isAnnotation() annotation}.
@param annotation is the type of the requested annotation.
@return the requested annotation or {@code null} if neither the {@code annotatedInterface} nor one of its
{@link Class#getInterfaces() super-interfaces} are {@link Class#getAnnotation(Class) annotated} with the
given {@code annotation}.
|
[
"This",
"method",
"gets",
"the",
"first",
"{",
"@link",
"Class#getAnnotation",
"(",
"Class",
")",
"annotation",
"}",
"of",
"the",
"type",
"given",
"by",
"{",
"@code",
"annotation",
"}",
"in",
"the",
"{",
"@link",
"Class#getInterfaces",
"()",
"hierarchy",
"}",
"of",
"the",
"given",
"{",
"@code",
"annotatedInterface",
"}",
".",
"<br",
">",
"This",
"method",
"is",
"only",
"useful",
"if",
"the",
"given",
"{",
"@code",
"annotation",
"}",
"is",
"a",
"{",
"@link",
"#isRuntimeAnnotation",
"(",
"Class",
")",
"runtime",
"annotation",
"}",
"that",
"is",
"{",
"@link",
"#isAnnotationForType",
"(",
"Class",
"ElementType",
")",
"applicable",
"}",
"for",
"{",
"@link",
"ElementType#TYPE",
"classes",
"}",
"."
] |
train
|
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/reflect/src/main/java/net/sf/mmm/util/reflect/base/AnnotationUtilImpl.java#L156-L172
|
actorapp/droidkit-actors
|
actors/src/main/java/com/droidkit/actors/ActorSystem.java
|
ActorSystem.actorOf
|
public <T extends Actor> ActorRef actorOf(Class<T> actor, String path) {
"""
Creating or getting existing actor from actor class
@param actor Actor Class
@param path Actor Path
@param <T> Actor Class
@return ActorRef
"""
return actorOf(Props.create(actor), path);
}
|
java
|
public <T extends Actor> ActorRef actorOf(Class<T> actor, String path) {
return actorOf(Props.create(actor), path);
}
|
[
"public",
"<",
"T",
"extends",
"Actor",
">",
"ActorRef",
"actorOf",
"(",
"Class",
"<",
"T",
">",
"actor",
",",
"String",
"path",
")",
"{",
"return",
"actorOf",
"(",
"Props",
".",
"create",
"(",
"actor",
")",
",",
"path",
")",
";",
"}"
] |
Creating or getting existing actor from actor class
@param actor Actor Class
@param path Actor Path
@param <T> Actor Class
@return ActorRef
|
[
"Creating",
"or",
"getting",
"existing",
"actor",
"from",
"actor",
"class"
] |
train
|
https://github.com/actorapp/droidkit-actors/blob/fdb72fcfdd1c5e54a970f203a33a71fa54344217/actors/src/main/java/com/droidkit/actors/ActorSystem.java#L104-L106
|
BioPAX/Paxtools
|
paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java
|
QueryExecuter.runPathsBetween
|
public static Set<BioPAXElement> runPathsBetween(Set<BioPAXElement> sourceSet, Model model,
int limit, Filter... filters) {
"""
Gets the graph constructed by the paths between the given seed nodes. Does not get paths
between physical entities that belong the same entity reference.
@param sourceSet Seed to the query
@param model BioPAX model
@param limit Length limit for the paths to be found
@param filters optional filters - for filtering graph elements
@return BioPAX elements in the result
"""
Graph graph;
if (model.getLevel() == BioPAXLevel.L3)
{
graph = new GraphL3(model, filters);
}
else return Collections.emptySet();
Collection<Set<Node>> sourceWrappers = prepareNodeSets(sourceSet, graph);
if (sourceWrappers.size() < 2) return Collections.emptySet();
PathsBetweenQuery query = new PathsBetweenQuery(sourceWrappers, limit);
Set<GraphObject> resultWrappers = query.run();
return convertQueryResult(resultWrappers, graph, true);
}
|
java
|
public static Set<BioPAXElement> runPathsBetween(Set<BioPAXElement> sourceSet, Model model,
int limit, Filter... filters)
{
Graph graph;
if (model.getLevel() == BioPAXLevel.L3)
{
graph = new GraphL3(model, filters);
}
else return Collections.emptySet();
Collection<Set<Node>> sourceWrappers = prepareNodeSets(sourceSet, graph);
if (sourceWrappers.size() < 2) return Collections.emptySet();
PathsBetweenQuery query = new PathsBetweenQuery(sourceWrappers, limit);
Set<GraphObject> resultWrappers = query.run();
return convertQueryResult(resultWrappers, graph, true);
}
|
[
"public",
"static",
"Set",
"<",
"BioPAXElement",
">",
"runPathsBetween",
"(",
"Set",
"<",
"BioPAXElement",
">",
"sourceSet",
",",
"Model",
"model",
",",
"int",
"limit",
",",
"Filter",
"...",
"filters",
")",
"{",
"Graph",
"graph",
";",
"if",
"(",
"model",
".",
"getLevel",
"(",
")",
"==",
"BioPAXLevel",
".",
"L3",
")",
"{",
"graph",
"=",
"new",
"GraphL3",
"(",
"model",
",",
"filters",
")",
";",
"}",
"else",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"Collection",
"<",
"Set",
"<",
"Node",
">",
">",
"sourceWrappers",
"=",
"prepareNodeSets",
"(",
"sourceSet",
",",
"graph",
")",
";",
"if",
"(",
"sourceWrappers",
".",
"size",
"(",
")",
"<",
"2",
")",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"PathsBetweenQuery",
"query",
"=",
"new",
"PathsBetweenQuery",
"(",
"sourceWrappers",
",",
"limit",
")",
";",
"Set",
"<",
"GraphObject",
">",
"resultWrappers",
"=",
"query",
".",
"run",
"(",
")",
";",
"return",
"convertQueryResult",
"(",
"resultWrappers",
",",
"graph",
",",
"true",
")",
";",
"}"
] |
Gets the graph constructed by the paths between the given seed nodes. Does not get paths
between physical entities that belong the same entity reference.
@param sourceSet Seed to the query
@param model BioPAX model
@param limit Length limit for the paths to be found
@param filters optional filters - for filtering graph elements
@return BioPAX elements in the result
|
[
"Gets",
"the",
"graph",
"constructed",
"by",
"the",
"paths",
"between",
"the",
"given",
"seed",
"nodes",
".",
"Does",
"not",
"get",
"paths",
"between",
"physical",
"entities",
"that",
"belong",
"the",
"same",
"entity",
"reference",
"."
] |
train
|
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java#L118-L136
|
nyla-solutions/nyla
|
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java
|
Organizer.makeCopies
|
@SuppressWarnings( {
"""
Copy data from object to object
@param aFrom
the object to copy from
@param aTo
the object to copy to
""" "unchecked", "rawtypes" })
public static void makeCopies(Collection<Copier> aFrom, Collection<Copier> aTo)
{
if (aFrom == null || aTo == null)
return;
List<Copier> fromList = new ArrayList<Copier>(aFrom);
List<Copier> toList = new ArrayList<Copier>(aTo);
Collections.sort((List) fromList);
Collections.sort((List) toList);
Copier from = null;
Copier to = null;
Iterator<Copier> toIter = toList.iterator();
for (Iterator<Copier> i = fromList.iterator(); i.hasNext() && toIter.hasNext();)
{
from = (Copier) i.next();
to = (Copier) toIter.next();
// copy data
to.copy(from);
}
}
|
java
|
@SuppressWarnings(
{ "unchecked", "rawtypes" })
public static void makeCopies(Collection<Copier> aFrom, Collection<Copier> aTo)
{
if (aFrom == null || aTo == null)
return;
List<Copier> fromList = new ArrayList<Copier>(aFrom);
List<Copier> toList = new ArrayList<Copier>(aTo);
Collections.sort((List) fromList);
Collections.sort((List) toList);
Copier from = null;
Copier to = null;
Iterator<Copier> toIter = toList.iterator();
for (Iterator<Copier> i = fromList.iterator(); i.hasNext() && toIter.hasNext();)
{
from = (Copier) i.next();
to = (Copier) toIter.next();
// copy data
to.copy(from);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"public",
"static",
"void",
"makeCopies",
"(",
"Collection",
"<",
"Copier",
">",
"aFrom",
",",
"Collection",
"<",
"Copier",
">",
"aTo",
")",
"{",
"if",
"(",
"aFrom",
"==",
"null",
"||",
"aTo",
"==",
"null",
")",
"return",
";",
"List",
"<",
"Copier",
">",
"fromList",
"=",
"new",
"ArrayList",
"<",
"Copier",
">",
"(",
"aFrom",
")",
";",
"List",
"<",
"Copier",
">",
"toList",
"=",
"new",
"ArrayList",
"<",
"Copier",
">",
"(",
"aTo",
")",
";",
"Collections",
".",
"sort",
"(",
"(",
"List",
")",
"fromList",
")",
";",
"Collections",
".",
"sort",
"(",
"(",
"List",
")",
"toList",
")",
";",
"Copier",
"from",
"=",
"null",
";",
"Copier",
"to",
"=",
"null",
";",
"Iterator",
"<",
"Copier",
">",
"toIter",
"=",
"toList",
".",
"iterator",
"(",
")",
";",
"for",
"(",
"Iterator",
"<",
"Copier",
">",
"i",
"=",
"fromList",
".",
"iterator",
"(",
")",
";",
"i",
".",
"hasNext",
"(",
")",
"&&",
"toIter",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"from",
"=",
"(",
"Copier",
")",
"i",
".",
"next",
"(",
")",
";",
"to",
"=",
"(",
"Copier",
")",
"toIter",
".",
"next",
"(",
")",
";",
"// copy data\r",
"to",
".",
"copy",
"(",
"from",
")",
";",
"}",
"}"
] |
Copy data from object to object
@param aFrom
the object to copy from
@param aTo
the object to copy to
|
[
"Copy",
"data",
"from",
"object",
"to",
"object"
] |
train
|
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L845-L868
|
tvesalainen/hoski-lib
|
src/main/java/fi/hoski/datastore/repository/DataObject.java
|
DataObject.writeCSV
|
public static void writeCSV(DataObjectModel model, Collection<? extends DataObject> collection, OutputStream os) throws IOException {
"""
Writes collection of DataObjects in csv format. OutputStream is not closed
after operation.
@param os
@param collection
@throws IOException
"""
BufferedOutputStream bos = new BufferedOutputStream(os);
OutputStreamWriter osw = new OutputStreamWriter(bos, "ISO-8859-1");
CSVWriter writer = new CSVWriter(osw, ',', '"', "\r\n");
String[] line = model.getProperties();
writer.writeNext(line);
for (DataObject dob : collection)
{
int index = 0;
for (String property : model.getPropertyList())
{
Object value = dob.get(property);
if (value != null)
{
line[index++] = value.toString();
}
else
{
line[index++] = "";
}
}
writer.writeNext(line);
}
writer.flush();
}
|
java
|
public static void writeCSV(DataObjectModel model, Collection<? extends DataObject> collection, OutputStream os) throws IOException
{
BufferedOutputStream bos = new BufferedOutputStream(os);
OutputStreamWriter osw = new OutputStreamWriter(bos, "ISO-8859-1");
CSVWriter writer = new CSVWriter(osw, ',', '"', "\r\n");
String[] line = model.getProperties();
writer.writeNext(line);
for (DataObject dob : collection)
{
int index = 0;
for (String property : model.getPropertyList())
{
Object value = dob.get(property);
if (value != null)
{
line[index++] = value.toString();
}
else
{
line[index++] = "";
}
}
writer.writeNext(line);
}
writer.flush();
}
|
[
"public",
"static",
"void",
"writeCSV",
"(",
"DataObjectModel",
"model",
",",
"Collection",
"<",
"?",
"extends",
"DataObject",
">",
"collection",
",",
"OutputStream",
"os",
")",
"throws",
"IOException",
"{",
"BufferedOutputStream",
"bos",
"=",
"new",
"BufferedOutputStream",
"(",
"os",
")",
";",
"OutputStreamWriter",
"osw",
"=",
"new",
"OutputStreamWriter",
"(",
"bos",
",",
"\"ISO-8859-1\"",
")",
";",
"CSVWriter",
"writer",
"=",
"new",
"CSVWriter",
"(",
"osw",
",",
"'",
"'",
",",
"'",
"'",
",",
"\"\\r\\n\"",
")",
";",
"String",
"[",
"]",
"line",
"=",
"model",
".",
"getProperties",
"(",
")",
";",
"writer",
".",
"writeNext",
"(",
"line",
")",
";",
"for",
"(",
"DataObject",
"dob",
":",
"collection",
")",
"{",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"String",
"property",
":",
"model",
".",
"getPropertyList",
"(",
")",
")",
"{",
"Object",
"value",
"=",
"dob",
".",
"get",
"(",
"property",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"line",
"[",
"index",
"++",
"]",
"=",
"value",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"line",
"[",
"index",
"++",
"]",
"=",
"\"\"",
";",
"}",
"}",
"writer",
".",
"writeNext",
"(",
"line",
")",
";",
"}",
"writer",
".",
"flush",
"(",
")",
";",
"}"
] |
Writes collection of DataObjects in csv format. OutputStream is not closed
after operation.
@param os
@param collection
@throws IOException
|
[
"Writes",
"collection",
"of",
"DataObjects",
"in",
"csv",
"format",
".",
"OutputStream",
"is",
"not",
"closed",
"after",
"operation",
"."
] |
train
|
https://github.com/tvesalainen/hoski-lib/blob/9b5bab44113e0adb74bf1ee436013e8a7c608d00/src/main/java/fi/hoski/datastore/repository/DataObject.java#L483-L508
|
apereo/cas
|
core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java
|
WebUtils.putServiceUserInterfaceMetadata
|
public static void putServiceUserInterfaceMetadata(final RequestContext requestContext, final Serializable mdui) {
"""
Sets service user interface metadata.
@param requestContext the request context
@param mdui the mdui
"""
if (mdui != null) {
requestContext.getFlowScope().put(PARAMETER_SERVICE_UI_METADATA, mdui);
}
}
|
java
|
public static void putServiceUserInterfaceMetadata(final RequestContext requestContext, final Serializable mdui) {
if (mdui != null) {
requestContext.getFlowScope().put(PARAMETER_SERVICE_UI_METADATA, mdui);
}
}
|
[
"public",
"static",
"void",
"putServiceUserInterfaceMetadata",
"(",
"final",
"RequestContext",
"requestContext",
",",
"final",
"Serializable",
"mdui",
")",
"{",
"if",
"(",
"mdui",
"!=",
"null",
")",
"{",
"requestContext",
".",
"getFlowScope",
"(",
")",
".",
"put",
"(",
"PARAMETER_SERVICE_UI_METADATA",
",",
"mdui",
")",
";",
"}",
"}"
] |
Sets service user interface metadata.
@param requestContext the request context
@param mdui the mdui
|
[
"Sets",
"service",
"user",
"interface",
"metadata",
"."
] |
train
|
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java#L725-L729
|
aws/aws-sdk-java
|
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/xspec/NS.java
|
NS.ifNotExists
|
public IfNotExistsFunction<NS> ifNotExists(Number... defaultValue) {
"""
Returns an <code>IfNotExistsFunction</code> object which represents an <a href=
"http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html"
>if_not_exists(path, operand)</a> function call where path refers to that
of the current path operand; used for building expressions.
<pre>
"if_not_exists (path, operand) – If the item does not contain an attribute
at the specified path, then if_not_exists evaluates to operand; otherwise,
it evaluates to path. You can use this function to avoid overwriting an
attribute already present in the item."
</pre>
@param defaultValue
the default value that will be used as the operand to the
if_not_exists function call.
"""
return new IfNotExistsFunction<NS>(this, new LiteralOperand(
new LinkedHashSet<Number>(Arrays.asList(defaultValue))));
}
|
java
|
public IfNotExistsFunction<NS> ifNotExists(Number... defaultValue) {
return new IfNotExistsFunction<NS>(this, new LiteralOperand(
new LinkedHashSet<Number>(Arrays.asList(defaultValue))));
}
|
[
"public",
"IfNotExistsFunction",
"<",
"NS",
">",
"ifNotExists",
"(",
"Number",
"...",
"defaultValue",
")",
"{",
"return",
"new",
"IfNotExistsFunction",
"<",
"NS",
">",
"(",
"this",
",",
"new",
"LiteralOperand",
"(",
"new",
"LinkedHashSet",
"<",
"Number",
">",
"(",
"Arrays",
".",
"asList",
"(",
"defaultValue",
")",
")",
")",
")",
";",
"}"
] |
Returns an <code>IfNotExistsFunction</code> object which represents an <a href=
"http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html"
>if_not_exists(path, operand)</a> function call where path refers to that
of the current path operand; used for building expressions.
<pre>
"if_not_exists (path, operand) – If the item does not contain an attribute
at the specified path, then if_not_exists evaluates to operand; otherwise,
it evaluates to path. You can use this function to avoid overwriting an
attribute already present in the item."
</pre>
@param defaultValue
the default value that will be used as the operand to the
if_not_exists function call.
|
[
"Returns",
"an",
"<code",
">",
"IfNotExistsFunction<",
"/",
"code",
">",
"object",
"which",
"represents",
"an",
"<a",
"href",
"=",
"http",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"amazondynamodb",
"/",
"latest",
"/",
"developerguide",
"/",
"Expressions",
".",
"Modifying",
".",
"html",
">",
"if_not_exists",
"(",
"path",
"operand",
")",
"<",
"/",
"a",
">",
"function",
"call",
"where",
"path",
"refers",
"to",
"that",
"of",
"the",
"current",
"path",
"operand",
";",
"used",
"for",
"building",
"expressions",
"."
] |
train
|
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/xspec/NS.java#L174-L177
|
dbracewell/hermes
|
hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java
|
DocumentFactory.fromTokens
|
public Document fromTokens(@NonNull Language language, @NonNull String... tokens) {
"""
Creates a document from the given tokens. The language parameter controls how the content of the documents is
created. If the language has whitespace tokens are joined with a single space between them, otherwise no space is
inserted between tokens.
@param tokens the tokens making up the document
@param language the language of the document
@return the document with tokens provided.
"""
return fromTokens(Arrays.asList(tokens), language);
}
|
java
|
public Document fromTokens(@NonNull Language language, @NonNull String... tokens) {
return fromTokens(Arrays.asList(tokens), language);
}
|
[
"public",
"Document",
"fromTokens",
"(",
"@",
"NonNull",
"Language",
"language",
",",
"@",
"NonNull",
"String",
"...",
"tokens",
")",
"{",
"return",
"fromTokens",
"(",
"Arrays",
".",
"asList",
"(",
"tokens",
")",
",",
"language",
")",
";",
"}"
] |
Creates a document from the given tokens. The language parameter controls how the content of the documents is
created. If the language has whitespace tokens are joined with a single space between them, otherwise no space is
inserted between tokens.
@param tokens the tokens making up the document
@param language the language of the document
@return the document with tokens provided.
|
[
"Creates",
"a",
"document",
"from",
"the",
"given",
"tokens",
".",
"The",
"language",
"parameter",
"controls",
"how",
"the",
"content",
"of",
"the",
"documents",
"is",
"created",
".",
"If",
"the",
"language",
"has",
"whitespace",
"tokens",
"are",
"joined",
"with",
"a",
"single",
"space",
"between",
"them",
"otherwise",
"no",
"space",
"is",
"inserted",
"between",
"tokens",
"."
] |
train
|
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java#L244-L246
|
EdwardRaff/JSAT
|
JSAT/src/jsat/io/LIBSVMLoader.java
|
LIBSVMLoader.loadR
|
public static RegressionDataSet loadR(File file, double sparseRatio) throws FileNotFoundException, IOException {
"""
Loads a new regression data set from a LIBSVM file, assuming the label is
a numeric target value to predict
@param file the file to load
@param sparseRatio the fraction of non zero values to qualify a data
point as sparse
@return a regression data set
@throws FileNotFoundException if the file was not found
@throws IOException if an error occurred reading the input stream
"""
return loadR(file, sparseRatio, -1);
}
|
java
|
public static RegressionDataSet loadR(File file, double sparseRatio) throws FileNotFoundException, IOException
{
return loadR(file, sparseRatio, -1);
}
|
[
"public",
"static",
"RegressionDataSet",
"loadR",
"(",
"File",
"file",
",",
"double",
"sparseRatio",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"return",
"loadR",
"(",
"file",
",",
"sparseRatio",
",",
"-",
"1",
")",
";",
"}"
] |
Loads a new regression data set from a LIBSVM file, assuming the label is
a numeric target value to predict
@param file the file to load
@param sparseRatio the fraction of non zero values to qualify a data
point as sparse
@return a regression data set
@throws FileNotFoundException if the file was not found
@throws IOException if an error occurred reading the input stream
|
[
"Loads",
"a",
"new",
"regression",
"data",
"set",
"from",
"a",
"LIBSVM",
"file",
"assuming",
"the",
"label",
"is",
"a",
"numeric",
"target",
"value",
"to",
"predict"
] |
train
|
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/LIBSVMLoader.java#L79-L82
|
biouno/figshare-java-api
|
src/main/java/org/biouno/figshare/FigShareClient.java
|
FigShareClient.uploadFile
|
public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) {
"""
Upload a file to an article.
@param articleId article ID
@param file java.io.File file
@return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL
"""
HttpClient httpClient = null;
try {
final String method = String.format("my_data/articles/%d/files", articleId);
// create an HTTP request to a protected resource
final String url = getURL(endpoint, version, method);
// create an HTTP request to a protected resource
final HttpPut request = new HttpPut(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentBody body = new FileBody(file);
FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build();
builder.addPart(part);
HttpEntity entity = builder.build();
request.setEntity(entity);
// sign the request
consumer.sign(request);
// send the request
httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
String json = EntityUtils.toString(responseEntity);
org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json);
return uploadedFile;
} catch (OAuthCommunicationException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (OAuthMessageSignerException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (OAuthExpectationFailedException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (ClientProtocolException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (IOException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
}
}
|
java
|
public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) {
HttpClient httpClient = null;
try {
final String method = String.format("my_data/articles/%d/files", articleId);
// create an HTTP request to a protected resource
final String url = getURL(endpoint, version, method);
// create an HTTP request to a protected resource
final HttpPut request = new HttpPut(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentBody body = new FileBody(file);
FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build();
builder.addPart(part);
HttpEntity entity = builder.build();
request.setEntity(entity);
// sign the request
consumer.sign(request);
// send the request
httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
String json = EntityUtils.toString(responseEntity);
org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json);
return uploadedFile;
} catch (OAuthCommunicationException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (OAuthMessageSignerException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (OAuthExpectationFailedException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (ClientProtocolException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
} catch (IOException e) {
throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
}
}
|
[
"public",
"org",
".",
"biouno",
".",
"figshare",
".",
"v1",
".",
"model",
".",
"File",
"uploadFile",
"(",
"long",
"articleId",
",",
"File",
"file",
")",
"{",
"HttpClient",
"httpClient",
"=",
"null",
";",
"try",
"{",
"final",
"String",
"method",
"=",
"String",
".",
"format",
"(",
"\"my_data/articles/%d/files\"",
",",
"articleId",
")",
";",
"// create an HTTP request to a protected resource",
"final",
"String",
"url",
"=",
"getURL",
"(",
"endpoint",
",",
"version",
",",
"method",
")",
";",
"// create an HTTP request to a protected resource",
"final",
"HttpPut",
"request",
"=",
"new",
"HttpPut",
"(",
"url",
")",
";",
"MultipartEntityBuilder",
"builder",
"=",
"MultipartEntityBuilder",
".",
"create",
"(",
")",
";",
"ContentBody",
"body",
"=",
"new",
"FileBody",
"(",
"file",
")",
";",
"FormBodyPart",
"part",
"=",
"FormBodyPartBuilder",
".",
"create",
"(",
"\"filedata\"",
",",
"body",
")",
".",
"build",
"(",
")",
";",
"builder",
".",
"addPart",
"(",
"part",
")",
";",
"HttpEntity",
"entity",
"=",
"builder",
".",
"build",
"(",
")",
";",
"request",
".",
"setEntity",
"(",
"entity",
")",
";",
"// sign the request",
"consumer",
".",
"sign",
"(",
"request",
")",
";",
"// send the request",
"httpClient",
"=",
"HttpClientBuilder",
".",
"create",
"(",
")",
".",
"build",
"(",
")",
";",
"HttpResponse",
"response",
"=",
"httpClient",
".",
"execute",
"(",
"request",
")",
";",
"HttpEntity",
"responseEntity",
"=",
"response",
".",
"getEntity",
"(",
")",
";",
"String",
"json",
"=",
"EntityUtils",
".",
"toString",
"(",
"responseEntity",
")",
";",
"org",
".",
"biouno",
".",
"figshare",
".",
"v1",
".",
"model",
".",
"File",
"uploadedFile",
"=",
"readFileFromJson",
"(",
"json",
")",
";",
"return",
"uploadedFile",
";",
"}",
"catch",
"(",
"OAuthCommunicationException",
"e",
")",
"{",
"throw",
"new",
"FigShareClientException",
"(",
"\"Failed to get articles: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"OAuthMessageSignerException",
"e",
")",
"{",
"throw",
"new",
"FigShareClientException",
"(",
"\"Failed to get articles: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"OAuthExpectationFailedException",
"e",
")",
"{",
"throw",
"new",
"FigShareClientException",
"(",
"\"Failed to get articles: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"ClientProtocolException",
"e",
")",
"{",
"throw",
"new",
"FigShareClientException",
"(",
"\"Failed to get articles: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"FigShareClientException",
"(",
"\"Failed to get articles: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] |
Upload a file to an article.
@param articleId article ID
@param file java.io.File file
@return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL
|
[
"Upload",
"a",
"file",
"to",
"an",
"article",
"."
] |
train
|
https://github.com/biouno/figshare-java-api/blob/6d447764efe8fa4329d15e339a8601351aade93c/src/main/java/org/biouno/figshare/FigShareClient.java#L286-L324
|
google/closure-compiler
|
src/com/google/javascript/jscomp/TypedCodeGenerator.java
|
TypedCodeGenerator.appendClassAnnotations
|
private void appendClassAnnotations(StringBuilder sb, FunctionType funType) {
"""
we should print it first, like users write it. Same for @interface and @record.
"""
FunctionType superConstructor = funType.getInstanceType().getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance = superConstructor.getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * ");
appendAnnotation(sb, "extends", superInstance.toAnnotationString(Nullability.IMPLICIT));
sb.append("\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = new TreeSet<>();
for (ObjectType interfaze : funType.getAncestorInterfaces()) {
interfaces.add(interfaze.toAnnotationString(Nullability.IMPLICIT));
}
for (String interfaze : interfaces) {
sb.append(" * ");
appendAnnotation(sb, "implements", interfaze);
sb.append("\n");
}
}
|
java
|
private void appendClassAnnotations(StringBuilder sb, FunctionType funType) {
FunctionType superConstructor = funType.getInstanceType().getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance = superConstructor.getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * ");
appendAnnotation(sb, "extends", superInstance.toAnnotationString(Nullability.IMPLICIT));
sb.append("\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = new TreeSet<>();
for (ObjectType interfaze : funType.getAncestorInterfaces()) {
interfaces.add(interfaze.toAnnotationString(Nullability.IMPLICIT));
}
for (String interfaze : interfaces) {
sb.append(" * ");
appendAnnotation(sb, "implements", interfaze);
sb.append("\n");
}
}
|
[
"private",
"void",
"appendClassAnnotations",
"(",
"StringBuilder",
"sb",
",",
"FunctionType",
"funType",
")",
"{",
"FunctionType",
"superConstructor",
"=",
"funType",
".",
"getInstanceType",
"(",
")",
".",
"getSuperClassConstructor",
"(",
")",
";",
"if",
"(",
"superConstructor",
"!=",
"null",
")",
"{",
"ObjectType",
"superInstance",
"=",
"superConstructor",
".",
"getInstanceType",
"(",
")",
";",
"if",
"(",
"!",
"superInstance",
".",
"toString",
"(",
")",
".",
"equals",
"(",
"\"Object\"",
")",
")",
"{",
"sb",
".",
"append",
"(",
"\" * \"",
")",
";",
"appendAnnotation",
"(",
"sb",
",",
"\"extends\"",
",",
"superInstance",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"IMPLICIT",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}",
"// Avoid duplicates, add implemented type to a set first",
"Set",
"<",
"String",
">",
"interfaces",
"=",
"new",
"TreeSet",
"<>",
"(",
")",
";",
"for",
"(",
"ObjectType",
"interfaze",
":",
"funType",
".",
"getAncestorInterfaces",
"(",
")",
")",
"{",
"interfaces",
".",
"add",
"(",
"interfaze",
".",
"toAnnotationString",
"(",
"Nullability",
".",
"IMPLICIT",
")",
")",
";",
"}",
"for",
"(",
"String",
"interfaze",
":",
"interfaces",
")",
"{",
"sb",
".",
"append",
"(",
"\" * \"",
")",
";",
"appendAnnotation",
"(",
"sb",
",",
"\"implements\"",
",",
"interfaze",
")",
";",
"sb",
".",
"append",
"(",
"\"\\n\"",
")",
";",
"}",
"}"
] |
we should print it first, like users write it. Same for @interface and @record.
|
[
"we",
"should",
"print",
"it",
"first",
"like",
"users",
"write",
"it",
".",
"Same",
"for"
] |
train
|
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedCodeGenerator.java#L342-L362
|
alkacon/opencms-core
|
src/org/opencms/ugc/CmsUgcSession.java
|
CmsUgcSession.addContentValues
|
protected CmsXmlContent addContentValues(CmsFile file, Map<String, String> contentValues) throws CmsException {
"""
Adds the given values to the content document.<p>
@param file the content file
@param contentValues the values to add
@return the content document
@throws CmsException if writing the XML fails
"""
CmsXmlContent content = unmarshalXmlContent(file);
Locale locale = m_cms.getRequestContext().getLocale();
addContentValues(content, locale, contentValues);
return content;
}
|
java
|
protected CmsXmlContent addContentValues(CmsFile file, Map<String, String> contentValues) throws CmsException {
CmsXmlContent content = unmarshalXmlContent(file);
Locale locale = m_cms.getRequestContext().getLocale();
addContentValues(content, locale, contentValues);
return content;
}
|
[
"protected",
"CmsXmlContent",
"addContentValues",
"(",
"CmsFile",
"file",
",",
"Map",
"<",
"String",
",",
"String",
">",
"contentValues",
")",
"throws",
"CmsException",
"{",
"CmsXmlContent",
"content",
"=",
"unmarshalXmlContent",
"(",
"file",
")",
";",
"Locale",
"locale",
"=",
"m_cms",
".",
"getRequestContext",
"(",
")",
".",
"getLocale",
"(",
")",
";",
"addContentValues",
"(",
"content",
",",
"locale",
",",
"contentValues",
")",
";",
"return",
"content",
";",
"}"
] |
Adds the given values to the content document.<p>
@param file the content file
@param contentValues the values to add
@return the content document
@throws CmsException if writing the XML fails
|
[
"Adds",
"the",
"given",
"values",
"to",
"the",
"content",
"document",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSession.java#L579-L586
|
baidubce/bce-sdk-java
|
src/main/java/com/baidubce/services/dcc/DccClient.java
|
DccClient.listDedicatedHosts
|
public ListDedicatedHostsResponse listDedicatedHosts(ListDedicatedHostsRequest request) {
"""
get a list of hosts owned by the authenticated user and specified conditions
@param request The request containing all options for query
@return
"""
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, null);
if (!Strings.isNullOrEmpty(request.getMarker())) {
internalRequest.addParameter("marker", request.getMarker());
}
if (request.getMaxKeys() >= 0) {
internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys()));
}
if (!Strings.isNullOrEmpty(request.getZoneName())) {
internalRequest.addParameter("zoneName", request.getZoneName());
}
return invokeHttpClient(internalRequest, ListDedicatedHostsResponse.class);
}
|
java
|
public ListDedicatedHostsResponse listDedicatedHosts(ListDedicatedHostsRequest request) {
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, null);
if (!Strings.isNullOrEmpty(request.getMarker())) {
internalRequest.addParameter("marker", request.getMarker());
}
if (request.getMaxKeys() >= 0) {
internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys()));
}
if (!Strings.isNullOrEmpty(request.getZoneName())) {
internalRequest.addParameter("zoneName", request.getZoneName());
}
return invokeHttpClient(internalRequest, ListDedicatedHostsResponse.class);
}
|
[
"public",
"ListDedicatedHostsResponse",
"listDedicatedHosts",
"(",
"ListDedicatedHostsRequest",
"request",
")",
"{",
"InternalRequest",
"internalRequest",
"=",
"this",
".",
"createRequest",
"(",
"request",
",",
"HttpMethodName",
".",
"GET",
",",
"null",
")",
";",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"request",
".",
"getMarker",
"(",
")",
")",
")",
"{",
"internalRequest",
".",
"addParameter",
"(",
"\"marker\"",
",",
"request",
".",
"getMarker",
"(",
")",
")",
";",
"}",
"if",
"(",
"request",
".",
"getMaxKeys",
"(",
")",
">=",
"0",
")",
"{",
"internalRequest",
".",
"addParameter",
"(",
"\"maxKeys\"",
",",
"String",
".",
"valueOf",
"(",
"request",
".",
"getMaxKeys",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"request",
".",
"getZoneName",
"(",
")",
")",
")",
"{",
"internalRequest",
".",
"addParameter",
"(",
"\"zoneName\"",
",",
"request",
".",
"getZoneName",
"(",
")",
")",
";",
"}",
"return",
"invokeHttpClient",
"(",
"internalRequest",
",",
"ListDedicatedHostsResponse",
".",
"class",
")",
";",
"}"
] |
get a list of hosts owned by the authenticated user and specified conditions
@param request The request containing all options for query
@return
|
[
"get",
"a",
"list",
"of",
"hosts",
"owned",
"by",
"the",
"authenticated",
"user",
"and",
"specified",
"conditions"
] |
train
|
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/dcc/DccClient.java#L107-L119
|
apache/incubator-gobblin
|
gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java
|
JobScheduler.scheduleJob
|
public void scheduleJob(Properties jobProps, JobListener jobListener, Map<String, Object> additionalJobData,
Class<? extends Job> jobClass)
throws JobException {
"""
Schedule a job.
<p>
This method does what {@link #scheduleJob(Properties, JobListener)} does, and additionally it
allows the caller to pass in additional job data and the {@link Job} implementation class.
</p>
@param jobProps Job configuration properties
@param jobListener {@link JobListener} used for callback,
can be <em>null</em> if no callback is needed.
@param additionalJobData additional job data in a {@link Map}
@param jobClass Quartz job class
@throws JobException when there is anything wrong
with scheduling the job
"""
Preconditions.checkArgument(jobProps.containsKey(ConfigurationKeys.JOB_NAME_KEY),
"A job must have a job name specified by job.name");
String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY);
if (this.scheduledJobs.containsKey(jobName)) {
LOG.info("Job " + jobName + " was already scheduled, un-scheduling it now.");
unscheduleJob(jobName);
}
// Check if the job has been disabled
boolean disabled = Boolean.valueOf(jobProps.getProperty(ConfigurationKeys.JOB_DISABLED_KEY, "false"));
if (disabled) {
LOG.info("Skipping disabled job " + jobName);
return;
}
if (!jobProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) {
// Submit the job to run
this.jobExecutor.execute(new NonScheduledJobRunner(jobProps, jobListener));
return;
}
if (jobListener != null) {
this.jobListenerMap.put(jobName, jobListener);
}
// Build a data map that gets passed to the job
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(JOB_SCHEDULER_KEY, this);
jobDataMap.put(PROPERTIES_KEY, jobProps);
jobDataMap.put(JOB_LISTENER_KEY, jobListener);
jobDataMap.putAll(additionalJobData);
// Build a Quartz job
JobDetail job = JobBuilder.newJob(jobClass)
.withIdentity(jobName, Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY)))
.withDescription(Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_DESCRIPTION_KEY)))
.usingJobData(jobDataMap)
.build();
try {
// Schedule the Quartz job with a trigger built from the job configuration
Trigger trigger = getTrigger(job.getKey(), jobProps);
this.scheduler.getScheduler().scheduleJob(job, trigger);
LOG.info(String.format("Scheduled job %s. Next run: %s.", job.getKey(), trigger.getNextFireTime()));
} catch (SchedulerException se) {
LOG.error("Failed to schedule job " + jobName, se);
throw new JobException("Failed to schedule job " + jobName, se);
}
this.scheduledJobs.put(jobName, job.getKey());
}
|
java
|
public void scheduleJob(Properties jobProps, JobListener jobListener, Map<String, Object> additionalJobData,
Class<? extends Job> jobClass)
throws JobException {
Preconditions.checkArgument(jobProps.containsKey(ConfigurationKeys.JOB_NAME_KEY),
"A job must have a job name specified by job.name");
String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY);
if (this.scheduledJobs.containsKey(jobName)) {
LOG.info("Job " + jobName + " was already scheduled, un-scheduling it now.");
unscheduleJob(jobName);
}
// Check if the job has been disabled
boolean disabled = Boolean.valueOf(jobProps.getProperty(ConfigurationKeys.JOB_DISABLED_KEY, "false"));
if (disabled) {
LOG.info("Skipping disabled job " + jobName);
return;
}
if (!jobProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) {
// Submit the job to run
this.jobExecutor.execute(new NonScheduledJobRunner(jobProps, jobListener));
return;
}
if (jobListener != null) {
this.jobListenerMap.put(jobName, jobListener);
}
// Build a data map that gets passed to the job
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(JOB_SCHEDULER_KEY, this);
jobDataMap.put(PROPERTIES_KEY, jobProps);
jobDataMap.put(JOB_LISTENER_KEY, jobListener);
jobDataMap.putAll(additionalJobData);
// Build a Quartz job
JobDetail job = JobBuilder.newJob(jobClass)
.withIdentity(jobName, Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY)))
.withDescription(Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_DESCRIPTION_KEY)))
.usingJobData(jobDataMap)
.build();
try {
// Schedule the Quartz job with a trigger built from the job configuration
Trigger trigger = getTrigger(job.getKey(), jobProps);
this.scheduler.getScheduler().scheduleJob(job, trigger);
LOG.info(String.format("Scheduled job %s. Next run: %s.", job.getKey(), trigger.getNextFireTime()));
} catch (SchedulerException se) {
LOG.error("Failed to schedule job " + jobName, se);
throw new JobException("Failed to schedule job " + jobName, se);
}
this.scheduledJobs.put(jobName, job.getKey());
}
|
[
"public",
"void",
"scheduleJob",
"(",
"Properties",
"jobProps",
",",
"JobListener",
"jobListener",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"additionalJobData",
",",
"Class",
"<",
"?",
"extends",
"Job",
">",
"jobClass",
")",
"throws",
"JobException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"jobProps",
".",
"containsKey",
"(",
"ConfigurationKeys",
".",
"JOB_NAME_KEY",
")",
",",
"\"A job must have a job name specified by job.name\"",
")",
";",
"String",
"jobName",
"=",
"jobProps",
".",
"getProperty",
"(",
"ConfigurationKeys",
".",
"JOB_NAME_KEY",
")",
";",
"if",
"(",
"this",
".",
"scheduledJobs",
".",
"containsKey",
"(",
"jobName",
")",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Job \"",
"+",
"jobName",
"+",
"\" was already scheduled, un-scheduling it now.\"",
")",
";",
"unscheduleJob",
"(",
"jobName",
")",
";",
"}",
"// Check if the job has been disabled",
"boolean",
"disabled",
"=",
"Boolean",
".",
"valueOf",
"(",
"jobProps",
".",
"getProperty",
"(",
"ConfigurationKeys",
".",
"JOB_DISABLED_KEY",
",",
"\"false\"",
")",
")",
";",
"if",
"(",
"disabled",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Skipping disabled job \"",
"+",
"jobName",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"jobProps",
".",
"containsKey",
"(",
"ConfigurationKeys",
".",
"JOB_SCHEDULE_KEY",
")",
")",
"{",
"// Submit the job to run",
"this",
".",
"jobExecutor",
".",
"execute",
"(",
"new",
"NonScheduledJobRunner",
"(",
"jobProps",
",",
"jobListener",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"jobListener",
"!=",
"null",
")",
"{",
"this",
".",
"jobListenerMap",
".",
"put",
"(",
"jobName",
",",
"jobListener",
")",
";",
"}",
"// Build a data map that gets passed to the job",
"JobDataMap",
"jobDataMap",
"=",
"new",
"JobDataMap",
"(",
")",
";",
"jobDataMap",
".",
"put",
"(",
"JOB_SCHEDULER_KEY",
",",
"this",
")",
";",
"jobDataMap",
".",
"put",
"(",
"PROPERTIES_KEY",
",",
"jobProps",
")",
";",
"jobDataMap",
".",
"put",
"(",
"JOB_LISTENER_KEY",
",",
"jobListener",
")",
";",
"jobDataMap",
".",
"putAll",
"(",
"additionalJobData",
")",
";",
"// Build a Quartz job",
"JobDetail",
"job",
"=",
"JobBuilder",
".",
"newJob",
"(",
"jobClass",
")",
".",
"withIdentity",
"(",
"jobName",
",",
"Strings",
".",
"nullToEmpty",
"(",
"jobProps",
".",
"getProperty",
"(",
"ConfigurationKeys",
".",
"JOB_GROUP_KEY",
")",
")",
")",
".",
"withDescription",
"(",
"Strings",
".",
"nullToEmpty",
"(",
"jobProps",
".",
"getProperty",
"(",
"ConfigurationKeys",
".",
"JOB_DESCRIPTION_KEY",
")",
")",
")",
".",
"usingJobData",
"(",
"jobDataMap",
")",
".",
"build",
"(",
")",
";",
"try",
"{",
"// Schedule the Quartz job with a trigger built from the job configuration",
"Trigger",
"trigger",
"=",
"getTrigger",
"(",
"job",
".",
"getKey",
"(",
")",
",",
"jobProps",
")",
";",
"this",
".",
"scheduler",
".",
"getScheduler",
"(",
")",
".",
"scheduleJob",
"(",
"job",
",",
"trigger",
")",
";",
"LOG",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Scheduled job %s. Next run: %s.\"",
",",
"job",
".",
"getKey",
"(",
")",
",",
"trigger",
".",
"getNextFireTime",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"SchedulerException",
"se",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Failed to schedule job \"",
"+",
"jobName",
",",
"se",
")",
";",
"throw",
"new",
"JobException",
"(",
"\"Failed to schedule job \"",
"+",
"jobName",
",",
"se",
")",
";",
"}",
"this",
".",
"scheduledJobs",
".",
"put",
"(",
"jobName",
",",
"job",
".",
"getKey",
"(",
")",
")",
";",
"}"
] |
Schedule a job.
<p>
This method does what {@link #scheduleJob(Properties, JobListener)} does, and additionally it
allows the caller to pass in additional job data and the {@link Job} implementation class.
</p>
@param jobProps Job configuration properties
@param jobListener {@link JobListener} used for callback,
can be <em>null</em> if no callback is needed.
@param additionalJobData additional job data in a {@link Map}
@param jobClass Quartz job class
@throws JobException when there is anything wrong
with scheduling the job
|
[
"Schedule",
"a",
"job",
"."
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java#L346-L400
|
mnlipp/jgrapes
|
org.jgrapes.http.freemarker/src/org/jgrapes/http/freemarker/FreeMarkerRequestHandler.java
|
FreeMarkerRequestHandler.sendProcessedTemplate
|
protected boolean sendProcessedTemplate(
Request.In event, IOSubchannel channel, String path) {
"""
Render a response using the template obtained from the config with
{@link Configuration#getTemplate(String)} and the given path.
@param event
the event
@param channel
the channel
@param path
the path
"""
try {
// Get template (no need to continue if this fails).
Template tpl = freemarkerConfig().getTemplate(path);
return sendProcessedTemplate(event, channel, tpl);
} catch (IOException e) {
fire(new Error(event, e), channel);
return false;
}
}
|
java
|
protected boolean sendProcessedTemplate(
Request.In event, IOSubchannel channel, String path) {
try {
// Get template (no need to continue if this fails).
Template tpl = freemarkerConfig().getTemplate(path);
return sendProcessedTemplate(event, channel, tpl);
} catch (IOException e) {
fire(new Error(event, e), channel);
return false;
}
}
|
[
"protected",
"boolean",
"sendProcessedTemplate",
"(",
"Request",
".",
"In",
"event",
",",
"IOSubchannel",
"channel",
",",
"String",
"path",
")",
"{",
"try",
"{",
"// Get template (no need to continue if this fails).",
"Template",
"tpl",
"=",
"freemarkerConfig",
"(",
")",
".",
"getTemplate",
"(",
"path",
")",
";",
"return",
"sendProcessedTemplate",
"(",
"event",
",",
"channel",
",",
"tpl",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"fire",
"(",
"new",
"Error",
"(",
"event",
",",
"e",
")",
",",
"channel",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Render a response using the template obtained from the config with
{@link Configuration#getTemplate(String)} and the given path.
@param event
the event
@param channel
the channel
@param path
the path
|
[
"Render",
"a",
"response",
"using",
"the",
"template",
"obtained",
"from",
"the",
"config",
"with",
"{",
"@link",
"Configuration#getTemplate",
"(",
"String",
")",
"}",
"and",
"the",
"given",
"path",
"."
] |
train
|
https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http.freemarker/src/org/jgrapes/http/freemarker/FreeMarkerRequestHandler.java#L285-L295
|
looly/hutool
|
hutool-cron/src/main/java/cn/hutool/cron/TaskTable.java
|
TaskTable.add
|
public TaskTable add(String id, CronPattern pattern, Task task) {
"""
新增Task
@param id ID
@param pattern {@link CronPattern}
@param task {@link Task}
@return this
"""
final Lock writeLock = lock.writeLock();
try {
writeLock.lock();
if (ids.contains(id)) {
throw new CronException("Id [{}] has been existed!", id);
}
ids.add(id);
patterns.add(pattern);
tasks.add(task);
size++;
} finally {
writeLock.unlock();
}
return this;
}
|
java
|
public TaskTable add(String id, CronPattern pattern, Task task) {
final Lock writeLock = lock.writeLock();
try {
writeLock.lock();
if (ids.contains(id)) {
throw new CronException("Id [{}] has been existed!", id);
}
ids.add(id);
patterns.add(pattern);
tasks.add(task);
size++;
} finally {
writeLock.unlock();
}
return this;
}
|
[
"public",
"TaskTable",
"add",
"(",
"String",
"id",
",",
"CronPattern",
"pattern",
",",
"Task",
"task",
")",
"{",
"final",
"Lock",
"writeLock",
"=",
"lock",
".",
"writeLock",
"(",
")",
";",
"try",
"{",
"writeLock",
".",
"lock",
"(",
")",
";",
"if",
"(",
"ids",
".",
"contains",
"(",
"id",
")",
")",
"{",
"throw",
"new",
"CronException",
"(",
"\"Id [{}] has been existed!\"",
",",
"id",
")",
";",
"}",
"ids",
".",
"add",
"(",
"id",
")",
";",
"patterns",
".",
"add",
"(",
"pattern",
")",
";",
"tasks",
".",
"add",
"(",
"task",
")",
";",
"size",
"++",
";",
"}",
"finally",
"{",
"writeLock",
".",
"unlock",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
新增Task
@param id ID
@param pattern {@link CronPattern}
@param task {@link Task}
@return this
|
[
"新增Task"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-cron/src/main/java/cn/hutool/cron/TaskTable.java#L50-L65
|
Comcast/jrugged
|
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/CircuitBreakerBeanFactory.java
|
CircuitBreakerBeanFactory.createCircuitBreaker
|
public synchronized CircuitBreaker createCircuitBreaker(String name, CircuitBreakerConfig config) {
"""
Create a new {@link CircuitBreakerBean} and map it to the provided value.
If the {@link MBeanExportOperations} is set, then the CircuitBreakerBean will be
exported as a JMX MBean.
If the CircuitBreaker already exists, then the existing instance is
returned.
@param name the value for the {@link org.fishwife.jrugged.CircuitBreaker}
@param config the {@link org.fishwife.jrugged.CircuitBreakerConfig}
"""
CircuitBreaker circuitBreaker = findCircuitBreaker(name);
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerBean(name);
configureCircuitBreaker(name, circuitBreaker, config);
if (mBeanExportOperations != null) {
ObjectName objectName;
try {
objectName = new ObjectName("org.fishwife.jrugged.spring:type=CircuitBreakerBean," + "name=" + name);
} catch (MalformedObjectNameException e) {
throw new IllegalArgumentException("Invalid MBean Name " + name, e);
}
mBeanExportOperations.registerManagedResource(circuitBreaker, objectName);
}
addCircuitBreakerToMap(name, circuitBreaker);
}
return circuitBreaker;
}
|
java
|
public synchronized CircuitBreaker createCircuitBreaker(String name, CircuitBreakerConfig config) {
CircuitBreaker circuitBreaker = findCircuitBreaker(name);
if (circuitBreaker == null) {
circuitBreaker = new CircuitBreakerBean(name);
configureCircuitBreaker(name, circuitBreaker, config);
if (mBeanExportOperations != null) {
ObjectName objectName;
try {
objectName = new ObjectName("org.fishwife.jrugged.spring:type=CircuitBreakerBean," + "name=" + name);
} catch (MalformedObjectNameException e) {
throw new IllegalArgumentException("Invalid MBean Name " + name, e);
}
mBeanExportOperations.registerManagedResource(circuitBreaker, objectName);
}
addCircuitBreakerToMap(name, circuitBreaker);
}
return circuitBreaker;
}
|
[
"public",
"synchronized",
"CircuitBreaker",
"createCircuitBreaker",
"(",
"String",
"name",
",",
"CircuitBreakerConfig",
"config",
")",
"{",
"CircuitBreaker",
"circuitBreaker",
"=",
"findCircuitBreaker",
"(",
"name",
")",
";",
"if",
"(",
"circuitBreaker",
"==",
"null",
")",
"{",
"circuitBreaker",
"=",
"new",
"CircuitBreakerBean",
"(",
"name",
")",
";",
"configureCircuitBreaker",
"(",
"name",
",",
"circuitBreaker",
",",
"config",
")",
";",
"if",
"(",
"mBeanExportOperations",
"!=",
"null",
")",
"{",
"ObjectName",
"objectName",
";",
"try",
"{",
"objectName",
"=",
"new",
"ObjectName",
"(",
"\"org.fishwife.jrugged.spring:type=CircuitBreakerBean,\"",
"+",
"\"name=\"",
"+",
"name",
")",
";",
"}",
"catch",
"(",
"MalformedObjectNameException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid MBean Name \"",
"+",
"name",
",",
"e",
")",
";",
"}",
"mBeanExportOperations",
".",
"registerManagedResource",
"(",
"circuitBreaker",
",",
"objectName",
")",
";",
"}",
"addCircuitBreakerToMap",
"(",
"name",
",",
"circuitBreaker",
")",
";",
"}",
"return",
"circuitBreaker",
";",
"}"
] |
Create a new {@link CircuitBreakerBean} and map it to the provided value.
If the {@link MBeanExportOperations} is set, then the CircuitBreakerBean will be
exported as a JMX MBean.
If the CircuitBreaker already exists, then the existing instance is
returned.
@param name the value for the {@link org.fishwife.jrugged.CircuitBreaker}
@param config the {@link org.fishwife.jrugged.CircuitBreakerConfig}
|
[
"Create",
"a",
"new",
"{"
] |
train
|
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/CircuitBreakerBeanFactory.java#L107-L133
|
assertthat/selenium-shutterbug
|
src/main/java/com/assertthat/selenium_shutterbug/core/Snapshot.java
|
Snapshot.withCroppedThumbnail
|
public T withCroppedThumbnail(String path, String name, double scale, double cropWidth, double cropHeight) {
"""
Generate cropped thumbnail of the original screenshot.
Will save different thumbnails depends on when it was called in the chain.
@param path to save thumbnail image to
@param name of the resulting image
@param scale to apply
@param cropWidth e.g. 0.2 will leave 20% of the initial width
@param cropHeight e.g. 0.1 will leave 10% of the initial width
@return instance of type Snapshot
"""
File thumbnailFile = new File(path.toString(), name);
if(!Files.exists(Paths.get(path))) {
thumbnailFile.mkdirs();
}
thumbnailImage=ImageProcessor.cropAndScale(image,scale, cropWidth, cropHeight);
FileUtil.writeImage(thumbnailImage, EXTENSION, thumbnailFile);
return self();
}
|
java
|
public T withCroppedThumbnail(String path, String name, double scale, double cropWidth, double cropHeight) {
File thumbnailFile = new File(path.toString(), name);
if(!Files.exists(Paths.get(path))) {
thumbnailFile.mkdirs();
}
thumbnailImage=ImageProcessor.cropAndScale(image,scale, cropWidth, cropHeight);
FileUtil.writeImage(thumbnailImage, EXTENSION, thumbnailFile);
return self();
}
|
[
"public",
"T",
"withCroppedThumbnail",
"(",
"String",
"path",
",",
"String",
"name",
",",
"double",
"scale",
",",
"double",
"cropWidth",
",",
"double",
"cropHeight",
")",
"{",
"File",
"thumbnailFile",
"=",
"new",
"File",
"(",
"path",
".",
"toString",
"(",
")",
",",
"name",
")",
";",
"if",
"(",
"!",
"Files",
".",
"exists",
"(",
"Paths",
".",
"get",
"(",
"path",
")",
")",
")",
"{",
"thumbnailFile",
".",
"mkdirs",
"(",
")",
";",
"}",
"thumbnailImage",
"=",
"ImageProcessor",
".",
"cropAndScale",
"(",
"image",
",",
"scale",
",",
"cropWidth",
",",
"cropHeight",
")",
";",
"FileUtil",
".",
"writeImage",
"(",
"thumbnailImage",
",",
"EXTENSION",
",",
"thumbnailFile",
")",
";",
"return",
"self",
"(",
")",
";",
"}"
] |
Generate cropped thumbnail of the original screenshot.
Will save different thumbnails depends on when it was called in the chain.
@param path to save thumbnail image to
@param name of the resulting image
@param scale to apply
@param cropWidth e.g. 0.2 will leave 20% of the initial width
@param cropHeight e.g. 0.1 will leave 10% of the initial width
@return instance of type Snapshot
|
[
"Generate",
"cropped",
"thumbnail",
"of",
"the",
"original",
"screenshot",
".",
"Will",
"save",
"different",
"thumbnails",
"depends",
"on",
"when",
"it",
"was",
"called",
"in",
"the",
"chain",
"."
] |
train
|
https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/Snapshot.java#L92-L100
|
elki-project/elki
|
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPNormDistanceFunction.java
|
LPNormDistanceFunction.preNormMBR
|
private double preNormMBR(SpatialComparable mbr, final int start, final int end) {
"""
Compute unscaled norm in a range of dimensions.
@param mbr Data object
@param start First dimension
@param end Exclusive last dimension
@return Aggregated values.
"""
double agg = 0.;
for(int d = start; d < end; d++) {
double delta = mbr.getMin(d);
delta = delta >= 0 ? delta : -mbr.getMax(d);
if(delta > 0.) {
agg += FastMath.pow(delta, p);
}
}
return agg;
}
|
java
|
private double preNormMBR(SpatialComparable mbr, final int start, final int end) {
double agg = 0.;
for(int d = start; d < end; d++) {
double delta = mbr.getMin(d);
delta = delta >= 0 ? delta : -mbr.getMax(d);
if(delta > 0.) {
agg += FastMath.pow(delta, p);
}
}
return agg;
}
|
[
"private",
"double",
"preNormMBR",
"(",
"SpatialComparable",
"mbr",
",",
"final",
"int",
"start",
",",
"final",
"int",
"end",
")",
"{",
"double",
"agg",
"=",
"0.",
";",
"for",
"(",
"int",
"d",
"=",
"start",
";",
"d",
"<",
"end",
";",
"d",
"++",
")",
"{",
"double",
"delta",
"=",
"mbr",
".",
"getMin",
"(",
"d",
")",
";",
"delta",
"=",
"delta",
">=",
"0",
"?",
"delta",
":",
"-",
"mbr",
".",
"getMax",
"(",
"d",
")",
";",
"if",
"(",
"delta",
">",
"0.",
")",
"{",
"agg",
"+=",
"FastMath",
".",
"pow",
"(",
"delta",
",",
"p",
")",
";",
"}",
"}",
"return",
"agg",
";",
"}"
] |
Compute unscaled norm in a range of dimensions.
@param mbr Data object
@param start First dimension
@param end Exclusive last dimension
@return Aggregated values.
|
[
"Compute",
"unscaled",
"norm",
"in",
"a",
"range",
"of",
"dimensions",
"."
] |
train
|
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/minkowski/LPNormDistanceFunction.java#L162-L172
|
google/error-prone-javac
|
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
|
HtmlTree.TR
|
public static HtmlTree TR(Content body) {
"""
Generates a TR tag for an HTML table with some content.
@param body content for the tag
@return an HtmlTree object for the TR tag
"""
HtmlTree htmltree = new HtmlTree(HtmlTag.TR, nullCheck(body));
return htmltree;
}
|
java
|
public static HtmlTree TR(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TR, nullCheck(body));
return htmltree;
}
|
[
"public",
"static",
"HtmlTree",
"TR",
"(",
"Content",
"body",
")",
"{",
"HtmlTree",
"htmltree",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"TR",
",",
"nullCheck",
"(",
"body",
")",
")",
";",
"return",
"htmltree",
";",
"}"
] |
Generates a TR tag for an HTML table with some content.
@param body content for the tag
@return an HtmlTree object for the TR tag
|
[
"Generates",
"a",
"TR",
"tag",
"for",
"an",
"HTML",
"table",
"with",
"some",
"content",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L853-L856
|
apache/flink
|
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java
|
SqlDateTimeUtils.dateFormat
|
public static String dateFormat(String dateStr, String fromFormat, String toFormat, TimeZone tz) {
"""
Format a string datetime as specific.
@param dateStr the string datetime.
@param fromFormat the original date format.
@param toFormat the target date format.
@param tz the time zone.
"""
SimpleDateFormat fromFormatter = FORMATTER_CACHE.get(fromFormat);
fromFormatter.setTimeZone(tz);
SimpleDateFormat toFormatter = FORMATTER_CACHE.get(toFormat);
toFormatter.setTimeZone(tz);
try {
return toFormatter.format(fromFormatter.parse(dateStr));
} catch (ParseException e) {
LOG.error("Exception when formatting: '" + dateStr +
"' from: '" + fromFormat + "' to: '" + toFormat + "'", e);
return null;
}
}
|
java
|
public static String dateFormat(String dateStr, String fromFormat, String toFormat, TimeZone tz) {
SimpleDateFormat fromFormatter = FORMATTER_CACHE.get(fromFormat);
fromFormatter.setTimeZone(tz);
SimpleDateFormat toFormatter = FORMATTER_CACHE.get(toFormat);
toFormatter.setTimeZone(tz);
try {
return toFormatter.format(fromFormatter.parse(dateStr));
} catch (ParseException e) {
LOG.error("Exception when formatting: '" + dateStr +
"' from: '" + fromFormat + "' to: '" + toFormat + "'", e);
return null;
}
}
|
[
"public",
"static",
"String",
"dateFormat",
"(",
"String",
"dateStr",
",",
"String",
"fromFormat",
",",
"String",
"toFormat",
",",
"TimeZone",
"tz",
")",
"{",
"SimpleDateFormat",
"fromFormatter",
"=",
"FORMATTER_CACHE",
".",
"get",
"(",
"fromFormat",
")",
";",
"fromFormatter",
".",
"setTimeZone",
"(",
"tz",
")",
";",
"SimpleDateFormat",
"toFormatter",
"=",
"FORMATTER_CACHE",
".",
"get",
"(",
"toFormat",
")",
";",
"toFormatter",
".",
"setTimeZone",
"(",
"tz",
")",
";",
"try",
"{",
"return",
"toFormatter",
".",
"format",
"(",
"fromFormatter",
".",
"parse",
"(",
"dateStr",
")",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Exception when formatting: '\"",
"+",
"dateStr",
"+",
"\"' from: '\"",
"+",
"fromFormat",
"+",
"\"' to: '\"",
"+",
"toFormat",
"+",
"\"'\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] |
Format a string datetime as specific.
@param dateStr the string datetime.
@param fromFormat the original date format.
@param toFormat the target date format.
@param tz the time zone.
|
[
"Format",
"a",
"string",
"datetime",
"as",
"specific",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java#L340-L352
|
anotheria/moskito
|
moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/parser/StatusData.java
|
StatusData.ensureValueCorrectness
|
private Object ensureValueCorrectness(T key, Object value) {
"""
Ensure that value is of correct type for the given key.
If value is not already of correct type but of type String, attempt parsing into correct type.
@return provided value if it's correctly typed or parsed value of correct type or {@code null} if auto-conversion failed.
@throws IllegalArgumentException if the given key is {@code null} or if value is neither of correct type nor of String type.
"""
checkKey(key);
if (key.isCorrectValue(value) || value == null) {
return value;
}
if (value instanceof String) {
value = key.parseValue(String.class.cast(value));
return value;
}
throw new IllegalArgumentException("Entry <'"+key+"','"+value+"'> rejected! Value should be of correct type or of type String(for auto-parsing)!");
}
|
java
|
private Object ensureValueCorrectness(T key, Object value) {
checkKey(key);
if (key.isCorrectValue(value) || value == null) {
return value;
}
if (value instanceof String) {
value = key.parseValue(String.class.cast(value));
return value;
}
throw new IllegalArgumentException("Entry <'"+key+"','"+value+"'> rejected! Value should be of correct type or of type String(for auto-parsing)!");
}
|
[
"private",
"Object",
"ensureValueCorrectness",
"(",
"T",
"key",
",",
"Object",
"value",
")",
"{",
"checkKey",
"(",
"key",
")",
";",
"if",
"(",
"key",
".",
"isCorrectValue",
"(",
"value",
")",
"||",
"value",
"==",
"null",
")",
"{",
"return",
"value",
";",
"}",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"value",
"=",
"key",
".",
"parseValue",
"(",
"String",
".",
"class",
".",
"cast",
"(",
"value",
")",
")",
";",
"return",
"value",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Entry <'\"",
"+",
"key",
"+",
"\"','\"",
"+",
"value",
"+",
"\"'> rejected! Value should be of correct type or of type String(for auto-parsing)!\"",
")",
";",
"}"
] |
Ensure that value is of correct type for the given key.
If value is not already of correct type but of type String, attempt parsing into correct type.
@return provided value if it's correctly typed or parsed value of correct type or {@code null} if auto-conversion failed.
@throws IllegalArgumentException if the given key is {@code null} or if value is neither of correct type nor of String type.
|
[
"Ensure",
"that",
"value",
"is",
"of",
"correct",
"type",
"for",
"the",
"given",
"key",
".",
"If",
"value",
"is",
"not",
"already",
"of",
"correct",
"type",
"but",
"of",
"type",
"String",
"attempt",
"parsing",
"into",
"correct",
"type",
"."
] |
train
|
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-extensions/moskito-monitoring-plugin/src/main/java/net/anotheria/moskito/extensions/monitoring/parser/StatusData.java#L65-L75
|
jferard/fastods
|
fastods/src/main/java/com/github/jferard/fastods/odselement/ContentElement.java
|
ContentElement.addChildCellStyle
|
public TableCellStyle addChildCellStyle(final TableCellStyle style, final TableCell.Type type) {
"""
Create an automatic style for this TableCellStyle and this type of cell.
Do not produce any effect if the type is Type.STRING or Type.VOID.
@param style the style of the cell (color, data style, etc.)
@param type the type of the cell
@return the created style, or style if the type is Type.STRING or Type.VOID
"""
final TableCellStyle newStyle;
final DataStyle dataStyle = this.format.getDataStyle(type);
if (dataStyle == null) {
newStyle = style;
} else {
newStyle = this.stylesContainer.addChildCellStyle(style, dataStyle);
}
return newStyle;
}
|
java
|
public TableCellStyle addChildCellStyle(final TableCellStyle style, final TableCell.Type type) {
final TableCellStyle newStyle;
final DataStyle dataStyle = this.format.getDataStyle(type);
if (dataStyle == null) {
newStyle = style;
} else {
newStyle = this.stylesContainer.addChildCellStyle(style, dataStyle);
}
return newStyle;
}
|
[
"public",
"TableCellStyle",
"addChildCellStyle",
"(",
"final",
"TableCellStyle",
"style",
",",
"final",
"TableCell",
".",
"Type",
"type",
")",
"{",
"final",
"TableCellStyle",
"newStyle",
";",
"final",
"DataStyle",
"dataStyle",
"=",
"this",
".",
"format",
".",
"getDataStyle",
"(",
"type",
")",
";",
"if",
"(",
"dataStyle",
"==",
"null",
")",
"{",
"newStyle",
"=",
"style",
";",
"}",
"else",
"{",
"newStyle",
"=",
"this",
".",
"stylesContainer",
".",
"addChildCellStyle",
"(",
"style",
",",
"dataStyle",
")",
";",
"}",
"return",
"newStyle",
";",
"}"
] |
Create an automatic style for this TableCellStyle and this type of cell.
Do not produce any effect if the type is Type.STRING or Type.VOID.
@param style the style of the cell (color, data style, etc.)
@param type the type of the cell
@return the created style, or style if the type is Type.STRING or Type.VOID
|
[
"Create",
"an",
"automatic",
"style",
"for",
"this",
"TableCellStyle",
"and",
"this",
"type",
"of",
"cell",
".",
"Do",
"not",
"produce",
"any",
"effect",
"if",
"the",
"type",
"is",
"Type",
".",
"STRING",
"or",
"Type",
".",
"VOID",
"."
] |
train
|
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/ContentElement.java#L87-L96
|
mgormley/agiga
|
src/main/java/edu/jhu/agiga/AgigaSentenceReader.java
|
AgigaSentenceReader.getElementFragmentAsString
|
public static String getElementFragmentAsString(byte[] b, VTDNav vn) throws NavException {
"""
This method will print out the XML from the current position of
<code>vn</code>. Very useful for debugging.
"""
long l = vn.getElementFragment();
int offset = (int) l;
int len = (int) (l >> 32);
String elementFragment = new String(Arrays.copyOfRange(b, offset, offset + len));
return elementFragment;
}
|
java
|
public static String getElementFragmentAsString(byte[] b, VTDNav vn) throws NavException {
long l = vn.getElementFragment();
int offset = (int) l;
int len = (int) (l >> 32);
String elementFragment = new String(Arrays.copyOfRange(b, offset, offset + len));
return elementFragment;
}
|
[
"public",
"static",
"String",
"getElementFragmentAsString",
"(",
"byte",
"[",
"]",
"b",
",",
"VTDNav",
"vn",
")",
"throws",
"NavException",
"{",
"long",
"l",
"=",
"vn",
".",
"getElementFragment",
"(",
")",
";",
"int",
"offset",
"=",
"(",
"int",
")",
"l",
";",
"int",
"len",
"=",
"(",
"int",
")",
"(",
"l",
">>",
"32",
")",
";",
"String",
"elementFragment",
"=",
"new",
"String",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"b",
",",
"offset",
",",
"offset",
"+",
"len",
")",
")",
";",
"return",
"elementFragment",
";",
"}"
] |
This method will print out the XML from the current position of
<code>vn</code>. Very useful for debugging.
|
[
"This",
"method",
"will",
"print",
"out",
"the",
"XML",
"from",
"the",
"current",
"position",
"of",
"<code",
">",
"vn<",
"/",
"code",
">",
".",
"Very",
"useful",
"for",
"debugging",
"."
] |
train
|
https://github.com/mgormley/agiga/blob/d61db78e3fa9d2470122d869a9ab798cb07eea3b/src/main/java/edu/jhu/agiga/AgigaSentenceReader.java#L348-L354
|
opentelecoms-org/jsmpp
|
jsmpp/src/main/java/org/jsmpp/session/BindRequestReceiver.java
|
BindRequestReceiver.notifyAcceptBind
|
void notifyAcceptBind(Bind bindParameter) throws IllegalStateException {
"""
Notify that the bind has accepted.
@param bindParameter is the {@link Bind} command.
@throws IllegalStateException if this method is already called before.
"""
lock.lock();
try {
if (request == null) {
request = new BindRequest(bindParameter, responseHandler);
requestCondition.signal();
} else {
throw new IllegalStateException("Already waiting for acceptance bind");
}
} finally {
lock.unlock();
}
}
|
java
|
void notifyAcceptBind(Bind bindParameter) throws IllegalStateException {
lock.lock();
try {
if (request == null) {
request = new BindRequest(bindParameter, responseHandler);
requestCondition.signal();
} else {
throw new IllegalStateException("Already waiting for acceptance bind");
}
} finally {
lock.unlock();
}
}
|
[
"void",
"notifyAcceptBind",
"(",
"Bind",
"bindParameter",
")",
"throws",
"IllegalStateException",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"request",
"==",
"null",
")",
"{",
"request",
"=",
"new",
"BindRequest",
"(",
"bindParameter",
",",
"responseHandler",
")",
";",
"requestCondition",
".",
"signal",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Already waiting for acceptance bind\"",
")",
";",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] |
Notify that the bind has accepted.
@param bindParameter is the {@link Bind} command.
@throws IllegalStateException if this method is already called before.
|
[
"Notify",
"that",
"the",
"bind",
"has",
"accepted",
"."
] |
train
|
https://github.com/opentelecoms-org/jsmpp/blob/acc15e73e7431deabc803731971b15323315baaf/jsmpp/src/main/java/org/jsmpp/session/BindRequestReceiver.java#L79-L91
|
xiaolongzuo/niubi-job
|
niubi-job-framework/niubi-job-scheduler/src/main/java/com/zuoxiaolong/niubi/job/scheduler/JobEnvironmentCache.java
|
JobEnvironmentCache.createJobBeanFactory
|
protected JobBeanFactory createJobBeanFactory(String jarFilePath, boolean isSpring) throws Exception {
"""
创建缓存JobBean实例的工厂
@param jarFilePath Jar包本地路径
@param isSpring 是否spring环境
@return 创建好的JobBean工厂
@throws Exception 当出现未检查的异常时抛出
"""
String jobBeanFactoryClassName;
if (isSpring) {
jobBeanFactoryClassName = "com.zuoxiaolong.niubi.job.spring.bean.SpringJobBeanFactory";
} else {
jobBeanFactoryClassName = "com.zuoxiaolong.niubi.job.scheduler.bean.DefaultJobBeanFactory";
}
ClassLoader jarApplicationClassLoader = ApplicationClassLoaderFactory.getJarApplicationClassLoader(jarFilePath);
Class<? extends JobBeanFactory> jobBeanFactoryClass = (Class<? extends JobBeanFactory>) jarApplicationClassLoader.loadClass(jobBeanFactoryClassName);
Class<?>[] parameterTypes = new Class[]{ClassLoader.class};
Constructor<? extends JobBeanFactory> jobBeanFactoryConstructor = jobBeanFactoryClass.getConstructor(parameterTypes);
return jobBeanFactoryConstructor.newInstance(jarApplicationClassLoader);
}
|
java
|
protected JobBeanFactory createJobBeanFactory(String jarFilePath, boolean isSpring) throws Exception {
String jobBeanFactoryClassName;
if (isSpring) {
jobBeanFactoryClassName = "com.zuoxiaolong.niubi.job.spring.bean.SpringJobBeanFactory";
} else {
jobBeanFactoryClassName = "com.zuoxiaolong.niubi.job.scheduler.bean.DefaultJobBeanFactory";
}
ClassLoader jarApplicationClassLoader = ApplicationClassLoaderFactory.getJarApplicationClassLoader(jarFilePath);
Class<? extends JobBeanFactory> jobBeanFactoryClass = (Class<? extends JobBeanFactory>) jarApplicationClassLoader.loadClass(jobBeanFactoryClassName);
Class<?>[] parameterTypes = new Class[]{ClassLoader.class};
Constructor<? extends JobBeanFactory> jobBeanFactoryConstructor = jobBeanFactoryClass.getConstructor(parameterTypes);
return jobBeanFactoryConstructor.newInstance(jarApplicationClassLoader);
}
|
[
"protected",
"JobBeanFactory",
"createJobBeanFactory",
"(",
"String",
"jarFilePath",
",",
"boolean",
"isSpring",
")",
"throws",
"Exception",
"{",
"String",
"jobBeanFactoryClassName",
";",
"if",
"(",
"isSpring",
")",
"{",
"jobBeanFactoryClassName",
"=",
"\"com.zuoxiaolong.niubi.job.spring.bean.SpringJobBeanFactory\"",
";",
"}",
"else",
"{",
"jobBeanFactoryClassName",
"=",
"\"com.zuoxiaolong.niubi.job.scheduler.bean.DefaultJobBeanFactory\"",
";",
"}",
"ClassLoader",
"jarApplicationClassLoader",
"=",
"ApplicationClassLoaderFactory",
".",
"getJarApplicationClassLoader",
"(",
"jarFilePath",
")",
";",
"Class",
"<",
"?",
"extends",
"JobBeanFactory",
">",
"jobBeanFactoryClass",
"=",
"(",
"Class",
"<",
"?",
"extends",
"JobBeanFactory",
">",
")",
"jarApplicationClassLoader",
".",
"loadClass",
"(",
"jobBeanFactoryClassName",
")",
";",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"new",
"Class",
"[",
"]",
"{",
"ClassLoader",
".",
"class",
"}",
";",
"Constructor",
"<",
"?",
"extends",
"JobBeanFactory",
">",
"jobBeanFactoryConstructor",
"=",
"jobBeanFactoryClass",
".",
"getConstructor",
"(",
"parameterTypes",
")",
";",
"return",
"jobBeanFactoryConstructor",
".",
"newInstance",
"(",
"jarApplicationClassLoader",
")",
";",
"}"
] |
创建缓存JobBean实例的工厂
@param jarFilePath Jar包本地路径
@param isSpring 是否spring环境
@return 创建好的JobBean工厂
@throws Exception 当出现未检查的异常时抛出
|
[
"创建缓存JobBean实例的工厂"
] |
train
|
https://github.com/xiaolongzuo/niubi-job/blob/ed21d5b80f8b16c8b3a0b2fbc688442b878edbe4/niubi-job-framework/niubi-job-scheduler/src/main/java/com/zuoxiaolong/niubi/job/scheduler/JobEnvironmentCache.java#L132-L144
|
hivemq/hivemq-spi
|
src/main/java/com/hivemq/spi/topic/MqttTopicPermission.java
|
MqttTopicPermission.topicImplicity
|
private boolean topicImplicity(final String topic, final String[] splitTopic) {
"""
Checks if the topic implies a given MqttTopicPermissions topic
@param topic the topic to check
@return <code>true</code> if the given MqttTopicPermissions topic is implied by the current one
"""
try {
return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic);
} catch (InvalidTopicException e) {
return false;
}
}
|
java
|
private boolean topicImplicity(final String topic, final String[] splitTopic) {
try {
return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic);
} catch (InvalidTopicException e) {
return false;
}
}
|
[
"private",
"boolean",
"topicImplicity",
"(",
"final",
"String",
"topic",
",",
"final",
"String",
"[",
"]",
"splitTopic",
")",
"{",
"try",
"{",
"return",
"topicMatcher",
".",
"matches",
"(",
"stripedTopic",
",",
"this",
".",
"splitTopic",
",",
"nonWildCard",
",",
"endsWithWildCard",
",",
"rootWildCard",
",",
"topic",
",",
"splitTopic",
")",
";",
"}",
"catch",
"(",
"InvalidTopicException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
Checks if the topic implies a given MqttTopicPermissions topic
@param topic the topic to check
@return <code>true</code> if the given MqttTopicPermissions topic is implied by the current one
|
[
"Checks",
"if",
"the",
"topic",
"implies",
"a",
"given",
"MqttTopicPermissions",
"topic"
] |
train
|
https://github.com/hivemq/hivemq-spi/blob/55fa89ccb081ad5b6d46eaca02179272148e64ed/src/main/java/com/hivemq/spi/topic/MqttTopicPermission.java#L368-L375
|
CenturyLinkCloud/mdw
|
mdw-common/src/com/centurylink/mdw/util/StringHelper.java
|
StringHelper.delimiterColumnCount
|
public static int delimiterColumnCount(String row, String delimeterChar, String escapeChar) {
"""
To count comma separated columns in a row to maintain compatibility
"""
if (row.indexOf(escapeChar) > 0)
return row.replace(escapeChar, " ").length() - row.replace(",", "").length();
else
return row.length() - row.replace(",", "").length();
}
|
java
|
public static int delimiterColumnCount(String row, String delimeterChar, String escapeChar) {
if (row.indexOf(escapeChar) > 0)
return row.replace(escapeChar, " ").length() - row.replace(",", "").length();
else
return row.length() - row.replace(",", "").length();
}
|
[
"public",
"static",
"int",
"delimiterColumnCount",
"(",
"String",
"row",
",",
"String",
"delimeterChar",
",",
"String",
"escapeChar",
")",
"{",
"if",
"(",
"row",
".",
"indexOf",
"(",
"escapeChar",
")",
">",
"0",
")",
"return",
"row",
".",
"replace",
"(",
"escapeChar",
",",
"\" \"",
")",
".",
"length",
"(",
")",
"-",
"row",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
".",
"length",
"(",
")",
";",
"else",
"return",
"row",
".",
"length",
"(",
")",
"-",
"row",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
".",
"length",
"(",
")",
";",
"}"
] |
To count comma separated columns in a row to maintain compatibility
|
[
"To",
"count",
"comma",
"separated",
"columns",
"in",
"a",
"row",
"to",
"maintain",
"compatibility"
] |
train
|
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1543-L1548
|
shekhargulati/strman-java
|
src/main/java/strman/Strman.java
|
Strman.countSubstr
|
public static long countSubstr(final String value, final String subStr) {
"""
Count the number of times substr appears in value
@param value input
@param subStr to search
@return count of times substring exists
"""
return countSubstr(value, subStr, true, false);
}
|
java
|
public static long countSubstr(final String value, final String subStr) {
return countSubstr(value, subStr, true, false);
}
|
[
"public",
"static",
"long",
"countSubstr",
"(",
"final",
"String",
"value",
",",
"final",
"String",
"subStr",
")",
"{",
"return",
"countSubstr",
"(",
"value",
",",
"subStr",
",",
"true",
",",
"false",
")",
";",
"}"
] |
Count the number of times substr appears in value
@param value input
@param subStr to search
@return count of times substring exists
|
[
"Count",
"the",
"number",
"of",
"times",
"substr",
"appears",
"in",
"value"
] |
train
|
https://github.com/shekhargulati/strman-java/blob/d0c2a10a6273fd6082f084e95156653ca55ce1be/src/main/java/strman/Strman.java#L229-L231
|
ManfredTremmel/gwt-commons-lang3
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
StringUtils.appendIfMissing
|
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
"""
Appends the suffix to the end of the string if the string does not
already end with any of the suffixes.
<pre>
StringUtils.appendIfMissing(null, null) = null
StringUtils.appendIfMissing("abc", null) = "abc"
StringUtils.appendIfMissing("", "xyz") = "xyz"
StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
</pre>
<p>With additional suffixes,</p>
<pre>
StringUtils.appendIfMissing(null, null, null) = null
StringUtils.appendIfMissing("abc", null, null) = "abc"
StringUtils.appendIfMissing("", "xyz", null) = "xyz"
StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
</pre>
@param str The string.
@param suffix The suffix to append to the end of the string.
@param suffixes Additional suffixes that are valid terminators.
@return A new String if suffix was appended, the same string otherwise.
@since 3.2
"""
return appendIfMissing(str, suffix, false, suffixes);
}
|
java
|
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, false, suffixes);
}
|
[
"public",
"static",
"String",
"appendIfMissing",
"(",
"final",
"String",
"str",
",",
"final",
"CharSequence",
"suffix",
",",
"final",
"CharSequence",
"...",
"suffixes",
")",
"{",
"return",
"appendIfMissing",
"(",
"str",
",",
"suffix",
",",
"false",
",",
"suffixes",
")",
";",
"}"
] |
Appends the suffix to the end of the string if the string does not
already end with any of the suffixes.
<pre>
StringUtils.appendIfMissing(null, null) = null
StringUtils.appendIfMissing("abc", null) = "abc"
StringUtils.appendIfMissing("", "xyz") = "xyz"
StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
</pre>
<p>With additional suffixes,</p>
<pre>
StringUtils.appendIfMissing(null, null, null) = null
StringUtils.appendIfMissing("abc", null, null) = "abc"
StringUtils.appendIfMissing("", "xyz", null) = "xyz"
StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
</pre>
@param str The string.
@param suffix The suffix to append to the end of the string.
@param suffixes Additional suffixes that are valid terminators.
@return A new String if suffix was appended, the same string otherwise.
@since 3.2
|
[
"Appends",
"the",
"suffix",
"to",
"the",
"end",
"of",
"the",
"string",
"if",
"the",
"string",
"does",
"not",
"already",
"end",
"with",
"any",
"of",
"the",
"suffixes",
"."
] |
train
|
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L8814-L8816
|
census-instrumentation/opencensus-java
|
contrib/dropwizard/src/main/java/io/opencensus/contrib/dropwizard/DropWizardMetrics.java
|
DropWizardMetrics.collectTimer
|
private Metric collectTimer(String dropwizardName, Timer timer) {
"""
Returns a {@code Metric} collected from {@link Timer}.
@param dropwizardName the metric name.
@param timer the timer object to collect
@return a {@code Metric}.
"""
String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "timer");
String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardName, timer);
return collectSnapshotAndCount(
metricName, metricDescription, NS_UNIT, timer.getSnapshot(), timer.getCount());
}
|
java
|
private Metric collectTimer(String dropwizardName, Timer timer) {
String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "timer");
String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardName, timer);
return collectSnapshotAndCount(
metricName, metricDescription, NS_UNIT, timer.getSnapshot(), timer.getCount());
}
|
[
"private",
"Metric",
"collectTimer",
"(",
"String",
"dropwizardName",
",",
"Timer",
"timer",
")",
"{",
"String",
"metricName",
"=",
"DropWizardUtils",
".",
"generateFullMetricName",
"(",
"dropwizardName",
",",
"\"timer\"",
")",
";",
"String",
"metricDescription",
"=",
"DropWizardUtils",
".",
"generateFullMetricDescription",
"(",
"dropwizardName",
",",
"timer",
")",
";",
"return",
"collectSnapshotAndCount",
"(",
"metricName",
",",
"metricDescription",
",",
"NS_UNIT",
",",
"timer",
".",
"getSnapshot",
"(",
")",
",",
"timer",
".",
"getCount",
"(",
")",
")",
";",
"}"
] |
Returns a {@code Metric} collected from {@link Timer}.
@param dropwizardName the metric name.
@param timer the timer object to collect
@return a {@code Metric}.
|
[
"Returns",
"a",
"{",
"@code",
"Metric",
"}",
"collected",
"from",
"{",
"@link",
"Timer",
"}",
"."
] |
train
|
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard/src/main/java/io/opencensus/contrib/dropwizard/DropWizardMetrics.java#L210-L215
|
casbin/jcasbin
|
src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java
|
ManagementEnforcer.removeNamedGroupingPolicy
|
public boolean removeNamedGroupingPolicy(String ptype, String... params) {
"""
removeNamedGroupingPolicy removes a role inheritance rule from the current named policy.
@param ptype the policy type, can be "g", "g2", "g3", ..
@param params the "g" policy rule.
@return succeeds or not.
"""
return removeNamedGroupingPolicy(ptype, Arrays.asList(params));
}
|
java
|
public boolean removeNamedGroupingPolicy(String ptype, String... params) {
return removeNamedGroupingPolicy(ptype, Arrays.asList(params));
}
|
[
"public",
"boolean",
"removeNamedGroupingPolicy",
"(",
"String",
"ptype",
",",
"String",
"...",
"params",
")",
"{",
"return",
"removeNamedGroupingPolicy",
"(",
"ptype",
",",
"Arrays",
".",
"asList",
"(",
"params",
")",
")",
";",
"}"
] |
removeNamedGroupingPolicy removes a role inheritance rule from the current named policy.
@param ptype the policy type, can be "g", "g2", "g3", ..
@param params the "g" policy rule.
@return succeeds or not.
|
[
"removeNamedGroupingPolicy",
"removes",
"a",
"role",
"inheritance",
"rule",
"from",
"the",
"current",
"named",
"policy",
"."
] |
train
|
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/ManagementEnforcer.java#L525-L527
|
neoremind/fluent-validator
|
fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java
|
FluentValidator.putClosure2Context
|
public FluentValidator putClosure2Context(String key, Closure value) {
"""
将闭包注入上下文
@param key 键
@param value 闭包
@return FluentValidator
"""
if (context == null) {
context = new ValidatorContext();
}
context.setClosure(key, value);
return this;
}
|
java
|
public FluentValidator putClosure2Context(String key, Closure value) {
if (context == null) {
context = new ValidatorContext();
}
context.setClosure(key, value);
return this;
}
|
[
"public",
"FluentValidator",
"putClosure2Context",
"(",
"String",
"key",
",",
"Closure",
"value",
")",
"{",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"context",
"=",
"new",
"ValidatorContext",
"(",
")",
";",
"}",
"context",
".",
"setClosure",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] |
将闭包注入上下文
@param key 键
@param value 闭包
@return FluentValidator
|
[
"将闭包注入上下文"
] |
train
|
https://github.com/neoremind/fluent-validator/blob/b516970591aa9468b44ba63938b98ec341fd6ead/fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/FluentValidator.java#L116-L122
|
baratine/baratine
|
core/src/main/java/com/caucho/v5/ramp/pipe/PipeNode.java
|
PipeNode.send
|
@Override
public void send(T value, Result<Void> result) {
"""
/*
private boolean pendingPublish(ResultPipeOut<T> result)
{
if (_init == StateInit.INIT) {
return false;
}
_pendingInit.add(()->publish(result));
return true;
}
"""
/*
if (! init() && pendingSend(value, result)) {
return;
}
*/
send(value);
result.ok(null);
}
|
java
|
@Override
public void send(T value, Result<Void> result)
{
/*
if (! init() && pendingSend(value, result)) {
return;
}
*/
send(value);
result.ok(null);
}
|
[
"@",
"Override",
"public",
"void",
"send",
"(",
"T",
"value",
",",
"Result",
"<",
"Void",
">",
"result",
")",
"{",
"/*\n if (! init() && pendingSend(value, result)) {\n return;\n }\n */",
"send",
"(",
"value",
")",
";",
"result",
".",
"ok",
"(",
"null",
")",
";",
"}"
] |
/*
private boolean pendingPublish(ResultPipeOut<T> result)
{
if (_init == StateInit.INIT) {
return false;
}
_pendingInit.add(()->publish(result));
return true;
}
|
[
"/",
"*",
"private",
"boolean",
"pendingPublish",
"(",
"ResultPipeOut<T",
">",
"result",
")",
"{",
"if",
"(",
"_init",
"==",
"StateInit",
".",
"INIT",
")",
"{",
"return",
"false",
";",
"}"
] |
train
|
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/core/src/main/java/com/caucho/v5/ramp/pipe/PipeNode.java#L129-L141
|
tipsy/javalin
|
src/main/java/io/javalin/Javalin.java
|
Javalin.ws
|
public Javalin ws(@NotNull String path, @NotNull Consumer<WsHandler> ws) {
"""
Adds a WebSocket handler on the specified path.
@see <a href="https://javalin.io/documentation#websockets">WebSockets in docs</a>
"""
return ws(path, ws, new HashSet<>());
}
|
java
|
public Javalin ws(@NotNull String path, @NotNull Consumer<WsHandler> ws) {
return ws(path, ws, new HashSet<>());
}
|
[
"public",
"Javalin",
"ws",
"(",
"@",
"NotNull",
"String",
"path",
",",
"@",
"NotNull",
"Consumer",
"<",
"WsHandler",
">",
"ws",
")",
"{",
"return",
"ws",
"(",
"path",
",",
"ws",
",",
"new",
"HashSet",
"<>",
"(",
")",
")",
";",
"}"
] |
Adds a WebSocket handler on the specified path.
@see <a href="https://javalin.io/documentation#websockets">WebSockets in docs</a>
|
[
"Adds",
"a",
"WebSocket",
"handler",
"on",
"the",
"specified",
"path",
"."
] |
train
|
https://github.com/tipsy/javalin/blob/68b2f7592f237db1c2b597e645697eb75fdaee53/src/main/java/io/javalin/Javalin.java#L523-L525
|
davidmoten/rxjava-jdbc
|
src/main/java/com/github/davidmoten/rx/jdbc/QuerySelectOnSubscribe.java
|
QuerySelectOnSubscribe.executeQuery
|
private void executeQuery(Subscriber<? super T> subscriber, State state) throws SQLException {
"""
Executes the prepared statement.
@param subscriber
@param state
@throws SQLException
"""
if (!subscriber.isUnsubscribed()) {
try {
log.debug("executing sql={}, parameters {}", query.sql(), parameters);
state.rs = query.resultSetTransform()
.call(query.context().resultSetTransform().call(state.ps.executeQuery()));
log.debug("executed ps={}", state.ps);
} catch (SQLException e) {
throw new SQLException("failed to run sql=" + query.sql(), e);
}
}
}
|
java
|
private void executeQuery(Subscriber<? super T> subscriber, State state) throws SQLException {
if (!subscriber.isUnsubscribed()) {
try {
log.debug("executing sql={}, parameters {}", query.sql(), parameters);
state.rs = query.resultSetTransform()
.call(query.context().resultSetTransform().call(state.ps.executeQuery()));
log.debug("executed ps={}", state.ps);
} catch (SQLException e) {
throw new SQLException("failed to run sql=" + query.sql(), e);
}
}
}
|
[
"private",
"void",
"executeQuery",
"(",
"Subscriber",
"<",
"?",
"super",
"T",
">",
"subscriber",
",",
"State",
"state",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"!",
"subscriber",
".",
"isUnsubscribed",
"(",
")",
")",
"{",
"try",
"{",
"log",
".",
"debug",
"(",
"\"executing sql={}, parameters {}\"",
",",
"query",
".",
"sql",
"(",
")",
",",
"parameters",
")",
";",
"state",
".",
"rs",
"=",
"query",
".",
"resultSetTransform",
"(",
")",
".",
"call",
"(",
"query",
".",
"context",
"(",
")",
".",
"resultSetTransform",
"(",
")",
".",
"call",
"(",
"state",
".",
"ps",
".",
"executeQuery",
"(",
")",
")",
")",
";",
"log",
".",
"debug",
"(",
"\"executed ps={}\"",
",",
"state",
".",
"ps",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"SQLException",
"(",
"\"failed to run sql=\"",
"+",
"query",
".",
"sql",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"}"
] |
Executes the prepared statement.
@param subscriber
@param state
@throws SQLException
|
[
"Executes",
"the",
"prepared",
"statement",
"."
] |
train
|
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/QuerySelectOnSubscribe.java#L126-L137
|
lesaint/damapping
|
core-parent/util/src/main/java/fr/javatronic/damapping/util/Preconditions.java
|
Preconditions.checkNotNull
|
@Nonnull
public static <T> T checkNotNull(@Nullable T obj, @Nullable String message) {
"""
Throws a NullPointerException with the specified message if the specified object is {@code null}, otherwise
returns it.
<p>
A default message will be used if the specified message is {@code null} or empty.
</p>
@param obj an object of any type or {@code null}
@param message a {@link String} or {@code null}
@param <T> any type
@return the argument
"""
if (obj == null) {
throw new NullPointerException(message == null || message.isEmpty() ? NPE_DEFAULT_MSG : message);
}
return obj;
}
|
java
|
@Nonnull
public static <T> T checkNotNull(@Nullable T obj, @Nullable String message) {
if (obj == null) {
throw new NullPointerException(message == null || message.isEmpty() ? NPE_DEFAULT_MSG : message);
}
return obj;
}
|
[
"@",
"Nonnull",
"public",
"static",
"<",
"T",
">",
"T",
"checkNotNull",
"(",
"@",
"Nullable",
"T",
"obj",
",",
"@",
"Nullable",
"String",
"message",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"message",
"==",
"null",
"||",
"message",
".",
"isEmpty",
"(",
")",
"?",
"NPE_DEFAULT_MSG",
":",
"message",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Throws a NullPointerException with the specified message if the specified object is {@code null}, otherwise
returns it.
<p>
A default message will be used if the specified message is {@code null} or empty.
</p>
@param obj an object of any type or {@code null}
@param message a {@link String} or {@code null}
@param <T> any type
@return the argument
|
[
"Throws",
"a",
"NullPointerException",
"with",
"the",
"specified",
"message",
"if",
"the",
"specified",
"object",
"is",
"{",
"@code",
"null",
"}",
"otherwise",
"returns",
"it",
".",
"<p",
">",
"A",
"default",
"message",
"will",
"be",
"used",
"if",
"the",
"specified",
"message",
"is",
"{",
"@code",
"null",
"}",
"or",
"empty",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/lesaint/damapping/blob/357afa5866939fd2a18c09213975ffef4836f328/core-parent/util/src/main/java/fr/javatronic/damapping/util/Preconditions.java#L62-L68
|
alibaba/ARouter
|
arouter-api/src/main/java/com/alibaba/android/arouter/thread/DefaultPoolExecutor.java
|
DefaultPoolExecutor.afterExecute
|
@Override
protected void afterExecute(Runnable r, Throwable t) {
"""
/*
线程执行结束,顺便看一下有么有什么乱七八糟的异常
@param r the runnable that has completed
@param t the exception that caused termination, or null if
"""
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null) {
ARouter.logger.warning(Consts.TAG, "Running task appeared exception! Thread [" + Thread.currentThread().getName() + "], because [" + t.getMessage() + "]\n" + TextUtils.formatStackTrace(t.getStackTrace()));
}
}
|
java
|
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null) {
ARouter.logger.warning(Consts.TAG, "Running task appeared exception! Thread [" + Thread.currentThread().getName() + "], because [" + t.getMessage() + "]\n" + TextUtils.formatStackTrace(t.getStackTrace()));
}
}
|
[
"@",
"Override",
"protected",
"void",
"afterExecute",
"(",
"Runnable",
"r",
",",
"Throwable",
"t",
")",
"{",
"super",
".",
"afterExecute",
"(",
"r",
",",
"t",
")",
";",
"if",
"(",
"t",
"==",
"null",
"&&",
"r",
"instanceof",
"Future",
"<",
"?",
">",
")",
"{",
"try",
"{",
"(",
"(",
"Future",
"<",
"?",
">",
")",
"r",
")",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"CancellationException",
"ce",
")",
"{",
"t",
"=",
"ce",
";",
"}",
"catch",
"(",
"ExecutionException",
"ee",
")",
"{",
"t",
"=",
"ee",
".",
"getCause",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"// ignore/reset",
"}",
"}",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"ARouter",
".",
"logger",
".",
"warning",
"(",
"Consts",
".",
"TAG",
",",
"\"Running task appeared exception! Thread [\"",
"+",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"], because [\"",
"+",
"t",
".",
"getMessage",
"(",
")",
"+",
"\"]\\n\"",
"+",
"TextUtils",
".",
"formatStackTrace",
"(",
"t",
".",
"getStackTrace",
"(",
")",
")",
")",
";",
"}",
"}"
] |
/*
线程执行结束,顺便看一下有么有什么乱七八糟的异常
@param r the runnable that has completed
@param t the exception that caused termination, or null if
|
[
"/",
"*",
"线程执行结束,顺便看一下有么有什么乱七八糟的异常"
] |
train
|
https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/thread/DefaultPoolExecutor.java#L65-L82
|
sarl/sarl
|
main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java
|
AbstractExtraLanguageValidator.doTypeMappingCheck
|
protected boolean doTypeMappingCheck(EObject source, JvmType type, Procedure3<? super EObject, ? super JvmType, ? super String> errorHandler) {
"""
Do a type mapping check.
@param source the source of the type.
@param type the type to check.
@param errorHandler the error handler.
@return {@code true} if a type mapping is defined.
"""
if (source != null && type != null) {
final ExtraLanguageTypeConverter converter = getTypeConverter();
final String qn = type.getQualifiedName();
if (converter != null && !converter.hasConversion(qn)) {
if (errorHandler != null) {
errorHandler.apply(source, type, qn);
}
return false;
}
}
return true;
}
|
java
|
protected boolean doTypeMappingCheck(EObject source, JvmType type, Procedure3<? super EObject, ? super JvmType, ? super String> errorHandler) {
if (source != null && type != null) {
final ExtraLanguageTypeConverter converter = getTypeConverter();
final String qn = type.getQualifiedName();
if (converter != null && !converter.hasConversion(qn)) {
if (errorHandler != null) {
errorHandler.apply(source, type, qn);
}
return false;
}
}
return true;
}
|
[
"protected",
"boolean",
"doTypeMappingCheck",
"(",
"EObject",
"source",
",",
"JvmType",
"type",
",",
"Procedure3",
"<",
"?",
"super",
"EObject",
",",
"?",
"super",
"JvmType",
",",
"?",
"super",
"String",
">",
"errorHandler",
")",
"{",
"if",
"(",
"source",
"!=",
"null",
"&&",
"type",
"!=",
"null",
")",
"{",
"final",
"ExtraLanguageTypeConverter",
"converter",
"=",
"getTypeConverter",
"(",
")",
";",
"final",
"String",
"qn",
"=",
"type",
".",
"getQualifiedName",
"(",
")",
";",
"if",
"(",
"converter",
"!=",
"null",
"&&",
"!",
"converter",
".",
"hasConversion",
"(",
"qn",
")",
")",
"{",
"if",
"(",
"errorHandler",
"!=",
"null",
")",
"{",
"errorHandler",
".",
"apply",
"(",
"source",
",",
"type",
",",
"qn",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Do a type mapping check.
@param source the source of the type.
@param type the type to check.
@param errorHandler the error handler.
@return {@code true} if a type mapping is defined.
|
[
"Do",
"a",
"type",
"mapping",
"check",
"."
] |
train
|
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/extralanguage/validator/AbstractExtraLanguageValidator.java#L390-L402
|
nmorel/gwt-jackson
|
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/bean/BeanProcessor.java
|
BeanProcessor.processType
|
public static Optional<BeanTypeInfo> processType( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration,
JClassType type, Optional<JsonTypeInfo> jsonTypeInfo, Optional<JsonSubTypes>
propertySubTypes ) throws UnableToCompleteException {
"""
<p>processType</p>
@param logger a {@link com.google.gwt.core.ext.TreeLogger} object.
@param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
@param configuration a {@link com.github.nmorel.gwtjackson.rebind.RebindConfiguration} object.
@param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
@param type a {@link com.google.gwt.core.ext.typeinfo.JClassType} object.
@param jsonTypeInfo a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@param propertySubTypes a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@return a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@throws com.google.gwt.core.ext.UnableToCompleteException if any.
"""
if ( !jsonTypeInfo.isPresent() ) {
jsonTypeInfo = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonTypeInfo.class );
if ( !jsonTypeInfo.isPresent() ) {
return Optional.absent();
}
}
Id use = jsonTypeInfo.get().use();
As include = jsonTypeInfo.get().include();
String propertyName = jsonTypeInfo.get().property().isEmpty() ? jsonTypeInfo.get().use().getDefaultPropertyName() : jsonTypeInfo
.get().property();
Optional<JsonSubTypes> typeSubTypes = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonSubTypes.class );
// TODO we could do better, we actually extract metadata twice for a lot of classes
ImmutableMap<JClassType, String> classToSerializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
propertySubTypes, typeSubTypes, CreatorUtils
.filterSubtypesForSerialization( logger, configuration, type ) );
ImmutableMap<JClassType, String> classToDeserializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
propertySubTypes, typeSubTypes, CreatorUtils
.filterSubtypesForDeserialization( logger, configuration, type ) );
return Optional.of(
new BeanTypeInfo( use, include, propertyName, classToSerializationMetadata, classToDeserializationMetadata ) );
}
|
java
|
public static Optional<BeanTypeInfo> processType( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration,
JClassType type, Optional<JsonTypeInfo> jsonTypeInfo, Optional<JsonSubTypes>
propertySubTypes ) throws UnableToCompleteException {
if ( !jsonTypeInfo.isPresent() ) {
jsonTypeInfo = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonTypeInfo.class );
if ( !jsonTypeInfo.isPresent() ) {
return Optional.absent();
}
}
Id use = jsonTypeInfo.get().use();
As include = jsonTypeInfo.get().include();
String propertyName = jsonTypeInfo.get().property().isEmpty() ? jsonTypeInfo.get().use().getDefaultPropertyName() : jsonTypeInfo
.get().property();
Optional<JsonSubTypes> typeSubTypes = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonSubTypes.class );
// TODO we could do better, we actually extract metadata twice for a lot of classes
ImmutableMap<JClassType, String> classToSerializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
propertySubTypes, typeSubTypes, CreatorUtils
.filterSubtypesForSerialization( logger, configuration, type ) );
ImmutableMap<JClassType, String> classToDeserializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
propertySubTypes, typeSubTypes, CreatorUtils
.filterSubtypesForDeserialization( logger, configuration, type ) );
return Optional.of(
new BeanTypeInfo( use, include, propertyName, classToSerializationMetadata, classToDeserializationMetadata ) );
}
|
[
"public",
"static",
"Optional",
"<",
"BeanTypeInfo",
">",
"processType",
"(",
"TreeLogger",
"logger",
",",
"JacksonTypeOracle",
"typeOracle",
",",
"RebindConfiguration",
"configuration",
",",
"JClassType",
"type",
",",
"Optional",
"<",
"JsonTypeInfo",
">",
"jsonTypeInfo",
",",
"Optional",
"<",
"JsonSubTypes",
">",
"propertySubTypes",
")",
"throws",
"UnableToCompleteException",
"{",
"if",
"(",
"!",
"jsonTypeInfo",
".",
"isPresent",
"(",
")",
")",
"{",
"jsonTypeInfo",
"=",
"findFirstEncounteredAnnotationsOnAllHierarchy",
"(",
"configuration",
",",
"type",
",",
"JsonTypeInfo",
".",
"class",
")",
";",
"if",
"(",
"!",
"jsonTypeInfo",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}",
"}",
"Id",
"use",
"=",
"jsonTypeInfo",
".",
"get",
"(",
")",
".",
"use",
"(",
")",
";",
"As",
"include",
"=",
"jsonTypeInfo",
".",
"get",
"(",
")",
".",
"include",
"(",
")",
";",
"String",
"propertyName",
"=",
"jsonTypeInfo",
".",
"get",
"(",
")",
".",
"property",
"(",
")",
".",
"isEmpty",
"(",
")",
"?",
"jsonTypeInfo",
".",
"get",
"(",
")",
".",
"use",
"(",
")",
".",
"getDefaultPropertyName",
"(",
")",
":",
"jsonTypeInfo",
".",
"get",
"(",
")",
".",
"property",
"(",
")",
";",
"Optional",
"<",
"JsonSubTypes",
">",
"typeSubTypes",
"=",
"findFirstEncounteredAnnotationsOnAllHierarchy",
"(",
"configuration",
",",
"type",
",",
"JsonSubTypes",
".",
"class",
")",
";",
"// TODO we could do better, we actually extract metadata twice for a lot of classes",
"ImmutableMap",
"<",
"JClassType",
",",
"String",
">",
"classToSerializationMetadata",
"=",
"extractMetadata",
"(",
"logger",
",",
"configuration",
",",
"type",
",",
"jsonTypeInfo",
",",
"propertySubTypes",
",",
"typeSubTypes",
",",
"CreatorUtils",
".",
"filterSubtypesForSerialization",
"(",
"logger",
",",
"configuration",
",",
"type",
")",
")",
";",
"ImmutableMap",
"<",
"JClassType",
",",
"String",
">",
"classToDeserializationMetadata",
"=",
"extractMetadata",
"(",
"logger",
",",
"configuration",
",",
"type",
",",
"jsonTypeInfo",
",",
"propertySubTypes",
",",
"typeSubTypes",
",",
"CreatorUtils",
".",
"filterSubtypesForDeserialization",
"(",
"logger",
",",
"configuration",
",",
"type",
")",
")",
";",
"return",
"Optional",
".",
"of",
"(",
"new",
"BeanTypeInfo",
"(",
"use",
",",
"include",
",",
"propertyName",
",",
"classToSerializationMetadata",
",",
"classToDeserializationMetadata",
")",
")",
";",
"}"
] |
<p>processType</p>
@param logger a {@link com.google.gwt.core.ext.TreeLogger} object.
@param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
@param configuration a {@link com.github.nmorel.gwtjackson.rebind.RebindConfiguration} object.
@param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
@param type a {@link com.google.gwt.core.ext.typeinfo.JClassType} object.
@param jsonTypeInfo a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@param propertySubTypes a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@return a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
@throws com.google.gwt.core.ext.UnableToCompleteException if any.
|
[
"<p",
">",
"processType<",
"/",
"p",
">"
] |
train
|
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/bean/BeanProcessor.java#L378-L406
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
|
ApiOvhHostingweb.serviceName_ownLogs_id_userLogs_login_PUT
|
public void serviceName_ownLogs_id_userLogs_login_PUT(String serviceName, Long id, String login, OvhUserLogs body) throws IOException {
"""
Alter this object properties
REST: PUT /hosting/web/{serviceName}/ownLogs/{id}/userLogs/{login}
@param body [required] New object properties
@param serviceName [required] The internal name of your hosting
@param id [required] Id of the object
@param login [required] The userLogs login used to connect to logs.ovh.net
"""
String qPath = "/hosting/web/{serviceName}/ownLogs/{id}/userLogs/{login}";
StringBuilder sb = path(qPath, serviceName, id, login);
exec(qPath, "PUT", sb.toString(), body);
}
|
java
|
public void serviceName_ownLogs_id_userLogs_login_PUT(String serviceName, Long id, String login, OvhUserLogs body) throws IOException {
String qPath = "/hosting/web/{serviceName}/ownLogs/{id}/userLogs/{login}";
StringBuilder sb = path(qPath, serviceName, id, login);
exec(qPath, "PUT", sb.toString(), body);
}
|
[
"public",
"void",
"serviceName_ownLogs_id_userLogs_login_PUT",
"(",
"String",
"serviceName",
",",
"Long",
"id",
",",
"String",
"login",
",",
"OvhUserLogs",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/hosting/web/{serviceName}/ownLogs/{id}/userLogs/{login}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"id",
",",
"login",
")",
";",
"exec",
"(",
"qPath",
",",
"\"PUT\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"body",
")",
";",
"}"
] |
Alter this object properties
REST: PUT /hosting/web/{serviceName}/ownLogs/{id}/userLogs/{login}
@param body [required] New object properties
@param serviceName [required] The internal name of your hosting
@param id [required] Id of the object
@param login [required] The userLogs login used to connect to logs.ovh.net
|
[
"Alter",
"this",
"object",
"properties"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L1020-L1024
|
reinert/requestor
|
requestor/ext/requestor-oauth2/src/main/java/io/reinert/requestor/oauth2/Auth.java
|
Auth.login
|
public void login(AuthRequest req, final Callback<TokenInfo, Throwable> callback) {
"""
Request an access token from an OAuth 2.0 provider.
<p/>
<p> If it can be determined that the user has already granted access, and the token has not yet expired, and that
the token will not expire soon, the existing token will be passed to the callback. </p>
<p/>
<p> Otherwise, a popup window will be displayed which may prompt the user to grant access. If the user has
already granted access the popup will immediately close and the token will be passed to the callback. If access
hasn't been granted, the user will be prompted, and when they grant, the token will be passed to the callback.
</p>
@param req Request for authentication.
@param callback Callback to pass the token to when access has been granted.
"""
lastRequest = req;
lastCallback = callback;
String authUrl = req.toUrl(urlCodex) + "&redirect_uri=" + urlCodex.encode(oauthWindowUrl);
// Try to look up the token we have stored.
final TokenInfo info = getToken(req);
if (info == null || info.getExpires() == null || expiringSoon(info)) {
// Token wasn't found, or doesn't have an expiration, or is expired or
// expiring soon. Requesting access will refresh the token.
doLogin(authUrl, callback);
} else {
// Token was found and is good, immediately execute the callback with the
// access token.
scheduler.scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
callback.onSuccess(info);
}
});
}
}
|
java
|
public void login(AuthRequest req, final Callback<TokenInfo, Throwable> callback) {
lastRequest = req;
lastCallback = callback;
String authUrl = req.toUrl(urlCodex) + "&redirect_uri=" + urlCodex.encode(oauthWindowUrl);
// Try to look up the token we have stored.
final TokenInfo info = getToken(req);
if (info == null || info.getExpires() == null || expiringSoon(info)) {
// Token wasn't found, or doesn't have an expiration, or is expired or
// expiring soon. Requesting access will refresh the token.
doLogin(authUrl, callback);
} else {
// Token was found and is good, immediately execute the callback with the
// access token.
scheduler.scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
callback.onSuccess(info);
}
});
}
}
|
[
"public",
"void",
"login",
"(",
"AuthRequest",
"req",
",",
"final",
"Callback",
"<",
"TokenInfo",
",",
"Throwable",
">",
"callback",
")",
"{",
"lastRequest",
"=",
"req",
";",
"lastCallback",
"=",
"callback",
";",
"String",
"authUrl",
"=",
"req",
".",
"toUrl",
"(",
"urlCodex",
")",
"+",
"\"&redirect_uri=\"",
"+",
"urlCodex",
".",
"encode",
"(",
"oauthWindowUrl",
")",
";",
"// Try to look up the token we have stored.",
"final",
"TokenInfo",
"info",
"=",
"getToken",
"(",
"req",
")",
";",
"if",
"(",
"info",
"==",
"null",
"||",
"info",
".",
"getExpires",
"(",
")",
"==",
"null",
"||",
"expiringSoon",
"(",
"info",
")",
")",
"{",
"// Token wasn't found, or doesn't have an expiration, or is expired or",
"// expiring soon. Requesting access will refresh the token.",
"doLogin",
"(",
"authUrl",
",",
"callback",
")",
";",
"}",
"else",
"{",
"// Token was found and is good, immediately execute the callback with the",
"// access token.",
"scheduler",
".",
"scheduleDeferred",
"(",
"new",
"ScheduledCommand",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"callback",
".",
"onSuccess",
"(",
"info",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Request an access token from an OAuth 2.0 provider.
<p/>
<p> If it can be determined that the user has already granted access, and the token has not yet expired, and that
the token will not expire soon, the existing token will be passed to the callback. </p>
<p/>
<p> Otherwise, a popup window will be displayed which may prompt the user to grant access. If the user has
already granted access the popup will immediately close and the token will be passed to the callback. If access
hasn't been granted, the user will be prompted, and when they grant, the token will be passed to the callback.
</p>
@param req Request for authentication.
@param callback Callback to pass the token to when access has been granted.
|
[
"Request",
"an",
"access",
"token",
"from",
"an",
"OAuth",
"2",
".",
"0",
"provider",
".",
"<p",
"/",
">",
"<p",
">",
"If",
"it",
"can",
"be",
"determined",
"that",
"the",
"user",
"has",
"already",
"granted",
"access",
"and",
"the",
"token",
"has",
"not",
"yet",
"expired",
"and",
"that",
"the",
"token",
"will",
"not",
"expire",
"soon",
"the",
"existing",
"token",
"will",
"be",
"passed",
"to",
"the",
"callback",
".",
"<",
"/",
"p",
">",
"<p",
"/",
">",
"<p",
">",
"Otherwise",
"a",
"popup",
"window",
"will",
"be",
"displayed",
"which",
"may",
"prompt",
"the",
"user",
"to",
"grant",
"access",
".",
"If",
"the",
"user",
"has",
"already",
"granted",
"access",
"the",
"popup",
"will",
"immediately",
"close",
"and",
"the",
"token",
"will",
"be",
"passed",
"to",
"the",
"callback",
".",
"If",
"access",
"hasn",
"t",
"been",
"granted",
"the",
"user",
"will",
"be",
"prompted",
"and",
"when",
"they",
"grant",
"the",
"token",
"will",
"be",
"passed",
"to",
"the",
"callback",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/reinert/requestor/blob/40163a75cd17815d5089935d0dd97b8d652ad6d4/requestor/ext/requestor-oauth2/src/main/java/io/reinert/requestor/oauth2/Auth.java#L73-L96
|
tvesalainen/util
|
util/src/main/java/org/vesalainen/nio/channels/GZIPChannel.java
|
GZIPChannel.extractAll
|
public void extractAll(Path targetDir, CopyOption... options) throws IOException {
"""
Extract files from this GZIPChannel to given directory.
@param targetDir
@param options
@throws IOException
"""
if (!Files.isDirectory(targetDir))
{
throw new NotDirectoryException(targetDir.toString());
}
ensureReading();
do
{
Path p = targetDir.resolve(filename);
InputStream is = Channels.newInputStream(this);
Files.copy(is, p, options);
Files.setLastModifiedTime(p, lastModified);
} while (nextInput());
}
|
java
|
public void extractAll(Path targetDir, CopyOption... options) throws IOException
{
if (!Files.isDirectory(targetDir))
{
throw new NotDirectoryException(targetDir.toString());
}
ensureReading();
do
{
Path p = targetDir.resolve(filename);
InputStream is = Channels.newInputStream(this);
Files.copy(is, p, options);
Files.setLastModifiedTime(p, lastModified);
} while (nextInput());
}
|
[
"public",
"void",
"extractAll",
"(",
"Path",
"targetDir",
",",
"CopyOption",
"...",
"options",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"Files",
".",
"isDirectory",
"(",
"targetDir",
")",
")",
"{",
"throw",
"new",
"NotDirectoryException",
"(",
"targetDir",
".",
"toString",
"(",
")",
")",
";",
"}",
"ensureReading",
"(",
")",
";",
"do",
"{",
"Path",
"p",
"=",
"targetDir",
".",
"resolve",
"(",
"filename",
")",
";",
"InputStream",
"is",
"=",
"Channels",
".",
"newInputStream",
"(",
"this",
")",
";",
"Files",
".",
"copy",
"(",
"is",
",",
"p",
",",
"options",
")",
";",
"Files",
".",
"setLastModifiedTime",
"(",
"p",
",",
"lastModified",
")",
";",
"}",
"while",
"(",
"nextInput",
"(",
")",
")",
";",
"}"
] |
Extract files from this GZIPChannel to given directory.
@param targetDir
@param options
@throws IOException
|
[
"Extract",
"files",
"from",
"this",
"GZIPChannel",
"to",
"given",
"directory",
"."
] |
train
|
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/channels/GZIPChannel.java#L220-L234
|
aspectran/aspectran
|
core/src/main/java/com/aspectran/core/util/ReflectionUtils.java
|
ReflectionUtils.invokeMethod
|
public static Object invokeMethod(Method method, Object target, Object... args) {
"""
Invoke the specified {@link Method} against the supplied target object with the
supplied arguments. The target object can be {@code null} when invoking a
static {@link Method}.
@param method the method to invoke
@param target the target object to invoke the method on
@param args the invocation arguments (may be {@code null})
@return the invocation result, if any
"""
try {
return method.invoke(target, args);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Could not access method: " + method, ExceptionUtils.getRootCause(e));
}
}
|
java
|
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Could not access method: " + method, ExceptionUtils.getRootCause(e));
}
}
|
[
"public",
"static",
"Object",
"invokeMethod",
"(",
"Method",
"method",
",",
"Object",
"target",
",",
"Object",
"...",
"args",
")",
"{",
"try",
"{",
"return",
"method",
".",
"invoke",
"(",
"target",
",",
"args",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"|",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Could not access method: \"",
"+",
"method",
",",
"ExceptionUtils",
".",
"getRootCause",
"(",
"e",
")",
")",
";",
"}",
"}"
] |
Invoke the specified {@link Method} against the supplied target object with the
supplied arguments. The target object can be {@code null} when invoking a
static {@link Method}.
@param method the method to invoke
@param target the target object to invoke the method on
@param args the invocation arguments (may be {@code null})
@return the invocation result, if any
|
[
"Invoke",
"the",
"specified",
"{",
"@link",
"Method",
"}",
"against",
"the",
"supplied",
"target",
"object",
"with",
"the",
"supplied",
"arguments",
".",
"The",
"target",
"object",
"can",
"be",
"{",
"@code",
"null",
"}",
"when",
"invoking",
"a",
"static",
"{",
"@link",
"Method",
"}",
"."
] |
train
|
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ReflectionUtils.java#L76-L82
|
kuali/ojb-1.0.4
|
src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java
|
OjbTagsHandler.ifPropertyValueEquals
|
public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException {
"""
Processes the template if the property value of the current object on the specified level equals the given value.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException If an error occurs
@doc.tag type="block"
@doc.param name="level" optional="false" description="The level for the current object"
values="class,field,reference,collection"
@doc.param name="name" optional="false" description="The name of the property"
@doc.param name="value" optional="false" description="The value to check for"
@doc.param name="default" optional="true" description="A default value to use if the property
is not defined"
"""
String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));
String expected = attributes.getProperty(ATTRIBUTE_VALUE);
if (value == null)
{
value = attributes.getProperty(ATTRIBUTE_DEFAULT);
}
if (expected.equals(value))
{
generate(template);
}
}
|
java
|
public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException
{
String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));
String expected = attributes.getProperty(ATTRIBUTE_VALUE);
if (value == null)
{
value = attributes.getProperty(ATTRIBUTE_DEFAULT);
}
if (expected.equals(value))
{
generate(template);
}
}
|
[
"public",
"void",
"ifPropertyValueEquals",
"(",
"String",
"template",
",",
"Properties",
"attributes",
")",
"throws",
"XDocletException",
"{",
"String",
"value",
"=",
"getPropertyValue",
"(",
"attributes",
".",
"getProperty",
"(",
"ATTRIBUTE_LEVEL",
")",
",",
"attributes",
".",
"getProperty",
"(",
"ATTRIBUTE_NAME",
")",
")",
";",
"String",
"expected",
"=",
"attributes",
".",
"getProperty",
"(",
"ATTRIBUTE_VALUE",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"value",
"=",
"attributes",
".",
"getProperty",
"(",
"ATTRIBUTE_DEFAULT",
")",
";",
"}",
"if",
"(",
"expected",
".",
"equals",
"(",
"value",
")",
")",
"{",
"generate",
"(",
"template",
")",
";",
"}",
"}"
] |
Processes the template if the property value of the current object on the specified level equals the given value.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException If an error occurs
@doc.tag type="block"
@doc.param name="level" optional="false" description="The level for the current object"
values="class,field,reference,collection"
@doc.param name="name" optional="false" description="The name of the property"
@doc.param name="value" optional="false" description="The value to check for"
@doc.param name="default" optional="true" description="A default value to use if the property
is not defined"
|
[
"Processes",
"the",
"template",
"if",
"the",
"property",
"value",
"of",
"the",
"current",
"object",
"on",
"the",
"specified",
"level",
"equals",
"the",
"given",
"value",
"."
] |
train
|
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1560-L1573
|
geomajas/geomajas-project-client-gwt2
|
impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java
|
JsonService.getGeometryValue
|
public static Geometry getGeometryValue(JSONObject jsonObject, String key) throws JSONException {
"""
Get a geometry value from a {@link JSONObject}.
@param jsonObject The object to get the key value from.
@param key The name of the key to search the value for.
@return Returns the value for the key in the object or null.
@throws JSONException Thrown in case the key could not be found in the JSON object, or if the date could not be
parsed correctly.
"""
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isObject() != null) {
JSONObject obj = value.isObject();
String type = JsonService.getStringValue(obj, "type");
Geometry geometry = new Geometry(type, 0, 5);
JSONArray array = JsonService.getChildArray(obj, "coordinates");
switch (GeometryType.fromValue(type)) {
case POINT:
parseSimple(GeometryType.POINT, geometry, array);
break;
case LINESTRING:
parseSimple(GeometryType.LINEARRING, geometry, array);
break;
case MULTILINESTRING:
parseCollection(GeometryType.LINESTRING, geometry, array);
break;
case MULTIPOINT:
parseCollection(GeometryType.POINT, geometry, array);
break;
case MULTIPOLYGON:
parseCollection(GeometryType.POLYGON, geometry, array);
break;
case POLYGON:
parseCollection(GeometryType.LINEARRING, geometry, array);
break;
default:
break;
}
return geometry;
}
return null;
}
|
java
|
public static Geometry getGeometryValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isObject() != null) {
JSONObject obj = value.isObject();
String type = JsonService.getStringValue(obj, "type");
Geometry geometry = new Geometry(type, 0, 5);
JSONArray array = JsonService.getChildArray(obj, "coordinates");
switch (GeometryType.fromValue(type)) {
case POINT:
parseSimple(GeometryType.POINT, geometry, array);
break;
case LINESTRING:
parseSimple(GeometryType.LINEARRING, geometry, array);
break;
case MULTILINESTRING:
parseCollection(GeometryType.LINESTRING, geometry, array);
break;
case MULTIPOINT:
parseCollection(GeometryType.POINT, geometry, array);
break;
case MULTIPOLYGON:
parseCollection(GeometryType.POLYGON, geometry, array);
break;
case POLYGON:
parseCollection(GeometryType.LINEARRING, geometry, array);
break;
default:
break;
}
return geometry;
}
return null;
}
|
[
"public",
"static",
"Geometry",
"getGeometryValue",
"(",
"JSONObject",
"jsonObject",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"checkArguments",
"(",
"jsonObject",
",",
"key",
")",
";",
"JSONValue",
"value",
"=",
"jsonObject",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"!=",
"null",
"&&",
"value",
".",
"isObject",
"(",
")",
"!=",
"null",
")",
"{",
"JSONObject",
"obj",
"=",
"value",
".",
"isObject",
"(",
")",
";",
"String",
"type",
"=",
"JsonService",
".",
"getStringValue",
"(",
"obj",
",",
"\"type\"",
")",
";",
"Geometry",
"geometry",
"=",
"new",
"Geometry",
"(",
"type",
",",
"0",
",",
"5",
")",
";",
"JSONArray",
"array",
"=",
"JsonService",
".",
"getChildArray",
"(",
"obj",
",",
"\"coordinates\"",
")",
";",
"switch",
"(",
"GeometryType",
".",
"fromValue",
"(",
"type",
")",
")",
"{",
"case",
"POINT",
":",
"parseSimple",
"(",
"GeometryType",
".",
"POINT",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"case",
"LINESTRING",
":",
"parseSimple",
"(",
"GeometryType",
".",
"LINEARRING",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"case",
"MULTILINESTRING",
":",
"parseCollection",
"(",
"GeometryType",
".",
"LINESTRING",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"case",
"MULTIPOINT",
":",
"parseCollection",
"(",
"GeometryType",
".",
"POINT",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"case",
"MULTIPOLYGON",
":",
"parseCollection",
"(",
"GeometryType",
".",
"POLYGON",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"case",
"POLYGON",
":",
"parseCollection",
"(",
"GeometryType",
".",
"LINEARRING",
",",
"geometry",
",",
"array",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"return",
"geometry",
";",
"}",
"return",
"null",
";",
"}"
] |
Get a geometry value from a {@link JSONObject}.
@param jsonObject The object to get the key value from.
@param key The name of the key to search the value for.
@return Returns the value for the key in the object or null.
@throws JSONException Thrown in case the key could not be found in the JSON object, or if the date could not be
parsed correctly.
|
[
"Get",
"a",
"geometry",
"value",
"from",
"a",
"{",
"@link",
"JSONObject",
"}",
"."
] |
train
|
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java#L216-L249
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
|
ApiOvhOrder.cdn_dedicated_serviceName_quota_duration_GET
|
public OvhOrder cdn_dedicated_serviceName_quota_duration_GET(String serviceName, String duration, OvhOrderQuotaEnum quota) throws IOException {
"""
Get prices and contracts information
REST: GET /order/cdn/dedicated/{serviceName}/quota/{duration}
@param quota [required] quota number in TB that will be added to the CDN service
@param serviceName [required] The internal name of your CDN offer
@param duration [required] Duration
"""
String qPath = "/order/cdn/dedicated/{serviceName}/quota/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
query(sb, "quota", quota);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
}
|
java
|
public OvhOrder cdn_dedicated_serviceName_quota_duration_GET(String serviceName, String duration, OvhOrderQuotaEnum quota) throws IOException {
String qPath = "/order/cdn/dedicated/{serviceName}/quota/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
query(sb, "quota", quota);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
}
|
[
"public",
"OvhOrder",
"cdn_dedicated_serviceName_quota_duration_GET",
"(",
"String",
"serviceName",
",",
"String",
"duration",
",",
"OvhOrderQuotaEnum",
"quota",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cdn/dedicated/{serviceName}/quota/{duration}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"duration",
")",
";",
"query",
"(",
"sb",
",",
"\"quota\"",
",",
"quota",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhOrder",
".",
"class",
")",
";",
"}"
] |
Get prices and contracts information
REST: GET /order/cdn/dedicated/{serviceName}/quota/{duration}
@param quota [required] quota number in TB that will be added to the CDN service
@param serviceName [required] The internal name of your CDN offer
@param duration [required] Duration
|
[
"Get",
"prices",
"and",
"contracts",
"information"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5353-L5359
|
BBN-E/bue-common-open
|
common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java
|
FileUtils.loadStringMapAllowingEmptyValues
|
public static ImmutableMap<String, String> loadStringMapAllowingEmptyValues(CharSource source)
throws IOException {
"""
Like {@link #loadStringMap(CharSource)}, but differs in that lines can contain only
a key and no value and will be treated as having a value of empty string in the resulting
map. This is useful for specifying absent values for a specific key.
@see FileUtils#loadStringMap(CharSource)
"""
return loadStringMap(source, true);
}
|
java
|
public static ImmutableMap<String, String> loadStringMapAllowingEmptyValues(CharSource source)
throws IOException {
return loadStringMap(source, true);
}
|
[
"public",
"static",
"ImmutableMap",
"<",
"String",
",",
"String",
">",
"loadStringMapAllowingEmptyValues",
"(",
"CharSource",
"source",
")",
"throws",
"IOException",
"{",
"return",
"loadStringMap",
"(",
"source",
",",
"true",
")",
";",
"}"
] |
Like {@link #loadStringMap(CharSource)}, but differs in that lines can contain only
a key and no value and will be treated as having a value of empty string in the resulting
map. This is useful for specifying absent values for a specific key.
@see FileUtils#loadStringMap(CharSource)
|
[
"Like",
"{",
"@link",
"#loadStringMap",
"(",
"CharSource",
")",
"}",
"but",
"differs",
"in",
"that",
"lines",
"can",
"contain",
"only",
"a",
"key",
"and",
"no",
"value",
"and",
"will",
"be",
"treated",
"as",
"having",
"a",
"value",
"of",
"empty",
"string",
"in",
"the",
"resulting",
"map",
".",
"This",
"is",
"useful",
"for",
"specifying",
"absent",
"values",
"for",
"a",
"specific",
"key",
"."
] |
train
|
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/files/FileUtils.java#L687-L690
|
alkacon/opencms-core
|
src/org/opencms/file/CmsLinkRewriter.java
|
CmsLinkRewriter.checkNotSubPath
|
protected void checkNotSubPath(String source, String target) {
"""
Checks that the target path is not a subfolder of the source path.<p>
@param source the source path
@param target the target path
"""
source = CmsStringUtil.joinPaths("/", source, "/");
target = CmsStringUtil.joinPaths("/", target, "/");
if (target.startsWith(source)) {
throw new CmsIllegalArgumentException(
org.opencms.file.Messages.get().container(
org.opencms.file.Messages.ERR_REWRITE_LINKS_ROOTS_DEPENDENT_2,
source,
target));
}
}
|
java
|
protected void checkNotSubPath(String source, String target) {
source = CmsStringUtil.joinPaths("/", source, "/");
target = CmsStringUtil.joinPaths("/", target, "/");
if (target.startsWith(source)) {
throw new CmsIllegalArgumentException(
org.opencms.file.Messages.get().container(
org.opencms.file.Messages.ERR_REWRITE_LINKS_ROOTS_DEPENDENT_2,
source,
target));
}
}
|
[
"protected",
"void",
"checkNotSubPath",
"(",
"String",
"source",
",",
"String",
"target",
")",
"{",
"source",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"\"/\"",
",",
"source",
",",
"\"/\"",
")",
";",
"target",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"\"/\"",
",",
"target",
",",
"\"/\"",
")",
";",
"if",
"(",
"target",
".",
"startsWith",
"(",
"source",
")",
")",
"{",
"throw",
"new",
"CmsIllegalArgumentException",
"(",
"org",
".",
"opencms",
".",
"file",
".",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"org",
".",
"opencms",
".",
"file",
".",
"Messages",
".",
"ERR_REWRITE_LINKS_ROOTS_DEPENDENT_2",
",",
"source",
",",
"target",
")",
")",
";",
"}",
"}"
] |
Checks that the target path is not a subfolder of the source path.<p>
@param source the source path
@param target the target path
|
[
"Checks",
"that",
"the",
"target",
"path",
"is",
"not",
"a",
"subfolder",
"of",
"the",
"source",
"path",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsLinkRewriter.java#L280-L291
|
haifengl/smile
|
math/src/main/java/smile/sort/SortUtils.java
|
SortUtils.siftUp
|
public static void siftUp(int[] arr, int k) {
"""
To restore the max-heap condition when a node's priority is increased.
We move up the heap, exchaning the node at position k with its parent
(at postion k/2) if necessary, continuing as long as a[k/2] < a[k] or
until we reach the top of the heap.
"""
while (k > 1 && arr[k/2] < arr[k]) {
swap(arr, k, k/2);
k = k/2;
}
}
|
java
|
public static void siftUp(int[] arr, int k) {
while (k > 1 && arr[k/2] < arr[k]) {
swap(arr, k, k/2);
k = k/2;
}
}
|
[
"public",
"static",
"void",
"siftUp",
"(",
"int",
"[",
"]",
"arr",
",",
"int",
"k",
")",
"{",
"while",
"(",
"k",
">",
"1",
"&&",
"arr",
"[",
"k",
"/",
"2",
"]",
"<",
"arr",
"[",
"k",
"]",
")",
"{",
"swap",
"(",
"arr",
",",
"k",
",",
"k",
"/",
"2",
")",
";",
"k",
"=",
"k",
"/",
"2",
";",
"}",
"}"
] |
To restore the max-heap condition when a node's priority is increased.
We move up the heap, exchaning the node at position k with its parent
(at postion k/2) if necessary, continuing as long as a[k/2] < a[k] or
until we reach the top of the heap.
|
[
"To",
"restore",
"the",
"max",
"-",
"heap",
"condition",
"when",
"a",
"node",
"s",
"priority",
"is",
"increased",
".",
"We",
"move",
"up",
"the",
"heap",
"exchaning",
"the",
"node",
"at",
"position",
"k",
"with",
"its",
"parent",
"(",
"at",
"postion",
"k",
"/",
"2",
")",
"if",
"necessary",
"continuing",
"as",
"long",
"as",
"a",
"[",
"k",
"/",
"2",
"]",
"<",
";",
"a",
"[",
"k",
"]",
"or",
"until",
"we",
"reach",
"the",
"top",
"of",
"the",
"heap",
"."
] |
train
|
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/sort/SortUtils.java#L75-L80
|
matthewhorridge/owlapi-gwt
|
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLFunctionalObjectPropertyAxiomImpl_CustomFieldSerializer.java
|
OWLFunctionalObjectPropertyAxiomImpl_CustomFieldSerializer.serializeInstance
|
@Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLFunctionalObjectPropertyAxiomImpl instance) throws SerializationException {
"""
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
"""
serialize(streamWriter, instance);
}
|
java
|
@Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLFunctionalObjectPropertyAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
}
|
[
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLFunctionalObjectPropertyAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] |
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
|
[
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
] |
train
|
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLFunctionalObjectPropertyAxiomImpl_CustomFieldSerializer.java#L75-L78
|
alkacon/opencms-core
|
src/org/opencms/staticexport/CmsStaticExportRfsRule.java
|
CmsStaticExportRfsRule.getLocalizedRfsName
|
public String getLocalizedRfsName(String rfsName, String fileSeparator) {
"""
Returns the rfs name for the given locale, only used for multi-language export.<p>
@param rfsName the original rfs name
@param fileSeparator the file separator to use
@return the rfs name for the given locale
"""
String locRfsName = null;
// this might be too simple
locRfsName = CmsStringUtil.substitute(
rfsName,
fileSeparator + CmsLocaleManager.getDefaultLocale().toString() + fileSeparator,
fileSeparator + getName() + fileSeparator);
return locRfsName;
}
|
java
|
public String getLocalizedRfsName(String rfsName, String fileSeparator) {
String locRfsName = null;
// this might be too simple
locRfsName = CmsStringUtil.substitute(
rfsName,
fileSeparator + CmsLocaleManager.getDefaultLocale().toString() + fileSeparator,
fileSeparator + getName() + fileSeparator);
return locRfsName;
}
|
[
"public",
"String",
"getLocalizedRfsName",
"(",
"String",
"rfsName",
",",
"String",
"fileSeparator",
")",
"{",
"String",
"locRfsName",
"=",
"null",
";",
"// this might be too simple",
"locRfsName",
"=",
"CmsStringUtil",
".",
"substitute",
"(",
"rfsName",
",",
"fileSeparator",
"+",
"CmsLocaleManager",
".",
"getDefaultLocale",
"(",
")",
".",
"toString",
"(",
")",
"+",
"fileSeparator",
",",
"fileSeparator",
"+",
"getName",
"(",
")",
"+",
"fileSeparator",
")",
";",
"return",
"locRfsName",
";",
"}"
] |
Returns the rfs name for the given locale, only used for multi-language export.<p>
@param rfsName the original rfs name
@param fileSeparator the file separator to use
@return the rfs name for the given locale
|
[
"Returns",
"the",
"rfs",
"name",
"for",
"the",
"given",
"locale",
"only",
"used",
"for",
"multi",
"-",
"language",
"export",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportRfsRule.java#L238-L248
|
google/auto
|
common/src/main/java/com/google/auto/common/SimpleAnnotationMirror.java
|
SimpleAnnotationMirror.of
|
public static AnnotationMirror of(
TypeElement annotationType, Map<String, ? extends AnnotationValue> namedValues) {
"""
An object representing an {@linkplain ElementKind#ANNOTATION_TYPE annotation} instance. If
{@code annotationType} has any annotation members, they must either be present in {@code
namedValues} or have default values.
"""
return new SimpleAnnotationMirror(annotationType, namedValues);
}
|
java
|
public static AnnotationMirror of(
TypeElement annotationType, Map<String, ? extends AnnotationValue> namedValues) {
return new SimpleAnnotationMirror(annotationType, namedValues);
}
|
[
"public",
"static",
"AnnotationMirror",
"of",
"(",
"TypeElement",
"annotationType",
",",
"Map",
"<",
"String",
",",
"?",
"extends",
"AnnotationValue",
">",
"namedValues",
")",
"{",
"return",
"new",
"SimpleAnnotationMirror",
"(",
"annotationType",
",",
"namedValues",
")",
";",
"}"
] |
An object representing an {@linkplain ElementKind#ANNOTATION_TYPE annotation} instance. If
{@code annotationType} has any annotation members, they must either be present in {@code
namedValues} or have default values.
|
[
"An",
"object",
"representing",
"an",
"{"
] |
train
|
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/SimpleAnnotationMirror.java#L98-L101
|
jayantk/jklol
|
src/com/jayantkrish/jklol/lisp/LispUtil.java
|
LispUtil.checkNotNull
|
public static void checkNotNull(Object ref, String message, Object ... values) {
"""
Identical to Preconditions.checkNotNull but throws an
{@code EvalError} instead of an IllegalArgumentException.
Use this check to verify properties of a Lisp program
execution, i.e., whenever the raised exception should be
catchable by the evaluator of the program.
@param condition
@param message
@param values
"""
if (ref == null) {
throw new EvalError(String.format(message, values));
}
}
|
java
|
public static void checkNotNull(Object ref, String message, Object ... values) {
if (ref == null) {
throw new EvalError(String.format(message, values));
}
}
|
[
"public",
"static",
"void",
"checkNotNull",
"(",
"Object",
"ref",
",",
"String",
"message",
",",
"Object",
"...",
"values",
")",
"{",
"if",
"(",
"ref",
"==",
"null",
")",
"{",
"throw",
"new",
"EvalError",
"(",
"String",
".",
"format",
"(",
"message",
",",
"values",
")",
")",
";",
"}",
"}"
] |
Identical to Preconditions.checkNotNull but throws an
{@code EvalError} instead of an IllegalArgumentException.
Use this check to verify properties of a Lisp program
execution, i.e., whenever the raised exception should be
catchable by the evaluator of the program.
@param condition
@param message
@param values
|
[
"Identical",
"to",
"Preconditions",
".",
"checkNotNull",
"but",
"throws",
"an",
"{",
"@code",
"EvalError",
"}",
"instead",
"of",
"an",
"IllegalArgumentException",
".",
"Use",
"this",
"check",
"to",
"verify",
"properties",
"of",
"a",
"Lisp",
"program",
"execution",
"i",
".",
"e",
".",
"whenever",
"the",
"raised",
"exception",
"should",
"be",
"catchable",
"by",
"the",
"evaluator",
"of",
"the",
"program",
"."
] |
train
|
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/lisp/LispUtil.java#L77-L81
|
foundation-runtime/service-directory
|
1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/DirectoryLookupService.java
|
DirectoryLookupService.getModelServiceInstanceByAddress
|
public ModelServiceInstance getModelServiceInstanceByAddress(String serviceName, String instanceAddress) {
"""
Get the ModelServiceInstance by serviceName and instanceAddress.
@param serviceName the service name.
@param instanceAddress the instanceAddress.
@return the ModelServiceInstance.
@since 1.2
"""
ModelService service = getModelService(serviceName);
if (service != null && service.getServiceInstances() != null) {
for (ModelServiceInstance instance : service.getServiceInstances()) {
if (instance.getAddress().equals(instanceAddress)) {
return instance;
}
}
}
return null;
}
|
java
|
public ModelServiceInstance getModelServiceInstanceByAddress(String serviceName, String instanceAddress) {
ModelService service = getModelService(serviceName);
if (service != null && service.getServiceInstances() != null) {
for (ModelServiceInstance instance : service.getServiceInstances()) {
if (instance.getAddress().equals(instanceAddress)) {
return instance;
}
}
}
return null;
}
|
[
"public",
"ModelServiceInstance",
"getModelServiceInstanceByAddress",
"(",
"String",
"serviceName",
",",
"String",
"instanceAddress",
")",
"{",
"ModelService",
"service",
"=",
"getModelService",
"(",
"serviceName",
")",
";",
"if",
"(",
"service",
"!=",
"null",
"&&",
"service",
".",
"getServiceInstances",
"(",
")",
"!=",
"null",
")",
"{",
"for",
"(",
"ModelServiceInstance",
"instance",
":",
"service",
".",
"getServiceInstances",
"(",
")",
")",
"{",
"if",
"(",
"instance",
".",
"getAddress",
"(",
")",
".",
"equals",
"(",
"instanceAddress",
")",
")",
"{",
"return",
"instance",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] |
Get the ModelServiceInstance by serviceName and instanceAddress.
@param serviceName the service name.
@param instanceAddress the instanceAddress.
@return the ModelServiceInstance.
@since 1.2
|
[
"Get",
"the",
"ModelServiceInstance",
"by",
"serviceName",
"and",
"instanceAddress",
"."
] |
train
|
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/DirectoryLookupService.java#L313-L323
|
zaproxy/zaproxy
|
src/org/parosproxy/paros/core/scanner/AbstractAppParamPlugin.java
|
AbstractAppParamPlugin.setEscapedParameter
|
protected String setEscapedParameter(HttpMessage message, String param, String value) {
"""
Sets the parameter into the given {@code message}. If both parameter name and value are {@code null}, the parameter will
be removed.
<p>
The value is expected to be properly encoded/escaped.
@param message the message that will be changed
@param param the name of the parameter
@param value the value of the parameter
@return the parameter set
@see #setParameter(HttpMessage, String, String)
"""
return variant.setEscapedParameter(message, originalPair, param, value);
}
|
java
|
protected String setEscapedParameter(HttpMessage message, String param, String value) {
return variant.setEscapedParameter(message, originalPair, param, value);
}
|
[
"protected",
"String",
"setEscapedParameter",
"(",
"HttpMessage",
"message",
",",
"String",
"param",
",",
"String",
"value",
")",
"{",
"return",
"variant",
".",
"setEscapedParameter",
"(",
"message",
",",
"originalPair",
",",
"param",
",",
"value",
")",
";",
"}"
] |
Sets the parameter into the given {@code message}. If both parameter name and value are {@code null}, the parameter will
be removed.
<p>
The value is expected to be properly encoded/escaped.
@param message the message that will be changed
@param param the name of the parameter
@param value the value of the parameter
@return the parameter set
@see #setParameter(HttpMessage, String, String)
|
[
"Sets",
"the",
"parameter",
"into",
"the",
"given",
"{",
"@code",
"message",
"}",
".",
"If",
"both",
"parameter",
"name",
"and",
"value",
"are",
"{",
"@code",
"null",
"}",
"the",
"parameter",
"will",
"be",
"removed",
".",
"<p",
">",
"The",
"value",
"is",
"expected",
"to",
"be",
"properly",
"encoded",
"/",
"escaped",
"."
] |
train
|
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/AbstractAppParamPlugin.java#L301-L303
|
acromusashi/acromusashi-stream
|
src/main/java/acromusashi/stream/config/StormConfigGenerator.java
|
StormConfigGenerator.convertYamlToStormConf
|
public static Config convertYamlToStormConf(Map<String, Object> yamlConf) {
"""
Convert config read from yaml file config to storm config object.
@param yamlConf config read from yaml
@return Storm config object
"""
Config stormConf = new Config();
for (Entry<String, Object> targetConfigEntry : yamlConf.entrySet())
{
stormConf.put(targetConfigEntry.getKey(), targetConfigEntry.getValue());
}
return stormConf;
}
|
java
|
public static Config convertYamlToStormConf(Map<String, Object> yamlConf)
{
Config stormConf = new Config();
for (Entry<String, Object> targetConfigEntry : yamlConf.entrySet())
{
stormConf.put(targetConfigEntry.getKey(), targetConfigEntry.getValue());
}
return stormConf;
}
|
[
"public",
"static",
"Config",
"convertYamlToStormConf",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"yamlConf",
")",
"{",
"Config",
"stormConf",
"=",
"new",
"Config",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"targetConfigEntry",
":",
"yamlConf",
".",
"entrySet",
"(",
")",
")",
"{",
"stormConf",
".",
"put",
"(",
"targetConfigEntry",
".",
"getKey",
"(",
")",
",",
"targetConfigEntry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"stormConf",
";",
"}"
] |
Convert config read from yaml file config to storm config object.
@param yamlConf config read from yaml
@return Storm config object
|
[
"Convert",
"config",
"read",
"from",
"yaml",
"file",
"config",
"to",
"storm",
"config",
"object",
"."
] |
train
|
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/StormConfigGenerator.java#L96-L106
|
pac4j/pac4j
|
pac4j-core/src/main/java/org/pac4j/core/util/JavaSerializationHelper.java
|
JavaSerializationHelper.deserializeFromBytes
|
public Serializable deserializeFromBytes(final byte[] bytes) {
"""
Deserialize a bytes array into a Java object.
@param bytes the serialized object as a bytes array
@return the deserialized Java object
"""
Serializable o = null;
try (final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
final ObjectInputStream ois = new RestrictedObjectInputStream(bais, this.trustedPackages, this.trustedClasses)) {
o = (Serializable) ois.readObject();
} catch (final IOException | ClassNotFoundException e) {
logger.warn("cannot Java deserialize object", e);
}
return o;
}
|
java
|
public Serializable deserializeFromBytes(final byte[] bytes) {
Serializable o = null;
try (final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
final ObjectInputStream ois = new RestrictedObjectInputStream(bais, this.trustedPackages, this.trustedClasses)) {
o = (Serializable) ois.readObject();
} catch (final IOException | ClassNotFoundException e) {
logger.warn("cannot Java deserialize object", e);
}
return o;
}
|
[
"public",
"Serializable",
"deserializeFromBytes",
"(",
"final",
"byte",
"[",
"]",
"bytes",
")",
"{",
"Serializable",
"o",
"=",
"null",
";",
"try",
"(",
"final",
"ByteArrayInputStream",
"bais",
"=",
"new",
"ByteArrayInputStream",
"(",
"bytes",
")",
";",
"final",
"ObjectInputStream",
"ois",
"=",
"new",
"RestrictedObjectInputStream",
"(",
"bais",
",",
"this",
".",
"trustedPackages",
",",
"this",
".",
"trustedClasses",
")",
")",
"{",
"o",
"=",
"(",
"Serializable",
")",
"ois",
".",
"readObject",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"|",
"ClassNotFoundException",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"cannot Java deserialize object\"",
",",
"e",
")",
";",
"}",
"return",
"o",
";",
"}"
] |
Deserialize a bytes array into a Java object.
@param bytes the serialized object as a bytes array
@return the deserialized Java object
|
[
"Deserialize",
"a",
"bytes",
"array",
"into",
"a",
"Java",
"object",
"."
] |
train
|
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/util/JavaSerializationHelper.java#L77-L86
|
intellimate/Izou
|
src/main/java/org/intellimate/izou/security/RootPermission.java
|
RootPermission.checkPermission
|
@Override
public void checkPermission(Permission permission, AddOnModel addon) throws IzouPermissionException {
"""
Checks if the given addOn is allowed to access the requested service and registers them if not yet registered.
@param permission the Permission to check
@param addon the identifiable to check
@throws IzouPermissionException thrown if the addOn is not allowed to access its requested service
"""
if (isRegistered(addon))
return;
if (permission instanceof FilePermission && !permission.getActions().intern().toLowerCase().equals("read")) {
String canonicalName = permission.getName().intern().toLowerCase();
getSecurityManager().getPermissionManager().getFilePermissionModule().fileWriteCheck(canonicalName, addon);
}
Function<PluginDescriptor, Boolean> checkPermission = descriptor -> {
try {
return descriptor.getAddOnProperties().get("root").equals("true");
} catch (NullPointerException e) {
return false;
}
};
String exceptionMessage = "Root permission denied for: " + addon + "is not registered to "
+ "use socket root connections.";
registerOrThrow(addon, () -> new IzouSocketPermissionException(exceptionMessage), checkPermission);
}
|
java
|
@Override
public void checkPermission(Permission permission, AddOnModel addon) throws IzouPermissionException {
if (isRegistered(addon))
return;
if (permission instanceof FilePermission && !permission.getActions().intern().toLowerCase().equals("read")) {
String canonicalName = permission.getName().intern().toLowerCase();
getSecurityManager().getPermissionManager().getFilePermissionModule().fileWriteCheck(canonicalName, addon);
}
Function<PluginDescriptor, Boolean> checkPermission = descriptor -> {
try {
return descriptor.getAddOnProperties().get("root").equals("true");
} catch (NullPointerException e) {
return false;
}
};
String exceptionMessage = "Root permission denied for: " + addon + "is not registered to "
+ "use socket root connections.";
registerOrThrow(addon, () -> new IzouSocketPermissionException(exceptionMessage), checkPermission);
}
|
[
"@",
"Override",
"public",
"void",
"checkPermission",
"(",
"Permission",
"permission",
",",
"AddOnModel",
"addon",
")",
"throws",
"IzouPermissionException",
"{",
"if",
"(",
"isRegistered",
"(",
"addon",
")",
")",
"return",
";",
"if",
"(",
"permission",
"instanceof",
"FilePermission",
"&&",
"!",
"permission",
".",
"getActions",
"(",
")",
".",
"intern",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"read\"",
")",
")",
"{",
"String",
"canonicalName",
"=",
"permission",
".",
"getName",
"(",
")",
".",
"intern",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"getSecurityManager",
"(",
")",
".",
"getPermissionManager",
"(",
")",
".",
"getFilePermissionModule",
"(",
")",
".",
"fileWriteCheck",
"(",
"canonicalName",
",",
"addon",
")",
";",
"}",
"Function",
"<",
"PluginDescriptor",
",",
"Boolean",
">",
"checkPermission",
"=",
"descriptor",
"->",
"{",
"try",
"{",
"return",
"descriptor",
".",
"getAddOnProperties",
"(",
")",
".",
"get",
"(",
"\"root\"",
")",
".",
"equals",
"(",
"\"true\"",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}",
";",
"String",
"exceptionMessage",
"=",
"\"Root permission denied for: \"",
"+",
"addon",
"+",
"\"is not registered to \"",
"+",
"\"use socket root connections.\"",
";",
"registerOrThrow",
"(",
"addon",
",",
"(",
")",
"->",
"new",
"IzouSocketPermissionException",
"(",
"exceptionMessage",
")",
",",
"checkPermission",
")",
";",
"}"
] |
Checks if the given addOn is allowed to access the requested service and registers them if not yet registered.
@param permission the Permission to check
@param addon the identifiable to check
@throws IzouPermissionException thrown if the addOn is not allowed to access its requested service
|
[
"Checks",
"if",
"the",
"given",
"addOn",
"is",
"allowed",
"to",
"access",
"the",
"requested",
"service",
"and",
"registers",
"them",
"if",
"not",
"yet",
"registered",
"."
] |
train
|
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/RootPermission.java#L46-L67
|
joniles/mpxj
|
src/main/java/net/sf/mpxj/Task.java
|
Task.setBaselineCost
|
public void setBaselineCost(int baselineNumber, Number value) {
"""
Set a baseline value.
@param baselineNumber baseline index (1-10)
@param value baseline value
"""
set(selectField(TaskFieldLists.BASELINE_COSTS, baselineNumber), value);
}
|
java
|
public void setBaselineCost(int baselineNumber, Number value)
{
set(selectField(TaskFieldLists.BASELINE_COSTS, baselineNumber), value);
}
|
[
"public",
"void",
"setBaselineCost",
"(",
"int",
"baselineNumber",
",",
"Number",
"value",
")",
"{",
"set",
"(",
"selectField",
"(",
"TaskFieldLists",
".",
"BASELINE_COSTS",
",",
"baselineNumber",
")",
",",
"value",
")",
";",
"}"
] |
Set a baseline value.
@param baselineNumber baseline index (1-10)
@param value baseline value
|
[
"Set",
"a",
"baseline",
"value",
"."
] |
train
|
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L3980-L3983
|
Ellzord/JALSE
|
src/main/java/jalse/entities/Entities.java
|
Entities.withinSameTree
|
public static boolean withinSameTree(final EntityContainer one, final EntityContainer two) {
"""
Checks to see if an container is in the same tree as the other container (checking highest
parent container).
@param one
Container to check.
@param two
Container to check.
@return Whether the container is within the same tree as the other container.
@see #getRootContainer(EntityContainer)
"""
return Objects.equals(getRootContainer(one), getRootContainer(two));
}
|
java
|
public static boolean withinSameTree(final EntityContainer one, final EntityContainer two) {
return Objects.equals(getRootContainer(one), getRootContainer(two));
}
|
[
"public",
"static",
"boolean",
"withinSameTree",
"(",
"final",
"EntityContainer",
"one",
",",
"final",
"EntityContainer",
"two",
")",
"{",
"return",
"Objects",
".",
"equals",
"(",
"getRootContainer",
"(",
"one",
")",
",",
"getRootContainer",
"(",
"two",
")",
")",
";",
"}"
] |
Checks to see if an container is in the same tree as the other container (checking highest
parent container).
@param one
Container to check.
@param two
Container to check.
@return Whether the container is within the same tree as the other container.
@see #getRootContainer(EntityContainer)
|
[
"Checks",
"to",
"see",
"if",
"an",
"container",
"is",
"in",
"the",
"same",
"tree",
"as",
"the",
"other",
"container",
"(",
"checking",
"highest",
"parent",
"container",
")",
"."
] |
train
|
https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/Entities.java#L539-L541
|
pressgang-ccms/PressGangCCMSBuilder
|
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java
|
DocBookBuilder.createDummyTranslatedTopic
|
private TranslatedTopicWrapper createDummyTranslatedTopic(final TopicWrapper topic, final LocaleWrapper locale) {
"""
Creates a dummy translated topic so that a book can be built using the same relationships as a normal build.
@param topic The topic to create the dummy topic from.
@param locale The locale to build the dummy translations for.
@return The dummy translated topic.
"""
final TranslatedTopicWrapper translatedTopic = translatedTopicProvider.newTranslatedTopic();
translatedTopic.setTopic(topic);
translatedTopic.setId(topic.getId() * -1);
// If we get to this point then no translation exists or the default locale translation failed to be downloaded.
translatedTopic.setTopicId(topic.getId());
translatedTopic.setTopicRevision(topic.getRevision());
translatedTopic.setTranslationPercentage(100);
translatedTopic.setXml(topic.getXml());
translatedTopic.setTags(topic.getTags());
translatedTopic.setSourceURLs(topic.getSourceURLs());
translatedTopic.setProperties(topic.getProperties());
translatedTopic.setLocale(locale);
translatedTopic.setTitle(topic.getTitle());
return translatedTopic;
}
|
java
|
private TranslatedTopicWrapper createDummyTranslatedTopic(final TopicWrapper topic, final LocaleWrapper locale) {
final TranslatedTopicWrapper translatedTopic = translatedTopicProvider.newTranslatedTopic();
translatedTopic.setTopic(topic);
translatedTopic.setId(topic.getId() * -1);
// If we get to this point then no translation exists or the default locale translation failed to be downloaded.
translatedTopic.setTopicId(topic.getId());
translatedTopic.setTopicRevision(topic.getRevision());
translatedTopic.setTranslationPercentage(100);
translatedTopic.setXml(topic.getXml());
translatedTopic.setTags(topic.getTags());
translatedTopic.setSourceURLs(topic.getSourceURLs());
translatedTopic.setProperties(topic.getProperties());
translatedTopic.setLocale(locale);
translatedTopic.setTitle(topic.getTitle());
return translatedTopic;
}
|
[
"private",
"TranslatedTopicWrapper",
"createDummyTranslatedTopic",
"(",
"final",
"TopicWrapper",
"topic",
",",
"final",
"LocaleWrapper",
"locale",
")",
"{",
"final",
"TranslatedTopicWrapper",
"translatedTopic",
"=",
"translatedTopicProvider",
".",
"newTranslatedTopic",
"(",
")",
";",
"translatedTopic",
".",
"setTopic",
"(",
"topic",
")",
";",
"translatedTopic",
".",
"setId",
"(",
"topic",
".",
"getId",
"(",
")",
"*",
"-",
"1",
")",
";",
"// If we get to this point then no translation exists or the default locale translation failed to be downloaded.",
"translatedTopic",
".",
"setTopicId",
"(",
"topic",
".",
"getId",
"(",
")",
")",
";",
"translatedTopic",
".",
"setTopicRevision",
"(",
"topic",
".",
"getRevision",
"(",
")",
")",
";",
"translatedTopic",
".",
"setTranslationPercentage",
"(",
"100",
")",
";",
"translatedTopic",
".",
"setXml",
"(",
"topic",
".",
"getXml",
"(",
")",
")",
";",
"translatedTopic",
".",
"setTags",
"(",
"topic",
".",
"getTags",
"(",
")",
")",
";",
"translatedTopic",
".",
"setSourceURLs",
"(",
"topic",
".",
"getSourceURLs",
"(",
")",
")",
";",
"translatedTopic",
".",
"setProperties",
"(",
"topic",
".",
"getProperties",
"(",
")",
")",
";",
"translatedTopic",
".",
"setLocale",
"(",
"locale",
")",
";",
"translatedTopic",
".",
"setTitle",
"(",
"topic",
".",
"getTitle",
"(",
")",
")",
";",
"return",
"translatedTopic",
";",
"}"
] |
Creates a dummy translated topic so that a book can be built using the same relationships as a normal build.
@param topic The topic to create the dummy topic from.
@param locale The locale to build the dummy translations for.
@return The dummy translated topic.
|
[
"Creates",
"a",
"dummy",
"translated",
"topic",
"so",
"that",
"a",
"book",
"can",
"be",
"built",
"using",
"the",
"same",
"relationships",
"as",
"a",
"normal",
"build",
"."
] |
train
|
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java#L1002-L1019
|
jqm4gwt/jqm4gwt
|
library/src/main/java/com/sksamuel/jqm4gwt/list/JQMListItem.java
|
JQMListItem.setControlGroup
|
public void setControlGroup(boolean value, boolean linkable) {
"""
true - prepare and allow to add widgets to this list box item.
@param linkable - if true <a> will be forcefully created, so row will be clickable.
"""
if (value) {
createControlGroup(linkable);
} else if (controlGroup != null) {
if (anchorPanel != null) remove(anchorPanel);
else if (anchor != null) getElement().removeChild(anchor);
anchor = null;
anchorPanel = null;
setSplitHref(null);
controlGroupRoot = null;
controlGroup = null;
checkBoxInput = null;
}
}
|
java
|
public void setControlGroup(boolean value, boolean linkable) {
if (value) {
createControlGroup(linkable);
} else if (controlGroup != null) {
if (anchorPanel != null) remove(anchorPanel);
else if (anchor != null) getElement().removeChild(anchor);
anchor = null;
anchorPanel = null;
setSplitHref(null);
controlGroupRoot = null;
controlGroup = null;
checkBoxInput = null;
}
}
|
[
"public",
"void",
"setControlGroup",
"(",
"boolean",
"value",
",",
"boolean",
"linkable",
")",
"{",
"if",
"(",
"value",
")",
"{",
"createControlGroup",
"(",
"linkable",
")",
";",
"}",
"else",
"if",
"(",
"controlGroup",
"!=",
"null",
")",
"{",
"if",
"(",
"anchorPanel",
"!=",
"null",
")",
"remove",
"(",
"anchorPanel",
")",
";",
"else",
"if",
"(",
"anchor",
"!=",
"null",
")",
"getElement",
"(",
")",
".",
"removeChild",
"(",
"anchor",
")",
";",
"anchor",
"=",
"null",
";",
"anchorPanel",
"=",
"null",
";",
"setSplitHref",
"(",
"null",
")",
";",
"controlGroupRoot",
"=",
"null",
";",
"controlGroup",
"=",
"null",
";",
"checkBoxInput",
"=",
"null",
";",
"}",
"}"
] |
true - prepare and allow to add widgets to this list box item.
@param linkable - if true <a> will be forcefully created, so row will be clickable.
|
[
"true",
"-",
"prepare",
"and",
"allow",
"to",
"add",
"widgets",
"to",
"this",
"list",
"box",
"item",
"."
] |
train
|
https://github.com/jqm4gwt/jqm4gwt/blob/cf59958e9ba6d4b70f42507b2c77f10c2465085b/library/src/main/java/com/sksamuel/jqm4gwt/list/JQMListItem.java#L747-L760
|
finmath/finmath-lib
|
src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java
|
LinearInterpolatedTimeDiscreteProcess.add
|
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {
"""
Create a new linear interpolated time discrete process by
using the time discretization of this process and the sum of this process and the given one
as its values.
@param process A given process.
@return A new process representing the of this and the given process.
@throws CalculationException Thrown if the given process fails to evaluate at a certain time point.
"""
Map<Double, RandomVariable> sum = new HashMap<>();
for(double time: timeDiscretization) {
sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));
}
return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);
}
|
java
|
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException {
Map<Double, RandomVariable> sum = new HashMap<>();
for(double time: timeDiscretization) {
sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0)));
}
return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum);
}
|
[
"public",
"LinearInterpolatedTimeDiscreteProcess",
"add",
"(",
"LinearInterpolatedTimeDiscreteProcess",
"process",
")",
"throws",
"CalculationException",
"{",
"Map",
"<",
"Double",
",",
"RandomVariable",
">",
"sum",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"double",
"time",
":",
"timeDiscretization",
")",
"{",
"sum",
".",
"put",
"(",
"time",
",",
"realizations",
".",
"get",
"(",
"time",
")",
".",
"add",
"(",
"process",
".",
"getProcessValue",
"(",
"time",
",",
"0",
")",
")",
")",
";",
"}",
"return",
"new",
"LinearInterpolatedTimeDiscreteProcess",
"(",
"timeDiscretization",
",",
"sum",
")",
";",
"}"
] |
Create a new linear interpolated time discrete process by
using the time discretization of this process and the sum of this process and the given one
as its values.
@param process A given process.
@return A new process representing the of this and the given process.
@throws CalculationException Thrown if the given process fails to evaluate at a certain time point.
|
[
"Create",
"a",
"new",
"linear",
"interpolated",
"time",
"discrete",
"process",
"by",
"using",
"the",
"time",
"discretization",
"of",
"this",
"process",
"and",
"the",
"sum",
"of",
"this",
"process",
"and",
"the",
"given",
"one",
"as",
"its",
"values",
"."
] |
train
|
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java#L70-L78
|
netscaler/nitro
|
src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocolicmp_stats.java
|
protocolicmp_stats.get_nitro_response
|
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
"""
<pre>
converts nitro response into object and returns the object array in case of get request.
</pre>
"""
protocolicmp_stats[] resources = new protocolicmp_stats[1];
protocolicmp_response result = (protocolicmp_response) service.get_payload_formatter().string_to_resource(protocolicmp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocolicmp;
return resources;
}
|
java
|
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
protocolicmp_stats[] resources = new protocolicmp_stats[1];
protocolicmp_response result = (protocolicmp_response) service.get_payload_formatter().string_to_resource(protocolicmp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocolicmp;
return resources;
}
|
[
"protected",
"base_resource",
"[",
"]",
"get_nitro_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"protocolicmp_stats",
"[",
"]",
"resources",
"=",
"new",
"protocolicmp_stats",
"[",
"1",
"]",
";",
"protocolicmp_response",
"result",
"=",
"(",
"protocolicmp_response",
")",
"service",
".",
"get_payload_formatter",
"(",
")",
".",
"string_to_resource",
"(",
"protocolicmp_response",
".",
"class",
",",
"response",
")",
";",
"if",
"(",
"result",
".",
"errorcode",
"!=",
"0",
")",
"{",
"if",
"(",
"result",
".",
"errorcode",
"==",
"444",
")",
"{",
"service",
".",
"clear_session",
"(",
")",
";",
"}",
"if",
"(",
"result",
".",
"severity",
"!=",
"null",
")",
"{",
"if",
"(",
"result",
".",
"severity",
".",
"equals",
"(",
"\"ERROR\"",
")",
")",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"nitro_exception",
"(",
"result",
".",
"message",
",",
"result",
".",
"errorcode",
")",
";",
"}",
"}",
"resources",
"[",
"0",
"]",
"=",
"result",
".",
"protocolicmp",
";",
"return",
"resources",
";",
"}"
] |
<pre>
converts nitro response into object and returns the object array in case of get request.
</pre>
|
[
"<pre",
">",
"converts",
"nitro",
"response",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocolicmp_stats.java#L392-L411
|
versionone/VersionOne.SDK.Java.ObjectModel
|
src/main/java/com/versionone/om/BuildProject.java
|
BuildProject.createBuildRun
|
public BuildRun createBuildRun(String name, DateTime date, Map<String, Object> attributes) {
"""
Create a Build Run with the given name and date in this Build Project.
@param name of creating BuildRun.
@param date of creating BuildRun.
@param attributes additional attributes for the BuildRun.
@return A new Build Run in this Build Project.
"""
return getInstance().create().buildRun(this, name, date, attributes);
}
|
java
|
public BuildRun createBuildRun(String name, DateTime date, Map<String, Object> attributes) {
return getInstance().create().buildRun(this, name, date, attributes);
}
|
[
"public",
"BuildRun",
"createBuildRun",
"(",
"String",
"name",
",",
"DateTime",
"date",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"attributes",
")",
"{",
"return",
"getInstance",
"(",
")",
".",
"create",
"(",
")",
".",
"buildRun",
"(",
"this",
",",
"name",
",",
"date",
",",
"attributes",
")",
";",
"}"
] |
Create a Build Run with the given name and date in this Build Project.
@param name of creating BuildRun.
@param date of creating BuildRun.
@param attributes additional attributes for the BuildRun.
@return A new Build Run in this Build Project.
|
[
"Create",
"a",
"Build",
"Run",
"with",
"the",
"given",
"name",
"and",
"date",
"in",
"this",
"Build",
"Project",
"."
] |
train
|
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/BuildProject.java#L82-L84
|
b3log/latke
|
latke-core/src/main/java/org/json/JSONPointer.java
|
JSONPointer.readByIndexToken
|
private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException {
"""
Matches a JSONArray element by ordinal position
@param current the JSONArray to be evaluated
@param indexToken the array index in string form
@return the matched object. If no matching item is found a
@throws JSONPointerException is thrown if the index is out of bounds
"""
try {
int index = Integer.parseInt(indexToken);
JSONArray currentArr = (JSONArray) current;
if (index >= currentArr.length()) {
throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken,
Integer.valueOf(currentArr.length())));
}
try {
return currentArr.get(index);
} catch (JSONException e) {
throw new JSONPointerException("Error reading value at index position " + index, e);
}
} catch (NumberFormatException e) {
throw new JSONPointerException(format("%s is not an array index", indexToken), e);
}
}
|
java
|
private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException {
try {
int index = Integer.parseInt(indexToken);
JSONArray currentArr = (JSONArray) current;
if (index >= currentArr.length()) {
throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken,
Integer.valueOf(currentArr.length())));
}
try {
return currentArr.get(index);
} catch (JSONException e) {
throw new JSONPointerException("Error reading value at index position " + index, e);
}
} catch (NumberFormatException e) {
throw new JSONPointerException(format("%s is not an array index", indexToken), e);
}
}
|
[
"private",
"Object",
"readByIndexToken",
"(",
"Object",
"current",
",",
"String",
"indexToken",
")",
"throws",
"JSONPointerException",
"{",
"try",
"{",
"int",
"index",
"=",
"Integer",
".",
"parseInt",
"(",
"indexToken",
")",
";",
"JSONArray",
"currentArr",
"=",
"(",
"JSONArray",
")",
"current",
";",
"if",
"(",
"index",
">=",
"currentArr",
".",
"length",
"(",
")",
")",
"{",
"throw",
"new",
"JSONPointerException",
"(",
"format",
"(",
"\"index %s is out of bounds - the array has %d elements\"",
",",
"indexToken",
",",
"Integer",
".",
"valueOf",
"(",
"currentArr",
".",
"length",
"(",
")",
")",
")",
")",
";",
"}",
"try",
"{",
"return",
"currentArr",
".",
"get",
"(",
"index",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"throw",
"new",
"JSONPointerException",
"(",
"\"Error reading value at index position \"",
"+",
"index",
",",
"e",
")",
";",
"}",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"throw",
"new",
"JSONPointerException",
"(",
"format",
"(",
"\"%s is not an array index\"",
",",
"indexToken",
")",
",",
"e",
")",
";",
"}",
"}"
] |
Matches a JSONArray element by ordinal position
@param current the JSONArray to be evaluated
@param indexToken the array index in string form
@return the matched object. If no matching item is found a
@throws JSONPointerException is thrown if the index is out of bounds
|
[
"Matches",
"a",
"JSONArray",
"element",
"by",
"ordinal",
"position"
] |
train
|
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONPointer.java#L231-L247
|
deeplearning4j/deeplearning4j
|
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/memory/MemoryReport.java
|
MemoryReport.getTotalMemoryBytes
|
public long getTotalMemoryBytes(int minibatchSize, @NonNull MemoryUseMode memoryUseMode,
@NonNull CacheMode cacheMode) {
"""
Get the total memory use in bytes for the given configuration (using the current ND4J data type)
@param minibatchSize Mini batch size to estimate the memory for
@param memoryUseMode The memory use mode (training or inference)
@param cacheMode The CacheMode to use
@return The estimated total memory consumption in bytes
"""
return getTotalMemoryBytes(minibatchSize, memoryUseMode, cacheMode, DataTypeUtil.getDtypeFromContext());
}
|
java
|
public long getTotalMemoryBytes(int minibatchSize, @NonNull MemoryUseMode memoryUseMode,
@NonNull CacheMode cacheMode) {
return getTotalMemoryBytes(minibatchSize, memoryUseMode, cacheMode, DataTypeUtil.getDtypeFromContext());
}
|
[
"public",
"long",
"getTotalMemoryBytes",
"(",
"int",
"minibatchSize",
",",
"@",
"NonNull",
"MemoryUseMode",
"memoryUseMode",
",",
"@",
"NonNull",
"CacheMode",
"cacheMode",
")",
"{",
"return",
"getTotalMemoryBytes",
"(",
"minibatchSize",
",",
"memoryUseMode",
",",
"cacheMode",
",",
"DataTypeUtil",
".",
"getDtypeFromContext",
"(",
")",
")",
";",
"}"
] |
Get the total memory use in bytes for the given configuration (using the current ND4J data type)
@param minibatchSize Mini batch size to estimate the memory for
@param memoryUseMode The memory use mode (training or inference)
@param cacheMode The CacheMode to use
@return The estimated total memory consumption in bytes
|
[
"Get",
"the",
"total",
"memory",
"use",
"in",
"bytes",
"for",
"the",
"given",
"configuration",
"(",
"using",
"the",
"current",
"ND4J",
"data",
"type",
")"
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/memory/MemoryReport.java#L123-L126
|
intendia-oss/rxjava-gwt
|
src/main/modified/io/reactivex/super/io/reactivex/Scheduler.java
|
Scheduler.scheduleDirect
|
@NonNull
public Disposable scheduleDirect(@NonNull Runnable run) {
"""
Schedules the given task on this Scheduler without any time delay.
<p>
This method is safe to be called from multiple threads but there are no
ordering or non-overlapping guarantees between tasks.
@param run the task to execute
@return the Disposable instance that let's one cancel this particular task.
@since 2.0
"""
return scheduleDirect(run, 0L, TimeUnit.NANOSECONDS);
}
|
java
|
@NonNull
public Disposable scheduleDirect(@NonNull Runnable run) {
return scheduleDirect(run, 0L, TimeUnit.NANOSECONDS);
}
|
[
"@",
"NonNull",
"public",
"Disposable",
"scheduleDirect",
"(",
"@",
"NonNull",
"Runnable",
"run",
")",
"{",
"return",
"scheduleDirect",
"(",
"run",
",",
"0L",
",",
"TimeUnit",
".",
"NANOSECONDS",
")",
";",
"}"
] |
Schedules the given task on this Scheduler without any time delay.
<p>
This method is safe to be called from multiple threads but there are no
ordering or non-overlapping guarantees between tasks.
@param run the task to execute
@return the Disposable instance that let's one cancel this particular task.
@since 2.0
|
[
"Schedules",
"the",
"given",
"task",
"on",
"this",
"Scheduler",
"without",
"any",
"time",
"delay",
"."
] |
train
|
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Scheduler.java#L176-L179
|
molgenis/molgenis
|
molgenis-data-icd10/src/main/java/org/molgenis/data/icd10/CollectionsQueryTransformerImpl.java
|
CollectionsQueryTransformerImpl.isTransformableRule
|
private boolean isTransformableRule(QueryRule nestedRule, String expandAttribute) {
"""
Returns <code>true</code> if a rule is 'IN' or 'EQUALS' on the attribute that should be
expanded
"""
return nestedRule != null
&& nestedRule.getField() != null
&& nestedRule.getField().equals(expandAttribute)
&& (nestedRule.getOperator() == QueryRule.Operator.IN
|| nestedRule.getOperator() == QueryRule.Operator.EQUALS);
}
|
java
|
private boolean isTransformableRule(QueryRule nestedRule, String expandAttribute) {
return nestedRule != null
&& nestedRule.getField() != null
&& nestedRule.getField().equals(expandAttribute)
&& (nestedRule.getOperator() == QueryRule.Operator.IN
|| nestedRule.getOperator() == QueryRule.Operator.EQUALS);
}
|
[
"private",
"boolean",
"isTransformableRule",
"(",
"QueryRule",
"nestedRule",
",",
"String",
"expandAttribute",
")",
"{",
"return",
"nestedRule",
"!=",
"null",
"&&",
"nestedRule",
".",
"getField",
"(",
")",
"!=",
"null",
"&&",
"nestedRule",
".",
"getField",
"(",
")",
".",
"equals",
"(",
"expandAttribute",
")",
"&&",
"(",
"nestedRule",
".",
"getOperator",
"(",
")",
"==",
"QueryRule",
".",
"Operator",
".",
"IN",
"||",
"nestedRule",
".",
"getOperator",
"(",
")",
"==",
"QueryRule",
".",
"Operator",
".",
"EQUALS",
")",
";",
"}"
] |
Returns <code>true</code> if a rule is 'IN' or 'EQUALS' on the attribute that should be
expanded
|
[
"Returns",
"<code",
">",
"true<",
"/",
"code",
">",
"if",
"a",
"rule",
"is",
"IN",
"or",
"EQUALS",
"on",
"the",
"attribute",
"that",
"should",
"be",
"expanded"
] |
train
|
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-icd10/src/main/java/org/molgenis/data/icd10/CollectionsQueryTransformerImpl.java#L72-L78
|
couchbase/couchbase-java-client
|
src/main/java/com/couchbase/client/java/query/dsl/functions/NumberFunctions.java
|
NumberFunctions.atan
|
public static Expression atan(Expression expression1, Expression expression2) {
"""
Returned expression results in the arctangent of expression2/expression1.
"""
return x("ATAN(" + expression1.toString() + ", " + expression2.toString() + ")");
}
|
java
|
public static Expression atan(Expression expression1, Expression expression2) {
return x("ATAN(" + expression1.toString() + ", " + expression2.toString() + ")");
}
|
[
"public",
"static",
"Expression",
"atan",
"(",
"Expression",
"expression1",
",",
"Expression",
"expression2",
")",
"{",
"return",
"x",
"(",
"\"ATAN(\"",
"+",
"expression1",
".",
"toString",
"(",
")",
"+",
"\", \"",
"+",
"expression2",
".",
"toString",
"(",
")",
"+",
"\")\"",
")",
";",
"}"
] |
Returned expression results in the arctangent of expression2/expression1.
|
[
"Returned",
"expression",
"results",
"in",
"the",
"arctangent",
"of",
"expression2",
"/",
"expression1",
"."
] |
train
|
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/NumberFunctions.java#L97-L99
|
eclipse/xtext-core
|
org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/util/NodeModelUtils.java
|
NodeModelUtils.getLineAndColumn
|
public static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) {
"""
Compute the line and column information at the given offset from any node that belongs the the document. The line is one-based, e.g.
the first line has the line number '1'. The line break belongs the line that it breaks. In other words, the first line break in the
document also has the line number '1'. The column number starts at '1', too. In effect, the document offset '0' will always return
line '1' and column '1'.
If the given documentOffset points exactly to {@code anyNode.root.text.length}, it's assumed to be a virtual character thus
the offset is valid and the column and line information is returned as if it was there.
This contract is in sync with {@link org.eclipse.emf.ecore.resource.Resource.Diagnostic}.
@throws IndexOutOfBoundsException
if the document offset does not belong to the document,
{@code documentOffset < 0 || documentOffset > anyNode.rootNode.text.length}
"""
// special treatment for inconsistent nodes such as SyntheticLinkingLeafNode
if (anyNode.getParent() == null && !(anyNode instanceof RootNode)) {
return LineAndColumn.from(1,1);
}
return InternalNodeModelUtils.getLineAndColumn(anyNode, documentOffset);
}
|
java
|
public static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) {
// special treatment for inconsistent nodes such as SyntheticLinkingLeafNode
if (anyNode.getParent() == null && !(anyNode instanceof RootNode)) {
return LineAndColumn.from(1,1);
}
return InternalNodeModelUtils.getLineAndColumn(anyNode, documentOffset);
}
|
[
"public",
"static",
"LineAndColumn",
"getLineAndColumn",
"(",
"INode",
"anyNode",
",",
"int",
"documentOffset",
")",
"{",
"// special treatment for inconsistent nodes such as SyntheticLinkingLeafNode",
"if",
"(",
"anyNode",
".",
"getParent",
"(",
")",
"==",
"null",
"&&",
"!",
"(",
"anyNode",
"instanceof",
"RootNode",
")",
")",
"{",
"return",
"LineAndColumn",
".",
"from",
"(",
"1",
",",
"1",
")",
";",
"}",
"return",
"InternalNodeModelUtils",
".",
"getLineAndColumn",
"(",
"anyNode",
",",
"documentOffset",
")",
";",
"}"
] |
Compute the line and column information at the given offset from any node that belongs the the document. The line is one-based, e.g.
the first line has the line number '1'. The line break belongs the line that it breaks. In other words, the first line break in the
document also has the line number '1'. The column number starts at '1', too. In effect, the document offset '0' will always return
line '1' and column '1'.
If the given documentOffset points exactly to {@code anyNode.root.text.length}, it's assumed to be a virtual character thus
the offset is valid and the column and line information is returned as if it was there.
This contract is in sync with {@link org.eclipse.emf.ecore.resource.Resource.Diagnostic}.
@throws IndexOutOfBoundsException
if the document offset does not belong to the document,
{@code documentOffset < 0 || documentOffset > anyNode.rootNode.text.length}
|
[
"Compute",
"the",
"line",
"and",
"column",
"information",
"at",
"the",
"given",
"offset",
"from",
"any",
"node",
"that",
"belongs",
"the",
"the",
"document",
".",
"The",
"line",
"is",
"one",
"-",
"based",
"e",
".",
"g",
".",
"the",
"first",
"line",
"has",
"the",
"line",
"number",
"1",
".",
"The",
"line",
"break",
"belongs",
"the",
"line",
"that",
"it",
"breaks",
".",
"In",
"other",
"words",
"the",
"first",
"line",
"break",
"in",
"the",
"document",
"also",
"has",
"the",
"line",
"number",
"1",
".",
"The",
"column",
"number",
"starts",
"at",
"1",
"too",
".",
"In",
"effect",
"the",
"document",
"offset",
"0",
"will",
"always",
"return",
"line",
"1",
"and",
"column",
"1",
"."
] |
train
|
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/util/NodeModelUtils.java#L125-L131
|
Omertron/api-rottentomatoes
|
src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java
|
RottenTomatoesApi.getCurrentReleaseDvds
|
public List<RTMovie> getCurrentReleaseDvds(String country) throws RottenTomatoesException {
"""
Retrieves current release DVDs
@param country Provides localized data for the selected country
@return
@throws RottenTomatoesException
"""
return getCurrentReleaseDvds(country, DEFAULT_PAGE, DEFAULT_PAGE_LIMIT);
}
|
java
|
public List<RTMovie> getCurrentReleaseDvds(String country) throws RottenTomatoesException {
return getCurrentReleaseDvds(country, DEFAULT_PAGE, DEFAULT_PAGE_LIMIT);
}
|
[
"public",
"List",
"<",
"RTMovie",
">",
"getCurrentReleaseDvds",
"(",
"String",
"country",
")",
"throws",
"RottenTomatoesException",
"{",
"return",
"getCurrentReleaseDvds",
"(",
"country",
",",
"DEFAULT_PAGE",
",",
"DEFAULT_PAGE_LIMIT",
")",
";",
"}"
] |
Retrieves current release DVDs
@param country Provides localized data for the selected country
@return
@throws RottenTomatoesException
|
[
"Retrieves",
"current",
"release",
"DVDs"
] |
train
|
https://github.com/Omertron/api-rottentomatoes/blob/abaf1833acafc6ada593d52b14ff1bacb4e441ee/src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java#L394-L396
|
FedericoPecora/meta-csp-framework
|
src/main/java/org/metacsp/multi/activity/ActivityNetworkSolver.java
|
ActivityNetworkSolver.drawAsGantt
|
public void drawAsGantt( String varsMatchingThis ) {
"""
Draw variables matching this {@link String} on Gantt chart
@param varsMatchingThis {@link String} that must be contained in a variable to be plotted
"""
Vector<String> selectedVariables = new Vector<String>();
for ( Variable v : this.getVariables() ) {
if ( v.getComponent().contains(varsMatchingThis)) {
selectedVariables.add(v.getComponent());
}
}
new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt");
}
|
java
|
public void drawAsGantt( String varsMatchingThis ) {
Vector<String> selectedVariables = new Vector<String>();
for ( Variable v : this.getVariables() ) {
if ( v.getComponent().contains(varsMatchingThis)) {
selectedVariables.add(v.getComponent());
}
}
new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt");
}
|
[
"public",
"void",
"drawAsGantt",
"(",
"String",
"varsMatchingThis",
")",
"{",
"Vector",
"<",
"String",
">",
"selectedVariables",
"=",
"new",
"Vector",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"Variable",
"v",
":",
"this",
".",
"getVariables",
"(",
")",
")",
"{",
"if",
"(",
"v",
".",
"getComponent",
"(",
")",
".",
"contains",
"(",
"varsMatchingThis",
")",
")",
"{",
"selectedVariables",
".",
"add",
"(",
"v",
".",
"getComponent",
"(",
")",
")",
";",
"}",
"}",
"new",
"PlotActivityNetworkGantt",
"(",
"this",
",",
"selectedVariables",
",",
"\"Activity Network Gantt\"",
")",
";",
"}"
] |
Draw variables matching this {@link String} on Gantt chart
@param varsMatchingThis {@link String} that must be contained in a variable to be plotted
|
[
"Draw",
"variables",
"matching",
"this",
"{"
] |
train
|
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/activity/ActivityNetworkSolver.java#L143-L151
|
ManfredTremmel/gwt-commons-lang3
|
src/main/java/org/apache/commons/lang3/Validate.java
|
Validate.matchesPattern
|
public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
"""
<p>Validate that the specified argument character sequence matches the specified regular
expression pattern; otherwise throwing an exception with the specified message.</p>
<pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
<p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
@param input the character sequence to validate, not null
@param pattern the regular expression pattern, not null
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@throws IllegalArgumentException if the character sequence does not match the pattern
@see #matchesPattern(CharSequence, String)
@since 3.0
"""
// TODO when breaking BC, consider returning input
if (input == null || !input.toString().matches(pattern)) {
throw new IllegalArgumentException(StringUtils.simpleFormat(message, values));
}
}
|
java
|
public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
// TODO when breaking BC, consider returning input
if (input == null || !input.toString().matches(pattern)) {
throw new IllegalArgumentException(StringUtils.simpleFormat(message, values));
}
}
|
[
"public",
"static",
"void",
"matchesPattern",
"(",
"final",
"CharSequence",
"input",
",",
"final",
"String",
"pattern",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"values",
")",
"{",
"// TODO when breaking BC, consider returning input",
"if",
"(",
"input",
"==",
"null",
"||",
"!",
"input",
".",
"toString",
"(",
")",
".",
"matches",
"(",
"pattern",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"StringUtils",
".",
"simpleFormat",
"(",
"message",
",",
"values",
")",
")",
";",
"}",
"}"
] |
<p>Validate that the specified argument character sequence matches the specified regular
expression pattern; otherwise throwing an exception with the specified message.</p>
<pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
<p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
@param input the character sequence to validate, not null
@param pattern the regular expression pattern, not null
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@throws IllegalArgumentException if the character sequence does not match the pattern
@see #matchesPattern(CharSequence, String)
@since 3.0
|
[
"<p",
">",
"Validate",
"that",
"the",
"specified",
"argument",
"character",
"sequence",
"matches",
"the",
"specified",
"regular",
"expression",
"pattern",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
"the",
"specified",
"message",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L881-L886
|
apache/flink
|
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java
|
StreamExecutionEnvironment.socketTextStream
|
@PublicEvolving
public DataStreamSource<String> socketTextStream(String hostname, int port, String delimiter) {
"""
Creates a new data stream that contains the strings received infinitely from a socket. Received strings are
decoded by the system's default character set. The reader is terminated immediately when the socket is down.
@param hostname
The host name which a server socket binds
@param port
The port number which a server socket binds. A port number of 0 means that the port number is automatically
allocated.
@param delimiter
A string which splits received strings into records
@return A data stream containing the strings received from the socket
"""
return socketTextStream(hostname, port, delimiter, 0);
}
|
java
|
@PublicEvolving
public DataStreamSource<String> socketTextStream(String hostname, int port, String delimiter) {
return socketTextStream(hostname, port, delimiter, 0);
}
|
[
"@",
"PublicEvolving",
"public",
"DataStreamSource",
"<",
"String",
">",
"socketTextStream",
"(",
"String",
"hostname",
",",
"int",
"port",
",",
"String",
"delimiter",
")",
"{",
"return",
"socketTextStream",
"(",
"hostname",
",",
"port",
",",
"delimiter",
",",
"0",
")",
";",
"}"
] |
Creates a new data stream that contains the strings received infinitely from a socket. Received strings are
decoded by the system's default character set. The reader is terminated immediately when the socket is down.
@param hostname
The host name which a server socket binds
@param port
The port number which a server socket binds. A port number of 0 means that the port number is automatically
allocated.
@param delimiter
A string which splits received strings into records
@return A data stream containing the strings received from the socket
|
[
"Creates",
"a",
"new",
"data",
"stream",
"that",
"contains",
"the",
"strings",
"received",
"infinitely",
"from",
"a",
"socket",
".",
"Received",
"strings",
"are",
"decoded",
"by",
"the",
"system",
"s",
"default",
"character",
"set",
".",
"The",
"reader",
"is",
"terminated",
"immediately",
"when",
"the",
"socket",
"is",
"down",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java#L1254-L1257
|
mattbertolini/Hermes
|
src/main/java/com/mattbertolini/hermes/MessagesProxy.java
|
MessagesProxy.instantiateCustomPluralRuleClass
|
private PluralRule instantiateCustomPluralRuleClass(Class<? extends PluralRule> clazz) {
"""
Instantiates the plural rule class given inside the PluralCount
annotation. The pluralRule class that is instantiated is based on the
language originally given to the library. If that language is not found,
defaults to the given class.
@param clazz The PluralRule class
@return An instantiated PluralRule class
"""
PluralRule retVal;
try {
String pluralClassName = clazz.getName() + "_" + this.getLocale().getLanguage();
try {
Class<?> pClass = Class.forName(pluralClassName);
retVal = (PluralRule) pClass.newInstance();
} catch (ClassNotFoundException e) {
retVal = clazz.newInstance();
}
} catch (InstantiationException e) {
throw new RuntimeException("Could not instantiate custom PluralRule class. "
+ "Make sure the class is not an abstract class or interface and has a default constructor.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Could not instantiate custom Plural Rule class.", e);
}
return retVal;
}
|
java
|
private PluralRule instantiateCustomPluralRuleClass(Class<? extends PluralRule> clazz) {
PluralRule retVal;
try {
String pluralClassName = clazz.getName() + "_" + this.getLocale().getLanguage();
try {
Class<?> pClass = Class.forName(pluralClassName);
retVal = (PluralRule) pClass.newInstance();
} catch (ClassNotFoundException e) {
retVal = clazz.newInstance();
}
} catch (InstantiationException e) {
throw new RuntimeException("Could not instantiate custom PluralRule class. "
+ "Make sure the class is not an abstract class or interface and has a default constructor.", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Could not instantiate custom Plural Rule class.", e);
}
return retVal;
}
|
[
"private",
"PluralRule",
"instantiateCustomPluralRuleClass",
"(",
"Class",
"<",
"?",
"extends",
"PluralRule",
">",
"clazz",
")",
"{",
"PluralRule",
"retVal",
";",
"try",
"{",
"String",
"pluralClassName",
"=",
"clazz",
".",
"getName",
"(",
")",
"+",
"\"_\"",
"+",
"this",
".",
"getLocale",
"(",
")",
".",
"getLanguage",
"(",
")",
";",
"try",
"{",
"Class",
"<",
"?",
">",
"pClass",
"=",
"Class",
".",
"forName",
"(",
"pluralClassName",
")",
";",
"retVal",
"=",
"(",
"PluralRule",
")",
"pClass",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"retVal",
"=",
"clazz",
".",
"newInstance",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not instantiate custom PluralRule class. \"",
"+",
"\"Make sure the class is not an abstract class or interface and has a default constructor.\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not instantiate custom Plural Rule class.\"",
",",
"e",
")",
";",
"}",
"return",
"retVal",
";",
"}"
] |
Instantiates the plural rule class given inside the PluralCount
annotation. The pluralRule class that is instantiated is based on the
language originally given to the library. If that language is not found,
defaults to the given class.
@param clazz The PluralRule class
@return An instantiated PluralRule class
|
[
"Instantiates",
"the",
"plural",
"rule",
"class",
"given",
"inside",
"the",
"PluralCount",
"annotation",
".",
"The",
"pluralRule",
"class",
"that",
"is",
"instantiated",
"is",
"based",
"on",
"the",
"language",
"originally",
"given",
"to",
"the",
"library",
".",
"If",
"that",
"language",
"is",
"not",
"found",
"defaults",
"to",
"the",
"given",
"class",
"."
] |
train
|
https://github.com/mattbertolini/Hermes/blob/2f99ac6c358bef39bccfde93185bd72ac7de7201/src/main/java/com/mattbertolini/hermes/MessagesProxy.java#L186-L203
|
alkacon/opencms-core
|
src/org/opencms/ade/sitemap/CmsModelPageHelper.java
|
CmsModelPageHelper.removeModelPage
|
public void removeModelPage(CmsResource sitemapConfig, CmsUUID structureId) throws CmsException {
"""
Removes a model page from the sitemap configuration.<p>
@param sitemapConfig the sitemap configuration resource
@param structureId the structure id of the model page to remove
@throws CmsException if something goes wrong
"""
CmsFile sitemapConfigFile = m_cms.readFile(sitemapConfig);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, sitemapConfigFile);
CmsConfigurationReader reader = new CmsConfigurationReader(m_cms);
reader.parseConfiguration(m_adeConfig.getBasePath(), content);
List<CmsModelPageConfig> modelPageConfigs = reader.getModelPageConfigs();
int i = 0;
for (CmsModelPageConfig config : modelPageConfigs) {
if (config.getResource().getStructureId().equals(structureId)) {
break;
}
i += 1;
}
if (i < modelPageConfigs.size()) {
content.removeValue(CmsConfigurationReader.N_MODEL_PAGE, Locale.ENGLISH, i);
}
writeSitemapConfig(content, sitemapConfigFile);
}
|
java
|
public void removeModelPage(CmsResource sitemapConfig, CmsUUID structureId) throws CmsException {
CmsFile sitemapConfigFile = m_cms.readFile(sitemapConfig);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, sitemapConfigFile);
CmsConfigurationReader reader = new CmsConfigurationReader(m_cms);
reader.parseConfiguration(m_adeConfig.getBasePath(), content);
List<CmsModelPageConfig> modelPageConfigs = reader.getModelPageConfigs();
int i = 0;
for (CmsModelPageConfig config : modelPageConfigs) {
if (config.getResource().getStructureId().equals(structureId)) {
break;
}
i += 1;
}
if (i < modelPageConfigs.size()) {
content.removeValue(CmsConfigurationReader.N_MODEL_PAGE, Locale.ENGLISH, i);
}
writeSitemapConfig(content, sitemapConfigFile);
}
|
[
"public",
"void",
"removeModelPage",
"(",
"CmsResource",
"sitemapConfig",
",",
"CmsUUID",
"structureId",
")",
"throws",
"CmsException",
"{",
"CmsFile",
"sitemapConfigFile",
"=",
"m_cms",
".",
"readFile",
"(",
"sitemapConfig",
")",
";",
"CmsXmlContent",
"content",
"=",
"CmsXmlContentFactory",
".",
"unmarshal",
"(",
"m_cms",
",",
"sitemapConfigFile",
")",
";",
"CmsConfigurationReader",
"reader",
"=",
"new",
"CmsConfigurationReader",
"(",
"m_cms",
")",
";",
"reader",
".",
"parseConfiguration",
"(",
"m_adeConfig",
".",
"getBasePath",
"(",
")",
",",
"content",
")",
";",
"List",
"<",
"CmsModelPageConfig",
">",
"modelPageConfigs",
"=",
"reader",
".",
"getModelPageConfigs",
"(",
")",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"CmsModelPageConfig",
"config",
":",
"modelPageConfigs",
")",
"{",
"if",
"(",
"config",
".",
"getResource",
"(",
")",
".",
"getStructureId",
"(",
")",
".",
"equals",
"(",
"structureId",
")",
")",
"{",
"break",
";",
"}",
"i",
"+=",
"1",
";",
"}",
"if",
"(",
"i",
"<",
"modelPageConfigs",
".",
"size",
"(",
")",
")",
"{",
"content",
".",
"removeValue",
"(",
"CmsConfigurationReader",
".",
"N_MODEL_PAGE",
",",
"Locale",
".",
"ENGLISH",
",",
"i",
")",
";",
"}",
"writeSitemapConfig",
"(",
"content",
",",
"sitemapConfigFile",
")",
";",
"}"
] |
Removes a model page from the sitemap configuration.<p>
@param sitemapConfig the sitemap configuration resource
@param structureId the structure id of the model page to remove
@throws CmsException if something goes wrong
|
[
"Removes",
"a",
"model",
"page",
"from",
"the",
"sitemap",
"configuration",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsModelPageHelper.java#L388-L407
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.