repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
Wadpam/guja | guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java | GeneratedDContactDaoImpl.queryByOtherEmail | public Iterable<DContact> queryByOtherEmail(Object parent, java.lang.String otherEmail) {
return queryByField(parent, DContactMapper.Field.OTHEREMAIL.getFieldName(), otherEmail);
} | java | public Iterable<DContact> queryByOtherEmail(Object parent, java.lang.String otherEmail) {
return queryByField(parent, DContactMapper.Field.OTHEREMAIL.getFieldName(), otherEmail);
} | [
"public",
"Iterable",
"<",
"DContact",
">",
"queryByOtherEmail",
"(",
"Object",
"parent",
",",
"java",
".",
"lang",
".",
"String",
"otherEmail",
")",
"{",
"return",
"queryByField",
"(",
"parent",
",",
"DContactMapper",
".",
"Field",
".",
"OTHEREMAIL",
".",
"... | query-by method for field otherEmail
@param otherEmail the specified attribute
@return an Iterable of DContacts for the specified otherEmail | [
"query",
"-",
"by",
"method",
"for",
"field",
"otherEmail"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-contact/src/main/java/com/wadpam/guja/dao/GeneratedDContactDaoImpl.java#L232-L234 |
prestodb/presto | presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java | SemiTransactionalHiveMetastore.createTable | public synchronized void createTable(
ConnectorSession session,
Table table,
PrincipalPrivileges principalPrivileges,
Optional<Path> currentPath,
boolean ignoreExisting,
PartitionStatistics statistics)
{
setShared();
// When creating a table, it should never have partition actions. This is just a sanity check.
checkNoPartitionAction(table.getDatabaseName(), table.getTableName());
SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName());
Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName);
TableAndMore tableAndMore = new TableAndMore(table, Optional.of(principalPrivileges), currentPath, Optional.empty(), ignoreExisting, statistics, statistics);
if (oldTableAction == null) {
HdfsContext context = new HdfsContext(session, table.getDatabaseName(), table.getTableName());
tableActions.put(schemaTableName, new Action<>(ActionType.ADD, tableAndMore, context));
return;
}
switch (oldTableAction.getType()) {
case DROP:
throw new PrestoException(TRANSACTION_CONFLICT, "Dropping and then recreating the same table in a transaction is not supported");
case ADD:
case ALTER:
case INSERT_EXISTING:
throw new TableAlreadyExistsException(schemaTableName);
default:
throw new IllegalStateException("Unknown action type");
}
} | java | public synchronized void createTable(
ConnectorSession session,
Table table,
PrincipalPrivileges principalPrivileges,
Optional<Path> currentPath,
boolean ignoreExisting,
PartitionStatistics statistics)
{
setShared();
// When creating a table, it should never have partition actions. This is just a sanity check.
checkNoPartitionAction(table.getDatabaseName(), table.getTableName());
SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName());
Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName);
TableAndMore tableAndMore = new TableAndMore(table, Optional.of(principalPrivileges), currentPath, Optional.empty(), ignoreExisting, statistics, statistics);
if (oldTableAction == null) {
HdfsContext context = new HdfsContext(session, table.getDatabaseName(), table.getTableName());
tableActions.put(schemaTableName, new Action<>(ActionType.ADD, tableAndMore, context));
return;
}
switch (oldTableAction.getType()) {
case DROP:
throw new PrestoException(TRANSACTION_CONFLICT, "Dropping and then recreating the same table in a transaction is not supported");
case ADD:
case ALTER:
case INSERT_EXISTING:
throw new TableAlreadyExistsException(schemaTableName);
default:
throw new IllegalStateException("Unknown action type");
}
} | [
"public",
"synchronized",
"void",
"createTable",
"(",
"ConnectorSession",
"session",
",",
"Table",
"table",
",",
"PrincipalPrivileges",
"principalPrivileges",
",",
"Optional",
"<",
"Path",
">",
"currentPath",
",",
"boolean",
"ignoreExisting",
",",
"PartitionStatistics",... | {@code currentLocation} needs to be supplied if a writePath exists for the table. | [
"{"
] | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-hive/src/main/java/com/facebook/presto/hive/metastore/SemiTransactionalHiveMetastore.java#L360-L389 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java | ConfigValueHelper.checkNormal | protected static void checkNormal(String configKey, String configValue) throws SofaRpcRuntimeException {
checkPattern(configKey, configValue, NORMAL, "only allow a-zA-Z0-9 '-' '_' '.'");
} | java | protected static void checkNormal(String configKey, String configValue) throws SofaRpcRuntimeException {
checkPattern(configKey, configValue, NORMAL, "only allow a-zA-Z0-9 '-' '_' '.'");
} | [
"protected",
"static",
"void",
"checkNormal",
"(",
"String",
"configKey",
",",
"String",
"configValue",
")",
"throws",
"SofaRpcRuntimeException",
"{",
"checkPattern",
"(",
"configKey",
",",
"configValue",
",",
"NORMAL",
",",
"\"only allow a-zA-Z0-9 '-' '_' '.'\"",
")",
... | 检查字符串是否是正常值,不是则抛出异常
@param configKey 配置项
@param configValue 配置值
@throws SofaRpcRuntimeException 非法异常 | [
"检查字符串是否是正常值,不是则抛出异常"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java#L97-L99 |
lightblue-platform/lightblue-esb-hook | publish-hook/src/main/java/com/redhat/lightblue/hook/publish/EventExctractionUtil.java | EventExctractionUtil.compareAndExtractEvents | public static Set<Event> compareAndExtractEvents(String pre, String post, String ids) throws JSONException, IllegalArgumentException {
Object preObject = null, postObject = null, idsObject = null;
if (pre != null) {
preObject = JSONParser.parseJSON(pre);
}
if (post != null && ids != null) {
postObject = JSONParser.parseJSON(post);
idsObject = JSONParser.parseJSON(ids);
} else {
throw new IllegalArgumentException("post state and projected ids cannot be null:: " + getErrorSignature(pre, post, ids));
}
if (!(preObject == null || preObject.getClass().equals(postObject.getClass())) || !postObject.getClass().equals(idsObject.getClass())) {
throw new IllegalArgumentException("pre state (optional), post state and projected ids need to be valid JSON of the same type:: "
+ getErrorSignature(pre, post, ids));
}
// JSONParser only returns JSONArray/ JSONObject/ JSONString
if (!postObject.getClass().equals(JSONArray.class) && !postObject.getClass().equals(JSONObject.class)) {
throw new IllegalArgumentException("Identities can only extracted from JSONArrays or JSONObjects:: " + getErrorSignature(pre, post, ids));
}
return compareAndGetEvents(preObject, postObject, idsObject);
} | java | public static Set<Event> compareAndExtractEvents(String pre, String post, String ids) throws JSONException, IllegalArgumentException {
Object preObject = null, postObject = null, idsObject = null;
if (pre != null) {
preObject = JSONParser.parseJSON(pre);
}
if (post != null && ids != null) {
postObject = JSONParser.parseJSON(post);
idsObject = JSONParser.parseJSON(ids);
} else {
throw new IllegalArgumentException("post state and projected ids cannot be null:: " + getErrorSignature(pre, post, ids));
}
if (!(preObject == null || preObject.getClass().equals(postObject.getClass())) || !postObject.getClass().equals(idsObject.getClass())) {
throw new IllegalArgumentException("pre state (optional), post state and projected ids need to be valid JSON of the same type:: "
+ getErrorSignature(pre, post, ids));
}
// JSONParser only returns JSONArray/ JSONObject/ JSONString
if (!postObject.getClass().equals(JSONArray.class) && !postObject.getClass().equals(JSONObject.class)) {
throw new IllegalArgumentException("Identities can only extracted from JSONArrays or JSONObjects:: " + getErrorSignature(pre, post, ids));
}
return compareAndGetEvents(preObject, postObject, idsObject);
} | [
"public",
"static",
"Set",
"<",
"Event",
">",
"compareAndExtractEvents",
"(",
"String",
"pre",
",",
"String",
"post",
",",
"String",
"ids",
")",
"throws",
"JSONException",
",",
"IllegalArgumentException",
"{",
"Object",
"preObject",
"=",
"null",
",",
"postObject... | /*
Accepts JSONObject / JSONArray and returns the Events for the required
permutations.
NOTE: this doesn't check if the objects are actually different, call this
only if an event is to be created for sure, just to find out what events
are to be created. | [
"/",
"*",
"Accepts",
"JSONObject",
"/",
"JSONArray",
"and",
"returns",
"the",
"Events",
"for",
"the",
"required",
"permutations",
"."
] | train | https://github.com/lightblue-platform/lightblue-esb-hook/blob/71afc88b595a629291a1a46da1a745348ddee428/publish-hook/src/main/java/com/redhat/lightblue/hook/publish/EventExctractionUtil.java#L28-L50 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/plugins/JarPluginProviderLoader.java | JarPluginProviderLoader.createProviderForClass | static <T,X extends T> T createProviderForClass(final PluggableService<T> service, final Class<X> cls) throws PluginException,
ProviderCreationException {
debug("Try loading provider " + cls.getName());
if(!(service instanceof JavaClassProviderLoadable)){
return null;
}
JavaClassProviderLoadable<T> loadable = (JavaClassProviderLoadable<T>) service;
final Plugin annotation = getPluginMetadata(cls);
final String pluginname = annotation.name();
if (!loadable.isValidProviderClass(cls)) {
throw new PluginException("Class " + cls.getName() + " was not a valid plugin class for service: "
+ service.getName() + ". Expected class " + cls.getName() + ", with a public constructor with no parameter");
}
debug("Succeeded loading plugin " + cls.getName() + " for service: " + service.getName());
return loadable.createProviderInstance(cls, pluginname);
} | java | static <T,X extends T> T createProviderForClass(final PluggableService<T> service, final Class<X> cls) throws PluginException,
ProviderCreationException {
debug("Try loading provider " + cls.getName());
if(!(service instanceof JavaClassProviderLoadable)){
return null;
}
JavaClassProviderLoadable<T> loadable = (JavaClassProviderLoadable<T>) service;
final Plugin annotation = getPluginMetadata(cls);
final String pluginname = annotation.name();
if (!loadable.isValidProviderClass(cls)) {
throw new PluginException("Class " + cls.getName() + " was not a valid plugin class for service: "
+ service.getName() + ". Expected class " + cls.getName() + ", with a public constructor with no parameter");
}
debug("Succeeded loading plugin " + cls.getName() + " for service: " + service.getName());
return loadable.createProviderInstance(cls, pluginname);
} | [
"static",
"<",
"T",
",",
"X",
"extends",
"T",
">",
"T",
"createProviderForClass",
"(",
"final",
"PluggableService",
"<",
"T",
">",
"service",
",",
"final",
"Class",
"<",
"X",
">",
"cls",
")",
"throws",
"PluginException",
",",
"ProviderCreationException",
"{"... | Attempt to create an instance of thea provider for the given service
@param cls class
@return created instance | [
"Attempt",
"to",
"create",
"an",
"instance",
"of",
"thea",
"provider",
"for",
"the",
"given",
"service"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/JarPluginProviderLoader.java#L308-L325 |
FasterXML/jackson-jr | jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/JSONObjectException.java | JSONObjectException.prependPath | public void prependPath(Object referrer, int index)
{
Reference ref = new Reference(referrer, index);
prependPath(ref);
} | java | public void prependPath(Object referrer, int index)
{
Reference ref = new Reference(referrer, index);
prependPath(ref);
} | [
"public",
"void",
"prependPath",
"(",
"Object",
"referrer",
",",
"int",
"index",
")",
"{",
"Reference",
"ref",
"=",
"new",
"Reference",
"(",
"referrer",
",",
"index",
")",
";",
"prependPath",
"(",
"ref",
")",
";",
"}"
] | Method called to prepend a reference information in front of
current path | [
"Method",
"called",
"to",
"prepend",
"a",
"reference",
"information",
"in",
"front",
"of",
"current",
"path"
] | train | https://github.com/FasterXML/jackson-jr/blob/62ca7a82bd90a9be77028e0b62364307d7532837/jr-objects/src/main/java/com/fasterxml/jackson/jr/ob/JSONObjectException.java#L288-L292 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java | AbstractValidate.exclusiveBetween | public long exclusiveBetween(long start, long end, long value) {
if (value <= start || value >= end) {
fail(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
return value;
} | java | public long exclusiveBetween(long start, long end, long value) {
if (value <= start || value >= end) {
fail(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
return value;
} | [
"public",
"long",
"exclusiveBetween",
"(",
"long",
"start",
",",
"long",
"end",
",",
"long",
"value",
")",
"{",
"if",
"(",
"value",
"<=",
"start",
"||",
"value",
">=",
"end",
")",
"{",
"fail",
"(",
"String",
".",
"format",
"(",
"DEFAULT_EXCLUSIVE_BETWEEN... | Validate that the specified primitive value falls between the two exclusive values specified; otherwise, throws an exception.
<pre>Validate.exclusiveBetween(0, 2, 1);</pre>
@param start
the exclusive start value
@param end
the exclusive end value
@param value
the value to validate
@return the value
@throws IllegalArgumentValidationException
if the value falls out of the boundaries | [
"Validate",
"that",
"the",
"specified",
"primitive",
"value",
"falls",
"between",
"the",
"two",
"exclusive",
"values",
"specified",
";",
"otherwise",
"throws",
"an",
"exception",
".",
"<pre",
">",
"Validate",
".",
"exclusiveBetween",
"(",
"0",
"2",
"1",
")",
... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/AbstractValidate.java#L1442-L1447 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java | GraphEdgeIdFinder.findEdgesInShape | public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) {
GHPoint center = shape.getCenter();
QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter);
// TODO: if there is no street close to the center it'll fail although there are roads covered. Maybe we should check edge points or some random points in the Shape instead?
if (!qr.isValid())
throw new IllegalArgumentException("Shape " + shape + " does not cover graph");
if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon))
edgeIds.add(qr.getClosestEdge().getEdge());
final boolean isPolygon = shape instanceof Polygon;
BreadthFirstSearch bfs = new BreadthFirstSearch() {
final NodeAccess na = graph.getNodeAccess();
final Shape localShape = shape;
@Override
protected boolean goFurther(int nodeId) {
if (isPolygon) return isInsideBBox(nodeId);
return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId));
}
@Override
protected boolean checkAdjacent(EdgeIteratorState edge) {
int adjNodeId = edge.getAdjNode();
if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) {
edgeIds.add(edge.getEdge());
return true;
}
return isPolygon && isInsideBBox(adjNodeId);
}
private boolean isInsideBBox(int nodeId) {
BBox bbox = localShape.getBounds();
double lat = na.getLatitude(nodeId);
double lon = na.getLongitude(nodeId);
return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon;
}
};
bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode());
} | java | public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) {
GHPoint center = shape.getCenter();
QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter);
// TODO: if there is no street close to the center it'll fail although there are roads covered. Maybe we should check edge points or some random points in the Shape instead?
if (!qr.isValid())
throw new IllegalArgumentException("Shape " + shape + " does not cover graph");
if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon))
edgeIds.add(qr.getClosestEdge().getEdge());
final boolean isPolygon = shape instanceof Polygon;
BreadthFirstSearch bfs = new BreadthFirstSearch() {
final NodeAccess na = graph.getNodeAccess();
final Shape localShape = shape;
@Override
protected boolean goFurther(int nodeId) {
if (isPolygon) return isInsideBBox(nodeId);
return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId));
}
@Override
protected boolean checkAdjacent(EdgeIteratorState edge) {
int adjNodeId = edge.getAdjNode();
if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) {
edgeIds.add(edge.getEdge());
return true;
}
return isPolygon && isInsideBBox(adjNodeId);
}
private boolean isInsideBBox(int nodeId) {
BBox bbox = localShape.getBounds();
double lat = na.getLatitude(nodeId);
double lon = na.getLongitude(nodeId);
return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon;
}
};
bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode());
} | [
"public",
"void",
"findEdgesInShape",
"(",
"final",
"GHIntHashSet",
"edgeIds",
",",
"final",
"Shape",
"shape",
",",
"EdgeFilter",
"filter",
")",
"{",
"GHPoint",
"center",
"=",
"shape",
".",
"getCenter",
"(",
")",
";",
"QueryResult",
"qr",
"=",
"locationIndex",... | This method fills the edgeIds hash with edgeIds found inside the specified shape | [
"This",
"method",
"fills",
"the",
"edgeIds",
"hash",
"with",
"edgeIds",
"found",
"inside",
"the",
"specified",
"shape"
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java#L71-L113 |
TheHortonMachine/hortonmachine | dbs/src/main/java/org/hortonmachine/dbs/h2gis/H2GisServer.java | H2GisServer.startTcpServerMode | public static Server startTcpServerMode( String port, boolean doSSL, String tcpPassword, boolean ifExists, String baseDir )
throws SQLException {
List<String> params = new ArrayList<>();
params.add("-tcpAllowOthers");
params.add("-tcpPort");
if (port == null) {
port = "9123";
}
params.add(port);
if (doSSL) {
params.add("-tcpSSL");
}
if (tcpPassword != null) {
params.add("-tcpPassword");
params.add(tcpPassword);
}
if (ifExists) {
params.add("-ifExists");
}
if (baseDir != null) {
params.add("-baseDir");
params.add(baseDir);
}
Server server = Server.createTcpServer(params.toArray(new String[0])).start();
return server;
} | java | public static Server startTcpServerMode( String port, boolean doSSL, String tcpPassword, boolean ifExists, String baseDir )
throws SQLException {
List<String> params = new ArrayList<>();
params.add("-tcpAllowOthers");
params.add("-tcpPort");
if (port == null) {
port = "9123";
}
params.add(port);
if (doSSL) {
params.add("-tcpSSL");
}
if (tcpPassword != null) {
params.add("-tcpPassword");
params.add(tcpPassword);
}
if (ifExists) {
params.add("-ifExists");
}
if (baseDir != null) {
params.add("-baseDir");
params.add(baseDir);
}
Server server = Server.createTcpServer(params.toArray(new String[0])).start();
return server;
} | [
"public",
"static",
"Server",
"startTcpServerMode",
"(",
"String",
"port",
",",
"boolean",
"doSSL",
",",
"String",
"tcpPassword",
",",
"boolean",
"ifExists",
",",
"String",
"baseDir",
")",
"throws",
"SQLException",
"{",
"List",
"<",
"String",
">",
"params",
"=... | Start the server mode.
<p>This calls:
<pre>
Server server = Server.createTcpServer(
"-tcpPort", "9123", "-tcpAllowOthers").start();
</pre>
Supported options are:
-tcpPort, -tcpSSL, -tcpPassword, -tcpAllowOthers, -tcpDaemon,
-trace, -ifExists, -baseDir, -key.
See the main method for details.
<p>
@param port the optional port to use.
@param doSSL if <code>true</code>, ssl is used.
@param tcpPassword an optional tcp passowrd to use.
@param ifExists is <code>true</code>, the database to connect to has to exist.
@param baseDir an optional basedir into which it is allowed to connect.
@return
@throws SQLException | [
"Start",
"the",
"server",
"mode",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/dbs/src/main/java/org/hortonmachine/dbs/h2gis/H2GisServer.java#L58-L87 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java | ComputeNodeOperations.enableComputeNodeScheduling | public void enableComputeNodeScheduling(String poolId, String nodeId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
ComputeNodeEnableSchedulingOptions options = new ComputeNodeEnableSchedulingOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().computeNodes().enableScheduling(poolId, nodeId, options);
} | java | public void enableComputeNodeScheduling(String poolId, String nodeId, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
ComputeNodeEnableSchedulingOptions options = new ComputeNodeEnableSchedulingOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().computeNodes().enableScheduling(poolId, nodeId, options);
} | [
"public",
"void",
"enableComputeNodeScheduling",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"ComputeNodeEnableSchedulingOptions",
... | Enables task scheduling on the specified compute node.
@param poolId The ID of the pool.
@param nodeId The ID of the compute node.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Enables",
"task",
"scheduling",
"on",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L424-L430 |
geomajas/geomajas-project-client-gwt2 | impl/src/main/java/org/geomajas/gwt2/client/service/JsonService.java | JsonService.getDoubleValue | public static Double getDoubleValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isNumber() != null) {
double number = ((JSONNumber) value).doubleValue();
return number;
}
return null;
} | java | public static Double getDoubleValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isNumber() != null) {
double number = ((JSONNumber) value).doubleValue();
return number;
}
return null;
} | [
"public",
"static",
"Double",
"getDoubleValue",
"(",
"JSONObject",
"jsonObject",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"checkArguments",
"(",
"jsonObject",
",",
"key",
")",
";",
"JSONValue",
"value",
"=",
"jsonObject",
".",
"get",
"(",
"ke... | Get a double 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 .
@throws JSONException Thrown in case the key could not be found in the JSON object. | [
"Get",
"a",
"double",
"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#L277-L285 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspContentAttachmentsBean.java | CmsJspContentAttachmentsBean.getAttachmentsForCurrentPage | public static CmsJspContentAttachmentsBean getAttachmentsForCurrentPage(CmsObject cms, CmsResource content)
throws CmsException {
CmsResource page = cms.readResource(cms.getRequestContext().getUri(), CmsResourceFilter.IGNORE_EXPIRATION);
String locale = CmsDetailOnlyContainerUtil.getDetailContainerLocale(
cms,
cms.getRequestContext().getLocale().toString(),
page);
Optional<CmsResource> detailOnly = CmsDetailOnlyContainerUtil.getDetailOnlyPage(cms, content, locale);
if (detailOnly.isPresent()) {
try {
return new CmsJspContentAttachmentsBean(cms, detailOnly.get());
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
return new CmsJspContentAttachmentsBean();
}
} else {
return new CmsJspContentAttachmentsBean();
}
} | java | public static CmsJspContentAttachmentsBean getAttachmentsForCurrentPage(CmsObject cms, CmsResource content)
throws CmsException {
CmsResource page = cms.readResource(cms.getRequestContext().getUri(), CmsResourceFilter.IGNORE_EXPIRATION);
String locale = CmsDetailOnlyContainerUtil.getDetailContainerLocale(
cms,
cms.getRequestContext().getLocale().toString(),
page);
Optional<CmsResource> detailOnly = CmsDetailOnlyContainerUtil.getDetailOnlyPage(cms, content, locale);
if (detailOnly.isPresent()) {
try {
return new CmsJspContentAttachmentsBean(cms, detailOnly.get());
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
return new CmsJspContentAttachmentsBean();
}
} else {
return new CmsJspContentAttachmentsBean();
}
} | [
"public",
"static",
"CmsJspContentAttachmentsBean",
"getAttachmentsForCurrentPage",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"content",
")",
"throws",
"CmsException",
"{",
"CmsResource",
"page",
"=",
"cms",
".",
"readResource",
"(",
"cms",
".",
"getRequestContext",
... | Gets the attachments / detail-only contents for the current page (i.e. cms.getRequestContext().getUri()).<p>
@param cms the CMS context
@param content the content for which to get the attachments
@return a bean providing access to the attachments for the resource
@throws CmsException if something goes wrong | [
"Gets",
"the",
"attachments",
"/",
"detail",
"-",
"only",
"contents",
"for",
"the",
"current",
"page",
"(",
"i",
".",
"e",
".",
"cms",
".",
"getRequestContext",
"()",
".",
"getUri",
"()",
")",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspContentAttachmentsBean.java#L146-L165 |
alibaba/ARouter | arouter-api/src/main/java/com/alibaba/android/arouter/core/InterceptorServiceImpl.java | InterceptorServiceImpl._excute | private static void _excute(final int index, final CancelableCountDownLatch counter, final Postcard postcard) {
if (index < Warehouse.interceptors.size()) {
IInterceptor iInterceptor = Warehouse.interceptors.get(index);
iInterceptor.process(postcard, new InterceptorCallback() {
@Override
public void onContinue(Postcard postcard) {
// Last interceptor excute over with no exception.
counter.countDown();
_excute(index + 1, counter, postcard); // When counter is down, it will be execute continue ,but index bigger than interceptors size, then U know.
}
@Override
public void onInterrupt(Throwable exception) {
// Last interceptor excute over with fatal exception.
postcard.setTag(null == exception ? new HandlerException("No message.") : exception.getMessage()); // save the exception message for backup.
counter.cancel();
// Be attention, maybe the thread in callback has been changed,
// then the catch block(L207) will be invalid.
// The worst is the thread changed to main thread, then the app will be crash, if you throw this exception!
// if (!Looper.getMainLooper().equals(Looper.myLooper())) { // You shouldn't throw the exception if the thread is main thread.
// throw new HandlerException(exception.getMessage());
// }
}
});
}
} | java | private static void _excute(final int index, final CancelableCountDownLatch counter, final Postcard postcard) {
if (index < Warehouse.interceptors.size()) {
IInterceptor iInterceptor = Warehouse.interceptors.get(index);
iInterceptor.process(postcard, new InterceptorCallback() {
@Override
public void onContinue(Postcard postcard) {
// Last interceptor excute over with no exception.
counter.countDown();
_excute(index + 1, counter, postcard); // When counter is down, it will be execute continue ,but index bigger than interceptors size, then U know.
}
@Override
public void onInterrupt(Throwable exception) {
// Last interceptor excute over with fatal exception.
postcard.setTag(null == exception ? new HandlerException("No message.") : exception.getMessage()); // save the exception message for backup.
counter.cancel();
// Be attention, maybe the thread in callback has been changed,
// then the catch block(L207) will be invalid.
// The worst is the thread changed to main thread, then the app will be crash, if you throw this exception!
// if (!Looper.getMainLooper().equals(Looper.myLooper())) { // You shouldn't throw the exception if the thread is main thread.
// throw new HandlerException(exception.getMessage());
// }
}
});
}
} | [
"private",
"static",
"void",
"_excute",
"(",
"final",
"int",
"index",
",",
"final",
"CancelableCountDownLatch",
"counter",
",",
"final",
"Postcard",
"postcard",
")",
"{",
"if",
"(",
"index",
"<",
"Warehouse",
".",
"interceptors",
".",
"size",
"(",
")",
")",
... | Excute interceptor
@param index current interceptor index
@param counter interceptor counter
@param postcard routeMeta | [
"Excute",
"interceptor"
] | train | https://github.com/alibaba/ARouter/blob/1a06912a6e14a57112db1204b43f81c43d721732/arouter-api/src/main/java/com/alibaba/android/arouter/core/InterceptorServiceImpl.java#L74-L100 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/WorkspaceResourcesImpl.java | WorkspaceResourcesImpl.copyWorkspace | public Workspace copyWorkspace(long workspaceId, ContainerDestination containerDestination, EnumSet<WorkspaceCopyInclusion> includes, EnumSet<WorkspaceRemapExclusion> skipRemap) throws SmartsheetException {
return copyWorkspace(workspaceId, containerDestination, includes, skipRemap, null);
} | java | public Workspace copyWorkspace(long workspaceId, ContainerDestination containerDestination, EnumSet<WorkspaceCopyInclusion> includes, EnumSet<WorkspaceRemapExclusion> skipRemap) throws SmartsheetException {
return copyWorkspace(workspaceId, containerDestination, includes, skipRemap, null);
} | [
"public",
"Workspace",
"copyWorkspace",
"(",
"long",
"workspaceId",
",",
"ContainerDestination",
"containerDestination",
",",
"EnumSet",
"<",
"WorkspaceCopyInclusion",
">",
"includes",
",",
"EnumSet",
"<",
"WorkspaceRemapExclusion",
">",
"skipRemap",
")",
"throws",
"Sma... | Creates a copy of the specified workspace.
It mirrors to the following Smartsheet REST API method: POST /workspaces/{workspaceId}/copy
Exceptions:
IllegalArgumentException : if folder is null
InvalidRequestException : if there is any problem with the REST API request
AuthorizationException : if there is any problem with the REST API authorization(access token)
ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
SmartsheetRestException : if there is any other REST API related error occurred during the operation
SmartsheetException : if there is any other error occurred during the operation
@param workspaceId the folder id
@param containerDestination describes the destination container
@param includes optional parameters to include
@param skipRemap optional parameters to exclude
@return the folder
@throws SmartsheetException the smartsheet exception | [
"Creates",
"a",
"copy",
"of",
"the",
"specified",
"workspace",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/WorkspaceResourcesImpl.java#L245-L247 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/JBBPParser.java | JBBPParser.assertArrayLength | private static void assertArrayLength(final int length, final JBBPNamedFieldInfo name) {
if (length < 0) {
throw new JBBPParsingException("Detected negative calculated array length for field '" + (name == null ? "<NO NAME>" : name.getFieldPath()) + "\' [" + JBBPUtils.int2msg(length) + ']');
}
} | java | private static void assertArrayLength(final int length, final JBBPNamedFieldInfo name) {
if (length < 0) {
throw new JBBPParsingException("Detected negative calculated array length for field '" + (name == null ? "<NO NAME>" : name.getFieldPath()) + "\' [" + JBBPUtils.int2msg(length) + ']');
}
} | [
"private",
"static",
"void",
"assertArrayLength",
"(",
"final",
"int",
"length",
",",
"final",
"JBBPNamedFieldInfo",
"name",
")",
"{",
"if",
"(",
"length",
"<",
"0",
")",
"{",
"throw",
"new",
"JBBPParsingException",
"(",
"\"Detected negative calculated array length ... | Ensure that an array length is not a negative one.
@param length the array length to be checked
@param name the name information of a field, it can be null | [
"Ensure",
"that",
"an",
"array",
"length",
"is",
"not",
"a",
"negative",
"one",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/JBBPParser.java#L146-L150 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/util/Utils.java | Utils.toLightweightTypeReference | public static LightweightTypeReference toLightweightTypeReference(
JvmTypeReference typeRef, CommonTypeComputationServices services,
boolean keepUnboundWildcardInformation) {
if (typeRef == null) {
return null;
}
final StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(services, typeRef);
final LightweightTypeReferenceFactory factory = new LightweightTypeReferenceFactory(owner,
keepUnboundWildcardInformation);
final LightweightTypeReference reference = factory.toLightweightReference(typeRef);
return reference;
} | java | public static LightweightTypeReference toLightweightTypeReference(
JvmTypeReference typeRef, CommonTypeComputationServices services,
boolean keepUnboundWildcardInformation) {
if (typeRef == null) {
return null;
}
final StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(services, typeRef);
final LightweightTypeReferenceFactory factory = new LightweightTypeReferenceFactory(owner,
keepUnboundWildcardInformation);
final LightweightTypeReference reference = factory.toLightweightReference(typeRef);
return reference;
} | [
"public",
"static",
"LightweightTypeReference",
"toLightweightTypeReference",
"(",
"JvmTypeReference",
"typeRef",
",",
"CommonTypeComputationServices",
"services",
",",
"boolean",
"keepUnboundWildcardInformation",
")",
"{",
"if",
"(",
"typeRef",
"==",
"null",
")",
"{",
"r... | Convert a type reference to a lightweight type reference.
@param typeRef - reference to convert.
@param services - services used for the conversion
@param keepUnboundWildcardInformation - indicates if the unbound wild card
information must be keeped in the lightweight reference.
@return the lightweight type reference. | [
"Convert",
"a",
"type",
"reference",
"to",
"a",
"lightweight",
"type",
"reference",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/util/Utils.java#L608-L619 |
google/closure-compiler | src/com/google/javascript/jscomp/ClosureRewriteModule.java | ClosureRewriteModule.maybeAddAliasToSymbolTable | private void maybeAddAliasToSymbolTable(Node n, String module) {
if (preprocessorSymbolTable != null) {
n.putBooleanProp(Node.MODULE_ALIAS, true);
// Alias can be used in js types. Types have node type STRING and not NAME so we have to
// use their name as string.
String nodeName =
n.getToken() == Token.STRING
? n.getString()
: preprocessorSymbolTable.getQualifiedName(n);
// We need to include module as part of the name because aliases are local to current module.
// Aliases with the same name from different module should be completely different entities.
String name = "alias_" + module + "_" + nodeName;
preprocessorSymbolTable.addReference(n, name);
}
} | java | private void maybeAddAliasToSymbolTable(Node n, String module) {
if (preprocessorSymbolTable != null) {
n.putBooleanProp(Node.MODULE_ALIAS, true);
// Alias can be used in js types. Types have node type STRING and not NAME so we have to
// use their name as string.
String nodeName =
n.getToken() == Token.STRING
? n.getString()
: preprocessorSymbolTable.getQualifiedName(n);
// We need to include module as part of the name because aliases are local to current module.
// Aliases with the same name from different module should be completely different entities.
String name = "alias_" + module + "_" + nodeName;
preprocessorSymbolTable.addReference(n, name);
}
} | [
"private",
"void",
"maybeAddAliasToSymbolTable",
"(",
"Node",
"n",
",",
"String",
"module",
")",
"{",
"if",
"(",
"preprocessorSymbolTable",
"!=",
"null",
")",
"{",
"n",
".",
"putBooleanProp",
"(",
"Node",
".",
"MODULE_ALIAS",
",",
"true",
")",
";",
"// Alias... | Add alias nodes to the symbol table as they going to be removed by rewriter. Example aliases:
const Foo = goog.require('my.project.Foo');
const bar = goog.require('my.project.baz');
const {baz} = goog.require('my.project.utils'); | [
"Add",
"alias",
"nodes",
"to",
"the",
"symbol",
"table",
"as",
"they",
"going",
"to",
"be",
"removed",
"by",
"rewriter",
".",
"Example",
"aliases",
":"
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ClosureRewriteModule.java#L1811-L1825 |
netty/netty | transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java | AbstractEpollStreamChannel.doWriteMultiple | private int doWriteMultiple(ChannelOutboundBuffer in) throws Exception {
final long maxBytesPerGatheringWrite = config().getMaxBytesPerGatheringWrite();
IovArray array = ((EpollEventLoop) eventLoop()).cleanIovArray();
array.maxBytes(maxBytesPerGatheringWrite);
in.forEachFlushedMessage(array);
if (array.count() >= 1) {
// TODO: Handle the case where cnt == 1 specially.
return writeBytesMultiple(in, array);
}
// cnt == 0, which means the outbound buffer contained empty buffers only.
in.removeBytes(0);
return 0;
} | java | private int doWriteMultiple(ChannelOutboundBuffer in) throws Exception {
final long maxBytesPerGatheringWrite = config().getMaxBytesPerGatheringWrite();
IovArray array = ((EpollEventLoop) eventLoop()).cleanIovArray();
array.maxBytes(maxBytesPerGatheringWrite);
in.forEachFlushedMessage(array);
if (array.count() >= 1) {
// TODO: Handle the case where cnt == 1 specially.
return writeBytesMultiple(in, array);
}
// cnt == 0, which means the outbound buffer contained empty buffers only.
in.removeBytes(0);
return 0;
} | [
"private",
"int",
"doWriteMultiple",
"(",
"ChannelOutboundBuffer",
"in",
")",
"throws",
"Exception",
"{",
"final",
"long",
"maxBytesPerGatheringWrite",
"=",
"config",
"(",
")",
".",
"getMaxBytesPerGatheringWrite",
"(",
")",
";",
"IovArray",
"array",
"=",
"(",
"(",... | Attempt to write multiple {@link ByteBuf} objects.
@param in the collection which contains objects to write.
@return The value that should be decremented from the write quantum which starts at
{@link ChannelConfig#getWriteSpinCount()}. The typical use cases are as follows:
<ul>
<li>0 - if no write was attempted. This is appropriate if an empty {@link ByteBuf} (or other empty content)
is encountered</li>
<li>1 - if a single call to write data was made to the OS</li>
<li>{@link ChannelUtils#WRITE_STATUS_SNDBUF_FULL} - if an attempt to write data was made to the OS, but
no data was accepted</li>
</ul>
@throws Exception If an I/O error occurs. | [
"Attempt",
"to",
"write",
"multiple",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L511-L524 |
jtrfp/javamod | src/main/java/de/quippy/javamod/multimedia/mod/mixer/BasicModMixer.java | BasicModMixer.fillRampDataIntoBuffers | private void fillRampDataIntoBuffers(final int[] leftBuffer, final int[] rightBuffer, final ChannelMemory aktMemo)
{
// Remember changeable values
final int currentTuningPos = aktMemo.currentTuningPos;
final int currentSamplePos = aktMemo.currentSamplePos;
final int currentDirection = aktMemo.currentDirection;
final boolean instrumentFinished = aktMemo.instrumentFinished;
final int actRampVolLeft = aktMemo.actRampVolLeft;
final int actRampVolRight = aktMemo.actRampVolRight;
mixChannelIntoBuffers(leftBuffer, rightBuffer, 0, Helpers.VOL_RAMP_LEN, aktMemo);
// set them back
aktMemo.currentTuningPos = currentTuningPos;
aktMemo.currentSamplePos = currentSamplePos;
aktMemo.instrumentFinished = instrumentFinished;
aktMemo.currentDirection = currentDirection;
aktMemo.actRampVolLeft = actRampVolLeft;
aktMemo.actRampVolRight = actRampVolRight;
} | java | private void fillRampDataIntoBuffers(final int[] leftBuffer, final int[] rightBuffer, final ChannelMemory aktMemo)
{
// Remember changeable values
final int currentTuningPos = aktMemo.currentTuningPos;
final int currentSamplePos = aktMemo.currentSamplePos;
final int currentDirection = aktMemo.currentDirection;
final boolean instrumentFinished = aktMemo.instrumentFinished;
final int actRampVolLeft = aktMemo.actRampVolLeft;
final int actRampVolRight = aktMemo.actRampVolRight;
mixChannelIntoBuffers(leftBuffer, rightBuffer, 0, Helpers.VOL_RAMP_LEN, aktMemo);
// set them back
aktMemo.currentTuningPos = currentTuningPos;
aktMemo.currentSamplePos = currentSamplePos;
aktMemo.instrumentFinished = instrumentFinished;
aktMemo.currentDirection = currentDirection;
aktMemo.actRampVolLeft = actRampVolLeft;
aktMemo.actRampVolRight = actRampVolRight;
} | [
"private",
"void",
"fillRampDataIntoBuffers",
"(",
"final",
"int",
"[",
"]",
"leftBuffer",
",",
"final",
"int",
"[",
"]",
"rightBuffer",
",",
"final",
"ChannelMemory",
"aktMemo",
")",
"{",
"// Remember changeable values",
"final",
"int",
"currentTuningPos",
"=",
"... | Retrieves Sample Data without manipulating the currentSamplePos and currentTuningPos and currentDirection
(a kind of read ahead)
@since 18.06.2006
@param leftBuffer
@param rightBuffer
@param aktMemo | [
"Retrieves",
"Sample",
"Data",
"without",
"manipulating",
"the",
"currentSamplePos",
"and",
"currentTuningPos",
"and",
"currentDirection",
"(",
"a",
"kind",
"of",
"read",
"ahead",
")"
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mod/mixer/BasicModMixer.java#L1292-L1311 |
agmip/agmip-common-functions | src/main/java/org/agmip/common/Event.java | Event.addEvent | public HashMap addEvent(String date, boolean useTemp) {
HashMap ret = new HashMap();
if (useTemp) {
ret.putAll(template);
} else {
ret.put("event", eventType);
}
ret.put("date", date);
getInertIndex(ret);
events.add(next, ret);
return ret;
} | java | public HashMap addEvent(String date, boolean useTemp) {
HashMap ret = new HashMap();
if (useTemp) {
ret.putAll(template);
} else {
ret.put("event", eventType);
}
ret.put("date", date);
getInertIndex(ret);
events.add(next, ret);
return ret;
} | [
"public",
"HashMap",
"addEvent",
"(",
"String",
"date",
",",
"boolean",
"useTemp",
")",
"{",
"HashMap",
"ret",
"=",
"new",
"HashMap",
"(",
")",
";",
"if",
"(",
"useTemp",
")",
"{",
"ret",
".",
"putAll",
"(",
"template",
")",
";",
"}",
"else",
"{",
... | Add a new event into array with selected event type and input date.
@param date The event date
@param useTemp True for using template to create new data
@return The generated event data map | [
"Add",
"a",
"new",
"event",
"into",
"array",
"with",
"selected",
"event",
"type",
"and",
"input",
"date",
"."
] | train | https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/common/Event.java#L123-L134 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/Db.java | Db.findFirst | public static Record findFirst(String sql, Object... paras) {
return MAIN.findFirst(sql, paras);
} | java | public static Record findFirst(String sql, Object... paras) {
return MAIN.findFirst(sql, paras);
} | [
"public",
"static",
"Record",
"findFirst",
"(",
"String",
"sql",
",",
"Object",
"...",
"paras",
")",
"{",
"return",
"MAIN",
".",
"findFirst",
"(",
"sql",
",",
"paras",
")",
";",
"}"
] | Find first record. I recommend add "limit 1" in your sql.
@param sql an SQL statement that may contain one or more '?' IN parameter placeholders
@param paras the parameters of sql
@return the Record object | [
"Find",
"first",
"record",
".",
"I",
"recommend",
"add",
"limit",
"1",
"in",
"your",
"sql",
"."
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Db.java#L292-L294 |
lessthanoptimal/BoofCV | main/boofcv-types/src/main/java/boofcv/struct/image/Planar.java | Planar.get32u8 | public int get32u8( int x , int y ) {
int i = startIndex + y*stride+x;
return ((((GrayU8)bands[0]).data[i]&0xFF) << 24) |
((((GrayU8)bands[1]).data[i]&0xFF) << 16) |
((((GrayU8)bands[2]).data[i]&0xFF) << 8) |
(((GrayU8)bands[3]).data[i]&0xFF);
} | java | public int get32u8( int x , int y ) {
int i = startIndex + y*stride+x;
return ((((GrayU8)bands[0]).data[i]&0xFF) << 24) |
((((GrayU8)bands[1]).data[i]&0xFF) << 16) |
((((GrayU8)bands[2]).data[i]&0xFF) << 8) |
(((GrayU8)bands[3]).data[i]&0xFF);
} | [
"public",
"int",
"get32u8",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"int",
"i",
"=",
"startIndex",
"+",
"y",
"*",
"stride",
"+",
"x",
";",
"return",
"(",
"(",
"(",
"(",
"GrayU8",
")",
"bands",
"[",
"0",
"]",
")",
".",
"data",
"[",
"i",
... | Returns an integer formed from 4 bands. band[0]<<24 | band[1] << 16 | band[2]<<8 | band[3]. Assumes
arrays are U8 type.
@param x column
@param y row
@return 32 bit integer | [
"Returns",
"an",
"integer",
"formed",
"from",
"4",
"bands",
".",
"band",
"[",
"0",
"]",
"<<24",
"|",
"band",
"[",
"1",
"]",
"<<",
"16",
"|",
"band",
"[",
"2",
"]",
"<<8",
"|",
"band",
"[",
"3",
"]",
".",
"Assumes",
"arrays",
"are",
"U8",
"type"... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/image/Planar.java#L322-L328 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndex.java | ClassReflectionIndex.getMethod | public Method getMethod(String returnType, String name, String... paramTypeNames) {
final Map<ParamNameList, Map<String, Method>> nameMap = methodsByTypeName.get(name);
if (nameMap == null) {
return null;
}
final Map<String, Method> paramsMap = nameMap.get(createParamNameList(paramTypeNames));
if (paramsMap == null) {
return null;
}
return paramsMap.get(returnType);
} | java | public Method getMethod(String returnType, String name, String... paramTypeNames) {
final Map<ParamNameList, Map<String, Method>> nameMap = methodsByTypeName.get(name);
if (nameMap == null) {
return null;
}
final Map<String, Method> paramsMap = nameMap.get(createParamNameList(paramTypeNames));
if (paramsMap == null) {
return null;
}
return paramsMap.get(returnType);
} | [
"public",
"Method",
"getMethod",
"(",
"String",
"returnType",
",",
"String",
"name",
",",
"String",
"...",
"paramTypeNames",
")",
"{",
"final",
"Map",
"<",
"ParamNameList",
",",
"Map",
"<",
"String",
",",
"Method",
">",
">",
"nameMap",
"=",
"methodsByTypeNam... | Get a method declared on this object.
@param returnType the method return type name
@param name the name of the method
@param paramTypeNames the parameter type names of the method
@return the method, or {@code null} if no method of that description exists | [
"Get",
"a",
"method",
"declared",
"on",
"this",
"object",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/reflect/ClassReflectionIndex.java#L235-L245 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/module/ModuleSpecProcessor.java | ModuleSpecProcessor.addAllDependenciesAndPermissions | private void addAllDependenciesAndPermissions(final ModuleSpecification moduleSpecification, final AdditionalModuleSpecification module) {
module.addSystemDependencies(moduleSpecification.getSystemDependencies());
module.addLocalDependencies(moduleSpecification.getLocalDependencies());
for(ModuleDependency dep : moduleSpecification.getUserDependencies()) {
if(!dep.getIdentifier().equals(module.getModuleIdentifier())) {
module.addUserDependency(dep);
}
}
for(PermissionFactory factory : moduleSpecification.getPermissionFactories()) {
module.addPermissionFactory(factory);
}
} | java | private void addAllDependenciesAndPermissions(final ModuleSpecification moduleSpecification, final AdditionalModuleSpecification module) {
module.addSystemDependencies(moduleSpecification.getSystemDependencies());
module.addLocalDependencies(moduleSpecification.getLocalDependencies());
for(ModuleDependency dep : moduleSpecification.getUserDependencies()) {
if(!dep.getIdentifier().equals(module.getModuleIdentifier())) {
module.addUserDependency(dep);
}
}
for(PermissionFactory factory : moduleSpecification.getPermissionFactories()) {
module.addPermissionFactory(factory);
}
} | [
"private",
"void",
"addAllDependenciesAndPermissions",
"(",
"final",
"ModuleSpecification",
"moduleSpecification",
",",
"final",
"AdditionalModuleSpecification",
"module",
")",
"{",
"module",
".",
"addSystemDependencies",
"(",
"moduleSpecification",
".",
"getSystemDependencies"... | Gives any additional modules the same dependencies and permissions as the primary module.
<p/>
This makes sure they can access all API classes etc.
@param moduleSpecification The primary module spec
@param module The additional module | [
"Gives",
"any",
"additional",
"modules",
"the",
"same",
"dependencies",
"and",
"permissions",
"as",
"the",
"primary",
"module",
".",
"<p",
"/",
">",
"This",
"makes",
"sure",
"they",
"can",
"access",
"all",
"API",
"classes",
"etc",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/module/ModuleSpecProcessor.java#L161-L172 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/security/impl/BasicEvaluationCtx.java | BasicEvaluationCtx.checkContext | private Attribute checkContext(URI type, URI id, URI issuer,
URI category, int designatorType) {
if (!STRING_ATTRIBUTE_TYPE_URI.equals(type)) return null;
String [] values = null;
switch(designatorType){
case AttributeDesignator.SUBJECT_TARGET:
values = context.getSubjectValues(id.toString());
break;
case AttributeDesignator.RESOURCE_TARGET:
values = context.getResourceValues(id);
break;
case AttributeDesignator.ACTION_TARGET:
values = context.getActionValues(id);
break;
case AttributeDesignator.ENVIRONMENT_TARGET:
values = context.getEnvironmentValues(id);
break;
}
if (values == null || values.length == 0) return null;
String iString = (issuer == null) ? null : issuer.toString();
String tString = type.toString();
if (values.length == 1) {
AttributeValue val = stringToValue(values[0], tString);
return (val == null) ? null :
new SingletonAttribute(id, iString, getCurrentDateTime(), val);
} else {
ArrayList<AttributeValue> valCollection = new ArrayList<AttributeValue>(values.length);
for (int i=0;i<values.length;i++) {
AttributeValue val = stringToValue(values[i], tString);
if (val != null) valCollection.add(val);
}
return new BasicAttribute(id, type, iString, getCurrentDateTime(), valCollection);
}
} | java | private Attribute checkContext(URI type, URI id, URI issuer,
URI category, int designatorType) {
if (!STRING_ATTRIBUTE_TYPE_URI.equals(type)) return null;
String [] values = null;
switch(designatorType){
case AttributeDesignator.SUBJECT_TARGET:
values = context.getSubjectValues(id.toString());
break;
case AttributeDesignator.RESOURCE_TARGET:
values = context.getResourceValues(id);
break;
case AttributeDesignator.ACTION_TARGET:
values = context.getActionValues(id);
break;
case AttributeDesignator.ENVIRONMENT_TARGET:
values = context.getEnvironmentValues(id);
break;
}
if (values == null || values.length == 0) return null;
String iString = (issuer == null) ? null : issuer.toString();
String tString = type.toString();
if (values.length == 1) {
AttributeValue val = stringToValue(values[0], tString);
return (val == null) ? null :
new SingletonAttribute(id, iString, getCurrentDateTime(), val);
} else {
ArrayList<AttributeValue> valCollection = new ArrayList<AttributeValue>(values.length);
for (int i=0;i<values.length;i++) {
AttributeValue val = stringToValue(values[i], tString);
if (val != null) valCollection.add(val);
}
return new BasicAttribute(id, type, iString, getCurrentDateTime(), valCollection);
}
} | [
"private",
"Attribute",
"checkContext",
"(",
"URI",
"type",
",",
"URI",
"id",
",",
"URI",
"issuer",
",",
"URI",
"category",
",",
"int",
"designatorType",
")",
"{",
"if",
"(",
"!",
"STRING_ATTRIBUTE_TYPE_URI",
".",
"equals",
"(",
"type",
")",
")",
"return",... | Private helper that checks the request context for an attribute, or else returns
null | [
"Private",
"helper",
"that",
"checks",
"the",
"request",
"context",
"for",
"an",
"attribute",
"or",
"else",
"returns",
"null"
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/security/impl/BasicEvaluationCtx.java#L706-L739 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTemplateMatching.java | TldTemplateMatching.computeNccDescriptor | public void computeNccDescriptor( NccFeature f , float x0 , float y0 , float x1 , float y1 ) {
double mean = 0;
float widthStep = (x1-x0)/15.0f;
float heightStep = (y1-y0)/15.0f;
// compute the mean value
int index = 0;
for( int y = 0; y < 15; y++ ) {
float sampleY = y0 + y*heightStep;
for( int x = 0; x < 15; x++ ) {
mean += f.value[index++] = interpolate.get_fast(x0 + x * widthStep, sampleY);
}
}
mean /= 15*15;
// compute the variance and save the difference from the mean
double variance = 0;
index = 0;
for( int y = 0; y < 15; y++ ) {
for( int x = 0; x < 15; x++ ) {
double v = f.value[index++] -= mean;
variance += v*v;
}
}
variance /= 15*15;
f.mean = mean;
f.sigma = Math.sqrt(variance);
} | java | public void computeNccDescriptor( NccFeature f , float x0 , float y0 , float x1 , float y1 ) {
double mean = 0;
float widthStep = (x1-x0)/15.0f;
float heightStep = (y1-y0)/15.0f;
// compute the mean value
int index = 0;
for( int y = 0; y < 15; y++ ) {
float sampleY = y0 + y*heightStep;
for( int x = 0; x < 15; x++ ) {
mean += f.value[index++] = interpolate.get_fast(x0 + x * widthStep, sampleY);
}
}
mean /= 15*15;
// compute the variance and save the difference from the mean
double variance = 0;
index = 0;
for( int y = 0; y < 15; y++ ) {
for( int x = 0; x < 15; x++ ) {
double v = f.value[index++] -= mean;
variance += v*v;
}
}
variance /= 15*15;
f.mean = mean;
f.sigma = Math.sqrt(variance);
} | [
"public",
"void",
"computeNccDescriptor",
"(",
"NccFeature",
"f",
",",
"float",
"x0",
",",
"float",
"y0",
",",
"float",
"x1",
",",
"float",
"y1",
")",
"{",
"double",
"mean",
"=",
"0",
";",
"float",
"widthStep",
"=",
"(",
"x1",
"-",
"x0",
")",
"/",
... | Computes the NCC descriptor by sample points at evenly spaced distances inside the rectangle | [
"Computes",
"the",
"NCC",
"descriptor",
"by",
"sample",
"points",
"at",
"evenly",
"spaced",
"distances",
"inside",
"the",
"rectangle"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTemplateMatching.java#L129-L156 |
mfornos/humanize | humanize-slim/src/main/java/humanize/Humanize.java | Humanize.naturalDay | @Expose
public static String naturalDay(Date then, Locale locale)
{
return naturalDay(DateFormat.SHORT, then, locale);
} | java | @Expose
public static String naturalDay(Date then, Locale locale)
{
return naturalDay(DateFormat.SHORT, then, locale);
} | [
"@",
"Expose",
"public",
"static",
"String",
"naturalDay",
"(",
"Date",
"then",
",",
"Locale",
"locale",
")",
"{",
"return",
"naturalDay",
"(",
"DateFormat",
".",
"SHORT",
",",
"then",
",",
"locale",
")",
";",
"}"
] | Same as {@link #naturalDay(Date)} with the given locale.
@param then
The date
@param locale
Target locale
@return String with 'today', 'tomorrow' or 'yesterday' compared to
current day. Otherwise, returns a string formatted according to a
locale sensitive DateFormat. | [
"Same",
"as",
"{",
"@link",
"#naturalDay",
"(",
"Date",
")",
"}",
"with",
"the",
"given",
"locale",
"."
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L1473-L1477 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java | ApiOvhCdndedicated.pops_name_GET | public OvhPop pops_name_GET(String name) throws IOException {
String qPath = "/cdn/dedicated/pops/{name}";
StringBuilder sb = path(qPath, name);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPop.class);
} | java | public OvhPop pops_name_GET(String name) throws IOException {
String qPath = "/cdn/dedicated/pops/{name}";
StringBuilder sb = path(qPath, name);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPop.class);
} | [
"public",
"OvhPop",
"pops_name_GET",
"(",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cdn/dedicated/pops/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"name",
")",
";",
"String",
"resp",
"=",
"execN... | Get this object properties
REST: GET /cdn/dedicated/pops/{name}
@param name [required] Name of the pop | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java#L56-L61 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java | SingleInputGate.assignExclusiveSegments | public void assignExclusiveSegments(NetworkBufferPool networkBufferPool, int networkBuffersPerChannel) throws IOException {
checkState(this.isCreditBased, "Bug in input gate setup logic: exclusive buffers only exist with credit-based flow control.");
checkState(this.networkBufferPool == null, "Bug in input gate setup logic: global buffer pool has" +
"already been set for this input gate.");
this.networkBufferPool = checkNotNull(networkBufferPool);
this.networkBuffersPerChannel = networkBuffersPerChannel;
synchronized (requestLock) {
for (InputChannel inputChannel : inputChannels.values()) {
if (inputChannel instanceof RemoteInputChannel) {
((RemoteInputChannel) inputChannel).assignExclusiveSegments(
networkBufferPool.requestMemorySegments(networkBuffersPerChannel));
}
}
}
} | java | public void assignExclusiveSegments(NetworkBufferPool networkBufferPool, int networkBuffersPerChannel) throws IOException {
checkState(this.isCreditBased, "Bug in input gate setup logic: exclusive buffers only exist with credit-based flow control.");
checkState(this.networkBufferPool == null, "Bug in input gate setup logic: global buffer pool has" +
"already been set for this input gate.");
this.networkBufferPool = checkNotNull(networkBufferPool);
this.networkBuffersPerChannel = networkBuffersPerChannel;
synchronized (requestLock) {
for (InputChannel inputChannel : inputChannels.values()) {
if (inputChannel instanceof RemoteInputChannel) {
((RemoteInputChannel) inputChannel).assignExclusiveSegments(
networkBufferPool.requestMemorySegments(networkBuffersPerChannel));
}
}
}
} | [
"public",
"void",
"assignExclusiveSegments",
"(",
"NetworkBufferPool",
"networkBufferPool",
",",
"int",
"networkBuffersPerChannel",
")",
"throws",
"IOException",
"{",
"checkState",
"(",
"this",
".",
"isCreditBased",
",",
"\"Bug in input gate setup logic: exclusive buffers only ... | Assign the exclusive buffers to all remote input channels directly for credit-based mode.
@param networkBufferPool The global pool to request and recycle exclusive buffers
@param networkBuffersPerChannel The number of exclusive buffers for each channel | [
"Assign",
"the",
"exclusive",
"buffers",
"to",
"all",
"remote",
"input",
"channels",
"directly",
"for",
"credit",
"-",
"based",
"mode",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java#L305-L321 |
code4everything/util | src/main/java/com/zhazhapan/util/Formatter.java | Formatter.toCurrency | public static String toCurrency(Locale locale, double number) {
return NumberFormat.getCurrencyInstance(locale).format(number);
} | java | public static String toCurrency(Locale locale, double number) {
return NumberFormat.getCurrencyInstance(locale).format(number);
} | [
"public",
"static",
"String",
"toCurrency",
"(",
"Locale",
"locale",
",",
"double",
"number",
")",
"{",
"return",
"NumberFormat",
".",
"getCurrencyInstance",
"(",
"locale",
")",
".",
"format",
"(",
"number",
")",
";",
"}"
] | 格式化为货币字符串
@param locale {@link Locale},比如:{@link Locale#CHINA}
@param number 数字
@return 货币字符串
@since 1.0.9 | [
"格式化为货币字符串"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Formatter.java#L156-L158 |
synchronoss/cpo-api | cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java | JdbcCpoAdapter.setContext | protected void setContext(Context context) throws CpoException {
try {
if (context == null) {
context_ = new InitialContext();
} else {
context_ = context;
}
} catch (NamingException e) {
throw new CpoException("Error setting Context", e);
}
} | java | protected void setContext(Context context) throws CpoException {
try {
if (context == null) {
context_ = new InitialContext();
} else {
context_ = context;
}
} catch (NamingException e) {
throw new CpoException("Error setting Context", e);
}
} | [
"protected",
"void",
"setContext",
"(",
"Context",
"context",
")",
"throws",
"CpoException",
"{",
"try",
"{",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"context_",
"=",
"new",
"InitialContext",
"(",
")",
";",
"}",
"else",
"{",
"context_",
"=",
"conte... | DOCUMENT ME!
@param context DOCUMENT ME!
@throws CpoException DOCUMENT ME! | [
"DOCUMENT",
"ME!"
] | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java#L1988-L1998 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/FastStringBuffer.java | FastStringBuffer.setLength | private final void setLength(int l, FastStringBuffer rootFSB)
{
m_lastChunk = l >>> m_chunkBits;
if (m_lastChunk == 0 && m_innerFSB != null)
{
m_innerFSB.setLength(l, rootFSB);
}
else
{
// Undo encapsulation -- pop the innerFSB data back up to root.
// Inefficient, but attempts to keep the code simple.
rootFSB.m_chunkBits = m_chunkBits;
rootFSB.m_maxChunkBits = m_maxChunkBits;
rootFSB.m_rebundleBits = m_rebundleBits;
rootFSB.m_chunkSize = m_chunkSize;
rootFSB.m_chunkMask = m_chunkMask;
rootFSB.m_array = m_array;
rootFSB.m_innerFSB = m_innerFSB;
rootFSB.m_lastChunk = m_lastChunk;
// Finally, truncate this sucker.
rootFSB.m_firstFree = l & m_chunkMask;
}
} | java | private final void setLength(int l, FastStringBuffer rootFSB)
{
m_lastChunk = l >>> m_chunkBits;
if (m_lastChunk == 0 && m_innerFSB != null)
{
m_innerFSB.setLength(l, rootFSB);
}
else
{
// Undo encapsulation -- pop the innerFSB data back up to root.
// Inefficient, but attempts to keep the code simple.
rootFSB.m_chunkBits = m_chunkBits;
rootFSB.m_maxChunkBits = m_maxChunkBits;
rootFSB.m_rebundleBits = m_rebundleBits;
rootFSB.m_chunkSize = m_chunkSize;
rootFSB.m_chunkMask = m_chunkMask;
rootFSB.m_array = m_array;
rootFSB.m_innerFSB = m_innerFSB;
rootFSB.m_lastChunk = m_lastChunk;
// Finally, truncate this sucker.
rootFSB.m_firstFree = l & m_chunkMask;
}
} | [
"private",
"final",
"void",
"setLength",
"(",
"int",
"l",
",",
"FastStringBuffer",
"rootFSB",
")",
"{",
"m_lastChunk",
"=",
"l",
">>>",
"m_chunkBits",
";",
"if",
"(",
"m_lastChunk",
"==",
"0",
"&&",
"m_innerFSB",
"!=",
"null",
")",
"{",
"m_innerFSB",
".",
... | Subroutine for the public setLength() method. Deals with the fact
that truncation may require restoring one of the innerFSBs
NEEDSDOC @param l
NEEDSDOC @param rootFSB | [
"Subroutine",
"for",
"the",
"public",
"setLength",
"()",
"method",
".",
"Deals",
"with",
"the",
"fact",
"that",
"truncation",
"may",
"require",
"restoring",
"one",
"of",
"the",
"innerFSBs"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/FastStringBuffer.java#L357-L383 |
Stratio/deep-spark | deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java | Cells.getShort | public Short getShort(String nameSpace, String cellName) {
return getValue(nameSpace, cellName, Short.class);
} | java | public Short getShort(String nameSpace, String cellName) {
return getValue(nameSpace, cellName, Short.class);
} | [
"public",
"Short",
"getShort",
"(",
"String",
"nameSpace",
",",
"String",
"cellName",
")",
"{",
"return",
"getValue",
"(",
"nameSpace",
",",
"cellName",
",",
"Short",
".",
"class",
")",
";",
"}"
] | Returns the {@code Short} value of the {@link Cell} (associated to {@code table}) whose name iscellName, or null
if this Cells object contains no cell whose name is cellName.
@param nameSpace the name of the owning table
@param cellName the name of the Cell we want to retrieve from this Cells object.
@return the {@code Short} value of the {@link Cell} (associated to {@code table}) whose name is cellName, or null
if this Cells object contains no cell whose name is cellName | [
"Returns",
"the",
"{",
"@code",
"Short",
"}",
"value",
"of",
"the",
"{",
"@link",
"Cell",
"}",
"(",
"associated",
"to",
"{",
"@code",
"table",
"}",
")",
"whose",
"name",
"iscellName",
"or",
"null",
"if",
"this",
"Cells",
"object",
"contains",
"no",
"ce... | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java#L979-L981 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newDataAccessException | public static DataAccessException newDataAccessException(Throwable cause, String message, Object... args) {
return new DataAccessException(format(message, args), cause);
} | java | public static DataAccessException newDataAccessException(Throwable cause, String message, Object... args) {
return new DataAccessException(format(message, args), cause);
} | [
"public",
"static",
"DataAccessException",
"newDataAccessException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"DataAccessException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
"cause... | Constructs and initializes a new {@link DataAccessException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link DataAccessException} was thrown.
@param message {@link String} describing the {@link DataAccessException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link DataAccessException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.dao.DataAccessException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"DataAccessException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Obje... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L167-L169 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java | Uris.getRawFile | public static String getRawFile(final URI uri, final boolean strict) {
return esc(strict).escapePath(getFile(getRawPath(uri, strict)));
} | java | public static String getRawFile(final URI uri, final boolean strict) {
return esc(strict).escapePath(getFile(getRawPath(uri, strict)));
} | [
"public",
"static",
"String",
"getRawFile",
"(",
"final",
"URI",
"uri",
",",
"final",
"boolean",
"strict",
")",
"{",
"return",
"esc",
"(",
"strict",
")",
".",
"escapePath",
"(",
"getFile",
"(",
"getRawPath",
"(",
"uri",
",",
"strict",
")",
")",
")",
";... | Returns the raw (and normalized) file portion of the given URI. The file is everything in the raw path after
(but not including) the last slash. This could also be an empty string, but will not be null.
@param uri the URI to extract the file from
@param strict whether or not to do strict escaping
@return the extracted file | [
"Returns",
"the",
"raw",
"(",
"and",
"normalized",
")",
"file",
"portion",
"of",
"the",
"given",
"URI",
".",
"The",
"file",
"is",
"everything",
"in",
"the",
"raw",
"path",
"after",
"(",
"but",
"not",
"including",
")",
"the",
"last",
"slash",
".",
"This... | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java#L211-L213 |
jbundle/jbundle | thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java | BaseApplet.pushHistory | public void pushHistory(String strHistory, boolean bPushToBrowser)
{
if (m_vHistory == null)
m_vHistory = new Vector<String>();
String strHelpURL = ThinUtil.fixDisplayURL(strHistory, true, true, true, this);
if (bPushToBrowser)
if ((strHistory != null) && (strHistory.length() > 0))
if (strHistory.indexOf(Params.APPLET + '=') == -1)
strHistory = UrlUtil.addURLParam(strHistory, Params.APPLET, this.getClass().getName()); // Adding &applet says this is a screen on not back/etc
m_vHistory.addElement(strHistory);
this.getApplication().showTheDocument(strHelpURL, this, ThinMenuConstants.HELP_WINDOW_CHANGE);
this.pushBrowserHistory(strHistory, this.getStatusText(Constants.INFORMATION), bPushToBrowser); // Let browser know about the new screen
} | java | public void pushHistory(String strHistory, boolean bPushToBrowser)
{
if (m_vHistory == null)
m_vHistory = new Vector<String>();
String strHelpURL = ThinUtil.fixDisplayURL(strHistory, true, true, true, this);
if (bPushToBrowser)
if ((strHistory != null) && (strHistory.length() > 0))
if (strHistory.indexOf(Params.APPLET + '=') == -1)
strHistory = UrlUtil.addURLParam(strHistory, Params.APPLET, this.getClass().getName()); // Adding &applet says this is a screen on not back/etc
m_vHistory.addElement(strHistory);
this.getApplication().showTheDocument(strHelpURL, this, ThinMenuConstants.HELP_WINDOW_CHANGE);
this.pushBrowserHistory(strHistory, this.getStatusText(Constants.INFORMATION), bPushToBrowser); // Let browser know about the new screen
} | [
"public",
"void",
"pushHistory",
"(",
"String",
"strHistory",
",",
"boolean",
"bPushToBrowser",
")",
"{",
"if",
"(",
"m_vHistory",
"==",
"null",
")",
"m_vHistory",
"=",
"new",
"Vector",
"<",
"String",
">",
"(",
")",
";",
"String",
"strHelpURL",
"=",
"ThinU... | Push this command onto the history stack.
@param strHistory The history command to push onto the stack. | [
"Push",
"this",
"command",
"onto",
"the",
"history",
"stack",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L1232-L1244 |
wcm-io/wcm-io-tooling | commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHttpActionException.java | PackageManagerHttpActionException.forIOException | public static PackageManagerHttpActionException forIOException(String url, IOException ex) {
String message = "HTTP call to " + url + " failed: "
+ StringUtils.defaultString(ex.getMessage(), ex.getClass().getSimpleName());
if (ex instanceof SocketTimeoutException) {
message += " (consider to increase the socket timeout using -Dvault.httpSocketTimeoutSec)";
}
return new PackageManagerHttpActionException(message, ex);
} | java | public static PackageManagerHttpActionException forIOException(String url, IOException ex) {
String message = "HTTP call to " + url + " failed: "
+ StringUtils.defaultString(ex.getMessage(), ex.getClass().getSimpleName());
if (ex instanceof SocketTimeoutException) {
message += " (consider to increase the socket timeout using -Dvault.httpSocketTimeoutSec)";
}
return new PackageManagerHttpActionException(message, ex);
} | [
"public",
"static",
"PackageManagerHttpActionException",
"forIOException",
"(",
"String",
"url",
",",
"IOException",
"ex",
")",
"{",
"String",
"message",
"=",
"\"HTTP call to \"",
"+",
"url",
"+",
"\" failed: \"",
"+",
"StringUtils",
".",
"defaultString",
"(",
"ex",... | Create exception instance for I/O exception.
@param url HTTP url called
@param ex I/O exception
@return Exception instance | [
"Create",
"exception",
"instance",
"for",
"I",
"/",
"O",
"exception",
"."
] | train | https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/PackageManagerHttpActionException.java#L55-L62 |
JetBrains/xodus | utils/src/main/java/jetbrains/exodus/util/UTFUtil.java | UTFUtil.writeUTF | public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {
try (DataOutputStream dataStream = new DataOutputStream(stream)) {
int len = str.length();
if (len < SINGLE_UTF_CHUNK_SIZE) {
dataStream.writeUTF(str);
} else {
int startIndex = 0;
int endIndex;
do {
endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;
if (endIndex > len) {
endIndex = len;
}
dataStream.writeUTF(str.substring(startIndex, endIndex));
startIndex += SINGLE_UTF_CHUNK_SIZE;
} while (endIndex < len);
}
}
} | java | public static void writeUTF(@NotNull final OutputStream stream, @NotNull final String str) throws IOException {
try (DataOutputStream dataStream = new DataOutputStream(stream)) {
int len = str.length();
if (len < SINGLE_UTF_CHUNK_SIZE) {
dataStream.writeUTF(str);
} else {
int startIndex = 0;
int endIndex;
do {
endIndex = startIndex + SINGLE_UTF_CHUNK_SIZE;
if (endIndex > len) {
endIndex = len;
}
dataStream.writeUTF(str.substring(startIndex, endIndex));
startIndex += SINGLE_UTF_CHUNK_SIZE;
} while (endIndex < len);
}
}
} | [
"public",
"static",
"void",
"writeUTF",
"(",
"@",
"NotNull",
"final",
"OutputStream",
"stream",
",",
"@",
"NotNull",
"final",
"String",
"str",
")",
"throws",
"IOException",
"{",
"try",
"(",
"DataOutputStream",
"dataStream",
"=",
"new",
"DataOutputStream",
"(",
... | Writes long strings to output stream as several chunks.
@param stream stream to write to.
@param str string to be written.
@throws IOException if something went wrong | [
"Writes",
"long",
"strings",
"to",
"output",
"stream",
"as",
"several",
"chunks",
"."
] | train | https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/utils/src/main/java/jetbrains/exodus/util/UTFUtil.java#L39-L57 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java | ConfigUtils.getLong | public static Long getLong(Config config, String path, Long def) {
if (config.hasPath(path)) {
return Long.valueOf(config.getLong(path));
}
return def;
} | java | public static Long getLong(Config config, String path, Long def) {
if (config.hasPath(path)) {
return Long.valueOf(config.getLong(path));
}
return def;
} | [
"public",
"static",
"Long",
"getLong",
"(",
"Config",
"config",
",",
"String",
"path",
",",
"Long",
"def",
")",
"{",
"if",
"(",
"config",
".",
"hasPath",
"(",
"path",
")",
")",
"{",
"return",
"Long",
".",
"valueOf",
"(",
"config",
".",
"getLong",
"("... | Return {@link Long} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code>
@param config in which the path may be present
@param path key to look for in the config object
@return {@link Long} value at <code>path</code> if <code>config</code> has path. If not return <code>def</code> | [
"Return",
"{",
"@link",
"Long",
"}",
"value",
"at",
"<code",
">",
"path<",
"/",
"code",
">",
"if",
"<code",
">",
"config<",
"/",
"code",
">",
"has",
"path",
".",
"If",
"not",
"return",
"<code",
">",
"def<",
"/",
"code",
">"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ConfigUtils.java#L336-L341 |
alibaba/otter | shared/arbitrate/src/main/java/com/alibaba/otter/shared/arbitrate/impl/zookeeper/ZooKeeperx.java | ZooKeeperx.createNoRetry | public String createNoRetry(final String path, final byte[] data, final CreateMode mode) throws KeeperException,
InterruptedException {
return zookeeper.create(path, data, acl, mode);
} | java | public String createNoRetry(final String path, final byte[] data, final CreateMode mode) throws KeeperException,
InterruptedException {
return zookeeper.create(path, data, acl, mode);
} | [
"public",
"String",
"createNoRetry",
"(",
"final",
"String",
"path",
",",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"CreateMode",
"mode",
")",
"throws",
"KeeperException",
",",
"InterruptedException",
"{",
"return",
"zookeeper",
".",
"create",
"(",
"pat... | add by ljh at 2012-09-13
<pre>
1. 使用zookeeper过程,针对出现ConnectionLoss异常,比如进行create/setData/delete,操作可能已经在zookeeper server上进行应用
2. 针对SelectStageListener进行processId创建时,会以最后一次创建的processId做为调度id. 如果进行retry,之前成功的processId就会被遗漏了
</pre>
@see org.apache.zookeeper.ZooKeeper#create(String path, byte[] path, List acl, CreateMode mode) | [
"add",
"by",
"ljh",
"at",
"2012",
"-",
"09",
"-",
"13"
] | train | https://github.com/alibaba/otter/blob/c7b5f94a0dd162e01ddffaf3a63cade7d23fca55/shared/arbitrate/src/main/java/com/alibaba/otter/shared/arbitrate/impl/zookeeper/ZooKeeperx.java#L75-L78 |
likethecolor/Alchemy-API | src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java | AbstractParser.getBoolean | protected Boolean getBoolean(final String key, final JSONObject jsonObject) {
Boolean value = null;
if(hasKey(key, jsonObject)) {
try {
value = jsonObject.getBoolean(key);
}
catch(JSONException e) {
LOGGER.debug("Could not get boolean from JSONObject for key: " + key, e);
LOGGER.debug("Trying to get the truthy value");
value = getNonStandardBoolean(key, jsonObject);
}
}
return value;
} | java | protected Boolean getBoolean(final String key, final JSONObject jsonObject) {
Boolean value = null;
if(hasKey(key, jsonObject)) {
try {
value = jsonObject.getBoolean(key);
}
catch(JSONException e) {
LOGGER.debug("Could not get boolean from JSONObject for key: " + key, e);
LOGGER.debug("Trying to get the truthy value");
value = getNonStandardBoolean(key, jsonObject);
}
}
return value;
} | [
"protected",
"Boolean",
"getBoolean",
"(",
"final",
"String",
"key",
",",
"final",
"JSONObject",
"jsonObject",
")",
"{",
"Boolean",
"value",
"=",
"null",
";",
"if",
"(",
"hasKey",
"(",
"key",
",",
"jsonObject",
")",
")",
"{",
"try",
"{",
"value",
"=",
... | Check to make sure the JSONObject has the specified key and if so return
the value as a boolean. If no key is found null is returned.
If the value is not JSON boolean (true/false) then {@link #getNonStandardBoolean(String, JSONObject)}
is called.
@param key name of the field to fetch from the json object
@param jsonObject object from which to fetch the value
@return boolean value corresponding to the key or null if key not found
@see #getNonStandardBoolean(String, JSONObject) | [
"Check",
"to",
"make",
"sure",
"the",
"JSONObject",
"has",
"the",
"specified",
"key",
"and",
"if",
"so",
"return",
"the",
"value",
"as",
"a",
"boolean",
".",
"If",
"no",
"key",
"is",
"found",
"null",
"is",
"returned",
"."
] | train | https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/AbstractParser.java#L80-L93 |
LearnLib/automatalib | commons/smartcollections/src/main/java/net/automatalib/commons/smartcollections/AbstractLinkedList.java | AbstractLinkedList.replaceEntry | protected void replaceEntry(T oldEntry, T newEntry) {
T prev = oldEntry.getPrev();
T next = newEntry.getNext();
if (prev != null) {
prev.setNext(newEntry);
} else {
head = newEntry;
}
if (next != null) {
next.setPrev(newEntry);
} else {
last = newEntry;
}
} | java | protected void replaceEntry(T oldEntry, T newEntry) {
T prev = oldEntry.getPrev();
T next = newEntry.getNext();
if (prev != null) {
prev.setNext(newEntry);
} else {
head = newEntry;
}
if (next != null) {
next.setPrev(newEntry);
} else {
last = newEntry;
}
} | [
"protected",
"void",
"replaceEntry",
"(",
"T",
"oldEntry",
",",
"T",
"newEntry",
")",
"{",
"T",
"prev",
"=",
"oldEntry",
".",
"getPrev",
"(",
")",
";",
"T",
"next",
"=",
"newEntry",
".",
"getNext",
"(",
")",
";",
"if",
"(",
"prev",
"!=",
"null",
")... | Replaces an entry in the list.
@param oldEntry
the entry to be replaced.
@param newEntry
the replacement entry. | [
"Replaces",
"an",
"entry",
"in",
"the",
"list",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/commons/smartcollections/src/main/java/net/automatalib/commons/smartcollections/AbstractLinkedList.java#L179-L192 |
spring-projects/spring-data-solr | src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java | DefaultQueryParser.appendSort | protected void appendSort(SolrQuery solrQuery, @Nullable Sort sort, @Nullable Class<?> domainType) {
if (sort == null) {
return;
}
for (Order order : sort) {
solrQuery.addSort(getMappedFieldName(order.getProperty(), domainType),
order.isAscending() ? ORDER.asc : ORDER.desc);
}
} | java | protected void appendSort(SolrQuery solrQuery, @Nullable Sort sort, @Nullable Class<?> domainType) {
if (sort == null) {
return;
}
for (Order order : sort) {
solrQuery.addSort(getMappedFieldName(order.getProperty(), domainType),
order.isAscending() ? ORDER.asc : ORDER.desc);
}
} | [
"protected",
"void",
"appendSort",
"(",
"SolrQuery",
"solrQuery",
",",
"@",
"Nullable",
"Sort",
"sort",
",",
"@",
"Nullable",
"Class",
"<",
"?",
">",
"domainType",
")",
"{",
"if",
"(",
"sort",
"==",
"null",
")",
"{",
"return",
";",
"}",
"for",
"(",
"... | Append sorting parameters to {@link SolrQuery}
@param solrQuery
@param sort | [
"Append",
"sorting",
"parameters",
"to",
"{",
"@link",
"SolrQuery",
"}"
] | train | https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/DefaultQueryParser.java#L505-L515 |
landawn/AbacusUtil | src/com/landawn/abacus/util/JdbcUtil.java | JdbcUtil.prepareQuery | public static PreparedQuery prepareQuery(final Connection conn, final String sql, final boolean autoGeneratedKeys) throws SQLException {
return new PreparedQuery(conn.prepareStatement(sql, autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS));
} | java | public static PreparedQuery prepareQuery(final Connection conn, final String sql, final boolean autoGeneratedKeys) throws SQLException {
return new PreparedQuery(conn.prepareStatement(sql, autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS));
} | [
"public",
"static",
"PreparedQuery",
"prepareQuery",
"(",
"final",
"Connection",
"conn",
",",
"final",
"String",
"sql",
",",
"final",
"boolean",
"autoGeneratedKeys",
")",
"throws",
"SQLException",
"{",
"return",
"new",
"PreparedQuery",
"(",
"conn",
".",
"prepareSt... | Never write below code because it will definitely cause {@code Connection} leak:
<pre>
<code>
JdbcUtil.prepareQuery(dataSource.getConnection(), sql, autoGeneratedKeys);
</code>
</pre>
@param conn the specified {@code conn} won't be close after this query is executed.
@param sql
@param autoGeneratedKeys
@return
@throws SQLException | [
"Never",
"write",
"below",
"code",
"because",
"it",
"will",
"definitely",
"cause",
"{",
"@code",
"Connection",
"}",
"leak",
":",
"<pre",
">",
"<code",
">",
"JdbcUtil",
".",
"prepareQuery",
"(",
"dataSource",
".",
"getConnection",
"()",
"sql",
"autoGeneratedKey... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L1291-L1293 |
Waikato/moa | moa/src/main/java/moa/classifiers/lazy/SAMkNN.java | SAMkNN.clean | private void clean(Instances cleanAgainst, Instances toClean, boolean onlyLast) {
if (cleanAgainst.numInstances() > this.kOption.getValue() && toClean.numInstances() > 0){
if (onlyLast){
cleanSingle(cleanAgainst, (cleanAgainst.numInstances()-1), toClean);
}else{
for (int i=0; i < cleanAgainst.numInstances(); i++){
cleanSingle(cleanAgainst, i, toClean);
}
}
}
} | java | private void clean(Instances cleanAgainst, Instances toClean, boolean onlyLast) {
if (cleanAgainst.numInstances() > this.kOption.getValue() && toClean.numInstances() > 0){
if (onlyLast){
cleanSingle(cleanAgainst, (cleanAgainst.numInstances()-1), toClean);
}else{
for (int i=0; i < cleanAgainst.numInstances(); i++){
cleanSingle(cleanAgainst, i, toClean);
}
}
}
} | [
"private",
"void",
"clean",
"(",
"Instances",
"cleanAgainst",
",",
"Instances",
"toClean",
",",
"boolean",
"onlyLast",
")",
"{",
"if",
"(",
"cleanAgainst",
".",
"numInstances",
"(",
")",
">",
"this",
".",
"kOption",
".",
"getValue",
"(",
")",
"&&",
"toClea... | Removes distance-based all instances from the input samples that contradict those in the STM. | [
"Removes",
"distance",
"-",
"based",
"all",
"instances",
"from",
"the",
"input",
"samples",
"that",
"contradict",
"those",
"in",
"the",
"STM",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/SAMkNN.java#L359-L369 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/util/GlobusPathMatchingResourcePatternResolver.java | GlobusPathMatchingResourcePatternResolver.parseFilesInDirectory | private void parseFilesInDirectory(File currentDirectory, Vector<GlobusResource> pathsMatchingLocationPattern) {
File[] directoryContents = null;
if (currentDirectory.isDirectory()) {
directoryContents = currentDirectory.listFiles(); //Get a list of the files and directories
} else {
directoryContents = new File[1];
directoryContents[0] = currentDirectory;
}
String absolutePath = null;
Matcher locationPatternMatcher = null;
if(directoryContents != null){
for (File currentFile : directoryContents) {
if (currentFile.isFile()) { //We are only interested in files not directories
absolutePath = currentFile.getAbsolutePath();
locationPatternMatcher = locationPattern.matcher(absolutePath);
if (locationPatternMatcher.find()) {
pathsMatchingLocationPattern.add(new GlobusResource(absolutePath));
}
}
}
}
} | java | private void parseFilesInDirectory(File currentDirectory, Vector<GlobusResource> pathsMatchingLocationPattern) {
File[] directoryContents = null;
if (currentDirectory.isDirectory()) {
directoryContents = currentDirectory.listFiles(); //Get a list of the files and directories
} else {
directoryContents = new File[1];
directoryContents[0] = currentDirectory;
}
String absolutePath = null;
Matcher locationPatternMatcher = null;
if(directoryContents != null){
for (File currentFile : directoryContents) {
if (currentFile.isFile()) { //We are only interested in files not directories
absolutePath = currentFile.getAbsolutePath();
locationPatternMatcher = locationPattern.matcher(absolutePath);
if (locationPatternMatcher.find()) {
pathsMatchingLocationPattern.add(new GlobusResource(absolutePath));
}
}
}
}
} | [
"private",
"void",
"parseFilesInDirectory",
"(",
"File",
"currentDirectory",
",",
"Vector",
"<",
"GlobusResource",
">",
"pathsMatchingLocationPattern",
")",
"{",
"File",
"[",
"]",
"directoryContents",
"=",
"null",
";",
"if",
"(",
"currentDirectory",
".",
"isDirector... | Compares every file's Absolute Path against the locationPattern, if they match
a GlobusResource is created with the file's Absolute Path and added to pathsMatchingLocationPattern.
@param currentDirectory The directory whose files to parse.
@param pathsMatchingLocationPattern Holds GlobusResource instances of all the paths which matched the locationPattern | [
"Compares",
"every",
"file",
"s",
"Absolute",
"Path",
"against",
"the",
"locationPattern",
"if",
"they",
"match",
"a",
"GlobusResource",
"is",
"created",
"with",
"the",
"file",
"s",
"Absolute",
"Path",
"and",
"added",
"to",
"pathsMatchingLocationPattern",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/util/GlobusPathMatchingResourcePatternResolver.java#L171-L192 |
fcrepo4/fcrepo4 | fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/BinaryServiceImpl.java | BinaryServiceImpl.find | @Override
public FedoraBinary find(final FedoraSession session, final String path) {
return cast(findNode(session, path));
} | java | @Override
public FedoraBinary find(final FedoraSession session, final String path) {
return cast(findNode(session, path));
} | [
"@",
"Override",
"public",
"FedoraBinary",
"find",
"(",
"final",
"FedoraSession",
"session",
",",
"final",
"String",
"path",
")",
"{",
"return",
"cast",
"(",
"findNode",
"(",
"session",
",",
"path",
")",
")",
";",
"}"
] | Retrieve a Datastream instance by pid and dsid
@param path jcr path to the datastream
@return datastream | [
"Retrieve",
"a",
"Datastream",
"instance",
"by",
"pid",
"and",
"dsid"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/BinaryServiceImpl.java#L127-L130 |
zandero/settings | src/main/java/com/zandero/settings/Settings.java | Settings.getList | public <T> List<T> getList(String name, Class<T> type) {
Object value = super.get(name);
// make sure correct objects are returned
if (value instanceof List) {
ArrayList<T> output = new ArrayList<>();
List list = (List) value;
for (Object item : list) {
output.add(type.cast(item));
}
return output;
}
throw new IllegalArgumentException("Setting: '" + name + "', can't be converted to List<" + type.getName() + ">: '" + value + "'!");
} | java | public <T> List<T> getList(String name, Class<T> type) {
Object value = super.get(name);
// make sure correct objects are returned
if (value instanceof List) {
ArrayList<T> output = new ArrayList<>();
List list = (List) value;
for (Object item : list) {
output.add(type.cast(item));
}
return output;
}
throw new IllegalArgumentException("Setting: '" + name + "', can't be converted to List<" + type.getName() + ">: '" + value + "'!");
} | [
"public",
"<",
"T",
">",
"List",
"<",
"T",
">",
"getList",
"(",
"String",
"name",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"Object",
"value",
"=",
"super",
".",
"get",
"(",
"name",
")",
";",
"// make sure correct objects are returned",
"if",
"(",... | Returns setting a list of objects
@param name setting name
@param type type of object
@param <T> type
@return list of found setting
@throws IllegalArgumentException in case settings could not be converted to given type | [
"Returns",
"setting",
"a",
"list",
"of",
"objects"
] | train | https://github.com/zandero/settings/blob/802b44f41bc75e7eb2761028db8c73b7e59620c7/src/main/java/com/zandero/settings/Settings.java#L201-L219 |
lightblueseas/vintage-time | src/main/java/de/alpharogroup/date/CalculateDateExtensions.java | CalculateDateExtensions.substractMonthsFromDate | public static Date substractMonthsFromDate(final Date date, final int substractMonths)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.MONTH, substractMonths * -1);
return dateOnCalendar.getTime();
} | java | public static Date substractMonthsFromDate(final Date date, final int substractMonths)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.MONTH, substractMonths * -1);
return dateOnCalendar.getTime();
} | [
"public",
"static",
"Date",
"substractMonthsFromDate",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"substractMonths",
")",
"{",
"final",
"Calendar",
"dateOnCalendar",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"dateOnCalendar",
".",
"setTime",
"(... | Substract months to the given Date object and returns it.
@param date
The Date object to substract the months.
@param substractMonths
The months to substract.
@return The resulted Date object. | [
"Substract",
"months",
"to",
"the",
"given",
"Date",
"object",
"and",
"returns",
"it",
"."
] | train | https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/CalculateDateExtensions.java#L405-L411 |
cdk/cdk | app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java | DepictionGenerator.withHighlight | public DepictionGenerator withHighlight(Iterable<? extends IChemObject> chemObjs, Color color) {
DepictionGenerator copy = new DepictionGenerator(this);
for (IChemObject chemObj : chemObjs)
copy.highlight.put(chemObj, color);
return copy;
} | java | public DepictionGenerator withHighlight(Iterable<? extends IChemObject> chemObjs, Color color) {
DepictionGenerator copy = new DepictionGenerator(this);
for (IChemObject chemObj : chemObjs)
copy.highlight.put(chemObj, color);
return copy;
} | [
"public",
"DepictionGenerator",
"withHighlight",
"(",
"Iterable",
"<",
"?",
"extends",
"IChemObject",
">",
"chemObjs",
",",
"Color",
"color",
")",
"{",
"DepictionGenerator",
"copy",
"=",
"new",
"DepictionGenerator",
"(",
"this",
")",
";",
"for",
"(",
"IChemObjec... | Highlight the provided set of atoms and bonds in the depiction in the
specified color.
Calling this methods appends to the current highlight buffer. The buffer
is cleared after each depiction is generated (e.g. {@link #depict(IAtomContainer)}).
@param chemObjs set of atoms and bonds
@param color the color to highlight
@return new generator for method chaining
@see StandardGenerator#HIGHLIGHT_COLOR | [
"Highlight",
"the",
"provided",
"set",
"of",
"atoms",
"and",
"bonds",
"in",
"the",
"depiction",
"in",
"the",
"specified",
"color",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/DepictionGenerator.java#L978-L983 |
kongchen/swagger-maven-plugin | src/main/java/com/github/kongchen/swagger/docgen/AbstractDocumentSource.java | AbstractDocumentSource.resolveSwaggerExtensions | protected List<SwaggerExtension> resolveSwaggerExtensions() throws GenerateException {
List<String> clazzes = apiSource.getSwaggerExtensions();
List<SwaggerExtension> resolved = new ArrayList<SwaggerExtension>();
if (clazzes != null) {
for (String clazz : clazzes) {
SwaggerExtension extension = null;
//Try to get a parameterized constructor for extensions that are log-enabled.
try {
try {
Constructor<?> constructor = Class.forName(clazz).getConstructor(Log.class);
extension = (SwaggerExtension) constructor.newInstance(LOG);
} catch (NoSuchMethodException nsme) {
extension = (SwaggerExtension) Class.forName(clazz).newInstance();
}
}
catch (Exception e) {
throw new GenerateException("Cannot load Swagger extension: " + clazz, e);
}
resolved.add(extension);
}
}
return resolved;
} | java | protected List<SwaggerExtension> resolveSwaggerExtensions() throws GenerateException {
List<String> clazzes = apiSource.getSwaggerExtensions();
List<SwaggerExtension> resolved = new ArrayList<SwaggerExtension>();
if (clazzes != null) {
for (String clazz : clazzes) {
SwaggerExtension extension = null;
//Try to get a parameterized constructor for extensions that are log-enabled.
try {
try {
Constructor<?> constructor = Class.forName(clazz).getConstructor(Log.class);
extension = (SwaggerExtension) constructor.newInstance(LOG);
} catch (NoSuchMethodException nsme) {
extension = (SwaggerExtension) Class.forName(clazz).newInstance();
}
}
catch (Exception e) {
throw new GenerateException("Cannot load Swagger extension: " + clazz, e);
}
resolved.add(extension);
}
}
return resolved;
} | [
"protected",
"List",
"<",
"SwaggerExtension",
">",
"resolveSwaggerExtensions",
"(",
")",
"throws",
"GenerateException",
"{",
"List",
"<",
"String",
">",
"clazzes",
"=",
"apiSource",
".",
"getSwaggerExtensions",
"(",
")",
";",
"List",
"<",
"SwaggerExtension",
">",
... | Resolves all {@link SwaggerExtension} instances configured to be added to the Swagger configuration.
@return List of {@link SwaggerExtension} which should be added to the swagger configuration
@throws GenerateException if the swagger extensions could not be created / resolved | [
"Resolves",
"all",
"{",
"@link",
"SwaggerExtension",
"}",
"instances",
"configured",
"to",
"be",
"added",
"to",
"the",
"Swagger",
"configuration",
"."
] | train | https://github.com/kongchen/swagger-maven-plugin/blob/0709b035ef45e1cb13189cd7f949c52c10557747/src/main/java/com/github/kongchen/swagger/docgen/AbstractDocumentSource.java#L429-L451 |
softindex/datakernel | cloud-fs/src/main/java/io/datakernel/remotefs/RemoteFsClusterClient.java | RemoteFsClusterClient.ofFailure | private static <T, U> Promise<T> ofFailure(String message, List<Try<U>> failed) {
StacklessException exception = new StacklessException(RemoteFsClusterClient.class, message);
failed.stream()
.map(Try::getExceptionOrNull)
.filter(Objects::nonNull)
.forEach(exception::addSuppressed);
return Promise.ofException(exception);
} | java | private static <T, U> Promise<T> ofFailure(String message, List<Try<U>> failed) {
StacklessException exception = new StacklessException(RemoteFsClusterClient.class, message);
failed.stream()
.map(Try::getExceptionOrNull)
.filter(Objects::nonNull)
.forEach(exception::addSuppressed);
return Promise.ofException(exception);
} | [
"private",
"static",
"<",
"T",
",",
"U",
">",
"Promise",
"<",
"T",
">",
"ofFailure",
"(",
"String",
"message",
",",
"List",
"<",
"Try",
"<",
"U",
">",
">",
"failed",
")",
"{",
"StacklessException",
"exception",
"=",
"new",
"StacklessException",
"(",
"R... | shortcut for creating single Exception from list of possibly failed tries | [
"shortcut",
"for",
"creating",
"single",
"Exception",
"from",
"list",
"of",
"possibly",
"failed",
"tries"
] | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/cloud-fs/src/main/java/io/datakernel/remotefs/RemoteFsClusterClient.java#L239-L246 |
pressgang-ccms/PressGangCCMSCommonUtilities | src/main/java/org/jboss/pressgang/ccms/utils/common/StringUtilities.java | StringUtilities.lastIndexOf | public static int lastIndexOf(final String input, final char delim) {
return input == null ? -1 : lastIndexOf(input, delim, input.length());
} | java | public static int lastIndexOf(final String input, final char delim) {
return input == null ? -1 : lastIndexOf(input, delim, input.length());
} | [
"public",
"static",
"int",
"lastIndexOf",
"(",
"final",
"String",
"input",
",",
"final",
"char",
"delim",
")",
"{",
"return",
"input",
"==",
"null",
"?",
"-",
"1",
":",
"lastIndexOf",
"(",
"input",
",",
"delim",
",",
"input",
".",
"length",
"(",
")",
... | Gets the last index of a character ignoring characters that have been escaped
@param input The string to be searched
@param delim The character to be found
@return The index of the found character or -1 if the character wasn't found | [
"Gets",
"the",
"last",
"index",
"of",
"a",
"character",
"ignoring",
"characters",
"that",
"have",
"been",
"escaped"
] | train | https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/StringUtilities.java#L248-L250 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java | SSLUtils.lengthOf | public static int lengthOf(WsByteBuffer[] src, int startIndex) {
int length = 0;
if (null != src) {
for (int i = startIndex; i < src.length && null != src[i]; i++) {
length += src[i].remaining();
}
}
return length;
} | java | public static int lengthOf(WsByteBuffer[] src, int startIndex) {
int length = 0;
if (null != src) {
for (int i = startIndex; i < src.length && null != src[i]; i++) {
length += src[i].remaining();
}
}
return length;
} | [
"public",
"static",
"int",
"lengthOf",
"(",
"WsByteBuffer",
"[",
"]",
"src",
",",
"int",
"startIndex",
")",
"{",
"int",
"length",
"=",
"0",
";",
"if",
"(",
"null",
"!=",
"src",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"startIndex",
";",
"i",
"<",
"... | Find the amount of data in the source buffers, starting at the input index.
@param src
@param startIndex
@return int | [
"Find",
"the",
"amount",
"of",
"data",
"in",
"the",
"source",
"buffers",
"starting",
"at",
"the",
"input",
"index",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L1448-L1456 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanO.java | BeanO.reAssociateHandleList | HandleListInterface reAssociateHandleList() // d662032
throws CSIException
{
HandleListInterface hl;
if (connectionHandleList == null)
{
hl = HandleListProxy.INSTANCE;
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "reAssociateHandleList: " + connectionHandleList);
hl = connectionHandleList;
try
{
hl.reAssociate();
} catch (Exception ex)
{
throw new CSIException("", ex);
}
}
return hl;
} | java | HandleListInterface reAssociateHandleList() // d662032
throws CSIException
{
HandleListInterface hl;
if (connectionHandleList == null)
{
hl = HandleListProxy.INSTANCE;
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "reAssociateHandleList: " + connectionHandleList);
hl = connectionHandleList;
try
{
hl.reAssociate();
} catch (Exception ex)
{
throw new CSIException("", ex);
}
}
return hl;
} | [
"HandleListInterface",
"reAssociateHandleList",
"(",
")",
"// d662032",
"throws",
"CSIException",
"{",
"HandleListInterface",
"hl",
";",
"if",
"(",
"connectionHandleList",
"==",
"null",
")",
"{",
"hl",
"=",
"HandleListProxy",
".",
"INSTANCE",
";",
"}",
"else",
"{"... | Reassociates handles in the handle list associated with this bean, and
returns a handle list to be pushed onto the thread handle list stack.
@return the handle list to push onto the thread stack | [
"Reassociates",
"handles",
"in",
"the",
"handle",
"list",
"associated",
"with",
"this",
"bean",
"and",
"returns",
"a",
"handle",
"list",
"to",
"be",
"pushed",
"onto",
"the",
"thread",
"handle",
"list",
"stack",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BeanO.java#L1782-L1807 |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/Timespan.java | Timespan.substractWithZeroFloor | public Timespan substractWithZeroFloor(Timespan other) {
if (getTimeUnit() == other.getTimeUnit()) {
long delta = Math.max(0, getDuration() - other.getDuration());
return new Timespan(delta, getTimeUnit());
}
long delta = Math.max(0, getDurationInMilliseconds() - other.getDurationInMilliseconds());
return new Timespan(delta, TimeUnit.MILLISECOND);
} | java | public Timespan substractWithZeroFloor(Timespan other) {
if (getTimeUnit() == other.getTimeUnit()) {
long delta = Math.max(0, getDuration() - other.getDuration());
return new Timespan(delta, getTimeUnit());
}
long delta = Math.max(0, getDurationInMilliseconds() - other.getDurationInMilliseconds());
return new Timespan(delta, TimeUnit.MILLISECOND);
} | [
"public",
"Timespan",
"substractWithZeroFloor",
"(",
"Timespan",
"other",
")",
"{",
"if",
"(",
"getTimeUnit",
"(",
")",
"==",
"other",
".",
"getTimeUnit",
"(",
")",
")",
"{",
"long",
"delta",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"getDuration",
"(",
... | Creates and returns a new timespan whose duration is {@code this}
timespan's duration minus the {@code other} timespan's duration.
<p>
The time unit is preserved if {@code other} has the same unit
as {@code this}.
<p>
Negative timespans are not supported, so if the {@code other}
timespan duration is greater than {@code this} timespan duration,
a timespan of zero is returned (i.e., a negative timespan is never
returned).
@param other
the timespan to subtract from this one
@return a new timespan representing {@code this - other} | [
"Creates",
"and",
"returns",
"a",
"new",
"timespan",
"whose",
"duration",
"is",
"{",
"@code",
"this",
"}",
"timespan",
"s",
"duration",
"minus",
"the",
"{",
"@code",
"other",
"}",
"timespan",
"s",
"duration",
".",
"<p",
">",
"The",
"time",
"unit",
"is",
... | train | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java#L174-L183 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/modules/SqlTileWriter.java | SqlTileWriter.exists | public boolean exists(final String pTileSource, final long pMapTileIndex) {
return 1 == getRowCount(primaryKey, getPrimaryKeyParameters(getIndex(pMapTileIndex), pTileSource));
} | java | public boolean exists(final String pTileSource, final long pMapTileIndex) {
return 1 == getRowCount(primaryKey, getPrimaryKeyParameters(getIndex(pMapTileIndex), pTileSource));
} | [
"public",
"boolean",
"exists",
"(",
"final",
"String",
"pTileSource",
",",
"final",
"long",
"pMapTileIndex",
")",
"{",
"return",
"1",
"==",
"getRowCount",
"(",
"primaryKey",
",",
"getPrimaryKeyParameters",
"(",
"getIndex",
"(",
"pMapTileIndex",
")",
",",
"pTileS... | Returns true if the given tile source and tile coordinates exist in the cache
@since 5.6 | [
"Returns",
"true",
"if",
"the",
"given",
"tile",
"source",
"and",
"tile",
"coordinates",
"exist",
"in",
"the",
"cache"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/modules/SqlTileWriter.java#L183-L185 |
cdapio/tephra | tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java | BalanceBooks.verify | public boolean verify() {
boolean success = false;
try {
TransactionAwareHTable table = new TransactionAwareHTable(conn.getTable(TABLE));
TransactionContext context = new TransactionContext(txClient, table);
LOG.info("VERIFYING BALANCES");
context.start();
long totalBalance = 0;
ResultScanner scanner = table.getScanner(new Scan());
try {
for (Result r : scanner) {
if (!r.isEmpty()) {
int rowId = Bytes.toInt(r.getRow());
long balance = Bytes.toLong(r.getValue(FAMILY, COL));
totalBalance += balance;
LOG.info("Client #{}: balance = ${}", rowId, balance);
}
}
} finally {
if (scanner != null) {
Closeables.closeQuietly(scanner);
}
}
if (totalBalance == 0) {
LOG.info("PASSED!");
success = true;
} else {
LOG.info("FAILED! Total balance should be 0 but was {}", totalBalance);
}
context.finish();
} catch (Exception e) {
LOG.error("Failed verification check", e);
}
return success;
} | java | public boolean verify() {
boolean success = false;
try {
TransactionAwareHTable table = new TransactionAwareHTable(conn.getTable(TABLE));
TransactionContext context = new TransactionContext(txClient, table);
LOG.info("VERIFYING BALANCES");
context.start();
long totalBalance = 0;
ResultScanner scanner = table.getScanner(new Scan());
try {
for (Result r : scanner) {
if (!r.isEmpty()) {
int rowId = Bytes.toInt(r.getRow());
long balance = Bytes.toLong(r.getValue(FAMILY, COL));
totalBalance += balance;
LOG.info("Client #{}: balance = ${}", rowId, balance);
}
}
} finally {
if (scanner != null) {
Closeables.closeQuietly(scanner);
}
}
if (totalBalance == 0) {
LOG.info("PASSED!");
success = true;
} else {
LOG.info("FAILED! Total balance should be 0 but was {}", totalBalance);
}
context.finish();
} catch (Exception e) {
LOG.error("Failed verification check", e);
}
return success;
} | [
"public",
"boolean",
"verify",
"(",
")",
"{",
"boolean",
"success",
"=",
"false",
";",
"try",
"{",
"TransactionAwareHTable",
"table",
"=",
"new",
"TransactionAwareHTable",
"(",
"conn",
".",
"getTable",
"(",
"TABLE",
")",
")",
";",
"TransactionContext",
"contex... | Validates the current state of the data stored at the end of the test. Each update by a client consists of two
parts: a withdrawal of a random amount from a randomly select other account, and a corresponding to deposit to
the client's own account. So, if all the updates were performed consistently (no partial updates or partial
rollbacks), then the total sum of all balances at the end should be 0. | [
"Validates",
"the",
"current",
"state",
"of",
"the",
"data",
"stored",
"at",
"the",
"end",
"of",
"the",
"test",
".",
"Each",
"update",
"by",
"a",
"client",
"consists",
"of",
"two",
"parts",
":",
"a",
"withdrawal",
"of",
"a",
"random",
"amount",
"from",
... | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java#L145-L180 |
michael-rapp/AndroidMaterialDialog | library/src/main/java/de/mrapp/android/dialog/view/ScrollView.java | ScrollView.notifyOnScrolled | private void notifyOnScrolled(final boolean scrolledToTop, final boolean scrolledToBottom) {
for (ScrollListener listener : scrollListeners) {
listener.onScrolled(scrolledToTop, scrolledToBottom);
}
} | java | private void notifyOnScrolled(final boolean scrolledToTop, final boolean scrolledToBottom) {
for (ScrollListener listener : scrollListeners) {
listener.onScrolled(scrolledToTop, scrolledToBottom);
}
} | [
"private",
"void",
"notifyOnScrolled",
"(",
"final",
"boolean",
"scrolledToTop",
",",
"final",
"boolean",
"scrolledToBottom",
")",
"{",
"for",
"(",
"ScrollListener",
"listener",
":",
"scrollListeners",
")",
"{",
"listener",
".",
"onScrolled",
"(",
"scrolledToTop",
... | Notifies, when the scroll view has been scrolled.
@param scrolledToTop
True, if the scroll view is scrolled to the top, false otherwise
@param scrolledToBottom
True, if the scroll view is scrolled to the bottom, false otherwise | [
"Notifies",
"when",
"the",
"scroll",
"view",
"has",
"been",
"scrolled",
"."
] | train | https://github.com/michael-rapp/AndroidMaterialDialog/blob/8990eed72ee5f5a9720836ee708f71ac0d43053b/library/src/main/java/de/mrapp/android/dialog/view/ScrollView.java#L76-L80 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/raytrace/RaytraceChunk.java | RaytraceChunk.getMin | public double getMin(double x, double z)
{
double ret = Double.NaN;
if (!Double.isNaN(x))
ret = x;
if (!Double.isNaN(z))
{
if (!Double.isNaN(ret))
ret = Math.min(ret, z);
else
ret = z;
}
return ret;
} | java | public double getMin(double x, double z)
{
double ret = Double.NaN;
if (!Double.isNaN(x))
ret = x;
if (!Double.isNaN(z))
{
if (!Double.isNaN(ret))
ret = Math.min(ret, z);
else
ret = z;
}
return ret;
} | [
"public",
"double",
"getMin",
"(",
"double",
"x",
",",
"double",
"z",
")",
"{",
"double",
"ret",
"=",
"Double",
".",
"NaN",
";",
"if",
"(",
"!",
"Double",
".",
"isNaN",
"(",
"x",
")",
")",
"ret",
"=",
"x",
";",
"if",
"(",
"!",
"Double",
".",
... | Gets the minimum value of <code>x</code>, <code>z</code>.
@param x the x
@param z the z
@return <code>Double.NaN</code> if <code>x</code> and <code>z</code> are all three <code>Double.NaN</code> | [
"Gets",
"the",
"minimum",
"value",
"of",
"<code",
">",
"x<",
"/",
"code",
">",
"<code",
">",
"z<",
"/",
"code",
">",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/raytrace/RaytraceChunk.java#L172-L185 |
Axway/Grapes | server/src/main/java/org/axway/grapes/server/webapp/resources/ArtifactResource.java | ArtifactResource.isPromoted | @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/isPromoted")
public Response isPromoted(@QueryParam("user") final String user,
@QueryParam("stage") final int stage,
@QueryParam("name") final String filename,
@QueryParam("sha256") final String sha256,
@QueryParam("type") final String type,
@QueryParam("location") final String location) {
LOG.info("Got a get artifact promotion request");
// Validating request
final ArtifactQuery query = new ArtifactQuery(user, stage, filename, sha256, type, location);
DataValidator.validate(query);
if(LOG.isInfoEnabled()) {
LOG.info(String.format("Artifact validation request. Details [%s]", query.toString()));
}
// Validating type of request file
final GrapesServerConfig cfg = getConfig();
final List<String> validatedTypes = cfg.getExternalValidatedTypes();
if(!validatedTypes.contains(type)) {
return Response.ok(buildArtifactNotSupportedResponse(validatedTypes)).status(HttpStatus.UNPROCESSABLE_ENTITY_422).build();
}
final DbArtifact dbArtifact = getArtifactHandler().getArtifactUsingSHA256(sha256);
//
// No such artifact was identified in the underlying data structure
//
if(dbArtifact == null) {
final String jiraLink = buildArtifactNotificationJiraLink(query);
sender.send(cfg.getArtifactNotificationRecipients(),
buildArtifactValidationSubject(filename),
buildArtifactValidationBody(query, "N/A")); // No Jenkins job if not artifact
return Response.ok(buildArtifactNotKnown(query, jiraLink)).status(HttpStatus.NOT_FOUND_404).build();
}
final ArtifactPromotionStatus promotionStatus = new ArtifactPromotionStatus();
promotionStatus.setPromoted(dbArtifact.isPromoted());
// If artifact is promoted
if(dbArtifact.isPromoted()){
promotionStatus.setMessage(Messages.get(ARTIFACT_VALIDATION_IS_PROMOTED));
return Response.ok(promotionStatus).build();
} else {
final String jenkinsJobInfo = getArtifactHandler().getModuleJenkinsJobInfo(dbArtifact);
promotionStatus.setMessage(buildArtifactNotPromotedYetResponse(query, jenkinsJobInfo.isEmpty() ? "<i>(Link to Jenkins job not found)</i>" : jenkinsJobInfo));
// If someone just did not promote the artifact, don't spam the support with more emails
}
return Response.ok(promotionStatus).build();
} | java | @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/isPromoted")
public Response isPromoted(@QueryParam("user") final String user,
@QueryParam("stage") final int stage,
@QueryParam("name") final String filename,
@QueryParam("sha256") final String sha256,
@QueryParam("type") final String type,
@QueryParam("location") final String location) {
LOG.info("Got a get artifact promotion request");
// Validating request
final ArtifactQuery query = new ArtifactQuery(user, stage, filename, sha256, type, location);
DataValidator.validate(query);
if(LOG.isInfoEnabled()) {
LOG.info(String.format("Artifact validation request. Details [%s]", query.toString()));
}
// Validating type of request file
final GrapesServerConfig cfg = getConfig();
final List<String> validatedTypes = cfg.getExternalValidatedTypes();
if(!validatedTypes.contains(type)) {
return Response.ok(buildArtifactNotSupportedResponse(validatedTypes)).status(HttpStatus.UNPROCESSABLE_ENTITY_422).build();
}
final DbArtifact dbArtifact = getArtifactHandler().getArtifactUsingSHA256(sha256);
//
// No such artifact was identified in the underlying data structure
//
if(dbArtifact == null) {
final String jiraLink = buildArtifactNotificationJiraLink(query);
sender.send(cfg.getArtifactNotificationRecipients(),
buildArtifactValidationSubject(filename),
buildArtifactValidationBody(query, "N/A")); // No Jenkins job if not artifact
return Response.ok(buildArtifactNotKnown(query, jiraLink)).status(HttpStatus.NOT_FOUND_404).build();
}
final ArtifactPromotionStatus promotionStatus = new ArtifactPromotionStatus();
promotionStatus.setPromoted(dbArtifact.isPromoted());
// If artifact is promoted
if(dbArtifact.isPromoted()){
promotionStatus.setMessage(Messages.get(ARTIFACT_VALIDATION_IS_PROMOTED));
return Response.ok(promotionStatus).build();
} else {
final String jenkinsJobInfo = getArtifactHandler().getModuleJenkinsJobInfo(dbArtifact);
promotionStatus.setMessage(buildArtifactNotPromotedYetResponse(query, jenkinsJobInfo.isEmpty() ? "<i>(Link to Jenkins job not found)</i>" : jenkinsJobInfo));
// If someone just did not promote the artifact, don't spam the support with more emails
}
return Response.ok(promotionStatus).build();
} | [
"@",
"GET",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Path",
"(",
"\"/isPromoted\"",
")",
"public",
"Response",
"isPromoted",
"(",
"@",
"QueryParam",
"(",
"\"user\"",
")",
"final",
"String",
"user",
",",
"@",
"QueryParam",
"(",
... | Return promotion status of an Artifact regarding artifactQuery from third party.
This method is call via POST <grapes_url>/artifact/isPromoted
@param user The user name in the external system
@param stage An integer value depending on the stage in the external system
@param filename The name of the file needing validation
@param sha256 The file checksum value
@param type The type of the file as defined in the external system
@param location The location of the binary file
@return Response A response message in case the request is invalid or
or an object containing the promotional status and additional message providing
human readable information | [
"Return",
"promotion",
"status",
"of",
"an",
"Artifact",
"regarding",
"artifactQuery",
"from",
"third",
"party",
".",
"This",
"method",
"is",
"call",
"via",
"POST",
"<grapes_url",
">",
"/",
"artifact",
"/",
"isPromoted"
] | train | https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/webapp/resources/ArtifactResource.java#L258-L318 |
QSFT/Doradus | doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java | TableDefinition.setOption | public void setOption(String optionName, String optionValue) {
// Ensure option value is not empty and trim excess whitespace.
Utils.require(optionName != null, "optionName");
Utils.require(optionValue != null && optionValue.trim().length() > 0,
"Value for option '" + optionName + "' can not be empty");
optionValue = optionValue.trim();
m_optionMap.put(optionName.toLowerCase(), optionValue);
// sharding-granularity and sharding-start are validated here since we must set
// local members when the table's definition is parsed.
if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_GRANULARITY)) {
m_shardingGranularity = ShardingGranularity.fromString(optionValue);
Utils.require(m_shardingGranularity != null,
"Unrecognized 'sharding-granularity' value: " + optionValue);
} else if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_START)) {
Utils.require(isValidShardDate(optionValue),
"'sharding-start' must be YYYY-MM-DD: " + optionValue);
m_shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE);
m_shardingStartDate.setTime(Utils.dateFromString(optionValue));
}
} | java | public void setOption(String optionName, String optionValue) {
// Ensure option value is not empty and trim excess whitespace.
Utils.require(optionName != null, "optionName");
Utils.require(optionValue != null && optionValue.trim().length() > 0,
"Value for option '" + optionName + "' can not be empty");
optionValue = optionValue.trim();
m_optionMap.put(optionName.toLowerCase(), optionValue);
// sharding-granularity and sharding-start are validated here since we must set
// local members when the table's definition is parsed.
if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_GRANULARITY)) {
m_shardingGranularity = ShardingGranularity.fromString(optionValue);
Utils.require(m_shardingGranularity != null,
"Unrecognized 'sharding-granularity' value: " + optionValue);
} else if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_START)) {
Utils.require(isValidShardDate(optionValue),
"'sharding-start' must be YYYY-MM-DD: " + optionValue);
m_shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE);
m_shardingStartDate.setTime(Utils.dateFromString(optionValue));
}
} | [
"public",
"void",
"setOption",
"(",
"String",
"optionName",
",",
"String",
"optionValue",
")",
"{",
"// Ensure option value is not empty and trim excess whitespace.\r",
"Utils",
".",
"require",
"(",
"optionName",
"!=",
"null",
",",
"\"optionName\"",
")",
";",
"Utils",
... | Set the option with the given name to the given value. This method does not
validate that the given option name and value are valid since options are
storage service-specific.
@param optionName Option name. This is down-cased when stored.
@param optionValue Option value. Cannot be null. | [
"Set",
"the",
"option",
"with",
"the",
"given",
"name",
"to",
"the",
"given",
"value",
".",
"This",
"method",
"does",
"not",
"validate",
"that",
"the",
"given",
"option",
"name",
"and",
"value",
"are",
"valid",
"since",
"options",
"are",
"storage",
"servic... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L599-L619 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/component/SimpleInternalFrame.java | SimpleInternalFrame.buildHeader | private JPanel buildHeader(JLabel label, JToolBar bar) {
gradientPanel = new GradientPanel(new BorderLayout(), getHeaderBackground());
label.setOpaque(false);
gradientPanel.add(label, BorderLayout.WEST);
gradientPanel.setBorder(BorderFactory.createEmptyBorder(3, 4, 3, 1));
headerPanel = new JPanel(new BorderLayout());
headerPanel.add(gradientPanel, BorderLayout.CENTER);
setToolBar(bar);
headerPanel.setBorder(new RaisedHeaderBorder());
headerPanel.setOpaque(false);
return headerPanel;
} | java | private JPanel buildHeader(JLabel label, JToolBar bar) {
gradientPanel = new GradientPanel(new BorderLayout(), getHeaderBackground());
label.setOpaque(false);
gradientPanel.add(label, BorderLayout.WEST);
gradientPanel.setBorder(BorderFactory.createEmptyBorder(3, 4, 3, 1));
headerPanel = new JPanel(new BorderLayout());
headerPanel.add(gradientPanel, BorderLayout.CENTER);
setToolBar(bar);
headerPanel.setBorder(new RaisedHeaderBorder());
headerPanel.setOpaque(false);
return headerPanel;
} | [
"private",
"JPanel",
"buildHeader",
"(",
"JLabel",
"label",
",",
"JToolBar",
"bar",
")",
"{",
"gradientPanel",
"=",
"new",
"GradientPanel",
"(",
"new",
"BorderLayout",
"(",
")",
",",
"getHeaderBackground",
"(",
")",
")",
";",
"label",
".",
"setOpaque",
"(",
... | Creates and answers the header panel, that consists of: an icon, a title
label, a tool bar, and a gradient background.
@param label
the label to paint the icon and text
@param bar
the panel's tool bar
@return the panel's built header area | [
"Creates",
"and",
"answers",
"the",
"header",
"panel",
"that",
"consists",
"of",
":",
"an",
"icon",
"a",
"title",
"label",
"a",
"tool",
"bar",
"and",
"a",
"gradient",
"background",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/component/SimpleInternalFrame.java#L272-L285 |
qiujuer/Genius-Android | caprice/ui/src/main/java/net/qiujuer/genius/ui/drawable/TouchEffectDrawable.java | TouchEffectDrawable.setPadding | public void setPadding(int left, int top, int right, int bottom) {
if ((left | top | right | bottom) == 0) {
mState.mPadding = null;
} else {
if (mState.mPadding == null) {
mState.mPadding = new Rect();
}
mState.mPadding.set(left, top, right, bottom);
}
invalidateSelf();
} | java | public void setPadding(int left, int top, int right, int bottom) {
if ((left | top | right | bottom) == 0) {
mState.mPadding = null;
} else {
if (mState.mPadding == null) {
mState.mPadding = new Rect();
}
mState.mPadding.set(left, top, right, bottom);
}
invalidateSelf();
} | [
"public",
"void",
"setPadding",
"(",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
")",
"{",
"if",
"(",
"(",
"left",
"|",
"top",
"|",
"right",
"|",
"bottom",
")",
"==",
"0",
")",
"{",
"mState",
".",
"mPadding",
"=",... | Sets padding for the shape.
@param left padding for the left side (in pixels)
@param top padding for the top (in pixels)
@param right padding for the right side (in pixels)
@param bottom padding for the bottom (in pixels) | [
"Sets",
"padding",
"for",
"the",
"shape",
"."
] | train | https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/drawable/TouchEffectDrawable.java#L167-L177 |
omise/omise-java | src/main/java/co/omise/Serializer.java | Serializer.deserializeFromMap | public <T extends OmiseObject> T deserializeFromMap(Map<String, Object> map, TypeReference<T> ref) {
return objectMapper.convertValue(map, ref);
} | java | public <T extends OmiseObject> T deserializeFromMap(Map<String, Object> map, TypeReference<T> ref) {
return objectMapper.convertValue(map, ref);
} | [
"public",
"<",
"T",
"extends",
"OmiseObject",
">",
"T",
"deserializeFromMap",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"TypeReference",
"<",
"T",
">",
"ref",
")",
"{",
"return",
"objectMapper",
".",
"convertValue",
"(",
"map",
",",
"ref... | Deserialize an instance of the given type reference from the map.
@param map The {@link Map} containing the JSON structure to deserialize from.
@param ref The {@link TypeReference} of the type to deserialize the result into.
@param <T> The type to deserialize the result into.
@return An instance of the given type T deserialized from the map. | [
"Deserialize",
"an",
"instance",
"of",
"the",
"given",
"type",
"reference",
"from",
"the",
"map",
"."
] | train | https://github.com/omise/omise-java/blob/95aafc5e8c21b44e6d00a5a9080b9e353fe98042/src/main/java/co/omise/Serializer.java#L152-L154 |
facebook/fresco | drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java | WrappingUtils.maybeWrapWithScaleType | @Nullable
static Drawable maybeWrapWithScaleType(
@Nullable Drawable drawable, @Nullable ScalingUtils.ScaleType scaleType) {
return maybeWrapWithScaleType(drawable, scaleType, null);
} | java | @Nullable
static Drawable maybeWrapWithScaleType(
@Nullable Drawable drawable, @Nullable ScalingUtils.ScaleType scaleType) {
return maybeWrapWithScaleType(drawable, scaleType, null);
} | [
"@",
"Nullable",
"static",
"Drawable",
"maybeWrapWithScaleType",
"(",
"@",
"Nullable",
"Drawable",
"drawable",
",",
"@",
"Nullable",
"ScalingUtils",
".",
"ScaleType",
"scaleType",
")",
"{",
"return",
"maybeWrapWithScaleType",
"(",
"drawable",
",",
"scaleType",
",",
... | Wraps the given drawable with a new {@link ScaleTypeDrawable}.
<p>If the provided drawable or scale type is null, the given drawable is returned without being
wrapped.
@return the wrapping scale type drawable, or the original drawable if the wrapping didn't take
place | [
"Wraps",
"the",
"given",
"drawable",
"with",
"a",
"new",
"{",
"@link",
"ScaleTypeDrawable",
"}",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/WrappingUtils.java#L65-L69 |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.splitString | public static List<String> splitString(String line, int begin, int end, char delim) {
return splitString(line, begin, end, delim, new ArrayList<String>());
} | java | public static List<String> splitString(String line, int begin, int end, char delim) {
return splitString(line, begin, end, delim, new ArrayList<String>());
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitString",
"(",
"String",
"line",
",",
"int",
"begin",
",",
"int",
"end",
",",
"char",
"delim",
")",
"{",
"return",
"splitString",
"(",
"line",
",",
"begin",
",",
"end",
",",
"delim",
",",
"new",
"A... | Splits a string on the given delimiter over the given range.
Does include all empty elements on the split.
@return the modifiable list from the split | [
"Splits",
"a",
"string",
"on",
"the",
"given",
"delimiter",
"over",
"the",
"given",
"range",
".",
"Does",
"include",
"all",
"empty",
"elements",
"on",
"the",
"split",
"."
] | train | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L933-L935 |
looly/hutool | hutool-json/src/main/java/cn/hutool/json/JSONConverter.java | JSONConverter.jsonConvert | @SuppressWarnings("unchecked")
protected static <T> T jsonConvert(Type targetType, Object value, boolean ignoreError) throws ConvertException {
if (JSONUtil.isNull(value)) {
return null;
}
Object targetValue = null;
try {
targetValue = Convert.convert(targetType, value);
} catch (ConvertException e) {
if (ignoreError) {
return null;
}
throw e;
}
if (null == targetValue && false == ignoreError) {
if (StrUtil.isBlankIfStr(value)) {
// 对于传入空字符串的情况,如果转换的目标对象是非字符串或非原始类型,转换器会返回false。
// 此处特殊处理,认为返回null属于正常情况
return null;
}
throw new ConvertException("Can not convert {} to type {}", value, ObjectUtil.defaultIfNull(TypeUtil.getClass(targetType), targetType));
}
return (T) targetValue;
} | java | @SuppressWarnings("unchecked")
protected static <T> T jsonConvert(Type targetType, Object value, boolean ignoreError) throws ConvertException {
if (JSONUtil.isNull(value)) {
return null;
}
Object targetValue = null;
try {
targetValue = Convert.convert(targetType, value);
} catch (ConvertException e) {
if (ignoreError) {
return null;
}
throw e;
}
if (null == targetValue && false == ignoreError) {
if (StrUtil.isBlankIfStr(value)) {
// 对于传入空字符串的情况,如果转换的目标对象是非字符串或非原始类型,转换器会返回false。
// 此处特殊处理,认为返回null属于正常情况
return null;
}
throw new ConvertException("Can not convert {} to type {}", value, ObjectUtil.defaultIfNull(TypeUtil.getClass(targetType), targetType));
}
return (T) targetValue;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"static",
"<",
"T",
">",
"T",
"jsonConvert",
"(",
"Type",
"targetType",
",",
"Object",
"value",
",",
"boolean",
"ignoreError",
")",
"throws",
"ConvertException",
"{",
"if",
"(",
"JSONUtil",
".",
... | JSON递归转换<br>
首先尝试JDK类型转换,如果失败尝试JSON转Bean
@param <T>
@param targetType 目标类型
@param value 值
@param ignoreError 是否忽略转换错误
@return 目标类型的值
@throws ConvertException 转换失败 | [
"JSON递归转换<br",
">",
"首先尝试JDK类型转换,如果失败尝试JSON转Bean",
"@param",
"<T",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-json/src/main/java/cn/hutool/json/JSONConverter.java#L65-L92 |
paypal/SeLion | server/src/main/java/com/paypal/selion/utils/ServletHelper.java | ServletHelper.respondAsHtmlWithMessage | public static void respondAsHtmlWithMessage(HttpServletResponse resp, String message) throws IOException {
respondAsHtmlUsingArgsAndTemplateWithHttpStatus(resp, MESSAGE_RESOURCE_PAGE_FILE, HttpStatus.SC_OK, message);
} | java | public static void respondAsHtmlWithMessage(HttpServletResponse resp, String message) throws IOException {
respondAsHtmlUsingArgsAndTemplateWithHttpStatus(resp, MESSAGE_RESOURCE_PAGE_FILE, HttpStatus.SC_OK, message);
} | [
"public",
"static",
"void",
"respondAsHtmlWithMessage",
"(",
"HttpServletResponse",
"resp",
",",
"String",
"message",
")",
"throws",
"IOException",
"{",
"respondAsHtmlUsingArgsAndTemplateWithHttpStatus",
"(",
"resp",
",",
"MESSAGE_RESOURCE_PAGE_FILE",
",",
"HttpStatus",
"."... | Utility method used to display a message when re-direction happens in the UI flow. Uses the template
{@link #MESSAGE_RESOURCE_PAGE_FILE}
@param resp
A {@link HttpServletResponse} object that the servlet is responding on.
@param message
Message to display.
@throws IOException | [
"Utility",
"method",
"used",
"to",
"display",
"a",
"message",
"when",
"re",
"-",
"direction",
"happens",
"in",
"the",
"UI",
"flow",
".",
"Uses",
"the",
"template",
"{",
"@link",
"#MESSAGE_RESOURCE_PAGE_FILE",
"}"
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/server/src/main/java/com/paypal/selion/utils/ServletHelper.java#L180-L182 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/component/DefinitionComponent.java | DefinitionComponent.addInlineDefinitionTitle | private void addInlineDefinitionTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
docBuilder.anchor(anchor, null);
docBuilder.newLine();
docBuilder.boldTextLine(title);
} | java | private void addInlineDefinitionTitle(String title, String anchor, MarkupDocBuilder docBuilder) {
docBuilder.anchor(anchor, null);
docBuilder.newLine();
docBuilder.boldTextLine(title);
} | [
"private",
"void",
"addInlineDefinitionTitle",
"(",
"String",
"title",
",",
"String",
"anchor",
",",
"MarkupDocBuilder",
"docBuilder",
")",
"{",
"docBuilder",
".",
"anchor",
"(",
"anchor",
",",
"null",
")",
";",
"docBuilder",
".",
"newLine",
"(",
")",
";",
"... | Builds the title of an inline schema.
Inline definitions should never been referenced in TOC because they have no real existence, so they are just text.
@param title inline schema title
@param anchor inline schema anchor
@param docBuilder the docbuilder do use for output | [
"Builds",
"the",
"title",
"of",
"an",
"inline",
"schema",
".",
"Inline",
"definitions",
"should",
"never",
"been",
"referenced",
"in",
"TOC",
"because",
"they",
"have",
"no",
"real",
"existence",
"so",
"they",
"are",
"just",
"text",
"."
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/component/DefinitionComponent.java#L120-L124 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.syncVirtualNetworkInfo | public void syncVirtualNetworkInfo(String resourceGroupName, String name) {
syncVirtualNetworkInfoWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
} | java | public void syncVirtualNetworkInfo(String resourceGroupName, String name) {
syncVirtualNetworkInfoWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
} | [
"public",
"void",
"syncVirtualNetworkInfo",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
")",
"{",
"syncVirtualNetworkInfoWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
... | Resume an App Service Environment.
Resume an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Resume",
"an",
"App",
"Service",
"Environment",
".",
"Resume",
"an",
"App",
"Service",
"Environment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceEnvironmentsInner.java#L5005-L5007 |
jayantk/jklol | src/com/jayantkrish/jklol/models/TableFactor.java | TableFactor.pointDistribution | public static TableFactor pointDistribution(VariableNumMap vars, Assignment... assignments) {
TableFactorBuilder builder = new TableFactorBuilder(vars, SparseTensorBuilder.getFactory());
for (int i = 0; i < assignments.length; i++) {
builder.setWeight(assignments[i], 1.0);
}
// TODO: support for implicit repmat of the assignments.
return builder.build();
} | java | public static TableFactor pointDistribution(VariableNumMap vars, Assignment... assignments) {
TableFactorBuilder builder = new TableFactorBuilder(vars, SparseTensorBuilder.getFactory());
for (int i = 0; i < assignments.length; i++) {
builder.setWeight(assignments[i], 1.0);
}
// TODO: support for implicit repmat of the assignments.
return builder.build();
} | [
"public",
"static",
"TableFactor",
"pointDistribution",
"(",
"VariableNumMap",
"vars",
",",
"Assignment",
"...",
"assignments",
")",
"{",
"TableFactorBuilder",
"builder",
"=",
"new",
"TableFactorBuilder",
"(",
"vars",
",",
"SparseTensorBuilder",
".",
"getFactory",
"("... | Gets a {@code TableFactor} over {@code vars} which assigns unit weight to
all assignments in {@code assignments} and 0 to all other assignments.
Requires each assignment in {@code assignments} to contain all of
{@code vars}.
@param vars
@param assignment
@return | [
"Gets",
"a",
"{",
"@code",
"TableFactor",
"}",
"over",
"{",
"@code",
"vars",
"}",
"which",
"assigns",
"unit",
"weight",
"to",
"all",
"assignments",
"in",
"{",
"@code",
"assignments",
"}",
"and",
"0",
"to",
"all",
"other",
"assignments",
".",
"Requires",
... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/TableFactor.java#L64-L72 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WDialog.java | WDialog.handleTriggerOpenAction | protected void handleTriggerOpenAction(final Request request) {
// Run the action (if set)
final Action action = getTriggerOpenAction();
if (action != null) {
final ActionEvent event = new ActionEvent(this, OPEN_DIALOG_ACTION);
Runnable later = new Runnable() {
@Override
public void run() {
action.execute(event);
}
};
invokeLater(later);
}
} | java | protected void handleTriggerOpenAction(final Request request) {
// Run the action (if set)
final Action action = getTriggerOpenAction();
if (action != null) {
final ActionEvent event = new ActionEvent(this, OPEN_DIALOG_ACTION);
Runnable later = new Runnable() {
@Override
public void run() {
action.execute(event);
}
};
invokeLater(later);
}
} | [
"protected",
"void",
"handleTriggerOpenAction",
"(",
"final",
"Request",
"request",
")",
"{",
"// Run the action (if set)",
"final",
"Action",
"action",
"=",
"getTriggerOpenAction",
"(",
")",
";",
"if",
"(",
"action",
"!=",
"null",
")",
"{",
"final",
"ActionEvent"... | Run the trigger open action.
@param request the request being processed | [
"Run",
"the",
"trigger",
"open",
"action",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WDialog.java#L337-L350 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/utils/TotpUtils.java | TotpUtils.getOtpauthURL | public static String getOtpauthURL(String name, String issuer, String secret, HmacShaAlgorithm algorithm, String digits, String period) {
Objects.requireNonNull(name, Required.ACCOUNT_NAME.toString());
Objects.requireNonNull(secret, Required.SECRET.toString());
Objects.requireNonNull(issuer, Required.ISSUER.toString());
Objects.requireNonNull(algorithm, Required.ALGORITHM.toString());
Objects.requireNonNull(digits, Required.DIGITS.toString());
Objects.requireNonNull(period, Required.PERIOD.toString());
var buffer = new StringBuilder();
buffer.append("otpauth://totp/")
.append(name)
.append("?secret=")
.append(RegExUtils.replaceAll(base32.encodeAsString(secret.getBytes(StandardCharsets.UTF_8)), "=", ""))
.append("&algorithm=")
.append(algorithm.getAlgorithm())
.append("&issuer=")
.append(issuer)
.append("&digits=")
.append(digits)
.append("&period=")
.append(period);
String url = "";
try {
url = URLEncoder.encode(buffer.toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
LOG.error("Failed to encode otpauth url", e);
}
return url;
} | java | public static String getOtpauthURL(String name, String issuer, String secret, HmacShaAlgorithm algorithm, String digits, String period) {
Objects.requireNonNull(name, Required.ACCOUNT_NAME.toString());
Objects.requireNonNull(secret, Required.SECRET.toString());
Objects.requireNonNull(issuer, Required.ISSUER.toString());
Objects.requireNonNull(algorithm, Required.ALGORITHM.toString());
Objects.requireNonNull(digits, Required.DIGITS.toString());
Objects.requireNonNull(period, Required.PERIOD.toString());
var buffer = new StringBuilder();
buffer.append("otpauth://totp/")
.append(name)
.append("?secret=")
.append(RegExUtils.replaceAll(base32.encodeAsString(secret.getBytes(StandardCharsets.UTF_8)), "=", ""))
.append("&algorithm=")
.append(algorithm.getAlgorithm())
.append("&issuer=")
.append(issuer)
.append("&digits=")
.append(digits)
.append("&period=")
.append(period);
String url = "";
try {
url = URLEncoder.encode(buffer.toString(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
LOG.error("Failed to encode otpauth url", e);
}
return url;
} | [
"public",
"static",
"String",
"getOtpauthURL",
"(",
"String",
"name",
",",
"String",
"issuer",
",",
"String",
"secret",
",",
"HmacShaAlgorithm",
"algorithm",
",",
"String",
"digits",
",",
"String",
"period",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"na... | Generates a otpauth code to share a secret with a user
@param name The name of the account
@param issuer The name of the issuer
@param secret The secret to use
@param algorithm The algorithm to use
@param digits The number of digits to use
@param period The period to use
@return An otpauth url | [
"Generates",
"a",
"otpauth",
"code",
"to",
"share",
"a",
"secret",
"with",
"a",
"user"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/utils/TotpUtils.java#L183-L213 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java | ServiceDirectoryConfig.getLong | public long getLong(String name, long defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getLong(name);
} else {
return defaultVal;
}
} | java | public long getLong(String name, long defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getLong(name);
} else {
return defaultVal;
}
} | [
"public",
"long",
"getLong",
"(",
"String",
"name",
",",
"long",
"defaultVal",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"return",
"this",
".",
"configuration",
".",
"getLong",
"(",
"name",
")",
... | Get the property object as long, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as long, return defaultVal if property is undefined. | [
"Get",
"the",
"property",
"object",
"as",
"long",
"or",
"return",
"defaultVal",
"if",
"property",
"is",
"not",
"defined",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java#L237-L243 |
code4everything/util | src/main/java/com/zhazhapan/util/LoggerUtils.java | LoggerUtils.info | public static void info(Class<?> clazz, String message, String... values) {
getLogger(clazz).info(formatString(message, values));
} | java | public static void info(Class<?> clazz, String message, String... values) {
getLogger(clazz).info(formatString(message, values));
} | [
"public",
"static",
"void",
"info",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"message",
",",
"String",
"...",
"values",
")",
"{",
"getLogger",
"(",
"clazz",
")",
".",
"info",
"(",
"formatString",
"(",
"message",
",",
"values",
")",
")",
"... | 信息
@param clazz 类
@param message 消息
@param values 格式化参数
@since 1.0.8 | [
"信息"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/LoggerUtils.java#L93-L95 |
ozimov/cirneco | hamcrest/hamcrest-matchers/src/main/java/it/ozimov/cirneco/hamcrest/date/IsDateWithTime.java | IsDateWithTime.hasHourMinSecAndMillis | public static Matcher<Date> hasHourMinSecAndMillis(final int hour, final int minute, final int second,
final int millisecond) {
return new IsDateWithTime(hour, minute, second, millisecond);
} | java | public static Matcher<Date> hasHourMinSecAndMillis(final int hour, final int minute, final int second,
final int millisecond) {
return new IsDateWithTime(hour, minute, second, millisecond);
} | [
"public",
"static",
"Matcher",
"<",
"Date",
">",
"hasHourMinSecAndMillis",
"(",
"final",
"int",
"hour",
",",
"final",
"int",
"minute",
",",
"final",
"int",
"second",
",",
"final",
"int",
"millisecond",
")",
"{",
"return",
"new",
"IsDateWithTime",
"(",
"hour"... | Creates a matcher that matches when the examined {@linkplain Date} has the given values <code>hour</code> in a 24
hours clock period, <code>minute</code>, <code>sec</code> and <code>millis</code>. | [
"Creates",
"a",
"matcher",
"that",
"matches",
"when",
"the",
"examined",
"{"
] | train | https://github.com/ozimov/cirneco/blob/78ad782da0a2256634cfbebb2f97ed78c993b999/hamcrest/hamcrest-matchers/src/main/java/it/ozimov/cirneco/hamcrest/date/IsDateWithTime.java#L125-L128 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.diagnostics | public Observable<DiagnosticsResponse> diagnostics(final String id) {
List<Observable<EndpointHealth>> diags = new ArrayList<Observable<EndpointHealth>>(nodes.size());
for (Node node : nodes) {
diags.add(node.diagnostics());
}
final RingBufferDiagnostics ringBufferDiagnostics = RingBufferMonitor.instance().diagnostics();
return Observable.merge(diags).toList().map(new Func1<List<EndpointHealth>, DiagnosticsResponse>() {
@Override
public DiagnosticsResponse call(List<EndpointHealth> checks) {
return new DiagnosticsResponse(new DiagnosticsReport(checks, environment.userAgent(), id, ringBufferDiagnostics));
}
});
} | java | public Observable<DiagnosticsResponse> diagnostics(final String id) {
List<Observable<EndpointHealth>> diags = new ArrayList<Observable<EndpointHealth>>(nodes.size());
for (Node node : nodes) {
diags.add(node.diagnostics());
}
final RingBufferDiagnostics ringBufferDiagnostics = RingBufferMonitor.instance().diagnostics();
return Observable.merge(diags).toList().map(new Func1<List<EndpointHealth>, DiagnosticsResponse>() {
@Override
public DiagnosticsResponse call(List<EndpointHealth> checks) {
return new DiagnosticsResponse(new DiagnosticsReport(checks, environment.userAgent(), id, ringBufferDiagnostics));
}
});
} | [
"public",
"Observable",
"<",
"DiagnosticsResponse",
">",
"diagnostics",
"(",
"final",
"String",
"id",
")",
"{",
"List",
"<",
"Observable",
"<",
"EndpointHealth",
">>",
"diags",
"=",
"new",
"ArrayList",
"<",
"Observable",
"<",
"EndpointHealth",
">",
">",
"(",
... | Performs the logistics of collecting and assembling the individual health check information
on a per-service basis.
@return an observable with the response once ready. | [
"Performs",
"the",
"logistics",
"of",
"collecting",
"and",
"assembling",
"the",
"individual",
"health",
"check",
"information",
"on",
"a",
"per",
"-",
"service",
"basis",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L420-L432 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java | JobsImpl.listFromJobScheduleNextWithServiceResponseAsync | public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> listFromJobScheduleNextWithServiceResponseAsync(final String nextPageLink, final JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions) {
return listFromJobScheduleNextSinglePageAsync(nextPageLink, jobListFromJobScheduleNextOptions)
.concatMap(new Func1<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> call(ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listFromJobScheduleNextWithServiceResponseAsync(nextPageLink, jobListFromJobScheduleNextOptions));
}
});
} | java | public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> listFromJobScheduleNextWithServiceResponseAsync(final String nextPageLink, final JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions) {
return listFromJobScheduleNextSinglePageAsync(nextPageLink, jobListFromJobScheduleNextOptions)
.concatMap(new Func1<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>, Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders>> call(ServiceResponseWithHeaders<Page<CloudJob>, JobListFromJobScheduleHeaders> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listFromJobScheduleNextWithServiceResponseAsync(nextPageLink, jobListFromJobScheduleNextOptions));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"CloudJob",
">",
",",
"JobListFromJobScheduleHeaders",
">",
">",
"listFromJobScheduleNextWithServiceResponseAsync",
"(",
"final",
"String",
"nextPageLink",
",",
"final",
"JobListFromJobScheduleNextOp... | Lists the jobs that have been created under the specified job schedule.
@param nextPageLink The NextLink from the previous successful call to List operation.
@param jobListFromJobScheduleNextOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<CloudJob> object | [
"Lists",
"the",
"jobs",
"that",
"have",
"been",
"created",
"under",
"the",
"specified",
"job",
"schedule",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L3730-L3742 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/BaseMessagingEngineImpl.java | BaseMessagingEngineImpl.getSIBDestinationByUuid | BaseDestinationDefinition getSIBDestinationByUuid(String bus, String key, boolean newCache) throws SIBExceptionDestinationNotFound, SIBExceptionBase {
String thisMethodName = "getSIBDestinationByUuid";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, new Object[] { bus, key, new Boolean(newCache) });
}
BaseDestinationDefinition bdd = null;
if (oldDestCache == null || newCache) {
bdd = (BaseDestinationDefinition) _bus.getDestinationCache().getSIBDestinationByUuid(bus, key).clone();
} else {
bdd = (BaseDestinationDefinition) oldDestCache.getSIBDestinationByUuid(bus, key).clone();
}
// Resolve Exception Destination if necessary
resolveExceptionDestination(bdd);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, thisMethodName, bdd);
}
return bdd;
} | java | BaseDestinationDefinition getSIBDestinationByUuid(String bus, String key, boolean newCache) throws SIBExceptionDestinationNotFound, SIBExceptionBase {
String thisMethodName = "getSIBDestinationByUuid";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, new Object[] { bus, key, new Boolean(newCache) });
}
BaseDestinationDefinition bdd = null;
if (oldDestCache == null || newCache) {
bdd = (BaseDestinationDefinition) _bus.getDestinationCache().getSIBDestinationByUuid(bus, key).clone();
} else {
bdd = (BaseDestinationDefinition) oldDestCache.getSIBDestinationByUuid(bus, key).clone();
}
// Resolve Exception Destination if necessary
resolveExceptionDestination(bdd);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, thisMethodName, bdd);
}
return bdd;
} | [
"BaseDestinationDefinition",
"getSIBDestinationByUuid",
"(",
"String",
"bus",
",",
"String",
"key",
",",
"boolean",
"newCache",
")",
"throws",
"SIBExceptionDestinationNotFound",
",",
"SIBExceptionBase",
"{",
"String",
"thisMethodName",
"=",
"\"getSIBDestinationByUuid\"",
";... | Accessor method to return a destination definition.
@param bus
@param key
@param newCache
@return the destination cache | [
"Accessor",
"method",
"to",
"return",
"a",
"destination",
"definition",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/BaseMessagingEngineImpl.java#L1133-L1157 |
libgdx/box2dlights | src/box2dLight/Light.java | Light.setColor | public void setColor(float r, float g, float b, float a) {
color.set(r, g, b, a);
colorF = color.toFloatBits();
if (staticLight) dirty = true;
} | java | public void setColor(float r, float g, float b, float a) {
color.set(r, g, b, a);
colorF = color.toFloatBits();
if (staticLight) dirty = true;
} | [
"public",
"void",
"setColor",
"(",
"float",
"r",
",",
"float",
"g",
",",
"float",
"b",
",",
"float",
"a",
")",
"{",
"color",
".",
"set",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
";",
"colorF",
"=",
"color",
".",
"toFloatBits",
"(",
")",
"... | Sets light color
<p>NOTE: you can also use colorless light with shadows, e.g. (0,0,0,1)
@param r
lights color red component
@param g
lights color green component
@param b
lights color blue component
@param a
lights shadow intensity
@see #setColor(Color) | [
"Sets",
"light",
"color"
] | train | https://github.com/libgdx/box2dlights/blob/08cf93a41464f71d32475aaa2fe280dc6af78ff3/src/box2dLight/Light.java#L191-L195 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/IntentUtils.java | IntentUtils.shareText | public static Intent shareText(String subject, String text) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setType("text/plain");
return intent;
} | java | public static Intent shareText(String subject, String text) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setType("text/plain");
return intent;
} | [
"public",
"static",
"Intent",
"shareText",
"(",
"String",
"subject",
",",
"String",
"text",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
")",
";",
"intent",
".",
"setAction",
"(",
"Intent",
".",
"ACTION_SEND",
")",
";",
"if",
"(",
"!",
"Tex... | Share text via thirdparty app like twitter, facebook, email, sms etc.
@param subject Optional subject of the message
@param text Text to share | [
"Share",
"text",
"via",
"thirdparty",
"app",
"like",
"twitter",
"facebook",
"email",
"sms",
"etc",
"."
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/IntentUtils.java#L100-L109 |
grails/gorm-hibernate5 | grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsHibernateUtil.java | GrailsHibernateUtil.getGrailsDomainClassProperty | private static PersistentProperty getGrailsDomainClassProperty(AbstractHibernateDatastore datastore, Class<?> targetClass, String propertyName) {
PersistentEntity grailsClass = datastore != null ? datastore.getMappingContext().getPersistentEntity( targetClass.getName()) : null;
if (grailsClass == null) {
throw new IllegalArgumentException("Unexpected: class is not a domain class:"+targetClass.getName());
}
return grailsClass.getPropertyByName(propertyName);
} | java | private static PersistentProperty getGrailsDomainClassProperty(AbstractHibernateDatastore datastore, Class<?> targetClass, String propertyName) {
PersistentEntity grailsClass = datastore != null ? datastore.getMappingContext().getPersistentEntity( targetClass.getName()) : null;
if (grailsClass == null) {
throw new IllegalArgumentException("Unexpected: class is not a domain class:"+targetClass.getName());
}
return grailsClass.getPropertyByName(propertyName);
} | [
"private",
"static",
"PersistentProperty",
"getGrailsDomainClassProperty",
"(",
"AbstractHibernateDatastore",
"datastore",
",",
"Class",
"<",
"?",
">",
"targetClass",
",",
"String",
"propertyName",
")",
"{",
"PersistentEntity",
"grailsClass",
"=",
"datastore",
"!=",
"nu... | Get hold of the GrailsDomainClassProperty represented by the targetClass' propertyName,
assuming targetClass corresponds to a GrailsDomainClass. | [
"Get",
"hold",
"of",
"the",
"GrailsDomainClassProperty",
"represented",
"by",
"the",
"targetClass",
"propertyName",
"assuming",
"targetClass",
"corresponds",
"to",
"a",
"GrailsDomainClass",
"."
] | train | https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsHibernateUtil.java#L242-L248 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java | Collectors.joining | public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
return new CollectorImpl<>(
() -> new StringJoiner(delimiter, prefix, suffix),
StringJoiner::add, StringJoiner::merge,
StringJoiner::toString, CH_NOID);
} | java | public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
return new CollectorImpl<>(
() -> new StringJoiner(delimiter, prefix, suffix),
StringJoiner::add, StringJoiner::merge,
StringJoiner::toString, CH_NOID);
} | [
"public",
"static",
"Collector",
"<",
"CharSequence",
",",
"?",
",",
"String",
">",
"joining",
"(",
"CharSequence",
"delimiter",
",",
"CharSequence",
"prefix",
",",
"CharSequence",
"suffix",
")",
"{",
"return",
"new",
"CollectorImpl",
"<>",
"(",
"(",
")",
"-... | Returns a {@code Collector} that concatenates the input elements,
separated by the specified delimiter, with the specified prefix and
suffix, in encounter order.
@param delimiter the delimiter to be used between each element
@param prefix the sequence of characters to be used at the beginning
of the joined result
@param suffix the sequence of characters to be used at the end
of the joined result
@return A {@code Collector} which concatenates CharSequence elements,
separated by the specified delimiter, in encounter order | [
"Returns",
"a",
"{",
"@code",
"Collector",
"}",
"that",
"concatenates",
"the",
"input",
"elements",
"separated",
"by",
"the",
"specified",
"delimiter",
"with",
"the",
"specified",
"prefix",
"and",
"suffix",
"in",
"encounter",
"order",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/Collectors.java#L295-L302 |
matomo-org/piwik-java-tracker | src/main/java/org/piwik/java/tracking/PiwikRequest.java | PiwikRequest.setRequestDatetime | public void setRequestDatetime(PiwikDate datetime){
if (datetime != null && new Date().getTime()-datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null){
throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.");
}
setParameter(REQUEST_DATETIME, datetime);
} | java | public void setRequestDatetime(PiwikDate datetime){
if (datetime != null && new Date().getTime()-datetime.getTime() > REQUEST_DATETIME_AUTH_LIMIT && getAuthToken() == null){
throw new IllegalStateException("Because you are trying to set RequestDatetime for a time greater than 4 hours ago, AuthToken must be set first.");
}
setParameter(REQUEST_DATETIME, datetime);
} | [
"public",
"void",
"setRequestDatetime",
"(",
"PiwikDate",
"datetime",
")",
"{",
"if",
"(",
"datetime",
"!=",
"null",
"&&",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"datetime",
".",
"getTime",
"(",
")",
">",
"REQUEST_DATETIME_AUTH_LIMIT",
"&&... | Set the datetime of the request (normally the current time is used).
This can be used to record visits and page views in the past. The datetime
must be sent in UTC timezone. <em>Note: if you record data in the past, you will
need to <a href="http://piwik.org/faq/how-to/#faq_59">force Piwik to re-process
reports for the past dates</a>.</em> If you set the <em>Request Datetime</em> to a datetime
older than four hours then <em>Auth Token</em> must be set. If you set
<em>Request Datetime</em> with a datetime in the last four hours then you
don't need to pass <em>Auth Token</em>.
@param datetime the datetime of the request to set. A null value will remove this parameter | [
"Set",
"the",
"datetime",
"of",
"the",
"request",
"(",
"normally",
"the",
"current",
"time",
"is",
"used",
")",
".",
"This",
"can",
"be",
"used",
"to",
"record",
"visits",
"and",
"page",
"views",
"in",
"the",
"past",
".",
"The",
"datetime",
"must",
"be... | train | https://github.com/matomo-org/piwik-java-tracker/blob/23df71d27a89e89dc7a539b2eda88c90a206458b/src/main/java/org/piwik/java/tracking/PiwikRequest.java#L1219-L1224 |
alkacon/opencms-core | src-modules/org/opencms/workplace/comparison/A_CmsDiffViewDialog.java | A_CmsDiffViewDialog.deactivatedEmphasizedButtonHtml | public String deactivatedEmphasizedButtonHtml(String name, String iconPath) {
StringBuffer result = new StringBuffer();
result.append(
"<span style='vertical-align:middle;'><img style='width:20px;height:20px;display:inline;vertical-align:middle;text-decoration:none;' src=\'");
result.append(CmsWorkplace.getSkinUri());
result.append(iconPath);
result.append("\' alt=\'");
result.append(name);
result.append("\' title=\'");
result.append(name);
result.append("\'> <b>");
result.append(name);
result.append("</b></span>");
return result.toString();
} | java | public String deactivatedEmphasizedButtonHtml(String name, String iconPath) {
StringBuffer result = new StringBuffer();
result.append(
"<span style='vertical-align:middle;'><img style='width:20px;height:20px;display:inline;vertical-align:middle;text-decoration:none;' src=\'");
result.append(CmsWorkplace.getSkinUri());
result.append(iconPath);
result.append("\' alt=\'");
result.append(name);
result.append("\' title=\'");
result.append(name);
result.append("\'> <b>");
result.append(name);
result.append("</b></span>");
return result.toString();
} | [
"public",
"String",
"deactivatedEmphasizedButtonHtml",
"(",
"String",
"name",
",",
"String",
"iconPath",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"result",
".",
"append",
"(",
"\"<span style='vertical-align:middle;'><img style='widt... | Returns the html code for a deactivated empfasized button.<p>
@param name the label of the button
@param iconPath the path to the icon
@return the html code for a deactivated empfasized button | [
"Returns",
"the",
"html",
"code",
"for",
"a",
"deactivated",
"empfasized",
"button",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/comparison/A_CmsDiffViewDialog.java#L208-L223 |
OpenLiberty/open-liberty | dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java | RecoveryDirectorImpl.removeRecoveryRecord | private boolean removeRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) {
if (tc.isEntryEnabled())
Tr.entry(tc, "removeRecoveryRecord", new Object[] { recoveryAgent, failureScope, this });
boolean found = false;
synchronized (_outstandingRecoveryRecords) {
final HashSet recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope);
if (recoveryAgentSet != null) {
found = recoveryAgentSet.remove(recoveryAgent);
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "removeRecoveryRecord", found);
return found;
} | java | private boolean removeRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) {
if (tc.isEntryEnabled())
Tr.entry(tc, "removeRecoveryRecord", new Object[] { recoveryAgent, failureScope, this });
boolean found = false;
synchronized (_outstandingRecoveryRecords) {
final HashSet recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope);
if (recoveryAgentSet != null) {
found = recoveryAgentSet.remove(recoveryAgent);
}
}
if (tc.isEntryEnabled())
Tr.exit(tc, "removeRecoveryRecord", found);
return found;
} | [
"private",
"boolean",
"removeRecoveryRecord",
"(",
"RecoveryAgent",
"recoveryAgent",
",",
"FailureScope",
"failureScope",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"removeRecoveryRecord\"",
",",
"new",... | <p>
Internal method to remove the record of an outstanding 'initialRecoveryComplete'
call from the supplied RecoveryAgent for the given failure scope.
</p>
<p>
This call will wake up all threads waiting for initial recovery to be completed.
</p>
<p>
Just prior to requesting a RecoveryAgent to "initiateRecovery" of a
FailureScope, the addRecoveryRecord method is driven to record the request.
When the client service completes the initial portion of the recovery process and
invokes RecoveryDirector.initialRecoveryComplete, this method called to remove
this record.
</p>
<p>
[ SERIAL PHASE ] [ INITIAL PHASE ] [ RETRY PHASE ]
</p>
@param recoveryAgent The RecoveryAgent that has completed the initial recovery
processing phase.
@param failureScope The FailureScope that defined the scope of this recovery
processing.
@return boolean true if there was an oustanding recovery record, otherwise false. | [
"<p",
">",
"Internal",
"method",
"to",
"remove",
"the",
"record",
"of",
"an",
"outstanding",
"initialRecoveryComplete",
"call",
"from",
"the",
"supplied",
"RecoveryAgent",
"for",
"the",
"given",
"failure",
"scope",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java#L1223-L1240 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java | TransformerHandlerImpl.processingInstruction | public void processingInstruction(String target, String data)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#processingInstruction: "
+ target + ", " + data);
if (m_contentHandler != null)
{
m_contentHandler.processingInstruction(target, data);
}
} | java | public void processingInstruction(String target, String data)
throws SAXException
{
if (DEBUG)
System.out.println("TransformerHandlerImpl#processingInstruction: "
+ target + ", " + data);
if (m_contentHandler != null)
{
m_contentHandler.processingInstruction(target, data);
}
} | [
"public",
"void",
"processingInstruction",
"(",
"String",
"target",
",",
"String",
"data",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"DEBUG",
")",
"System",
".",
"out",
".",
"println",
"(",
"\"TransformerHandlerImpl#processingInstruction: \"",
"+",
"target",
... | Filter a processing instruction event.
@param target The processing instruction target.
@param data The text following the target.
@throws SAXException The client may throw
an exception during processing.
@see org.xml.sax.ContentHandler#processingInstruction | [
"Filter",
"a",
"processing",
"instruction",
"event",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerHandlerImpl.java#L584-L596 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java | VMath.setMatrix | public static void setMatrix(final double[][] m1, final int r0, final int r1, final int[] c, final double[][] m2) {
assert r0 <= r1 : ERR_INVALID_RANGE;
assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
for(int i = r0; i < r1; i++) {
final double[] row1 = m1[i], row2 = m2[i - r0];
for(int j = 0; j < c.length; j++) {
row1[c[j]] = row2[j];
}
}
} | java | public static void setMatrix(final double[][] m1, final int r0, final int r1, final int[] c, final double[][] m2) {
assert r0 <= r1 : ERR_INVALID_RANGE;
assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
for(int i = r0; i < r1; i++) {
final double[] row1 = m1[i], row2 = m2[i - r0];
for(int j = 0; j < c.length; j++) {
row1[c[j]] = row2[j];
}
}
} | [
"public",
"static",
"void",
"setMatrix",
"(",
"final",
"double",
"[",
"]",
"[",
"]",
"m1",
",",
"final",
"int",
"r0",
",",
"final",
"int",
"r1",
",",
"final",
"int",
"[",
"]",
"c",
",",
"final",
"double",
"[",
"]",
"[",
"]",
"m2",
")",
"{",
"as... | Set a submatrix.
@param m1 Input matrix
@param r0 Initial row index
@param r1 Final row index
@param c Array of column indices.
@param m2 New values for m1(r0:r1-1,c(:)) | [
"Set",
"a",
"submatrix",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java#L1049-L1058 |
actframework/actframework | src/main/java/act/util/JsonUtilConfig.java | JsonUtilConfig.writeJson | private static final void writeJson(Writer os, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
DateFormat dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(writer, config);
if (dateFormat != null) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
} finally {
writer.close();
}
} | java | private static final void writeJson(Writer os, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
DateFormat dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(writer, config);
if (dateFormat != null) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
} finally {
writer.close();
}
} | [
"private",
"static",
"final",
"void",
"writeJson",
"(",
"Writer",
"os",
",",
"//",
"Object",
"object",
",",
"//",
"SerializeConfig",
"config",
",",
"//",
"SerializeFilter",
"[",
"]",
"filters",
",",
"//",
"DateFormat",
"dateFormat",
",",
"//",
"int",
"defaul... | FastJSON does not provide the API so we have to create our own | [
"FastJSON",
"does",
"not",
"provide",
"the",
"API",
"so",
"we",
"have",
"to",
"create",
"our",
"own"
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/JsonUtilConfig.java#L235-L261 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/DataSinkTask.java | DataSinkTask.initInputReaders | @SuppressWarnings("unchecked")
private void initInputReaders() throws Exception {
int numGates = 0;
// ---------------- create the input readers ---------------------
// in case where a logical input unions multiple physical inputs, create a union reader
final int groupSize = this.config.getGroupSize(0);
numGates += groupSize;
if (groupSize == 1) {
// non-union case
inputReader = new MutableRecordReader<DeserializationDelegate<IT>>(
getEnvironment().getInputGate(0),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else if (groupSize > 1){
// union case
inputReader = new MutableRecordReader<IOReadableWritable>(
new UnionInputGate(getEnvironment().getAllInputGates()),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else {
throw new Exception("Illegal input group size in task configuration: " + groupSize);
}
this.inputTypeSerializerFactory = this.config.getInputSerializer(0, getUserCodeClassLoader());
@SuppressWarnings({ "rawtypes" })
final MutableObjectIterator<?> iter = new ReaderIterator(inputReader, this.inputTypeSerializerFactory.getSerializer());
this.reader = (MutableObjectIterator<IT>)iter;
// final sanity check
if (numGates != this.config.getNumInputs()) {
throw new Exception("Illegal configuration: Number of input gates and group sizes are not consistent.");
}
} | java | @SuppressWarnings("unchecked")
private void initInputReaders() throws Exception {
int numGates = 0;
// ---------------- create the input readers ---------------------
// in case where a logical input unions multiple physical inputs, create a union reader
final int groupSize = this.config.getGroupSize(0);
numGates += groupSize;
if (groupSize == 1) {
// non-union case
inputReader = new MutableRecordReader<DeserializationDelegate<IT>>(
getEnvironment().getInputGate(0),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else if (groupSize > 1){
// union case
inputReader = new MutableRecordReader<IOReadableWritable>(
new UnionInputGate(getEnvironment().getAllInputGates()),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else {
throw new Exception("Illegal input group size in task configuration: " + groupSize);
}
this.inputTypeSerializerFactory = this.config.getInputSerializer(0, getUserCodeClassLoader());
@SuppressWarnings({ "rawtypes" })
final MutableObjectIterator<?> iter = new ReaderIterator(inputReader, this.inputTypeSerializerFactory.getSerializer());
this.reader = (MutableObjectIterator<IT>)iter;
// final sanity check
if (numGates != this.config.getNumInputs()) {
throw new Exception("Illegal configuration: Number of input gates and group sizes are not consistent.");
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"void",
"initInputReaders",
"(",
")",
"throws",
"Exception",
"{",
"int",
"numGates",
"=",
"0",
";",
"// ---------------- create the input readers ---------------------",
"// in case where a logical input unions mul... | Initializes the input readers of the DataSinkTask.
@throws RuntimeException
Thrown in case of invalid task input configuration. | [
"Initializes",
"the",
"input",
"readers",
"of",
"the",
"DataSinkTask",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/DataSinkTask.java#L360-L390 |
omalley/hadoop-gpl-compression | src/java/com/hadoop/mapreduce/LzoTextInputFormat.java | LzoTextInputFormat.readIndex | private LzoIndex readIndex(Path file, FileSystem fs) throws IOException {
FSDataInputStream indexIn = null;
try {
Path indexFile = new Path(file.toString() + LZO_INDEX_SUFFIX);
if (!fs.exists(indexFile)) {
// return empty index, fall back to the unsplittable mode
return new LzoIndex();
}
long indexLen = fs.getFileStatus(indexFile).getLen();
int blocks = (int) (indexLen / 8);
LzoIndex index = new LzoIndex(blocks);
indexIn = fs.open(indexFile);
for (int i = 0; i < blocks; i++) {
index.set(i, indexIn.readLong());
}
return index;
} finally {
if (indexIn != null) {
indexIn.close();
}
}
} | java | private LzoIndex readIndex(Path file, FileSystem fs) throws IOException {
FSDataInputStream indexIn = null;
try {
Path indexFile = new Path(file.toString() + LZO_INDEX_SUFFIX);
if (!fs.exists(indexFile)) {
// return empty index, fall back to the unsplittable mode
return new LzoIndex();
}
long indexLen = fs.getFileStatus(indexFile).getLen();
int blocks = (int) (indexLen / 8);
LzoIndex index = new LzoIndex(blocks);
indexIn = fs.open(indexFile);
for (int i = 0; i < blocks; i++) {
index.set(i, indexIn.readLong());
}
return index;
} finally {
if (indexIn != null) {
indexIn.close();
}
}
} | [
"private",
"LzoIndex",
"readIndex",
"(",
"Path",
"file",
",",
"FileSystem",
"fs",
")",
"throws",
"IOException",
"{",
"FSDataInputStream",
"indexIn",
"=",
"null",
";",
"try",
"{",
"Path",
"indexFile",
"=",
"new",
"Path",
"(",
"file",
".",
"toString",
"(",
"... | Read the index of the lzo file.
@param split
Read the index of this file.
@param fs
The index file is on this file system.
@throws IOException | [
"Read",
"the",
"index",
"of",
"the",
"lzo",
"file",
"."
] | train | https://github.com/omalley/hadoop-gpl-compression/blob/64ab3eb60fffac2a4d77680d506b34b02fcc3d7e/src/java/com/hadoop/mapreduce/LzoTextInputFormat.java#L156-L178 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_line_serviceName_click2CallUser_id_changePassword_POST | public void billingAccount_line_serviceName_click2CallUser_id_changePassword_POST(String billingAccount, String serviceName, Long id, String password) throws IOException {
String qPath = "/telephony/{billingAccount}/line/{serviceName}/click2CallUser/{id}/changePassword";
StringBuilder sb = path(qPath, billingAccount, serviceName, id);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "password", password);
exec(qPath, "POST", sb.toString(), o);
} | java | public void billingAccount_line_serviceName_click2CallUser_id_changePassword_POST(String billingAccount, String serviceName, Long id, String password) throws IOException {
String qPath = "/telephony/{billingAccount}/line/{serviceName}/click2CallUser/{id}/changePassword";
StringBuilder sb = path(qPath, billingAccount, serviceName, id);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "password", password);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"billingAccount_line_serviceName_click2CallUser_id_changePassword_POST",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"Long",
"id",
",",
"String",
"password",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony... | Change the password of the click2call user
REST: POST /telephony/{billingAccount}/line/{serviceName}/click2CallUser/{id}/changePassword
@param password [required] The password
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param id [required] Id of the object | [
"Change",
"the",
"password",
"of",
"the",
"click2call",
"user"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L871-L877 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java | WideningCategories.lowestUpperBound | public static ClassNode lowestUpperBound(ClassNode a, ClassNode b) {
ClassNode lub = lowestUpperBound(a, b, null, null);
if (lub==null || !lub.isUsingGenerics()) return lub;
// types may be parameterized. If so, we must ensure that generic type arguments
// are made compatible
if (lub instanceof LowestUpperBoundClassNode) {
// no parent super class representing both types could be found
// or both class nodes implement common interfaces which may have
// been parameterized differently.
// We must create a classnode for which the "superclass" is potentially parameterized
// plus the interfaces
ClassNode superClass = lub.getSuperClass();
ClassNode psc = superClass.isUsingGenerics()?parameterizeLowestUpperBound(superClass, a, b, lub):superClass;
ClassNode[] interfaces = lub.getInterfaces();
ClassNode[] pinterfaces = new ClassNode[interfaces.length];
for (int i = 0, interfacesLength = interfaces.length; i < interfacesLength; i++) {
final ClassNode icn = interfaces[i];
if (icn.isUsingGenerics()) {
pinterfaces[i] = parameterizeLowestUpperBound(icn, a, b, lub);
} else {
pinterfaces[i] = icn;
}
}
return new LowestUpperBoundClassNode(((LowestUpperBoundClassNode)lub).name, psc, pinterfaces);
} else {
return parameterizeLowestUpperBound(lub, a, b, lub);
}
} | java | public static ClassNode lowestUpperBound(ClassNode a, ClassNode b) {
ClassNode lub = lowestUpperBound(a, b, null, null);
if (lub==null || !lub.isUsingGenerics()) return lub;
// types may be parameterized. If so, we must ensure that generic type arguments
// are made compatible
if (lub instanceof LowestUpperBoundClassNode) {
// no parent super class representing both types could be found
// or both class nodes implement common interfaces which may have
// been parameterized differently.
// We must create a classnode for which the "superclass" is potentially parameterized
// plus the interfaces
ClassNode superClass = lub.getSuperClass();
ClassNode psc = superClass.isUsingGenerics()?parameterizeLowestUpperBound(superClass, a, b, lub):superClass;
ClassNode[] interfaces = lub.getInterfaces();
ClassNode[] pinterfaces = new ClassNode[interfaces.length];
for (int i = 0, interfacesLength = interfaces.length; i < interfacesLength; i++) {
final ClassNode icn = interfaces[i];
if (icn.isUsingGenerics()) {
pinterfaces[i] = parameterizeLowestUpperBound(icn, a, b, lub);
} else {
pinterfaces[i] = icn;
}
}
return new LowestUpperBoundClassNode(((LowestUpperBoundClassNode)lub).name, psc, pinterfaces);
} else {
return parameterizeLowestUpperBound(lub, a, b, lub);
}
} | [
"public",
"static",
"ClassNode",
"lowestUpperBound",
"(",
"ClassNode",
"a",
",",
"ClassNode",
"b",
")",
"{",
"ClassNode",
"lub",
"=",
"lowestUpperBound",
"(",
"a",
",",
"b",
",",
"null",
",",
"null",
")",
";",
"if",
"(",
"lub",
"==",
"null",
"||",
"!",... | Given two class nodes, returns the first common supertype, or the class itself
if there are equal. For example, Double and Float would return Number, while
Set and String would return Object.
This method is not guaranteed to return a class node which corresponds to a
real type. For example, if two types have more than one interface in common
and are not in the same hierarchy branch, then the returned type will be a
virtual type implementing all those interfaces.
Calls to this method are supposed to be made with resolved generics. This means
that you can have wildcards, but no placeholder.
@param a first class node
@param b second class node
@return first common supertype | [
"Given",
"two",
"class",
"nodes",
"returns",
"the",
"first",
"common",
"supertype",
"or",
"the",
"class",
"itself",
"if",
"there",
"are",
"equal",
".",
"For",
"example",
"Double",
"and",
"Float",
"would",
"return",
"Number",
"while",
"Set",
"and",
"String",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java#L209-L240 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxFile.java | BoxFile.getInfoWithRepresentations | public BoxFile.Info getInfoWithRepresentations(String representationHints, String... fields) {
if (representationHints.matches(Representation.X_REP_HINTS_PATTERN)) {
//Since the user intends to get representations, add it to fields, even if user has missed it
Set<String> fieldsSet = new HashSet<String>(Arrays.asList(fields));
fieldsSet.add("representations");
String queryString = new QueryStringBuilder().appendParam("fields",
fieldsSet.toArray(new String[fieldsSet.size()])).toString();
URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
request.addHeader("X-Rep-Hints", representationHints);
BoxJSONResponse response = (BoxJSONResponse) request.send();
return new Info(response.getJSON());
} else {
throw new BoxAPIException("Represention hints is not valid."
+ " Refer documention on how to construct X-Rep-Hints Header");
}
} | java | public BoxFile.Info getInfoWithRepresentations(String representationHints, String... fields) {
if (representationHints.matches(Representation.X_REP_HINTS_PATTERN)) {
//Since the user intends to get representations, add it to fields, even if user has missed it
Set<String> fieldsSet = new HashSet<String>(Arrays.asList(fields));
fieldsSet.add("representations");
String queryString = new QueryStringBuilder().appendParam("fields",
fieldsSet.toArray(new String[fieldsSet.size()])).toString();
URL url = FILE_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET");
request.addHeader("X-Rep-Hints", representationHints);
BoxJSONResponse response = (BoxJSONResponse) request.send();
return new Info(response.getJSON());
} else {
throw new BoxAPIException("Represention hints is not valid."
+ " Refer documention on how to construct X-Rep-Hints Header");
}
} | [
"public",
"BoxFile",
".",
"Info",
"getInfoWithRepresentations",
"(",
"String",
"representationHints",
",",
"String",
"...",
"fields",
")",
"{",
"if",
"(",
"representationHints",
".",
"matches",
"(",
"Representation",
".",
"X_REP_HINTS_PATTERN",
")",
")",
"{",
"//S... | Gets information about this item including a specified set of representations.
@see <a href=https://developer.box.com/reference#section-x-rep-hints-header>X-Rep-Hints Header</a>
@param representationHints hints for representations to be retrieved
@param fields the fields to retrieve.
@return info about this item containing only the specified fields, including representations. | [
"Gets",
"information",
"about",
"this",
"item",
"including",
"a",
"specified",
"set",
"of",
"representations",
".",
"@see",
"<a",
"href",
"=",
"https",
":",
"//",
"developer",
".",
"box",
".",
"com",
"/",
"reference#section",
"-",
"x",
"-",
"rep",
"-",
"... | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFile.java#L474-L491 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/operators/LatchedObserver.java | LatchedObserver.createIndexed | public static <T> LatchedObserver<T> createIndexed(Action2<? super T, ? super Integer> onNext) {
return createIndexed(onNext, new CountDownLatch(1));
} | java | public static <T> LatchedObserver<T> createIndexed(Action2<? super T, ? super Integer> onNext) {
return createIndexed(onNext, new CountDownLatch(1));
} | [
"public",
"static",
"<",
"T",
">",
"LatchedObserver",
"<",
"T",
">",
"createIndexed",
"(",
"Action2",
"<",
"?",
"super",
"T",
",",
"?",
"super",
"Integer",
">",
"onNext",
")",
"{",
"return",
"createIndexed",
"(",
"onNext",
",",
"new",
"CountDownLatch",
"... | Create a LatchedObserver with the given indexed callback function(s). | [
"Create",
"a",
"LatchedObserver",
"with",
"the",
"given",
"indexed",
"callback",
"function",
"(",
"s",
")",
"."
] | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/operators/LatchedObserver.java#L165-L167 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java | DateFunctions.millisToStr | public static Expression millisToStr(String expression, String format) {
return millisToStr(x(expression), format);
} | java | public static Expression millisToStr(String expression, String format) {
return millisToStr(x(expression), format);
} | [
"public",
"static",
"Expression",
"millisToStr",
"(",
"String",
"expression",
",",
"String",
"format",
")",
"{",
"return",
"millisToStr",
"(",
"x",
"(",
"expression",
")",
",",
"format",
")",
";",
"}"
] | Returned expression results in the string in the supported format to which
the UNIX milliseconds has been converted. | [
"Returned",
"expression",
"results",
"in",
"the",
"string",
"in",
"the",
"supported",
"format",
"to",
"which",
"the",
"UNIX",
"milliseconds",
"has",
"been",
"converted",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L243-L245 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/RuntimeHttpUtils.java | RuntimeHttpUtils.fetchFile | @SuppressWarnings("deprecation")
public static InputStream fetchFile(
final URI uri,
final ClientConfiguration config) throws IOException {
HttpParams httpClientParams = new BasicHttpParams();
HttpProtocolParams.setUserAgent(
httpClientParams, getUserAgent(config, null));
HttpConnectionParams.setConnectionTimeout(
httpClientParams, getConnectionTimeout(config));
HttpConnectionParams.setSoTimeout(
httpClientParams, getSocketTimeout(config));
DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);
if (config != null) {
String proxyHost = config.getProxyHost();
int proxyPort = config.getProxyPort();
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpclient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
if (config.getProxyUsername() != null
&& config.getProxyPassword() != null) {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, proxyPort),
new NTCredentials(config.getProxyUsername(),
config.getProxyPassword(),
config.getProxyWorkstation(),
config.getProxyDomain()));
}
}
}
HttpResponse response = httpclient.execute(new HttpGet(uri));
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("Error fetching file from " + uri + ": "
+ response);
}
return new HttpClientWrappingInputStream(
httpclient,
response.getEntity().getContent());
} | java | @SuppressWarnings("deprecation")
public static InputStream fetchFile(
final URI uri,
final ClientConfiguration config) throws IOException {
HttpParams httpClientParams = new BasicHttpParams();
HttpProtocolParams.setUserAgent(
httpClientParams, getUserAgent(config, null));
HttpConnectionParams.setConnectionTimeout(
httpClientParams, getConnectionTimeout(config));
HttpConnectionParams.setSoTimeout(
httpClientParams, getSocketTimeout(config));
DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);
if (config != null) {
String proxyHost = config.getProxyHost();
int proxyPort = config.getProxyPort();
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpclient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
if (config.getProxyUsername() != null
&& config.getProxyPassword() != null) {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, proxyPort),
new NTCredentials(config.getProxyUsername(),
config.getProxyPassword(),
config.getProxyWorkstation(),
config.getProxyDomain()));
}
}
}
HttpResponse response = httpclient.execute(new HttpGet(uri));
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("Error fetching file from " + uri + ": "
+ response);
}
return new HttpClientWrappingInputStream(
httpclient,
response.getEntity().getContent());
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"static",
"InputStream",
"fetchFile",
"(",
"final",
"URI",
"uri",
",",
"final",
"ClientConfiguration",
"config",
")",
"throws",
"IOException",
"{",
"HttpParams",
"httpClientParams",
"=",
"new",
"BasicHt... | Fetches a file from the URI given and returns an input stream to it.
@param uri the uri of the file to fetch
@param config optional configuration overrides
@return an InputStream containing the retrieved data
@throws IOException on error | [
"Fetches",
"a",
"file",
"from",
"the",
"URI",
"given",
"and",
"returns",
"an",
"input",
"stream",
"to",
"it",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/RuntimeHttpUtils.java#L60-L109 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/log/LogStreamResponse.java | LogStreamResponse.openStream | public InputStream openStream() {
try {
URLConnection urlConnection = logStreamURL.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) urlConnection;
https.setSSLSocketFactory(Heroku.sslContext(false).getSocketFactory());
https.setHostnameVerifier(Heroku.hostnameVerifier(false));
}
urlConnection.connect();
return urlConnection.getInputStream();
} catch (IOException e) {
throw new HerokuAPIException("IOException while opening log stream", e);
}
} | java | public InputStream openStream() {
try {
URLConnection urlConnection = logStreamURL.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) urlConnection;
https.setSSLSocketFactory(Heroku.sslContext(false).getSocketFactory());
https.setHostnameVerifier(Heroku.hostnameVerifier(false));
}
urlConnection.connect();
return urlConnection.getInputStream();
} catch (IOException e) {
throw new HerokuAPIException("IOException while opening log stream", e);
}
} | [
"public",
"InputStream",
"openStream",
"(",
")",
"{",
"try",
"{",
"URLConnection",
"urlConnection",
"=",
"logStreamURL",
".",
"openConnection",
"(",
")",
";",
"if",
"(",
"urlConnection",
"instanceof",
"HttpsURLConnection",
")",
"{",
"HttpsURLConnection",
"https",
... | Creates a {@link URLConnection} to logplex. SSL verification is not used because Logplex's certificate is not signed by an authority that exists
in the standard java keystore.
@return input stream | [
"Creates",
"a",
"{"
] | train | https://github.com/heroku/heroku.jar/blob/d9e52991293159498c10c498c6f91fcdd637378e/heroku-api/src/main/java/com/heroku/api/request/log/LogStreamResponse.java#L39-L53 |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java | StringUtil.toCSVString | public static String toCSVString(Object[] pStringArray, String pDelimiterString) {
if (pStringArray == null) {
return "";
}
if (pDelimiterString == null) {
throw new IllegalArgumentException("delimiter == null");
}
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < pStringArray.length; i++) {
if (i > 0) {
buffer.append(pDelimiterString);
}
buffer.append(pStringArray[i]);
}
return buffer.toString();
} | java | public static String toCSVString(Object[] pStringArray, String pDelimiterString) {
if (pStringArray == null) {
return "";
}
if (pDelimiterString == null) {
throw new IllegalArgumentException("delimiter == null");
}
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < pStringArray.length; i++) {
if (i > 0) {
buffer.append(pDelimiterString);
}
buffer.append(pStringArray[i]);
}
return buffer.toString();
} | [
"public",
"static",
"String",
"toCSVString",
"(",
"Object",
"[",
"]",
"pStringArray",
",",
"String",
"pDelimiterString",
")",
"{",
"if",
"(",
"pStringArray",
"==",
"null",
")",
"{",
"return",
"\"\"",
";",
"}",
"if",
"(",
"pDelimiterString",
"==",
"null",
"... | Converts a string array to a string separated by the given delimiter.
@param pStringArray the string array
@param pDelimiterString the delimiter string
@return string of delimiter separated values
@throws IllegalArgumentException if {@code pDelimiterString == null} | [
"Converts",
"a",
"string",
"array",
"to",
"a",
"string",
"separated",
"by",
"the",
"given",
"delimiter",
"."
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/StringUtil.java#L1589-L1607 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.