repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
anotheria/moskito | moskito-core/src/main/java/net/anotheria/moskito/core/stats/impl/StatValueFactory.java | StatValueFactory.createStatValue | public static TypeAwareStatValue createStatValue(StatValueTypes aType, String aName, Interval[] aIntervals) {
"""
This method creates a StatValue instance.
@param aType the type of the value
@param aName the name of the value
@param aIntervals the list of Intervals to be used
@return the StatValue instance
"""
IValueHolderFactory valueHolderFactory = StatValueTypeUtility.createValueHolderFactory(aType);
TypeAwareStatValue value = new TypeAwareStatValueImpl(aName, aType, valueHolderFactory);
// now we have to add the Intervals to the new value....
for (int i = 0; i < aIntervals.length; i++) {
value.addInterval(aIntervals[i]);
}
return value;
} | java | public static TypeAwareStatValue createStatValue(StatValueTypes aType, String aName, Interval[] aIntervals) {
IValueHolderFactory valueHolderFactory = StatValueTypeUtility.createValueHolderFactory(aType);
TypeAwareStatValue value = new TypeAwareStatValueImpl(aName, aType, valueHolderFactory);
// now we have to add the Intervals to the new value....
for (int i = 0; i < aIntervals.length; i++) {
value.addInterval(aIntervals[i]);
}
return value;
} | [
"public",
"static",
"TypeAwareStatValue",
"createStatValue",
"(",
"StatValueTypes",
"aType",
",",
"String",
"aName",
",",
"Interval",
"[",
"]",
"aIntervals",
")",
"{",
"IValueHolderFactory",
"valueHolderFactory",
"=",
"StatValueTypeUtility",
".",
"createValueHolderFactory... | This method creates a StatValue instance.
@param aType the type of the value
@param aName the name of the value
@param aIntervals the list of Intervals to be used
@return the StatValue instance | [
"This",
"method",
"creates",
"a",
"StatValue",
"instance",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/stats/impl/StatValueFactory.java#L73-L81 |
weld/core | impl/src/main/java/org/jboss/weld/injection/producer/AbstractMemberProducer.java | AbstractMemberProducer.getReceiver | protected Object getReceiver(CreationalContext<?> productCreationalContext, CreationalContext<?> receiverCreationalContext) {
"""
Gets the receiver of the product. The two creational contexts need to be separated because the receiver only serves the product
creation (it is not a dependent instance of the created instance).
@param productCreationalContext the creational context of the produced instance
@param receiverCreationalContext the creational context of the receiver
@return The receiver
"""
// This is a bit dangerous, as it means that producer methods can end up
// executing on partially constructed instances. Also, it's not required
// by the spec...
if (getAnnotated().isStatic()) {
return null;
} else {
if (productCreationalContext instanceof WeldCreationalContext<?>) {
WeldCreationalContext<?> creationalContextImpl = (WeldCreationalContext<?>) productCreationalContext;
final Object incompleteInstance = creationalContextImpl.getIncompleteInstance(getDeclaringBean());
if (incompleteInstance != null) {
BeanLogger.LOG.circularCall(getAnnotated(), getDeclaringBean());
return incompleteInstance;
}
}
return getBeanManager().getReference(getDeclaringBean(), null, receiverCreationalContext, true);
}
} | java | protected Object getReceiver(CreationalContext<?> productCreationalContext, CreationalContext<?> receiverCreationalContext) {
// This is a bit dangerous, as it means that producer methods can end up
// executing on partially constructed instances. Also, it's not required
// by the spec...
if (getAnnotated().isStatic()) {
return null;
} else {
if (productCreationalContext instanceof WeldCreationalContext<?>) {
WeldCreationalContext<?> creationalContextImpl = (WeldCreationalContext<?>) productCreationalContext;
final Object incompleteInstance = creationalContextImpl.getIncompleteInstance(getDeclaringBean());
if (incompleteInstance != null) {
BeanLogger.LOG.circularCall(getAnnotated(), getDeclaringBean());
return incompleteInstance;
}
}
return getBeanManager().getReference(getDeclaringBean(), null, receiverCreationalContext, true);
}
} | [
"protected",
"Object",
"getReceiver",
"(",
"CreationalContext",
"<",
"?",
">",
"productCreationalContext",
",",
"CreationalContext",
"<",
"?",
">",
"receiverCreationalContext",
")",
"{",
"// This is a bit dangerous, as it means that producer methods can end up",
"// executing on ... | Gets the receiver of the product. The two creational contexts need to be separated because the receiver only serves the product
creation (it is not a dependent instance of the created instance).
@param productCreationalContext the creational context of the produced instance
@param receiverCreationalContext the creational context of the receiver
@return The receiver | [
"Gets",
"the",
"receiver",
"of",
"the",
"product",
".",
"The",
"two",
"creational",
"contexts",
"need",
"to",
"be",
"separated",
"because",
"the",
"receiver",
"only",
"serves",
"the",
"product",
"creation",
"(",
"it",
"is",
"not",
"a",
"dependent",
"instance... | train | https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/injection/producer/AbstractMemberProducer.java#L108-L125 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java | GJGeometryReader.parsePolygon | private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException {
"""
Coordinates of a Polygon are an array of LinearRing coordinate arrays.
The first element in the array represents the exterior ring. Any
subsequent elements represent interior rings (or holes).
Syntax:
No holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
With holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
[100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
@param jp
@return Polygon
"""
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the RING
int linesIndex = 0;
LinearRing linearRing = null;
ArrayList<LinearRing> holes = new ArrayList<LinearRing>();
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
if (linesIndex == 0) {
linearRing = GF.createLinearRing(parseCoordinates(jp));
} else {
holes.add(GF.createLinearRing(parseCoordinates(jp)));
}
jp.nextToken();//END RING
linesIndex++;
}
if (linesIndex > 1) {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, holes.toArray(new LinearRing[0]));
} else {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, null);
}
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | java | private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ coordinates
jp.nextToken(); //Start the RING
int linesIndex = 0;
LinearRing linearRing = null;
ArrayList<LinearRing> holes = new ArrayList<LinearRing>();
while (jp.getCurrentToken() != JsonToken.END_ARRAY) {
if (linesIndex == 0) {
linearRing = GF.createLinearRing(parseCoordinates(jp));
} else {
holes.add(GF.createLinearRing(parseCoordinates(jp)));
}
jp.nextToken();//END RING
linesIndex++;
}
if (linesIndex > 1) {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, holes.toArray(new LinearRing[0]));
} else {
jp.nextToken();//END_OBJECT } geometry
return GF.createPolygon(linearRing, null);
}
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | [
"private",
"Polygon",
"parsePolygon",
"(",
"JsonParser",
"jp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"jp",
".",
"nextToken",
"(",
")",
";",
"// FIELD_NAME coordinates ",
"String",
"coordinatesField",
"=",
"jp",
".",
"getText",
"(",
")",
... | Coordinates of a Polygon are an array of LinearRing coordinate arrays.
The first element in the array represents the exterior ring. Any
subsequent elements represent interior rings (or holes).
Syntax:
No holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }
With holes:
{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0],
[101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.8, 0.2],
[100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] ] }
@param jp
@return Polygon | [
"Coordinates",
"of",
"a",
"Polygon",
"are",
"an",
"array",
"of",
"LinearRing",
"coordinate",
"arrays",
".",
"The",
"first",
"element",
"in",
"the",
"array",
"represents",
"the",
"exterior",
"ring",
".",
"Any",
"subsequent",
"elements",
"represent",
"interior",
... | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java#L203-L231 |
segmentio/analytics-android | analytics/src/main/java/com/segment/analytics/QueueFile.java | QueueFile.ringRead | @Private
void ringRead(int position, byte[] buffer, int offset, int count) throws IOException {
"""
Reads count bytes into buffer from file. Wraps if necessary.
@param position in file to read from
@param buffer to read into
@param count # of bytes to read
"""
position = wrapPosition(position);
if (position + count <= fileLength) {
raf.seek(position);
raf.readFully(buffer, offset, count);
} else {
// The read overlaps the EOF.
// # of bytes to read before the EOF.
int beforeEof = fileLength - position;
raf.seek(position);
raf.readFully(buffer, offset, beforeEof);
raf.seek(HEADER_LENGTH);
raf.readFully(buffer, offset + beforeEof, count - beforeEof);
}
} | java | @Private
void ringRead(int position, byte[] buffer, int offset, int count) throws IOException {
position = wrapPosition(position);
if (position + count <= fileLength) {
raf.seek(position);
raf.readFully(buffer, offset, count);
} else {
// The read overlaps the EOF.
// # of bytes to read before the EOF.
int beforeEof = fileLength - position;
raf.seek(position);
raf.readFully(buffer, offset, beforeEof);
raf.seek(HEADER_LENGTH);
raf.readFully(buffer, offset + beforeEof, count - beforeEof);
}
} | [
"@",
"Private",
"void",
"ringRead",
"(",
"int",
"position",
",",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"count",
")",
"throws",
"IOException",
"{",
"position",
"=",
"wrapPosition",
"(",
"position",
")",
";",
"if",
"(",
"position",
... | Reads count bytes into buffer from file. Wraps if necessary.
@param position in file to read from
@param buffer to read into
@param count # of bytes to read | [
"Reads",
"count",
"bytes",
"into",
"buffer",
"from",
"file",
".",
"Wraps",
"if",
"necessary",
"."
] | train | https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/QueueFile.java#L265-L280 |
cdk/cdk | descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java | XLogPDescriptor.getAromaticCarbonsCount | private int getAromaticCarbonsCount(IAtomContainer ac, IAtom atom) {
"""
Gets the aromaticCarbonsCount attribute of the XLogPDescriptor object.
@param ac Description of the Parameter
@param atom Description of the Parameter
@return The aromaticCarbonsCount value
"""
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
int carocounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("C") && neighbour.getFlag(CDKConstants.ISAROMATIC)) {
carocounter += 1;
}
}
return carocounter;
} | java | private int getAromaticCarbonsCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
int carocounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("C") && neighbour.getFlag(CDKConstants.ISAROMATIC)) {
carocounter += 1;
}
}
return carocounter;
} | [
"private",
"int",
"getAromaticCarbonsCount",
"(",
"IAtomContainer",
"ac",
",",
"IAtom",
"atom",
")",
"{",
"List",
"<",
"IAtom",
">",
"neighbours",
"=",
"ac",
".",
"getConnectedAtomsList",
"(",
"atom",
")",
";",
"int",
"carocounter",
"=",
"0",
";",
"for",
"... | Gets the aromaticCarbonsCount attribute of the XLogPDescriptor object.
@param ac Description of the Parameter
@param atom Description of the Parameter
@return The aromaticCarbonsCount value | [
"Gets",
"the",
"aromaticCarbonsCount",
"attribute",
"of",
"the",
"XLogPDescriptor",
"object",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java#L1074-L1083 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.setPassword | public void setPassword(CmsDbContext dbc, String username, String newPassword)
throws CmsException, CmsIllegalArgumentException {
"""
Sets the password for a user.<p>
@param dbc the current database context
@param username the name of the user
@param newPassword the new password
@throws CmsException if operation was not successful
@throws CmsIllegalArgumentException if the user with the <code>username</code> was not found
"""
validatePassword(newPassword);
// read the user as a system user to verify that the specified old password is correct
CmsUser user = getUserDriver(dbc).readUser(dbc, username);
// only continue if not found and read user from web might succeed
getUserDriver(dbc).writePassword(dbc, username, null, newPassword);
user.getAdditionalInfo().put(
CmsUserSettings.ADDITIONAL_INFO_LAST_PASSWORD_CHANGE,
"" + System.currentTimeMillis());
getUserDriver(dbc).writeUser(dbc, user);
// fire user modified event
Map<String, Object> eventData = new HashMap<String, Object>();
eventData.put(I_CmsEventListener.KEY_USER_ID, user.getId().toString());
eventData.put(I_CmsEventListener.KEY_USER_ACTION, I_CmsEventListener.VALUE_USER_MODIFIED_ACTION_RESET_PASSWORD);
eventData.put(
I_CmsEventListener.KEY_USER_CHANGES,
Integer.valueOf(CmsUser.FLAG_CORE_DATA | CmsUser.FLAG_CORE_DATA));
OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_USER_MODIFIED, eventData));
} | java | public void setPassword(CmsDbContext dbc, String username, String newPassword)
throws CmsException, CmsIllegalArgumentException {
validatePassword(newPassword);
// read the user as a system user to verify that the specified old password is correct
CmsUser user = getUserDriver(dbc).readUser(dbc, username);
// only continue if not found and read user from web might succeed
getUserDriver(dbc).writePassword(dbc, username, null, newPassword);
user.getAdditionalInfo().put(
CmsUserSettings.ADDITIONAL_INFO_LAST_PASSWORD_CHANGE,
"" + System.currentTimeMillis());
getUserDriver(dbc).writeUser(dbc, user);
// fire user modified event
Map<String, Object> eventData = new HashMap<String, Object>();
eventData.put(I_CmsEventListener.KEY_USER_ID, user.getId().toString());
eventData.put(I_CmsEventListener.KEY_USER_ACTION, I_CmsEventListener.VALUE_USER_MODIFIED_ACTION_RESET_PASSWORD);
eventData.put(
I_CmsEventListener.KEY_USER_CHANGES,
Integer.valueOf(CmsUser.FLAG_CORE_DATA | CmsUser.FLAG_CORE_DATA));
OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_USER_MODIFIED, eventData));
} | [
"public",
"void",
"setPassword",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"username",
",",
"String",
"newPassword",
")",
"throws",
"CmsException",
",",
"CmsIllegalArgumentException",
"{",
"validatePassword",
"(",
"newPassword",
")",
";",
"// read the user as a system ... | Sets the password for a user.<p>
@param dbc the current database context
@param username the name of the user
@param newPassword the new password
@throws CmsException if operation was not successful
@throws CmsIllegalArgumentException if the user with the <code>username</code> was not found | [
"Sets",
"the",
"password",
"for",
"a",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L8988-L9010 |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java | BermudanSwaption.getValue | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
"""
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
Cashflows prior evaluationTime are not considered.
@param evaluationTime The time on which this products value should be observed.
@param model The model used to price the product.
@return The random variable representing the value of the product discounted to evaluation time
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
"""
return (RandomVariableInterface) getValues(evaluationTime, model).get("value");
} | java | @Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
return (RandomVariableInterface) getValues(evaluationTime, model).get("value");
} | [
"@",
"Override",
"public",
"RandomVariableInterface",
"getValue",
"(",
"double",
"evaluationTime",
",",
"LIBORModelMonteCarloSimulationInterface",
"model",
")",
"throws",
"CalculationException",
"{",
"return",
"(",
"RandomVariableInterface",
")",
"getValues",
"(",
"evaluati... | This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
Cashflows prior evaluationTime are not considered.
@param evaluationTime The time on which this products value should be observed.
@param model The model used to price the product.
@return The random variable representing the value of the product discounted to evaluation time
@throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method. | [
"This",
"method",
"returns",
"the",
"value",
"random",
"variable",
"of",
"the",
"product",
"within",
"the",
"specified",
"model",
"evaluated",
"at",
"a",
"given",
"evalutationTime",
".",
"Note",
":",
"For",
"a",
"lattice",
"this",
"is",
"often",
"the",
"valu... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/interestrate/products/BermudanSwaption.java#L147-L150 |
mboudreau/Alternator | src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java | DynamoDBMapper.queryPage | public <T> QueryResultPage<T> queryPage(Class<T> clazz, DynamoDBQueryExpression queryExpression) {
"""
Queries an Amazon DynamoDB table and returns a single page of matching
results. The table to query is determined by looking at the annotations
on the specified class, which declares where to store the object data in
Amazon DynamoDB, and the query expression parameter allows the caller to
filter results and control how the query is executed.
@see DynamoDBMapper#queryPage(Class, DynamoDBQueryExpression, DynamoDBMapperConfig)
"""
return queryPage(clazz, queryExpression, this.config);
} | java | public <T> QueryResultPage<T> queryPage(Class<T> clazz, DynamoDBQueryExpression queryExpression) {
return queryPage(clazz, queryExpression, this.config);
} | [
"public",
"<",
"T",
">",
"QueryResultPage",
"<",
"T",
">",
"queryPage",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"DynamoDBQueryExpression",
"queryExpression",
")",
"{",
"return",
"queryPage",
"(",
"clazz",
",",
"queryExpression",
",",
"this",
".",
"config"... | Queries an Amazon DynamoDB table and returns a single page of matching
results. The table to query is determined by looking at the annotations
on the specified class, which declares where to store the object data in
Amazon DynamoDB, and the query expression parameter allows the caller to
filter results and control how the query is executed.
@see DynamoDBMapper#queryPage(Class, DynamoDBQueryExpression, DynamoDBMapperConfig) | [
"Queries",
"an",
"Amazon",
"DynamoDB",
"table",
"and",
"returns",
"a",
"single",
"page",
"of",
"matching",
"results",
".",
"The",
"table",
"to",
"query",
"is",
"determined",
"by",
"looking",
"at",
"the",
"annotations",
"on",
"the",
"specified",
"class",
"whi... | train | https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java#L1184-L1186 |
saxsys/SynchronizeFX | synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/ListPropertyMetaDataStore.java | ListPropertyMetaDataStore.storeMetaDataOrFail | public void storeMetaDataOrFail(final List<?> list, final ListPropertyMetaData metaData)
throws ObjectToIdMappingException {
"""
Stores meta data for a new {@link List}.
@param list
The list that meta data should be stored for.
@param metaData
The initial meta data for the new {@link List}.
@throws ObjectToIdMappingException
If the list isn't. That means that there is already meta data stored for a {@link List} with
<code>listId</code>
"""
if (listToData.get(list) != null) {
throw new ObjectToIdMappingException("Meta data for a known property should be registered twice. "
+ "The clients may no longer be synchron.");
}
listToData.put(list, metaData);
} | java | public void storeMetaDataOrFail(final List<?> list, final ListPropertyMetaData metaData)
throws ObjectToIdMappingException {
if (listToData.get(list) != null) {
throw new ObjectToIdMappingException("Meta data for a known property should be registered twice. "
+ "The clients may no longer be synchron.");
}
listToData.put(list, metaData);
} | [
"public",
"void",
"storeMetaDataOrFail",
"(",
"final",
"List",
"<",
"?",
">",
"list",
",",
"final",
"ListPropertyMetaData",
"metaData",
")",
"throws",
"ObjectToIdMappingException",
"{",
"if",
"(",
"listToData",
".",
"get",
"(",
"list",
")",
"!=",
"null",
")",
... | Stores meta data for a new {@link List}.
@param list
The list that meta data should be stored for.
@param metaData
The initial meta data for the new {@link List}.
@throws ObjectToIdMappingException
If the list isn't. That means that there is already meta data stored for a {@link List} with
<code>listId</code> | [
"Stores",
"meta",
"data",
"for",
"a",
"new",
"{",
"@link",
"List",
"}",
"."
] | train | https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/ListPropertyMetaDataStore.java#L108-L115 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/BootstrapTools.java | BootstrapTools.startActorSystem | public static ActorSystem startActorSystem(
Configuration configuration,
String actorSystemName,
String listeningAddress,
int listeningPort,
Logger logger,
ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {
"""
Starts an Actor System at a specific port.
@param configuration The Flink configuration.
@param actorSystemName Name of the started {@link ActorSystem}
@param listeningAddress The address to listen at.
@param listeningPort The port to listen at.
@param logger the logger to output log information.
@param actorSystemExecutorConfiguration configuration for the ActorSystem's underlying executor
@return The ActorSystem which has been started.
@throws Exception
"""
String hostPortUrl = NetUtils.unresolvedHostAndPortToNormalizedString(listeningAddress, listeningPort);
logger.info("Trying to start actor system at {}", hostPortUrl);
try {
Config akkaConfig = AkkaUtils.getAkkaConfig(
configuration,
new Some<>(new Tuple2<>(listeningAddress, listeningPort)),
actorSystemExecutorConfiguration.getAkkaConfig());
logger.debug("Using akka configuration\n {}", akkaConfig);
ActorSystem actorSystem = AkkaUtils.createActorSystem(actorSystemName, akkaConfig);
logger.info("Actor system started at {}", AkkaUtils.getAddress(actorSystem));
return actorSystem;
}
catch (Throwable t) {
if (t instanceof ChannelException) {
Throwable cause = t.getCause();
if (cause != null && t.getCause() instanceof BindException) {
throw new IOException("Unable to create ActorSystem at address " + hostPortUrl +
" : " + cause.getMessage(), t);
}
}
throw new Exception("Could not create actor system", t);
}
} | java | public static ActorSystem startActorSystem(
Configuration configuration,
String actorSystemName,
String listeningAddress,
int listeningPort,
Logger logger,
ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {
String hostPortUrl = NetUtils.unresolvedHostAndPortToNormalizedString(listeningAddress, listeningPort);
logger.info("Trying to start actor system at {}", hostPortUrl);
try {
Config akkaConfig = AkkaUtils.getAkkaConfig(
configuration,
new Some<>(new Tuple2<>(listeningAddress, listeningPort)),
actorSystemExecutorConfiguration.getAkkaConfig());
logger.debug("Using akka configuration\n {}", akkaConfig);
ActorSystem actorSystem = AkkaUtils.createActorSystem(actorSystemName, akkaConfig);
logger.info("Actor system started at {}", AkkaUtils.getAddress(actorSystem));
return actorSystem;
}
catch (Throwable t) {
if (t instanceof ChannelException) {
Throwable cause = t.getCause();
if (cause != null && t.getCause() instanceof BindException) {
throw new IOException("Unable to create ActorSystem at address " + hostPortUrl +
" : " + cause.getMessage(), t);
}
}
throw new Exception("Could not create actor system", t);
}
} | [
"public",
"static",
"ActorSystem",
"startActorSystem",
"(",
"Configuration",
"configuration",
",",
"String",
"actorSystemName",
",",
"String",
"listeningAddress",
",",
"int",
"listeningPort",
",",
"Logger",
"logger",
",",
"ActorSystemExecutorConfiguration",
"actorSystemExec... | Starts an Actor System at a specific port.
@param configuration The Flink configuration.
@param actorSystemName Name of the started {@link ActorSystem}
@param listeningAddress The address to listen at.
@param listeningPort The port to listen at.
@param logger the logger to output log information.
@param actorSystemExecutorConfiguration configuration for the ActorSystem's underlying executor
@return The ActorSystem which has been started.
@throws Exception | [
"Starts",
"an",
"Actor",
"System",
"at",
"a",
"specific",
"port",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/BootstrapTools.java#L235-L269 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/user/UserRepository.java | UserRepository.deleteUser | public void deleteUser (final User user)
throws PersistenceException {
"""
'Delete' the users account such that they can no longer access it, however we do not delete
the record from the db. The name is changed such that the original name has XX=FOO if the
name were FOO originally. If we have to lop off any of the name to get our prefix to fit we
use a minus sign instead of a equals side. The password field is set to be the empty string
so that no one can log in (since nothing hashes to the empty string. We also make sure
their email address no longer works, so in case we don't ignore 'deleted' users when we do
the sql to get emailaddresses for the mass mailings we still won't spam delete folk. We
leave the emailaddress intact exect for the @ sign which gets turned to a #, so that we can
see what their email was incase it was an accidently deletion and we have to verify through
email.
"""
if (user.isDeleted()) {
return;
}
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
// create our modified fields mask
FieldMask mask = _utable.getFieldMask();
mask.setModified("username");
mask.setModified("password");
mask.setModified("email");
// set the password to unusable
user.password = "";
// 'disable' their email address
String newEmail = user.email.replace('@','#');
user.email = newEmail;
String oldName = user.username;
for (int ii = 0; ii < 100; ii++) {
try {
user.username = StringUtil.truncate(ii + "=" + oldName, 24);
_utable.update(conn, user, mask);
return null; // nothing to return
} catch (SQLException se) {
if (!liaison.isDuplicateRowException(se)) {
throw se;
}
}
}
// ok we failed to rename the user, lets bust an error
throw new PersistenceException("Failed to 'delete' the user");
}
});
} | java | public void deleteUser (final User user)
throws PersistenceException
{
if (user.isDeleted()) {
return;
}
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws PersistenceException, SQLException
{
// create our modified fields mask
FieldMask mask = _utable.getFieldMask();
mask.setModified("username");
mask.setModified("password");
mask.setModified("email");
// set the password to unusable
user.password = "";
// 'disable' their email address
String newEmail = user.email.replace('@','#');
user.email = newEmail;
String oldName = user.username;
for (int ii = 0; ii < 100; ii++) {
try {
user.username = StringUtil.truncate(ii + "=" + oldName, 24);
_utable.update(conn, user, mask);
return null; // nothing to return
} catch (SQLException se) {
if (!liaison.isDuplicateRowException(se)) {
throw se;
}
}
}
// ok we failed to rename the user, lets bust an error
throw new PersistenceException("Failed to 'delete' the user");
}
});
} | [
"public",
"void",
"deleteUser",
"(",
"final",
"User",
"user",
")",
"throws",
"PersistenceException",
"{",
"if",
"(",
"user",
".",
"isDeleted",
"(",
")",
")",
"{",
"return",
";",
"}",
"executeUpdate",
"(",
"new",
"Operation",
"<",
"Object",
">",
"(",
")",... | 'Delete' the users account such that they can no longer access it, however we do not delete
the record from the db. The name is changed such that the original name has XX=FOO if the
name were FOO originally. If we have to lop off any of the name to get our prefix to fit we
use a minus sign instead of a equals side. The password field is set to be the empty string
so that no one can log in (since nothing hashes to the empty string. We also make sure
their email address no longer works, so in case we don't ignore 'deleted' users when we do
the sql to get emailaddresses for the mass mailings we still won't spam delete folk. We
leave the emailaddress intact exect for the @ sign which gets turned to a #, so that we can
see what their email was incase it was an accidently deletion and we have to verify through
email. | [
"Delete",
"the",
"users",
"account",
"such",
"that",
"they",
"can",
"no",
"longer",
"access",
"it",
"however",
"we",
"do",
"not",
"delete",
"the",
"record",
"from",
"the",
"db",
".",
"The",
"name",
"is",
"changed",
"such",
"that",
"the",
"original",
"nam... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/user/UserRepository.java#L200-L241 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.serviceName_modem_lan_lanName_GET | public OvhLAN serviceName_modem_lan_lanName_GET(String serviceName, String lanName) throws IOException {
"""
Get this object properties
REST: GET /xdsl/{serviceName}/modem/lan/{lanName}
@param serviceName [required] The internal name of your XDSL offer
@param lanName [required] Name of the LAN
"""
String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}";
StringBuilder sb = path(qPath, serviceName, lanName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhLAN.class);
} | java | public OvhLAN serviceName_modem_lan_lanName_GET(String serviceName, String lanName) throws IOException {
String qPath = "/xdsl/{serviceName}/modem/lan/{lanName}";
StringBuilder sb = path(qPath, serviceName, lanName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhLAN.class);
} | [
"public",
"OvhLAN",
"serviceName_modem_lan_lanName_GET",
"(",
"String",
"serviceName",
",",
"String",
"lanName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/{serviceName}/modem/lan/{lanName}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPat... | Get this object properties
REST: GET /xdsl/{serviceName}/modem/lan/{lanName}
@param serviceName [required] The internal name of your XDSL offer
@param lanName [required] Name of the LAN | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L979-L984 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/client/ApiClient.java | ApiClient.requestJWTUserToken | public OAuth.OAuthToken requestJWTUserToken(String clientId, String userId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, IOException, ApiException {
"""
Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
@param clientId DocuSign OAuth Client Id (AKA Integrator Key)
@param userId DocuSign user Id to be impersonated (This is a UUID)
@param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
@param rsaPrivateKey the byte contents of the RSA private key
@param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
@return OAuth.OAuthToken object.
@throws IllegalArgumentException if one of the arguments is invalid
@throws IOException if there is an issue with either the public or private file
@throws ApiException if there is an error while exchanging the JWT with an access token
"""
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append(" " + scopes.get(i));
}
try {
String assertion = JWTUtils.generateJWTAssertionFromByteArray(rsaPrivateKey, getOAuthBasePath(), clientId, userId, expiresIn, sb.toString());
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("assertion", assertion);
form.add("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/token");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OAuth.OAuthToken oAuthToken = mapper.readValue(response.getEntityInputStream(), OAuth.OAuthToken.class);
if (oAuthToken.getAccessToken() == null || "".equals(oAuthToken.getAccessToken()) || oAuthToken.getExpiresIn() <= 0) {
throw new ApiException("Error while requesting an access token: " + response.toString());
}
return oAuthToken;
} catch (JsonParseException e) {
throw new ApiException("Error while parsing the response for the access token: " + e);
} catch (JsonMappingException e) {
throw e;
} catch (IOException e) {
throw e;
}
} | java | public OAuth.OAuthToken requestJWTUserToken(String clientId, String userId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, IOException, ApiException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append(" " + scopes.get(i));
}
try {
String assertion = JWTUtils.generateJWTAssertionFromByteArray(rsaPrivateKey, getOAuthBasePath(), clientId, userId, expiresIn, sb.toString());
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("assertion", assertion);
form.add("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/token");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OAuth.OAuthToken oAuthToken = mapper.readValue(response.getEntityInputStream(), OAuth.OAuthToken.class);
if (oAuthToken.getAccessToken() == null || "".equals(oAuthToken.getAccessToken()) || oAuthToken.getExpiresIn() <= 0) {
throw new ApiException("Error while requesting an access token: " + response.toString());
}
return oAuthToken;
} catch (JsonParseException e) {
throw new ApiException("Error while parsing the response for the access token: " + e);
} catch (JsonMappingException e) {
throw e;
} catch (IOException e) {
throw e;
}
} | [
"public",
"OAuth",
".",
"OAuthToken",
"requestJWTUserToken",
"(",
"String",
"clientId",
",",
"String",
"userId",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
"scopes",
",",
"byte",
"[",
"]",
"rsaPrivateKey",
",",
"long",
"expiresIn",
")",
"th... | Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
@param clientId DocuSign OAuth Client Id (AKA Integrator Key)
@param userId DocuSign user Id to be impersonated (This is a UUID)
@param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
@param rsaPrivateKey the byte contents of the RSA private key
@param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
@return OAuth.OAuthToken object.
@throws IllegalArgumentException if one of the arguments is invalid
@throws IOException if there is an issue with either the public or private file
@throws ApiException if there is an error while exchanging the JWT with an access token | [
"Configures",
"the",
"current",
"instance",
"of",
"ApiClient",
"with",
"a",
"fresh",
"OAuth",
"JWT",
"access",
"token",
"from",
"DocuSign"
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/client/ApiClient.java#L717-L750 |
lamydev/Android-Notification | core/src/zemin/notification/NotificationBoardCallback.java | NotificationBoardCallback.onRowViewAdded | public void onRowViewAdded(NotificationBoard board, RowView rowView, NotificationEntry entry) {
"""
Called when a row view is added to the board.
@param board
@param rowView
@param entry
"""
if (DBG) Log.v(TAG, "onRowViewAdded - " + entry.ID);
if (entry.hasActions()) {
ArrayList<Action> actions = entry.getActions();
ViewGroup vg = (ViewGroup) rowView.findViewById(R.id.actions);
vg.setVisibility(View.VISIBLE);
vg = (ViewGroup) vg.getChildAt(0);
final View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Action act = (Action) view.getTag();
onClickActionView(act.entry, act, view);
act.execute(view.getContext());
}
};
for (int i = 0, count = actions.size(); i < count; i++) {
Action act = actions.get(i);
Button actionBtn = (Button) vg.getChildAt(i);
actionBtn.setVisibility(View.VISIBLE);
actionBtn.setTag(act);
actionBtn.setText(act.title);
actionBtn.setOnClickListener(onClickListener);
actionBtn.setCompoundDrawablesWithIntrinsicBounds(act.icon, 0, 0, 0);
}
}
} | java | public void onRowViewAdded(NotificationBoard board, RowView rowView, NotificationEntry entry) {
if (DBG) Log.v(TAG, "onRowViewAdded - " + entry.ID);
if (entry.hasActions()) {
ArrayList<Action> actions = entry.getActions();
ViewGroup vg = (ViewGroup) rowView.findViewById(R.id.actions);
vg.setVisibility(View.VISIBLE);
vg = (ViewGroup) vg.getChildAt(0);
final View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Action act = (Action) view.getTag();
onClickActionView(act.entry, act, view);
act.execute(view.getContext());
}
};
for (int i = 0, count = actions.size(); i < count; i++) {
Action act = actions.get(i);
Button actionBtn = (Button) vg.getChildAt(i);
actionBtn.setVisibility(View.VISIBLE);
actionBtn.setTag(act);
actionBtn.setText(act.title);
actionBtn.setOnClickListener(onClickListener);
actionBtn.setCompoundDrawablesWithIntrinsicBounds(act.icon, 0, 0, 0);
}
}
} | [
"public",
"void",
"onRowViewAdded",
"(",
"NotificationBoard",
"board",
",",
"RowView",
"rowView",
",",
"NotificationEntry",
"entry",
")",
"{",
"if",
"(",
"DBG",
")",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"onRowViewAdded - \"",
"+",
"entry",
".",
"ID",
")",
"... | Called when a row view is added to the board.
@param board
@param rowView
@param entry | [
"Called",
"when",
"a",
"row",
"view",
"is",
"added",
"to",
"the",
"board",
"."
] | train | https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationBoardCallback.java#L113-L142 |
TheBlackChamber/commons-encryption | src/main/java/net/theblackchamber/crypto/implementations/FileEncryptor.java | FileEncryptor.encryptFile | public void encryptFile(File file, boolean replace) throws MissingParameterException, IOException {
"""
Encrypt a file.
@param file
The file to encrypt
@param replace
True - Replace the specified file with the encrypted version.
False - Keep the unencrypted file.
@throws MissingParameterException
@throws IOException
"""
if(file == null || !file.exists()){
throw new MissingParameterException("File not specified or file does not exist.");
}
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
encryptStream(fis, baos);
File tmpEncrypted = File.createTempFile("commonsencryption", RandomStringUtils.randomAlphanumeric(10));
if(!tmpEncrypted.exists()){
throw new IOException("Failed to encrypt file.");
}
FileOutputStream fos = new FileOutputStream(tmpEncrypted);
IOUtils.write(baos.toByteArray(),fos);
fos.close();
if(replace){
File bkpFile = FileUtils.getFile(file.getAbsolutePath() + ".bkp");
FileUtils.moveFile(file, bkpFile);
try{
FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath()));
}catch(IOException e){
throw new IOException("Failed to encrypt file. Existing file saved with \".bkp\": " + e.getMessage(),e);
}
bkpFile.delete();
}else{
FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath() + ".encrypted"));
}
} | java | public void encryptFile(File file, boolean replace) throws MissingParameterException, IOException {
if(file == null || !file.exists()){
throw new MissingParameterException("File not specified or file does not exist.");
}
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
encryptStream(fis, baos);
File tmpEncrypted = File.createTempFile("commonsencryption", RandomStringUtils.randomAlphanumeric(10));
if(!tmpEncrypted.exists()){
throw new IOException("Failed to encrypt file.");
}
FileOutputStream fos = new FileOutputStream(tmpEncrypted);
IOUtils.write(baos.toByteArray(),fos);
fos.close();
if(replace){
File bkpFile = FileUtils.getFile(file.getAbsolutePath() + ".bkp");
FileUtils.moveFile(file, bkpFile);
try{
FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath()));
}catch(IOException e){
throw new IOException("Failed to encrypt file. Existing file saved with \".bkp\": " + e.getMessage(),e);
}
bkpFile.delete();
}else{
FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath() + ".encrypted"));
}
} | [
"public",
"void",
"encryptFile",
"(",
"File",
"file",
",",
"boolean",
"replace",
")",
"throws",
"MissingParameterException",
",",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"... | Encrypt a file.
@param file
The file to encrypt
@param replace
True - Replace the specified file with the encrypted version.
False - Keep the unencrypted file.
@throws MissingParameterException
@throws IOException | [
"Encrypt",
"a",
"file",
"."
] | train | https://github.com/TheBlackChamber/commons-encryption/blob/0cbbf7c07ae3c133cc82b6dde7ab7af91ddf64d0/src/main/java/net/theblackchamber/crypto/implementations/FileEncryptor.java#L85-L129 |
beanshell/beanshell | src/main/java/bsh/Reflect.java | Reflect.constructObject | static Object constructObject( Class<?> clas, Object[] args )
throws ReflectError, InvocationTargetException {
"""
Primary object constructor
This method is simpler than those that must resolve general method
invocation because constructors are not inherited.
<p/>
This method determines whether to attempt to use non-public constructors
based on Capabilities.haveAccessibility() and will set the accessibilty
flag on the method as necessary.
<p/>
"""
return constructObject(clas, null, args);
} | java | static Object constructObject( Class<?> clas, Object[] args )
throws ReflectError, InvocationTargetException {
return constructObject(clas, null, args);
} | [
"static",
"Object",
"constructObject",
"(",
"Class",
"<",
"?",
">",
"clas",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"ReflectError",
",",
"InvocationTargetException",
"{",
"return",
"constructObject",
"(",
"clas",
",",
"null",
",",
"args",
")",
";",
... | Primary object constructor
This method is simpler than those that must resolve general method
invocation because constructors are not inherited.
<p/>
This method determines whether to attempt to use non-public constructors
based on Capabilities.haveAccessibility() and will set the accessibilty
flag on the method as necessary.
<p/> | [
"Primary",
"object",
"constructor",
"This",
"method",
"is",
"simpler",
"than",
"those",
"that",
"must",
"resolve",
"general",
"method",
"invocation",
"because",
"constructors",
"are",
"not",
"inherited",
".",
"<p",
"/",
">",
"This",
"method",
"determines",
"whet... | train | https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Reflect.java#L383-L386 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Inet6Address.java | Inet6Address.getByAddress | public static Inet6Address getByAddress(String host, byte[] addr, int scope_id)
throws UnknownHostException {
"""
Create an Inet6Address in the exact manner of {@link InetAddress#getByAddress(String,byte[])}
except that the IPv6 scope_id is set to the given numeric value.
The scope_id is not checked to determine if it corresponds to any interface on the system.
See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
scoped addresses.
@param host the specified host
@param addr the raw IP address in network byte order
@param scope_id the numeric scope_id for the address.
@return an Inet6Address object created from the raw IP address.
@exception UnknownHostException if IP address is of illegal length.
@since 1.5
"""
if (host != null && host.length() > 0 && host.charAt(0) == '[') {
if (host.charAt(host.length()-1) == ']') {
host = host.substring(1, host.length() -1);
}
}
if (addr != null) {
if (addr.length == Inet6Address.INADDRSZ) {
return new Inet6Address(host, addr, scope_id);
}
}
throw new UnknownHostException("addr is of illegal length");
} | java | public static Inet6Address getByAddress(String host, byte[] addr, int scope_id)
throws UnknownHostException {
if (host != null && host.length() > 0 && host.charAt(0) == '[') {
if (host.charAt(host.length()-1) == ']') {
host = host.substring(1, host.length() -1);
}
}
if (addr != null) {
if (addr.length == Inet6Address.INADDRSZ) {
return new Inet6Address(host, addr, scope_id);
}
}
throw new UnknownHostException("addr is of illegal length");
} | [
"public",
"static",
"Inet6Address",
"getByAddress",
"(",
"String",
"host",
",",
"byte",
"[",
"]",
"addr",
",",
"int",
"scope_id",
")",
"throws",
"UnknownHostException",
"{",
"if",
"(",
"host",
"!=",
"null",
"&&",
"host",
".",
"length",
"(",
")",
">",
"0"... | Create an Inet6Address in the exact manner of {@link InetAddress#getByAddress(String,byte[])}
except that the IPv6 scope_id is set to the given numeric value.
The scope_id is not checked to determine if it corresponds to any interface on the system.
See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
scoped addresses.
@param host the specified host
@param addr the raw IP address in network byte order
@param scope_id the numeric scope_id for the address.
@return an Inet6Address object created from the raw IP address.
@exception UnknownHostException if IP address is of illegal length.
@since 1.5 | [
"Create",
"an",
"Inet6Address",
"in",
"the",
"exact",
"manner",
"of",
"{",
"@link",
"InetAddress#getByAddress",
"(",
"String",
"byte",
"[]",
")",
"}",
"except",
"that",
"the",
"IPv6",
"scope_id",
"is",
"set",
"to",
"the",
"given",
"numeric",
"value",
".",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/Inet6Address.java#L320-L333 |
hdbeukel/james-core | src/main/java/org/jamesframework/core/subset/algo/tabu/IDBasedSubsetTabuMemory.java | IDBasedSubsetTabuMemory.isTabu | @Override
public boolean isTabu(Move<? super SubsetSolution> move, SubsetSolution currentSolution) {
"""
A move is considered tabu if any involved ID (added or deleted) is currently contained in the tabu memory.
If not, the move is allowed. It is required that the given move is of type {@link SubsetMove}, else an
{@link IncompatibleTabuMemoryException} will be thrown. Note that the argument <code>currentSolution</code>
is not used here, because the move itself contains all necessary information, and may be <code>null</code>.
@param move subset move to be applied to the current solution (required to be of type {@link SubsetMove})
@param currentSolution current solution (not used here, allowed to be <code>null</code>)
@return <code>true</code> if the current memory contains any ID which is added or deleted by the given move
@throws IncompatibleTabuMemoryException if the given move is not of type {@link SubsetMove}
"""
// check move type
if(move instanceof SubsetMove){
// cast
SubsetMove sMove = (SubsetMove) move;
// check if any involved ID is tabu
return containsTabuID(sMove.getAddedIDs()) || containsTabuID(sMove.getDeletedIDs());
} else {
// wrong move type
throw new IncompatibleTabuMemoryException("ID based subset tabu memory can only be used in combination with "
+ "neighbourhoods that generate moves of type SubsetMove. Received: "
+ move.getClass().getSimpleName());
}
} | java | @Override
public boolean isTabu(Move<? super SubsetSolution> move, SubsetSolution currentSolution) {
// check move type
if(move instanceof SubsetMove){
// cast
SubsetMove sMove = (SubsetMove) move;
// check if any involved ID is tabu
return containsTabuID(sMove.getAddedIDs()) || containsTabuID(sMove.getDeletedIDs());
} else {
// wrong move type
throw new IncompatibleTabuMemoryException("ID based subset tabu memory can only be used in combination with "
+ "neighbourhoods that generate moves of type SubsetMove. Received: "
+ move.getClass().getSimpleName());
}
} | [
"@",
"Override",
"public",
"boolean",
"isTabu",
"(",
"Move",
"<",
"?",
"super",
"SubsetSolution",
">",
"move",
",",
"SubsetSolution",
"currentSolution",
")",
"{",
"// check move type",
"if",
"(",
"move",
"instanceof",
"SubsetMove",
")",
"{",
"// cast",
"SubsetMo... | A move is considered tabu if any involved ID (added or deleted) is currently contained in the tabu memory.
If not, the move is allowed. It is required that the given move is of type {@link SubsetMove}, else an
{@link IncompatibleTabuMemoryException} will be thrown. Note that the argument <code>currentSolution</code>
is not used here, because the move itself contains all necessary information, and may be <code>null</code>.
@param move subset move to be applied to the current solution (required to be of type {@link SubsetMove})
@param currentSolution current solution (not used here, allowed to be <code>null</code>)
@return <code>true</code> if the current memory contains any ID which is added or deleted by the given move
@throws IncompatibleTabuMemoryException if the given move is not of type {@link SubsetMove} | [
"A",
"move",
"is",
"considered",
"tabu",
"if",
"any",
"involved",
"ID",
"(",
"added",
"or",
"deleted",
")",
"is",
"currently",
"contained",
"in",
"the",
"tabu",
"memory",
".",
"If",
"not",
"the",
"move",
"is",
"allowed",
".",
"It",
"is",
"required",
"t... | train | https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/algo/tabu/IDBasedSubsetTabuMemory.java#L69-L83 |
cdk/cdk | tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java | GeometricCumulativeDoubleBondFactory.axial3DEncoder | private static StereoEncoder axial3DEncoder(IAtomContainer container, IAtom start, List<IBond> startBonds,
IAtom end, List<IBond> endBonds) {
"""
Create an encoder for axial 3D stereochemistry for the given start and
end atoms.
@param container the molecule
@param start start of the cumulated system
@param startBonds bonds connected to the start
@param end end of the cumulated system
@param endBonds bonds connected to the end
@return an encoder
"""
Point3d[] coordinates = new Point3d[4];
PermutationParity perm = new CombinedPermutationParity(fill3DCoordinates(container, start, startBonds,
coordinates, 0), fill3DCoordinates(container, end, endBonds, coordinates, 2));
GeometricParity geom = new Tetrahedral3DParity(coordinates);
int u = container.indexOf(start);
int v = container.indexOf(end);
return new GeometryEncoder(new int[]{u, v}, perm, geom);
} | java | private static StereoEncoder axial3DEncoder(IAtomContainer container, IAtom start, List<IBond> startBonds,
IAtom end, List<IBond> endBonds) {
Point3d[] coordinates = new Point3d[4];
PermutationParity perm = new CombinedPermutationParity(fill3DCoordinates(container, start, startBonds,
coordinates, 0), fill3DCoordinates(container, end, endBonds, coordinates, 2));
GeometricParity geom = new Tetrahedral3DParity(coordinates);
int u = container.indexOf(start);
int v = container.indexOf(end);
return new GeometryEncoder(new int[]{u, v}, perm, geom);
} | [
"private",
"static",
"StereoEncoder",
"axial3DEncoder",
"(",
"IAtomContainer",
"container",
",",
"IAtom",
"start",
",",
"List",
"<",
"IBond",
">",
"startBonds",
",",
"IAtom",
"end",
",",
"List",
"<",
"IBond",
">",
"endBonds",
")",
"{",
"Point3d",
"[",
"]",
... | Create an encoder for axial 3D stereochemistry for the given start and
end atoms.
@param container the molecule
@param start start of the cumulated system
@param startBonds bonds connected to the start
@param end end of the cumulated system
@param endBonds bonds connected to the end
@return an encoder | [
"Create",
"an",
"encoder",
"for",
"axial",
"3D",
"stereochemistry",
"for",
"the",
"given",
"start",
"and",
"end",
"atoms",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java#L199-L213 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java | Execution.setAccumulators | public void setAccumulators(Map<String, Accumulator<?, ?>> userAccumulators) {
"""
Update accumulators (discarded when the Execution has already been terminated).
@param userAccumulators the user accumulators
"""
synchronized (accumulatorLock) {
if (!state.isTerminal()) {
this.userAccumulators = userAccumulators;
}
}
} | java | public void setAccumulators(Map<String, Accumulator<?, ?>> userAccumulators) {
synchronized (accumulatorLock) {
if (!state.isTerminal()) {
this.userAccumulators = userAccumulators;
}
}
} | [
"public",
"void",
"setAccumulators",
"(",
"Map",
"<",
"String",
",",
"Accumulator",
"<",
"?",
",",
"?",
">",
">",
"userAccumulators",
")",
"{",
"synchronized",
"(",
"accumulatorLock",
")",
"{",
"if",
"(",
"!",
"state",
".",
"isTerminal",
"(",
")",
")",
... | Update accumulators (discarded when the Execution has already been terminated).
@param userAccumulators the user accumulators | [
"Update",
"accumulators",
"(",
"discarded",
"when",
"the",
"Execution",
"has",
"already",
"been",
"terminated",
")",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java#L1386-L1392 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/Assert.java | Assert.notEmpty | public static void notEmpty(Collection<?> collection, String message, Object... arguments) {
"""
Asserts that the {@link Collection} is not empty.
The assertion holds if and only if the {@link Collection} is not {@literal null} and contains at least 1 element.
@param collection {@link Collection} to evaluate.
@param message {@link String} containing the message using in the {@link IllegalArgumentException} thrown
if the assertion fails.
@param arguments array of {@link Object arguments} used as placeholder values
when formatting the {@link String message}.
@throws java.lang.IllegalArgumentException if the {@link Collection} is {@literal null} or empty.
@see #notEmpty(java.util.Collection, RuntimeException)
@see java.util.Collection#isEmpty()
"""
notEmpty(collection, new IllegalArgumentException(format(message, arguments)));
} | java | public static void notEmpty(Collection<?> collection, String message, Object... arguments) {
notEmpty(collection, new IllegalArgumentException(format(message, arguments)));
} | [
"public",
"static",
"void",
"notEmpty",
"(",
"Collection",
"<",
"?",
">",
"collection",
",",
"String",
"message",
",",
"Object",
"...",
"arguments",
")",
"{",
"notEmpty",
"(",
"collection",
",",
"new",
"IllegalArgumentException",
"(",
"format",
"(",
"message",... | Asserts that the {@link Collection} is not empty.
The assertion holds if and only if the {@link Collection} is not {@literal null} and contains at least 1 element.
@param collection {@link Collection} to evaluate.
@param message {@link String} containing the message using in the {@link IllegalArgumentException} thrown
if the assertion fails.
@param arguments array of {@link Object arguments} used as placeholder values
when formatting the {@link String message}.
@throws java.lang.IllegalArgumentException if the {@link Collection} is {@literal null} or empty.
@see #notEmpty(java.util.Collection, RuntimeException)
@see java.util.Collection#isEmpty() | [
"Asserts",
"that",
"the",
"{",
"@link",
"Collection",
"}",
"is",
"not",
"empty",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L1034-L1036 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java | SoapCallMapColumnFixture.callSoapService | protected void callSoapService(String url, String templateName, String soapAction, XmlHttpResponse response) {
"""
Calls SOAP service using template and current row's values.
@param url url of service to call.
@param templateName name of template to use to create POST body.
@param soapAction SOAPAction header value (null if no header is required).
@param response response to fill based on call.
"""
Map<String, Object> headers = soapAction != null ? Collections.singletonMap("SOAPAction", (Object) soapAction) : null;
getEnvironment().callService(url, templateName, getCurrentRowValues(), response, headers);
} | java | protected void callSoapService(String url, String templateName, String soapAction, XmlHttpResponse response) {
Map<String, Object> headers = soapAction != null ? Collections.singletonMap("SOAPAction", (Object) soapAction) : null;
getEnvironment().callService(url, templateName, getCurrentRowValues(), response, headers);
} | [
"protected",
"void",
"callSoapService",
"(",
"String",
"url",
",",
"String",
"templateName",
",",
"String",
"soapAction",
",",
"XmlHttpResponse",
"response",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"headers",
"=",
"soapAction",
"!=",
"null",
"?",
... | Calls SOAP service using template and current row's values.
@param url url of service to call.
@param templateName name of template to use to create POST body.
@param soapAction SOAPAction header value (null if no header is required).
@param response response to fill based on call. | [
"Calls",
"SOAP",
"service",
"using",
"template",
"and",
"current",
"row",
"s",
"values",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java#L83-L86 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectInputStream.java | ObjectInputStream.readNonPrimitiveContent | private Object readNonPrimitiveContent(boolean unshared)
throws ClassNotFoundException, IOException {
"""
Reads the content of the receiver based on the previously read token
{@code tc}. Primitive data content is considered an error.
@param unshared
read the object unshared
@return the object read from the stream
@throws IOException
If an IO exception happened when reading the class
descriptor.
@throws ClassNotFoundException
If the class corresponding to the object being read could not
be found.
"""
checkReadPrimitiveTypes();
int remaining = primitiveData.available();
if (remaining > 0) {
OptionalDataException e = new OptionalDataException(remaining);
e.length = remaining;
throw e;
}
do {
byte tc = nextTC();
switch (tc) {
case TC_CLASS:
return readNewClass(unshared);
case TC_CLASSDESC:
return readNewClassDesc(unshared);
case TC_ARRAY:
return readNewArray(unshared);
case TC_OBJECT:
return readNewObject(unshared);
case TC_STRING:
return readNewString(unshared);
case TC_LONGSTRING:
return readNewLongString(unshared);
case TC_ENUM:
return readEnum(unshared);
case TC_REFERENCE:
if (unshared) {
readNewHandle();
throw new InvalidObjectException("Unshared read of back reference");
}
return readCyclicReference();
case TC_NULL:
return null;
case TC_EXCEPTION:
Exception exc = readException();
throw new WriteAbortedException("Read an exception", exc);
case TC_RESET:
resetState();
break;
case TC_ENDBLOCKDATA: // Can occur reading class annotation
pushbackTC();
OptionalDataException e = new OptionalDataException(true);
e.eof = true;
throw e;
default:
throw corruptStream(tc);
}
// Only TC_RESET falls through
} while (true);
} | java | private Object readNonPrimitiveContent(boolean unshared)
throws ClassNotFoundException, IOException {
checkReadPrimitiveTypes();
int remaining = primitiveData.available();
if (remaining > 0) {
OptionalDataException e = new OptionalDataException(remaining);
e.length = remaining;
throw e;
}
do {
byte tc = nextTC();
switch (tc) {
case TC_CLASS:
return readNewClass(unshared);
case TC_CLASSDESC:
return readNewClassDesc(unshared);
case TC_ARRAY:
return readNewArray(unshared);
case TC_OBJECT:
return readNewObject(unshared);
case TC_STRING:
return readNewString(unshared);
case TC_LONGSTRING:
return readNewLongString(unshared);
case TC_ENUM:
return readEnum(unshared);
case TC_REFERENCE:
if (unshared) {
readNewHandle();
throw new InvalidObjectException("Unshared read of back reference");
}
return readCyclicReference();
case TC_NULL:
return null;
case TC_EXCEPTION:
Exception exc = readException();
throw new WriteAbortedException("Read an exception", exc);
case TC_RESET:
resetState();
break;
case TC_ENDBLOCKDATA: // Can occur reading class annotation
pushbackTC();
OptionalDataException e = new OptionalDataException(true);
e.eof = true;
throw e;
default:
throw corruptStream(tc);
}
// Only TC_RESET falls through
} while (true);
} | [
"private",
"Object",
"readNonPrimitiveContent",
"(",
"boolean",
"unshared",
")",
"throws",
"ClassNotFoundException",
",",
"IOException",
"{",
"checkReadPrimitiveTypes",
"(",
")",
";",
"int",
"remaining",
"=",
"primitiveData",
".",
"available",
"(",
")",
";",
"if",
... | Reads the content of the receiver based on the previously read token
{@code tc}. Primitive data content is considered an error.
@param unshared
read the object unshared
@return the object read from the stream
@throws IOException
If an IO exception happened when reading the class
descriptor.
@throws ClassNotFoundException
If the class corresponding to the object being read could not
be found. | [
"Reads",
"the",
"content",
"of",
"the",
"receiver",
"based",
"on",
"the",
"previously",
"read",
"token",
"{",
"@code",
"tc",
"}",
".",
"Primitive",
"data",
"content",
"is",
"considered",
"an",
"error",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectInputStream.java#L770-L821 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java | CmsContainerpageHandler.changeTemplateContextManually | @SuppressWarnings("deprecation")
public void changeTemplateContextManually(final String cookieName, final String value) {
"""
Switches the template context.<p>
@param cookieName the cookie name
@param value the new template context
"""
if (value != null) {
Cookies.setCookie(cookieName, value, new Date(300, 0, 1), null, "/", false);
} else {
Cookies.removeCookie(cookieName, "/");
}
Window.Location.reload();
} | java | @SuppressWarnings("deprecation")
public void changeTemplateContextManually(final String cookieName, final String value) {
if (value != null) {
Cookies.setCookie(cookieName, value, new Date(300, 0, 1), null, "/", false);
} else {
Cookies.removeCookie(cookieName, "/");
}
Window.Location.reload();
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"void",
"changeTemplateContextManually",
"(",
"final",
"String",
"cookieName",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"Cookies",
".",
"setCookie",
"... | Switches the template context.<p>
@param cookieName the cookie name
@param value the new template context | [
"Switches",
"the",
"template",
"context",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L256-L265 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/route/Route.java | Route.PUT | public static Route PUT(String uriPattern, RouteHandler routeHandler) {
"""
Create a {@code PUT} route.
@param uriPattern
@param routeHandler
@return
"""
return new Route(HttpConstants.Method.PUT, uriPattern, routeHandler);
} | java | public static Route PUT(String uriPattern, RouteHandler routeHandler) {
return new Route(HttpConstants.Method.PUT, uriPattern, routeHandler);
} | [
"public",
"static",
"Route",
"PUT",
"(",
"String",
"uriPattern",
",",
"RouteHandler",
"routeHandler",
")",
"{",
"return",
"new",
"Route",
"(",
"HttpConstants",
".",
"Method",
".",
"PUT",
",",
"uriPattern",
",",
"routeHandler",
")",
";",
"}"
] | Create a {@code PUT} route.
@param uriPattern
@param routeHandler
@return | [
"Create",
"a",
"{",
"@code",
"PUT",
"}",
"route",
"."
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/route/Route.java#L114-L116 |
maestrano/maestrano-java | src/main/java/com/maestrano/Maestrano.java | Maestrano.reloadConfiguration | public static Preset reloadConfiguration(String marketplace, Properties props) throws MnoConfigurationException {
"""
reload the configuration for the given preset and overload the existing one if any
@throws MnoConfigurationException
"""
Preset preset = new Preset(marketplace, props);
configurations.put(marketplace, preset);
return preset;
} | java | public static Preset reloadConfiguration(String marketplace, Properties props) throws MnoConfigurationException {
Preset preset = new Preset(marketplace, props);
configurations.put(marketplace, preset);
return preset;
} | [
"public",
"static",
"Preset",
"reloadConfiguration",
"(",
"String",
"marketplace",
",",
"Properties",
"props",
")",
"throws",
"MnoConfigurationException",
"{",
"Preset",
"preset",
"=",
"new",
"Preset",
"(",
"marketplace",
",",
"props",
")",
";",
"configurations",
... | reload the configuration for the given preset and overload the existing one if any
@throws MnoConfigurationException | [
"reload",
"the",
"configuration",
"for",
"the",
"given",
"preset",
"and",
"overload",
"the",
"existing",
"one",
"if",
"any"
] | train | https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/Maestrano.java#L144-L148 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/TimeLimitDaemon.java | TimeLimitDaemon.valueWasRemoved | public void valueWasRemoved(DCache cache, Object id) {
"""
This notifies this daemon that an entry has removed,
It removes the entry from the internal tables.
@param cache The cache instance.
@param id The cache id.
"""
//final String methodName = "valueWasRemoved()";
if ( UNIT_TEST_INACTIVITY ) {
System.out.println("valueWasRemoved() - entry");
}
ExpirationMetaData expirationMetaData = (ExpirationMetaData)cacheInstancesTable.get(cache);
if (expirationMetaData == null) {
return;
}
synchronized (expirationMetaData) {
InvalidationTask it = (InvalidationTask) expirationMetaData.expirationTable.remove(id);
if (it != null) {
expirationMetaData.timeLimitHeap.delete(it);
it.reset();
taskPool.add(it);
//traceDebug(methodName, "cacheName=" + cache.cacheName + " id=" + id + " expirationTableSize=" + expirationMetaData.expirationTable.size() + " timeLimitHeapSize=" + expirationMetaData.timeLimitHeap.size());
}
}
} | java | public void valueWasRemoved(DCache cache, Object id) {
//final String methodName = "valueWasRemoved()";
if ( UNIT_TEST_INACTIVITY ) {
System.out.println("valueWasRemoved() - entry");
}
ExpirationMetaData expirationMetaData = (ExpirationMetaData)cacheInstancesTable.get(cache);
if (expirationMetaData == null) {
return;
}
synchronized (expirationMetaData) {
InvalidationTask it = (InvalidationTask) expirationMetaData.expirationTable.remove(id);
if (it != null) {
expirationMetaData.timeLimitHeap.delete(it);
it.reset();
taskPool.add(it);
//traceDebug(methodName, "cacheName=" + cache.cacheName + " id=" + id + " expirationTableSize=" + expirationMetaData.expirationTable.size() + " timeLimitHeapSize=" + expirationMetaData.timeLimitHeap.size());
}
}
} | [
"public",
"void",
"valueWasRemoved",
"(",
"DCache",
"cache",
",",
"Object",
"id",
")",
"{",
"//final String methodName = \"valueWasRemoved()\";",
"if",
"(",
"UNIT_TEST_INACTIVITY",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"valueWasRemoved() - entry\"",
"... | This notifies this daemon that an entry has removed,
It removes the entry from the internal tables.
@param cache The cache instance.
@param id The cache id. | [
"This",
"notifies",
"this",
"daemon",
"that",
"an",
"entry",
"has",
"removed",
"It",
"removes",
"the",
"entry",
"from",
"the",
"internal",
"tables",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/TimeLimitDaemon.java#L277-L295 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java | ReUtil.contains | public static boolean contains(Pattern pattern, CharSequence content) {
"""
指定内容中是否有表达式匹配的内容
@param pattern 编译后的正则模式
@param content 被查找的内容
@return 指定内容中是否有表达式匹配的内容
@since 3.3.1
"""
if (null == pattern || null == content) {
return false;
}
return pattern.matcher(content).find();
} | java | public static boolean contains(Pattern pattern, CharSequence content) {
if (null == pattern || null == content) {
return false;
}
return pattern.matcher(content).find();
} | [
"public",
"static",
"boolean",
"contains",
"(",
"Pattern",
"pattern",
",",
"CharSequence",
"content",
")",
"{",
"if",
"(",
"null",
"==",
"pattern",
"||",
"null",
"==",
"content",
")",
"{",
"return",
"false",
";",
"}",
"return",
"pattern",
".",
"matcher",
... | 指定内容中是否有表达式匹配的内容
@param pattern 编译后的正则模式
@param content 被查找的内容
@return 指定内容中是否有表达式匹配的内容
@since 3.3.1 | [
"指定内容中是否有表达式匹配的内容"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L536-L541 |
apiman/apiman | common/plugin/src/main/java/io/apiman/common/plugin/PluginCoordinates.java | PluginCoordinates.fromPolicySpec | public static final PluginCoordinates fromPolicySpec(String pluginPolicySpec) {
"""
Returns the plugin coordinates associated with the given plugin policy specification. The format
of a plugin policy specification is:
plugin:groupId:artifactId:version[:classifier][:type]/org.example.plugins.PluginImpl
@param pluginPolicySpec the policy specification
@return plugin coordinates
"""
if (pluginPolicySpec == null) {
return null;
}
int startIdx = 7;
int endIdx = pluginPolicySpec.indexOf('/');
String [] split = pluginPolicySpec.substring(startIdx, endIdx).split(":"); //$NON-NLS-1$
String groupId = split[0];
String artifactId = split[1];
String version = split[2];
String classifier = null;
String type = null;
if (split.length == 4) {
type = split[3];
}
if (split.length == 5) {
classifier = split[3];
type = split[4];
}
PluginCoordinates rval = new PluginCoordinates(groupId, artifactId, version, classifier, type);
return rval;
} | java | public static final PluginCoordinates fromPolicySpec(String pluginPolicySpec) {
if (pluginPolicySpec == null) {
return null;
}
int startIdx = 7;
int endIdx = pluginPolicySpec.indexOf('/');
String [] split = pluginPolicySpec.substring(startIdx, endIdx).split(":"); //$NON-NLS-1$
String groupId = split[0];
String artifactId = split[1];
String version = split[2];
String classifier = null;
String type = null;
if (split.length == 4) {
type = split[3];
}
if (split.length == 5) {
classifier = split[3];
type = split[4];
}
PluginCoordinates rval = new PluginCoordinates(groupId, artifactId, version, classifier, type);
return rval;
} | [
"public",
"static",
"final",
"PluginCoordinates",
"fromPolicySpec",
"(",
"String",
"pluginPolicySpec",
")",
"{",
"if",
"(",
"pluginPolicySpec",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"int",
"startIdx",
"=",
"7",
";",
"int",
"endIdx",
"=",
"plugi... | Returns the plugin coordinates associated with the given plugin policy specification. The format
of a plugin policy specification is:
plugin:groupId:artifactId:version[:classifier][:type]/org.example.plugins.PluginImpl
@param pluginPolicySpec the policy specification
@return plugin coordinates | [
"Returns",
"the",
"plugin",
"coordinates",
"associated",
"with",
"the",
"given",
"plugin",
"policy",
"specification",
".",
"The",
"format",
"of",
"a",
"plugin",
"policy",
"specification",
"is",
":"
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/plugin/src/main/java/io/apiman/common/plugin/PluginCoordinates.java#L236-L258 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/service/AbstractDynamicService.java | AbstractDynamicService.logIdent | protected static String logIdent(final String hostname, final Service service) {
"""
Simple log helper to give logs a common prefix.
@param hostname the address.
@param service the service.
@return a prefix string for logs.
"""
return "[" + hostname + "][" + service.getClass().getSimpleName() + "]: ";
} | java | protected static String logIdent(final String hostname, final Service service) {
return "[" + hostname + "][" + service.getClass().getSimpleName() + "]: ";
} | [
"protected",
"static",
"String",
"logIdent",
"(",
"final",
"String",
"hostname",
",",
"final",
"Service",
"service",
")",
"{",
"return",
"\"[\"",
"+",
"hostname",
"+",
"\"][\"",
"+",
"service",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+"... | Simple log helper to give logs a common prefix.
@param hostname the address.
@param service the service.
@return a prefix string for logs. | [
"Simple",
"log",
"helper",
"to",
"give",
"logs",
"a",
"common",
"prefix",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/service/AbstractDynamicService.java#L190-L192 |
dwdyer/reportng | reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java | HTMLReporter.createResults | private void createResults(List<ISuite> suites,
File outputDirectory,
boolean onlyShowFailures) throws Exception {
"""
Generate a results file for each test in each suite.
@param outputDirectory The target directory for the generated file(s).
"""
int index = 1;
for (ISuite suite : suites)
{
int index2 = 1;
for (ISuiteResult result : suite.getResults().values())
{
boolean failuresExist = result.getTestContext().getFailedTests().size() > 0
|| result.getTestContext().getFailedConfigurations().size() > 0;
if (!onlyShowFailures || failuresExist)
{
VelocityContext context = createContext();
context.put(RESULT_KEY, result);
context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));
context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));
context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));
context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));
context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));
String fileName = String.format("suite%d_test%d_%s", index, index2, RESULTS_FILE);
generateFile(new File(outputDirectory, fileName),
RESULTS_FILE + TEMPLATE_EXTENSION,
context);
}
++index2;
}
++index;
}
} | java | private void createResults(List<ISuite> suites,
File outputDirectory,
boolean onlyShowFailures) throws Exception
{
int index = 1;
for (ISuite suite : suites)
{
int index2 = 1;
for (ISuiteResult result : suite.getResults().values())
{
boolean failuresExist = result.getTestContext().getFailedTests().size() > 0
|| result.getTestContext().getFailedConfigurations().size() > 0;
if (!onlyShowFailures || failuresExist)
{
VelocityContext context = createContext();
context.put(RESULT_KEY, result);
context.put(FAILED_CONFIG_KEY, sortByTestClass(result.getTestContext().getFailedConfigurations()));
context.put(SKIPPED_CONFIG_KEY, sortByTestClass(result.getTestContext().getSkippedConfigurations()));
context.put(FAILED_TESTS_KEY, sortByTestClass(result.getTestContext().getFailedTests()));
context.put(SKIPPED_TESTS_KEY, sortByTestClass(result.getTestContext().getSkippedTests()));
context.put(PASSED_TESTS_KEY, sortByTestClass(result.getTestContext().getPassedTests()));
String fileName = String.format("suite%d_test%d_%s", index, index2, RESULTS_FILE);
generateFile(new File(outputDirectory, fileName),
RESULTS_FILE + TEMPLATE_EXTENSION,
context);
}
++index2;
}
++index;
}
} | [
"private",
"void",
"createResults",
"(",
"List",
"<",
"ISuite",
">",
"suites",
",",
"File",
"outputDirectory",
",",
"boolean",
"onlyShowFailures",
")",
"throws",
"Exception",
"{",
"int",
"index",
"=",
"1",
";",
"for",
"(",
"ISuite",
"suite",
":",
"suites",
... | Generate a results file for each test in each suite.
@param outputDirectory The target directory for the generated file(s). | [
"Generate",
"a",
"results",
"file",
"for",
"each",
"test",
"in",
"each",
"suite",
"."
] | train | https://github.com/dwdyer/reportng/blob/df11f9cd9ab3fb5847fbba94ed3098ae0448f770/reportng/src/java/main/org/uncommons/reportng/HTMLReporter.java#L170-L200 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/MapExpressionBase.java | MapExpressionBase.contains | @SuppressWarnings("unchecked")
public final BooleanExpression contains(Expression<K> key, Expression<V> value) {
"""
Create a {@code (key, value) in this} expression
@param key key of entry
@param value value of entry
@return expression
"""
return get(key).eq((Expression) value);
} | java | @SuppressWarnings("unchecked")
public final BooleanExpression contains(Expression<K> key, Expression<V> value) {
return get(key).eq((Expression) value);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"final",
"BooleanExpression",
"contains",
"(",
"Expression",
"<",
"K",
">",
"key",
",",
"Expression",
"<",
"V",
">",
"value",
")",
"{",
"return",
"get",
"(",
"key",
")",
".",
"eq",
"(",
"(",
... | Create a {@code (key, value) in this} expression
@param key key of entry
@param value value of entry
@return expression | [
"Create",
"a",
"{",
"@code",
"(",
"key",
"value",
")",
"in",
"this",
"}",
"expression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/MapExpressionBase.java#L66-L69 |
jbundle/jbundle | thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/DatabaseProxy.java | DatabaseProxy.setDBProperties | public void setDBProperties(Map<String, Object> properties) throws DBException, RemoteException {
"""
Get the database properties.
@return The database properties object (Always non-null).
"""
BaseTransport transport = this.createProxyTransport(SET_DB_PROPERTIES);
transport.addParam(PROPERTIES, properties);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
this.checkDBException(objReturn);
} | java | public void setDBProperties(Map<String, Object> properties) throws DBException, RemoteException
{
BaseTransport transport = this.createProxyTransport(SET_DB_PROPERTIES);
transport.addParam(PROPERTIES, properties);
Object strReturn = transport.sendMessageAndGetReply();
Object objReturn = transport.convertReturnObject(strReturn);
this.checkDBException(objReturn);
} | [
"public",
"void",
"setDBProperties",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"throws",
"DBException",
",",
"RemoteException",
"{",
"BaseTransport",
"transport",
"=",
"this",
".",
"createProxyTransport",
"(",
"SET_DB_PROPERTIES",
")",
";",... | Get the database properties.
@return The database properties object (Always non-null). | [
"Get",
"the",
"database",
"properties",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/DatabaseProxy.java#L105-L112 |
phax/ph-masterdata | ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java | PostalCodeManager.isValidPostalCode | @Nonnull
public ETriState isValidPostalCode (@Nullable final Locale aCountry, @Nullable final String sPostalCode) {
"""
Check if the passed postal code is valid for the passed country.
@param aCountry
The country to check. May be <code>null</code>.
@param sPostalCode
The postal code to check. May be <code>null</code>.
@return {@link ETriState#UNDEFINED} if no information for the passed
country are present, {@link ETriState#TRUE} if the postal code is
valid or {@link ETriState#FALSE} if the passed postal code is
explicitly not valid for the passed country.
"""
final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry);
if (aPostalCountry == null)
return ETriState.UNDEFINED;
return ETriState.valueOf (aPostalCountry.isValidPostalCode (sPostalCode));
} | java | @Nonnull
public ETriState isValidPostalCode (@Nullable final Locale aCountry, @Nullable final String sPostalCode)
{
final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry);
if (aPostalCountry == null)
return ETriState.UNDEFINED;
return ETriState.valueOf (aPostalCountry.isValidPostalCode (sPostalCode));
} | [
"@",
"Nonnull",
"public",
"ETriState",
"isValidPostalCode",
"(",
"@",
"Nullable",
"final",
"Locale",
"aCountry",
",",
"@",
"Nullable",
"final",
"String",
"sPostalCode",
")",
"{",
"final",
"IPostalCodeCountry",
"aPostalCountry",
"=",
"getPostalCountryOfCountry",
"(",
... | Check if the passed postal code is valid for the passed country.
@param aCountry
The country to check. May be <code>null</code>.
@param sPostalCode
The postal code to check. May be <code>null</code>.
@return {@link ETriState#UNDEFINED} if no information for the passed
country are present, {@link ETriState#TRUE} if the postal code is
valid or {@link ETriState#FALSE} if the passed postal code is
explicitly not valid for the passed country. | [
"Check",
"if",
"the",
"passed",
"postal",
"code",
"is",
"valid",
"for",
"the",
"passed",
"country",
"."
] | train | https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java#L111-L118 |
samskivert/samskivert | src/main/java/com/samskivert/swing/util/DialogUtil.java | DialogUtil.createDialog | public static JInternalDialog createDialog (JFrame frame, JPanel content) {
"""
Creates and shows an internal dialog with the specified panel.
"""
return createDialog(frame, null, content);
} | java | public static JInternalDialog createDialog (JFrame frame, JPanel content)
{
return createDialog(frame, null, content);
} | [
"public",
"static",
"JInternalDialog",
"createDialog",
"(",
"JFrame",
"frame",
",",
"JPanel",
"content",
")",
"{",
"return",
"createDialog",
"(",
"frame",
",",
"null",
",",
"content",
")",
";",
"}"
] | Creates and shows an internal dialog with the specified panel. | [
"Creates",
"and",
"shows",
"an",
"internal",
"dialog",
"with",
"the",
"specified",
"panel",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/DialogUtil.java#L25-L28 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java | SheetBindingErrors.pushNestedPath | public void pushNestedPath(final String subPath, final int index) {
"""
配列やリストなどのインデックス付きのパスを1つ下位に移動します。
@param subPath ネストするパス
@param index インデックス番号(0から始まります。)
@throws IllegalArgumentException {@literal subPath is empty or index < 0}
"""
final String canonicalPath = normalizePath(subPath);
ArgUtils.notEmpty(subPath, "subPath");
ArgUtils.notMin(index, -1, "index");
pushNestedPath(String.format("%s[%d]", canonicalPath, index));
} | java | public void pushNestedPath(final String subPath, final int index) {
final String canonicalPath = normalizePath(subPath);
ArgUtils.notEmpty(subPath, "subPath");
ArgUtils.notMin(index, -1, "index");
pushNestedPath(String.format("%s[%d]", canonicalPath, index));
} | [
"public",
"void",
"pushNestedPath",
"(",
"final",
"String",
"subPath",
",",
"final",
"int",
"index",
")",
"{",
"final",
"String",
"canonicalPath",
"=",
"normalizePath",
"(",
"subPath",
")",
";",
"ArgUtils",
".",
"notEmpty",
"(",
"subPath",
",",
"\"subPath\"",
... | 配列やリストなどのインデックス付きのパスを1つ下位に移動します。
@param subPath ネストするパス
@param index インデックス番号(0から始まります。)
@throws IllegalArgumentException {@literal subPath is empty or index < 0} | [
"配列やリストなどのインデックス付きのパスを1つ下位に移動します。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java#L318-L324 |
bi-geek/flink-connector-ethereum | src/main/java/com/bigeek/flink/utils/EthereumWrapper.java | EthereumWrapper.configureInstance | public static Web3j configureInstance(String address, Long timeout) {
"""
Get instance with parameters.
@param address
@param timeout
@return web3j client
"""
web3jInstance = EthereumUtils.generateClient(address, timeout);
return web3jInstance;
} | java | public static Web3j configureInstance(String address, Long timeout) {
web3jInstance = EthereumUtils.generateClient(address, timeout);
return web3jInstance;
} | [
"public",
"static",
"Web3j",
"configureInstance",
"(",
"String",
"address",
",",
"Long",
"timeout",
")",
"{",
"web3jInstance",
"=",
"EthereumUtils",
".",
"generateClient",
"(",
"address",
",",
"timeout",
")",
";",
"return",
"web3jInstance",
";",
"}"
] | Get instance with parameters.
@param address
@param timeout
@return web3j client | [
"Get",
"instance",
"with",
"parameters",
"."
] | train | https://github.com/bi-geek/flink-connector-ethereum/blob/9ecedbf999fc410e50225c3f69b5041df4c61a33/src/main/java/com/bigeek/flink/utils/EthereumWrapper.java#L19-L22 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/transfer/internal/TransferManagerUtils.java | TransferManagerUtils.shouldUseMultipartUpload | public static boolean shouldUseMultipartUpload(PutObjectRequest putObjectRequest, TransferManagerConfiguration configuration) {
"""
Returns true if the the specified request should be processed as a
multipart upload (instead of a single part upload).
@param putObjectRequest
The request containing all the details of the upload.
@param configuration
Configuration settings controlling how transfer manager
processes requests.
@return True if the the specified request should be processed as a
multipart upload.
"""
long contentLength = TransferManagerUtils.getContentLength(putObjectRequest);
return contentLength > configuration.getMultipartUploadThreshold();
} | java | public static boolean shouldUseMultipartUpload(PutObjectRequest putObjectRequest, TransferManagerConfiguration configuration) {
long contentLength = TransferManagerUtils.getContentLength(putObjectRequest);
return contentLength > configuration.getMultipartUploadThreshold();
} | [
"public",
"static",
"boolean",
"shouldUseMultipartUpload",
"(",
"PutObjectRequest",
"putObjectRequest",
",",
"TransferManagerConfiguration",
"configuration",
")",
"{",
"long",
"contentLength",
"=",
"TransferManagerUtils",
".",
"getContentLength",
"(",
"putObjectRequest",
")",... | Returns true if the the specified request should be processed as a
multipart upload (instead of a single part upload).
@param putObjectRequest
The request containing all the details of the upload.
@param configuration
Configuration settings controlling how transfer manager
processes requests.
@return True if the the specified request should be processed as a
multipart upload. | [
"Returns",
"true",
"if",
"the",
"the",
"specified",
"request",
"should",
"be",
"processed",
"as",
"a",
"multipart",
"upload",
"(",
"instead",
"of",
"a",
"single",
"part",
"upload",
")",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/transfer/internal/TransferManagerUtils.java#L139-L143 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.addEntry | public static void addEntry(final File zip, final String path, final byte[] bytes) {
"""
Changes a zip file, adds one new entry in-place.
@param zip
an existing ZIP file (only read).
@param path
new ZIP entry path.
@param bytes
new entry bytes (or <code>null</code> if directory).
"""
operateInPlace(zip, new InPlaceAction() {
public boolean act(File tmpFile) {
addEntry(zip, path, bytes, tmpFile);
return true;
}
});
} | java | public static void addEntry(final File zip, final String path, final byte[] bytes) {
operateInPlace(zip, new InPlaceAction() {
public boolean act(File tmpFile) {
addEntry(zip, path, bytes, tmpFile);
return true;
}
});
} | [
"public",
"static",
"void",
"addEntry",
"(",
"final",
"File",
"zip",
",",
"final",
"String",
"path",
",",
"final",
"byte",
"[",
"]",
"bytes",
")",
"{",
"operateInPlace",
"(",
"zip",
",",
"new",
"InPlaceAction",
"(",
")",
"{",
"public",
"boolean",
"act",
... | Changes a zip file, adds one new entry in-place.
@param zip
an existing ZIP file (only read).
@param path
new ZIP entry path.
@param bytes
new entry bytes (or <code>null</code> if directory). | [
"Changes",
"a",
"zip",
"file",
"adds",
"one",
"new",
"entry",
"in",
"-",
"place",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2093-L2100 |
encircled/Joiner | joiner-core/src/main/java/cz/encircled/joiner/core/DefaultAliasResolver.java | DefaultAliasResolver.findPathOnParentSubclasses | private void findPathOnParentSubclasses(Path<?> parent, Class<?> targetType, List<Path<?>> candidatePaths) {
"""
Try to find attribute on a subclass of parent (for instance in test domain when looking for <code>Key</code> on <code>User</code>)
@param parent parent join or "from" element
@param targetType type of joined attribute
@param candidatePaths container for found paths
"""
for (Class child : ReflectionUtils.getSubclasses(parent.getType(), entityManager)) {
try {
Class clazz = Class.forName(child.getPackage().getName() + ".Q" + child.getSimpleName());
Object childInstance = ReflectionUtils.instantiate(clazz, (String) parent.getMetadata().getElement());
for (Field field : clazz.getFields()) {
testAliasCandidate(targetType, candidatePaths, getField(field, childInstance));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | java | private void findPathOnParentSubclasses(Path<?> parent, Class<?> targetType, List<Path<?>> candidatePaths) {
for (Class child : ReflectionUtils.getSubclasses(parent.getType(), entityManager)) {
try {
Class clazz = Class.forName(child.getPackage().getName() + ".Q" + child.getSimpleName());
Object childInstance = ReflectionUtils.instantiate(clazz, (String) parent.getMetadata().getElement());
for (Field field : clazz.getFields()) {
testAliasCandidate(targetType, candidatePaths, getField(field, childInstance));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | [
"private",
"void",
"findPathOnParentSubclasses",
"(",
"Path",
"<",
"?",
">",
"parent",
",",
"Class",
"<",
"?",
">",
"targetType",
",",
"List",
"<",
"Path",
"<",
"?",
">",
">",
"candidatePaths",
")",
"{",
"for",
"(",
"Class",
"child",
":",
"ReflectionUtil... | Try to find attribute on a subclass of parent (for instance in test domain when looking for <code>Key</code> on <code>User</code>)
@param parent parent join or "from" element
@param targetType type of joined attribute
@param candidatePaths container for found paths | [
"Try",
"to",
"find",
"attribute",
"on",
"a",
"subclass",
"of",
"parent",
"(",
"for",
"instance",
"in",
"test",
"domain",
"when",
"looking",
"for",
"<code",
">",
"Key<",
"/",
"code",
">",
"on",
"<code",
">",
"User<",
"/",
"code",
">",
")"
] | train | https://github.com/encircled/Joiner/blob/7b9117db05d8b89feeeb9ef7ce944256330d405c/joiner-core/src/main/java/cz/encircled/joiner/core/DefaultAliasResolver.java#L106-L118 |
omadahealth/TypefaceView | lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceTextView.java | TypefaceTextView.setCustomHtml | @BindingAdapter("bind:tv_html")
public static void setCustomHtml(TypefaceTextView textView, Boolean isHtml) {
"""
Data-binding method for custom attribute bind:tv_html to be set
@param textView The instance of the object to set value on
@param isHtml True if html text, false otherwise
"""
isHtml = isHtml != null ? isHtml : false;
textView.mHtmlEnabled = isHtml;
textView.setText(textView.getText());
} | java | @BindingAdapter("bind:tv_html")
public static void setCustomHtml(TypefaceTextView textView, Boolean isHtml) {
isHtml = isHtml != null ? isHtml : false;
textView.mHtmlEnabled = isHtml;
textView.setText(textView.getText());
} | [
"@",
"BindingAdapter",
"(",
"\"bind:tv_html\"",
")",
"public",
"static",
"void",
"setCustomHtml",
"(",
"TypefaceTextView",
"textView",
",",
"Boolean",
"isHtml",
")",
"{",
"isHtml",
"=",
"isHtml",
"!=",
"null",
"?",
"isHtml",
":",
"false",
";",
"textView",
".",... | Data-binding method for custom attribute bind:tv_html to be set
@param textView The instance of the object to set value on
@param isHtml True if html text, false otherwise | [
"Data",
"-",
"binding",
"method",
"for",
"custom",
"attribute",
"bind",
":",
"tv_html",
"to",
"be",
"set"
] | train | https://github.com/omadahealth/TypefaceView/blob/9a36a67b0fb26584c3e20a24f8f0bafad6a0badd/lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceTextView.java#L91-L96 |
RestComm/media-core | rtp/src/main/java/org/restcomm/media/core/rtp/crypto/SRTPCryptoContext.java | SRTPCryptoContext.deriveContext | public SRTPCryptoContext deriveContext(long ssrc, int roc, long deriveRate) {
"""
Derive a new SRTPCryptoContext for use with a new SSRC
This method returns a new SRTPCryptoContext initialized with the data of
this SRTPCryptoContext. Replacing the SSRC, Roll-over-Counter, and the
key derivation rate the application cab use this SRTPCryptoContext to
encrypt / decrypt a new stream (Synchronization source) inside one RTP
session.
Before the application can use this SRTPCryptoContext it must call the
deriveSrtpKeys method.
@param ssrc
The SSRC for this context
@param roc
The Roll-Over-Counter for this context
@param deriveRate
The key derivation rate for this context
@return a new SRTPCryptoContext with all relevant data set.
"""
return new SRTPCryptoContext(ssrc, roc, deriveRate, masterKey, masterSalt, policy);
} | java | public SRTPCryptoContext deriveContext(long ssrc, int roc, long deriveRate) {
return new SRTPCryptoContext(ssrc, roc, deriveRate, masterKey, masterSalt, policy);
} | [
"public",
"SRTPCryptoContext",
"deriveContext",
"(",
"long",
"ssrc",
",",
"int",
"roc",
",",
"long",
"deriveRate",
")",
"{",
"return",
"new",
"SRTPCryptoContext",
"(",
"ssrc",
",",
"roc",
",",
"deriveRate",
",",
"masterKey",
",",
"masterSalt",
",",
"policy",
... | Derive a new SRTPCryptoContext for use with a new SSRC
This method returns a new SRTPCryptoContext initialized with the data of
this SRTPCryptoContext. Replacing the SSRC, Roll-over-Counter, and the
key derivation rate the application cab use this SRTPCryptoContext to
encrypt / decrypt a new stream (Synchronization source) inside one RTP
session.
Before the application can use this SRTPCryptoContext it must call the
deriveSrtpKeys method.
@param ssrc
The SSRC for this context
@param roc
The Roll-Over-Counter for this context
@param deriveRate
The key derivation rate for this context
@return a new SRTPCryptoContext with all relevant data set. | [
"Derive",
"a",
"new",
"SRTPCryptoContext",
"for",
"use",
"with",
"a",
"new",
"SSRC"
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/crypto/SRTPCryptoContext.java#L731-L733 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryParameterValue.java | QueryParameterValue.of | public static <T> QueryParameterValue of(T value, Class<T> type) {
"""
Creates a {@code QueryParameterValue} object with the given value and type.
"""
return of(value, classToType(type));
} | java | public static <T> QueryParameterValue of(T value, Class<T> type) {
return of(value, classToType(type));
} | [
"public",
"static",
"<",
"T",
">",
"QueryParameterValue",
"of",
"(",
"T",
"value",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"of",
"(",
"value",
",",
"classToType",
"(",
"type",
")",
")",
";",
"}"
] | Creates a {@code QueryParameterValue} object with the given value and type. | [
"Creates",
"a",
"{"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryParameterValue.java#L164-L166 |
aol/cyclops | cyclops/src/main/java/cyclops/companion/Functions.java | Functions.concatInts | public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> concatInts( ReactiveSeq<Integer> b) {
"""
/*
Fluent integer concat operation using primitive types
e.g.
<pre>
{@code
import static cyclops.ReactiveSeq.concatInts;
ReactiveSeq.ofInts(1,2,3)
.to(concatInts(ReactiveSeq.range(5,10)));
//[1,2,3,5,6,7,8,9]
}
</pre>
"""
return a->ReactiveSeq.fromSpliterator(IntStream.concat(a.mapToInt(i->i),b.mapToInt(i->i)).spliterator());
} | java | public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> concatInts( ReactiveSeq<Integer> b){
return a->ReactiveSeq.fromSpliterator(IntStream.concat(a.mapToInt(i->i),b.mapToInt(i->i)).spliterator());
} | [
"public",
"static",
"Function",
"<",
"?",
"super",
"ReactiveSeq",
"<",
"Integer",
">",
",",
"?",
"extends",
"ReactiveSeq",
"<",
"Integer",
">",
">",
"concatInts",
"(",
"ReactiveSeq",
"<",
"Integer",
">",
"b",
")",
"{",
"return",
"a",
"->",
"ReactiveSeq",
... | /*
Fluent integer concat operation using primitive types
e.g.
<pre>
{@code
import static cyclops.ReactiveSeq.concatInts;
ReactiveSeq.ofInts(1,2,3)
.to(concatInts(ReactiveSeq.range(5,10)));
//[1,2,3,5,6,7,8,9]
}
</pre> | [
"/",
"*",
"Fluent",
"integer",
"concat",
"operation",
"using",
"primitive",
"types",
"e",
".",
"g",
".",
"<pre",
">",
"{",
"@code",
"import",
"static",
"cyclops",
".",
"ReactiveSeq",
".",
"concatInts",
";"
] | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Functions.java#L316-L318 |
BioPAX/Paxtools | paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java | QueryExecuter.prepareSingleNodeSetFromSets | public static Set<Node> prepareSingleNodeSetFromSets(Set<Set<BioPAXElement>> sets, Graph graph) {
"""
Gets the related wrappers of the given elements in the sets.
@param sets Sets of elements to get the related wrappers
@param graph Owner graph
@return Related wrappers in a set
"""
Set<BioPAXElement> elements = new HashSet<BioPAXElement>();
for (Set<BioPAXElement> set : sets)
{
elements.addAll(set);
}
return prepareSingleNodeSet(elements, graph);
} | java | public static Set<Node> prepareSingleNodeSetFromSets(Set<Set<BioPAXElement>> sets, Graph graph)
{
Set<BioPAXElement> elements = new HashSet<BioPAXElement>();
for (Set<BioPAXElement> set : sets)
{
elements.addAll(set);
}
return prepareSingleNodeSet(elements, graph);
} | [
"public",
"static",
"Set",
"<",
"Node",
">",
"prepareSingleNodeSetFromSets",
"(",
"Set",
"<",
"Set",
"<",
"BioPAXElement",
">",
">",
"sets",
",",
"Graph",
"graph",
")",
"{",
"Set",
"<",
"BioPAXElement",
">",
"elements",
"=",
"new",
"HashSet",
"<",
"BioPAXE... | Gets the related wrappers of the given elements in the sets.
@param sets Sets of elements to get the related wrappers
@param graph Owner graph
@return Related wrappers in a set | [
"Gets",
"the",
"related",
"wrappers",
"of",
"the",
"given",
"elements",
"in",
"the",
"sets",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java#L525-L533 |
brettwooldridge/SansOrm | src/main/java/com/zaxxer/sansorm/SqlClosureElf.java | SqlClosureElf.objectFromClause | public static <T> T objectFromClause(Class<T> type, String clause, Object... args) {
"""
Gets an object using a from clause.
@param type The type of the desired object.
@param clause The WHERE clause.
@param args The arguments for the WHERE clause.
@param <T> The type of the object.
@return The object or {@code null}
"""
return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args));
} | java | public static <T> T objectFromClause(Class<T> type, String clause, Object... args)
{
return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args));
} | [
"public",
"static",
"<",
"T",
">",
"T",
"objectFromClause",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"clause",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"SqlClosure",
".",
"sqlExecute",
"(",
"c",
"->",
"OrmElf",
".",
"objectFromClause"... | Gets an object using a from clause.
@param type The type of the desired object.
@param clause The WHERE clause.
@param args The arguments for the WHERE clause.
@param <T> The type of the object.
@return The object or {@code null} | [
"Gets",
"an",
"object",
"using",
"a",
"from",
"clause",
"."
] | train | https://github.com/brettwooldridge/SansOrm/blob/ab22721db79c5f20c0e8483f09eda2844d596557/src/main/java/com/zaxxer/sansorm/SqlClosureElf.java#L56-L59 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/query/filter/DimFilterUtils.java | DimFilterUtils.filterShards | public static <T> Set<T> filterShards(DimFilter dimFilter, Iterable<T> input, Function<T, ShardSpec> converter) {
"""
Filter the given iterable of objects by removing any object whose ShardSpec, obtained from the converter function,
does not fit in the RangeSet of the dimFilter {@link DimFilter#getDimensionRangeSet(String)}. The returned set
contains the filtered objects in the same order as they appear in input.
If you plan to call this multiple times with the same dimFilter, consider using
{@link #filterShards(DimFilter, Iterable, Function, Map)} instead with a cached map
@param dimFilter The filter to use
@param input The iterable of objects to be filtered
@param converter The function to convert T to ShardSpec that can be filtered by
@param <T> This can be any type, as long as transform function is provided to convert this to ShardSpec
@return The set of filtered object, in the same order as input
"""
return filterShards(dimFilter, input, converter, new HashMap<String, Optional<RangeSet<String>>>());
} | java | public static <T> Set<T> filterShards(DimFilter dimFilter, Iterable<T> input, Function<T, ShardSpec> converter)
{
return filterShards(dimFilter, input, converter, new HashMap<String, Optional<RangeSet<String>>>());
} | [
"public",
"static",
"<",
"T",
">",
"Set",
"<",
"T",
">",
"filterShards",
"(",
"DimFilter",
"dimFilter",
",",
"Iterable",
"<",
"T",
">",
"input",
",",
"Function",
"<",
"T",
",",
"ShardSpec",
">",
"converter",
")",
"{",
"return",
"filterShards",
"(",
"di... | Filter the given iterable of objects by removing any object whose ShardSpec, obtained from the converter function,
does not fit in the RangeSet of the dimFilter {@link DimFilter#getDimensionRangeSet(String)}. The returned set
contains the filtered objects in the same order as they appear in input.
If you plan to call this multiple times with the same dimFilter, consider using
{@link #filterShards(DimFilter, Iterable, Function, Map)} instead with a cached map
@param dimFilter The filter to use
@param input The iterable of objects to be filtered
@param converter The function to convert T to ShardSpec that can be filtered by
@param <T> This can be any type, as long as transform function is provided to convert this to ShardSpec
@return The set of filtered object, in the same order as input | [
"Filter",
"the",
"given",
"iterable",
"of",
"objects",
"by",
"removing",
"any",
"object",
"whose",
"ShardSpec",
"obtained",
"from",
"the",
"converter",
"function",
"does",
"not",
"fit",
"in",
"the",
"RangeSet",
"of",
"the",
"dimFilter",
"{",
"@link",
"DimFilte... | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/filter/DimFilterUtils.java#L95-L98 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/Validate.java | Validate.validState | public static void validState(final boolean expression, final String message, final Object... values) {
"""
<p>Validate that the stateful condition is {@code true}; otherwise
throwing an exception with the specified message. This method is useful when
validating according to an arbitrary boolean expression, such as validating a
primitive number or using your own custom validation expression.</p>
<pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
@param expression the boolean expression to check
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@throws IllegalStateException if expression is {@code false}
@see #validState(boolean)
@since 3.0
"""
if (!expression) {
throw new IllegalStateException(StringUtils.simpleFormat(message, values));
}
} | java | public static void validState(final boolean expression, final String message, final Object... values) {
if (!expression) {
throw new IllegalStateException(StringUtils.simpleFormat(message, values));
}
} | [
"public",
"static",
"void",
"validState",
"(",
"final",
"boolean",
"expression",
",",
"final",
"String",
"message",
",",
"final",
"Object",
"...",
"values",
")",
"{",
"if",
"(",
"!",
"expression",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"Stri... | <p>Validate that the stateful condition is {@code true}; otherwise
throwing an exception with the specified message. This method is useful when
validating according to an arbitrary boolean expression, such as validating a
primitive number or using your own custom validation expression.</p>
<pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
@param expression the boolean expression to check
@param message the {@link String#format(String, Object...)} exception message if invalid, not null
@param values the optional values for the formatted exception message, null array not recommended
@throws IllegalStateException if expression is {@code false}
@see #validState(boolean)
@since 3.0 | [
"<p",
">",
"Validate",
"that",
"the",
"stateful",
"condition",
"is",
"{",
"@code",
"true",
"}",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
"the",
"specified",
"message",
".",
"This",
"method",
"is",
"useful",
"when",
"validating",
"according",
... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L833-L837 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.unescapeUriPath | public static void unescapeUriPath(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
"""
<p>
Perform am URI path <strong>unescape</strong> operation
on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use <tt>UTF-8</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the escape operation should start.
@param len the number of characters in <tt>text</tt> that should be escaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
"""
unescapeUriPath(text, offset, len, writer, DEFAULT_ENCODING);
} | java | public static void unescapeUriPath(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
unescapeUriPath(text, offset, len, writer, DEFAULT_ENCODING);
} | [
"public",
"static",
"void",
"unescapeUriPath",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"unescapeUriPath",
"(",
"text",
",",
"off... | <p>
Perform am URI path <strong>unescape</strong> operation
on a <tt>char[]</tt> input using <tt>UTF-8</tt> as encoding.
</p>
<p>
This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input,
even for those characters that do not need to be percent-encoded in this context (unreserved characters
can be percent-encoded even if/when this is not required, though it is not generally considered a
good practice).
</p>
<p>
This method will use <tt>UTF-8</tt> in order to determine the characters specified in the
percent-encoded byte sequences.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the escape operation should start.
@param len the number of characters in <tt>text</tt> that should be escaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"am",
"URI",
"path",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
"using",
"<tt",
">",
"UTF",
"-",
"8<",
"/",
"tt",
">",
"as",
"encoding",
"... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L2418-L2421 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java | TargetValidator.parseDirectory | public static List<ModelError> parseDirectory( File directory, Component c ) {
"""
Parses a directory with one or several properties files.
@param directory an existing directory
@return a non-null list of errors
"""
// Validate all the properties
List<ModelError> result = new ArrayList<> ();
Set<String> targetIds = new HashSet<> ();
for( File f : Utils.listDirectFiles( directory, Constants.FILE_EXT_PROPERTIES )) {
TargetValidator tv = new TargetValidator( f, c );
tv.validate();
result.addAll( tv.getErrors());
String id = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID );
if( targetIds.contains( id ))
result.add( new ModelError( ErrorCode.REC_TARGET_CONFLICTING_ID, tv.modelObject, name( id )));
targetIds.add( id );
}
// There should be properties files
if( targetIds.isEmpty())
result.add( new ModelError( ErrorCode.REC_TARGET_NO_PROPERTIES, null, directory( directory )));
return result;
} | java | public static List<ModelError> parseDirectory( File directory, Component c ) {
// Validate all the properties
List<ModelError> result = new ArrayList<> ();
Set<String> targetIds = new HashSet<> ();
for( File f : Utils.listDirectFiles( directory, Constants.FILE_EXT_PROPERTIES )) {
TargetValidator tv = new TargetValidator( f, c );
tv.validate();
result.addAll( tv.getErrors());
String id = tv.getProperties().getProperty( Constants.TARGET_PROPERTY_ID );
if( targetIds.contains( id ))
result.add( new ModelError( ErrorCode.REC_TARGET_CONFLICTING_ID, tv.modelObject, name( id )));
targetIds.add( id );
}
// There should be properties files
if( targetIds.isEmpty())
result.add( new ModelError( ErrorCode.REC_TARGET_NO_PROPERTIES, null, directory( directory )));
return result;
} | [
"public",
"static",
"List",
"<",
"ModelError",
">",
"parseDirectory",
"(",
"File",
"directory",
",",
"Component",
"c",
")",
"{",
"// Validate all the properties",
"List",
"<",
"ModelError",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Set",
... | Parses a directory with one or several properties files.
@param directory an existing directory
@return a non-null list of errors | [
"Parses",
"a",
"directory",
"with",
"one",
"or",
"several",
"properties",
"files",
"."
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/model/TargetValidator.java#L167-L190 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java | ComputationGraph.evaluateRegression | public <T extends RegressionEvaluation> T evaluateRegression(DataSetIterator iterator, List<String> columnNames) {
"""
Evaluate the (single output layer only) network for regression performance
@param iterator Data to evaluate on
@param columnNames Column names for the regression evaluation. May be null.
@return Regression evaluation
"""
return (T)doEvaluation(iterator, new org.deeplearning4j.eval.RegressionEvaluation(columnNames))[0];
} | java | public <T extends RegressionEvaluation> T evaluateRegression(DataSetIterator iterator, List<String> columnNames) {
return (T)doEvaluation(iterator, new org.deeplearning4j.eval.RegressionEvaluation(columnNames))[0];
} | [
"public",
"<",
"T",
"extends",
"RegressionEvaluation",
">",
"T",
"evaluateRegression",
"(",
"DataSetIterator",
"iterator",
",",
"List",
"<",
"String",
">",
"columnNames",
")",
"{",
"return",
"(",
"T",
")",
"doEvaluation",
"(",
"iterator",
",",
"new",
"org",
... | Evaluate the (single output layer only) network for regression performance
@param iterator Data to evaluate on
@param columnNames Column names for the regression evaluation. May be null.
@return Regression evaluation | [
"Evaluate",
"the",
"(",
"single",
"output",
"layer",
"only",
")",
"network",
"for",
"regression",
"performance"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java#L3903-L3905 |
jMetal/jMetal | jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/AbstractMOEAD.java | AbstractMOEAD.updateNeighborhood | @SuppressWarnings("unchecked")
protected void updateNeighborhood(S individual, int subProblemId, NeighborType neighborType) throws JMetalException {
"""
Update neighborhood method
@param individual
@param subProblemId
@param neighborType
@throws JMetalException
"""
int size;
int time;
time = 0;
if (neighborType == NeighborType.NEIGHBOR) {
size = neighborhood[subProblemId].length;
} else {
size = population.size();
}
int[] perm = new int[size];
MOEADUtils.randomPermutation(perm, size);
for (int i = 0; i < size; i++) {
int k;
if (neighborType == NeighborType.NEIGHBOR) {
k = neighborhood[subProblemId][perm[i]];
} else {
k = perm[i];
}
double f1, f2;
f1 = fitnessFunction(population.get(k), lambda[k]);
f2 = fitnessFunction(individual, lambda[k]);
if (f2 < f1) {
population.set(k, (S)individual.copy());
time++;
}
if (time >= maximumNumberOfReplacedSolutions) {
return;
}
}
} | java | @SuppressWarnings("unchecked")
protected void updateNeighborhood(S individual, int subProblemId, NeighborType neighborType) throws JMetalException {
int size;
int time;
time = 0;
if (neighborType == NeighborType.NEIGHBOR) {
size = neighborhood[subProblemId].length;
} else {
size = population.size();
}
int[] perm = new int[size];
MOEADUtils.randomPermutation(perm, size);
for (int i = 0; i < size; i++) {
int k;
if (neighborType == NeighborType.NEIGHBOR) {
k = neighborhood[subProblemId][perm[i]];
} else {
k = perm[i];
}
double f1, f2;
f1 = fitnessFunction(population.get(k), lambda[k]);
f2 = fitnessFunction(individual, lambda[k]);
if (f2 < f1) {
population.set(k, (S)individual.copy());
time++;
}
if (time >= maximumNumberOfReplacedSolutions) {
return;
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"void",
"updateNeighborhood",
"(",
"S",
"individual",
",",
"int",
"subProblemId",
",",
"NeighborType",
"neighborType",
")",
"throws",
"JMetalException",
"{",
"int",
"size",
";",
"int",
"time",
";",
... | Update neighborhood method
@param individual
@param subProblemId
@param neighborType
@throws JMetalException | [
"Update",
"neighborhood",
"method"
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/AbstractMOEAD.java#L230-L267 |
derari/cthul | objects/src/main/java/org/cthul/objects/Boxing.java | Boxing.boxAllAs | public static <T> T boxAllAs(Object src, Class<T> type) {
"""
Transforms any array into an array of boxed values.
@param <T>
@param type target type
@param src source array
@return array
"""
return (T) boxAll(type, src, 0, -1);
} | java | public static <T> T boxAllAs(Object src, Class<T> type) {
return (T) boxAll(type, src, 0, -1);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"boxAllAs",
"(",
"Object",
"src",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"(",
"T",
")",
"boxAll",
"(",
"type",
",",
"src",
",",
"0",
",",
"-",
"1",
")",
";",
"}"
] | Transforms any array into an array of boxed values.
@param <T>
@param type target type
@param src source array
@return array | [
"Transforms",
"any",
"array",
"into",
"an",
"array",
"of",
"boxed",
"values",
"."
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/Boxing.java#L491-L493 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/io/sstable/IndexHelper.java | IndexHelper.indexFor | public static int indexFor(Composite name, List<IndexInfo> indexList, CType comparator, boolean reversed, int lastIndex) {
"""
The index of the IndexInfo in which a scan starting with @name should begin.
@param name
name of the index
@param indexList
list of the indexInfo objects
@param comparator
comparator type
@param reversed
is name reversed
@return int index
"""
if (name.isEmpty())
return lastIndex >= 0 ? lastIndex : reversed ? indexList.size() - 1 : 0;
if (lastIndex >= indexList.size())
return -1;
IndexInfo target = new IndexInfo(name, name, 0, 0);
/*
Take the example from the unit test, and say your index looks like this:
[0..5][10..15][20..25]
and you look for the slice [13..17].
When doing forward slice, we we doing a binary search comparing 13 (the start of the query)
to the lastName part of the index slot. You'll end up with the "first" slot, going from left to right,
that may contain the start.
When doing a reverse slice, we do the same thing, only using as a start column the end of the query,
i.e. 17 in this example, compared to the firstName part of the index slots. bsearch will give us the
first slot where firstName > start ([20..25] here), so we subtract an extra one to get the slot just before.
*/
int startIdx = 0;
List<IndexInfo> toSearch = indexList;
if (lastIndex >= 0)
{
if (reversed)
{
toSearch = indexList.subList(0, lastIndex + 1);
}
else
{
startIdx = lastIndex;
toSearch = indexList.subList(lastIndex, indexList.size());
}
}
int index = Collections.binarySearch(toSearch, target, getComparator(comparator, reversed));
return startIdx + (index < 0 ? -index - (reversed ? 2 : 1) : index);
} | java | public static int indexFor(Composite name, List<IndexInfo> indexList, CType comparator, boolean reversed, int lastIndex)
{
if (name.isEmpty())
return lastIndex >= 0 ? lastIndex : reversed ? indexList.size() - 1 : 0;
if (lastIndex >= indexList.size())
return -1;
IndexInfo target = new IndexInfo(name, name, 0, 0);
/*
Take the example from the unit test, and say your index looks like this:
[0..5][10..15][20..25]
and you look for the slice [13..17].
When doing forward slice, we we doing a binary search comparing 13 (the start of the query)
to the lastName part of the index slot. You'll end up with the "first" slot, going from left to right,
that may contain the start.
When doing a reverse slice, we do the same thing, only using as a start column the end of the query,
i.e. 17 in this example, compared to the firstName part of the index slots. bsearch will give us the
first slot where firstName > start ([20..25] here), so we subtract an extra one to get the slot just before.
*/
int startIdx = 0;
List<IndexInfo> toSearch = indexList;
if (lastIndex >= 0)
{
if (reversed)
{
toSearch = indexList.subList(0, lastIndex + 1);
}
else
{
startIdx = lastIndex;
toSearch = indexList.subList(lastIndex, indexList.size());
}
}
int index = Collections.binarySearch(toSearch, target, getComparator(comparator, reversed));
return startIdx + (index < 0 ? -index - (reversed ? 2 : 1) : index);
} | [
"public",
"static",
"int",
"indexFor",
"(",
"Composite",
"name",
",",
"List",
"<",
"IndexInfo",
">",
"indexList",
",",
"CType",
"comparator",
",",
"boolean",
"reversed",
",",
"int",
"lastIndex",
")",
"{",
"if",
"(",
"name",
".",
"isEmpty",
"(",
")",
")",... | The index of the IndexInfo in which a scan starting with @name should begin.
@param name
name of the index
@param indexList
list of the indexInfo objects
@param comparator
comparator type
@param reversed
is name reversed
@return int index | [
"The",
"index",
"of",
"the",
"IndexInfo",
"in",
"which",
"a",
"scan",
"starting",
"with",
"@name",
"should",
"begin",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexHelper.java#L112-L150 |
icode/ameba | src/main/java/ameba/websocket/internal/LocalizationMessages.java | LocalizationMessages.ENDPOINT_UNKNOWN_PARAMS | public static String ENDPOINT_UNKNOWN_PARAMS(Object arg0, Object arg1, Object arg2) {
"""
Unknown parameter(s) for {0}.{1} method annotated with @OnError annotation: {2}. This method will be ignored.
"""
return localizer.localize(localizableENDPOINT_UNKNOWN_PARAMS(arg0, arg1, arg2));
} | java | public static String ENDPOINT_UNKNOWN_PARAMS(Object arg0, Object arg1, Object arg2) {
return localizer.localize(localizableENDPOINT_UNKNOWN_PARAMS(arg0, arg1, arg2));
} | [
"public",
"static",
"String",
"ENDPOINT_UNKNOWN_PARAMS",
"(",
"Object",
"arg0",
",",
"Object",
"arg1",
",",
"Object",
"arg2",
")",
"{",
"return",
"localizer",
".",
"localize",
"(",
"localizableENDPOINT_UNKNOWN_PARAMS",
"(",
"arg0",
",",
"arg1",
",",
"arg2",
")",... | Unknown parameter(s) for {0}.{1} method annotated with @OnError annotation: {2}. This method will be ignored. | [
"Unknown",
"parameter",
"(",
"s",
")",
"for",
"{",
"0",
"}",
".",
"{",
"1",
"}",
"method",
"annotated",
"with"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/websocket/internal/LocalizationMessages.java#L66-L68 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java | GISCoordinates.L1_L4 | @Pure
public static Point2d L1_L4(double x, double y) {
"""
This function convert France Lambert I coordinate to
France Lambert IV coordinate.
@param x is the coordinate in France Lambert I
@param y is the coordinate in France Lambert I
@return the France Lambert IV coordinate.
"""
final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y,
LAMBERT_1_N,
LAMBERT_1_C,
LAMBERT_1_XS,
LAMBERT_1_YS);
return NTFLambdaPhi_NTFLambert(
ntfLambdaPhi.getX(), ntfLambdaPhi.getY(),
LAMBERT_4_N,
LAMBERT_4_C,
LAMBERT_4_XS,
LAMBERT_4_YS);
} | java | @Pure
public static Point2d L1_L4(double x, double y) {
final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y,
LAMBERT_1_N,
LAMBERT_1_C,
LAMBERT_1_XS,
LAMBERT_1_YS);
return NTFLambdaPhi_NTFLambert(
ntfLambdaPhi.getX(), ntfLambdaPhi.getY(),
LAMBERT_4_N,
LAMBERT_4_C,
LAMBERT_4_XS,
LAMBERT_4_YS);
} | [
"@",
"Pure",
"public",
"static",
"Point2d",
"L1_L4",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"final",
"Point2d",
"ntfLambdaPhi",
"=",
"NTFLambert_NTFLambdaPhi",
"(",
"x",
",",
"y",
",",
"LAMBERT_1_N",
",",
"LAMBERT_1_C",
",",
"LAMBERT_1_XS",
",",
... | This function convert France Lambert I coordinate to
France Lambert IV coordinate.
@param x is the coordinate in France Lambert I
@param y is the coordinate in France Lambert I
@return the France Lambert IV coordinate. | [
"This",
"function",
"convert",
"France",
"Lambert",
"I",
"coordinate",
"to",
"France",
"Lambert",
"IV",
"coordinate",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java#L374-L387 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/config/AliasedDiscoveryConfig.java | AliasedDiscoveryConfig.setProperty | public T setProperty(String name, String value) {
"""
Sets the property understood by the given SPI Discovery Strategy.
<p>
Note that it interprets and stores as fields the following properties: "enabled", "use-public-ip".
@param name property name
@param value property value
@return the updated discovery config
"""
if (USE_PUBLIC_IP_PROPERTY.equals(name)) {
usePublicIp = Boolean.parseBoolean(value);
} else if (ENABLED_PROPERTY.equals(name)) {
enabled = Boolean.parseBoolean(value);
} else {
properties.put(name, value);
}
return (T) this;
} | java | public T setProperty(String name, String value) {
if (USE_PUBLIC_IP_PROPERTY.equals(name)) {
usePublicIp = Boolean.parseBoolean(value);
} else if (ENABLED_PROPERTY.equals(name)) {
enabled = Boolean.parseBoolean(value);
} else {
properties.put(name, value);
}
return (T) this;
} | [
"public",
"T",
"setProperty",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"USE_PUBLIC_IP_PROPERTY",
".",
"equals",
"(",
"name",
")",
")",
"{",
"usePublicIp",
"=",
"Boolean",
".",
"parseBoolean",
"(",
"value",
")",
";",
"}",
"else"... | Sets the property understood by the given SPI Discovery Strategy.
<p>
Note that it interprets and stores as fields the following properties: "enabled", "use-public-ip".
@param name property name
@param value property value
@return the updated discovery config | [
"Sets",
"the",
"property",
"understood",
"by",
"the",
"given",
"SPI",
"Discovery",
"Strategy",
".",
"<p",
">",
"Note",
"that",
"it",
"interprets",
"and",
"stores",
"as",
"fields",
"the",
"following",
"properties",
":",
"enabled",
"use",
"-",
"public",
"-",
... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/AliasedDiscoveryConfig.java#L85-L94 |
javalite/activeweb | activeweb/src/main/java/org/javalite/activeweb/freemarker/AbstractFreeMarkerConfig.java | AbstractFreeMarkerConfig.registerTag | public void registerTag(String name, FreeMarkerTag tag) {
"""
Registers an application-specific tag.
@param name name of tag.
@param tag tag instance.
"""
configuration.setSharedVariable(name, tag);
userTags.add(tag);
} | java | public void registerTag(String name, FreeMarkerTag tag){
configuration.setSharedVariable(name, tag);
userTags.add(tag);
} | [
"public",
"void",
"registerTag",
"(",
"String",
"name",
",",
"FreeMarkerTag",
"tag",
")",
"{",
"configuration",
".",
"setSharedVariable",
"(",
"name",
",",
"tag",
")",
";",
"userTags",
".",
"add",
"(",
"tag",
")",
";",
"}"
] | Registers an application-specific tag.
@param name name of tag.
@param tag tag instance. | [
"Registers",
"an",
"application",
"-",
"specific",
"tag",
"."
] | train | https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/activeweb/src/main/java/org/javalite/activeweb/freemarker/AbstractFreeMarkerConfig.java#L48-L51 |
apache/groovy | subprojects/groovy-swing/src/main/java/groovy/inspect/swingui/TableSorter.java | TableSorter.getValueAt | public Object getValueAt(int aRow, int aColumn) {
"""
Pass all requests to these rows through the mapping array: "indexes".
"""
checkModel();
return model.getValueAt(indexes[aRow], aColumn);
} | java | public Object getValueAt(int aRow, int aColumn) {
checkModel();
return model.getValueAt(indexes[aRow], aColumn);
} | [
"public",
"Object",
"getValueAt",
"(",
"int",
"aRow",
",",
"int",
"aColumn",
")",
"{",
"checkModel",
"(",
")",
";",
"return",
"model",
".",
"getValueAt",
"(",
"indexes",
"[",
"aRow",
"]",
",",
"aColumn",
")",
";",
"}"
] | Pass all requests to these rows through the mapping array: "indexes". | [
"Pass",
"all",
"requests",
"to",
"these",
"rows",
"through",
"the",
"mapping",
"array",
":",
"indexes",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-swing/src/main/java/groovy/inspect/swingui/TableSorter.java#L279-L282 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Primitives.java | Primitives.unbox | public static boolean[] unbox(final Boolean[] a, final boolean valueForNull) {
"""
<p>
Converts an array of object Booleans to primitives handling {@code null}.
</p>
<p>
This method returns {@code null} for a {@code null} input array.
</p>
@param a
a {@code Boolean} array, may be {@code null}
@param valueForNull
the value to insert if {@code null} found
@return a {@code boolean} array, {@code null} if null array input
"""
if (a == null) {
return null;
}
return unbox(a, 0, a.length, valueForNull);
} | java | public static boolean[] unbox(final Boolean[] a, final boolean valueForNull) {
if (a == null) {
return null;
}
return unbox(a, 0, a.length, valueForNull);
} | [
"public",
"static",
"boolean",
"[",
"]",
"unbox",
"(",
"final",
"Boolean",
"[",
"]",
"a",
",",
"final",
"boolean",
"valueForNull",
")",
"{",
"if",
"(",
"a",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"unbox",
"(",
"a",
",",
"0",
... | <p>
Converts an array of object Booleans to primitives handling {@code null}.
</p>
<p>
This method returns {@code null} for a {@code null} input array.
</p>
@param a
a {@code Boolean} array, may be {@code null}
@param valueForNull
the value to insert if {@code null} found
@return a {@code boolean} array, {@code null} if null array input | [
"<p",
">",
"Converts",
"an",
"array",
"of",
"object",
"Booleans",
"to",
"primitives",
"handling",
"{",
"@code",
"null",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Primitives.java#L782-L788 |
osglworks/java-tool | src/main/java/org/osgl/util/E.java | E.invalidArgIf | public static void invalidArgIf(boolean tester, String msg, Object... args) {
"""
Throws out an {@link InvalidArgException} with error message specified
when `tester` is `true`.
@param tester
when `true` then throws out the exception.
@param msg
the error message format pattern.
@param args
the error message format arguments.
"""
if (tester) {
throw invalidArg(msg, args);
}
} | java | public static void invalidArgIf(boolean tester, String msg, Object... args) {
if (tester) {
throw invalidArg(msg, args);
}
} | [
"public",
"static",
"void",
"invalidArgIf",
"(",
"boolean",
"tester",
",",
"String",
"msg",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"tester",
")",
"{",
"throw",
"invalidArg",
"(",
"msg",
",",
"args",
")",
";",
"}",
"}"
] | Throws out an {@link InvalidArgException} with error message specified
when `tester` is `true`.
@param tester
when `true` then throws out the exception.
@param msg
the error message format pattern.
@param args
the error message format arguments. | [
"Throws",
"out",
"an",
"{",
"@link",
"InvalidArgException",
"}",
"with",
"error",
"message",
"specified",
"when",
"tester",
"is",
"true",
"."
] | train | https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L403-L407 |
op4j/op4j | src/main/java/org/op4j/Op.java | Op.onArray | public static <T> Level0ArrayOperator<Short[],Short> onArray(final Short[] target) {
"""
<p>
Creates an <i>operation expression</i> on the specified target object.
</p>
@param target the target object on which the expression will execute
@return an operator, ready for chaining
"""
return onArrayOf(Types.SHORT, target);
} | java | public static <T> Level0ArrayOperator<Short[],Short> onArray(final Short[] target) {
return onArrayOf(Types.SHORT, target);
} | [
"public",
"static",
"<",
"T",
">",
"Level0ArrayOperator",
"<",
"Short",
"[",
"]",
",",
"Short",
">",
"onArray",
"(",
"final",
"Short",
"[",
"]",
"target",
")",
"{",
"return",
"onArrayOf",
"(",
"Types",
".",
"SHORT",
",",
"target",
")",
";",
"}"
] | <p>
Creates an <i>operation expression</i> on the specified target object.
</p>
@param target the target object on which the expression will execute
@return an operator, ready for chaining | [
"<p",
">",
"Creates",
"an",
"<i",
">",
"operation",
"expression<",
"/",
"i",
">",
"on",
"the",
"specified",
"target",
"object",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L676-L678 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java | MariaDbDatabaseMetaData.getPrimaryKeys | public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
"""
Retrieves a description of the given table's primary key columns. They are ordered by
COLUMN_NAME.
<P>Each primary key column description has the following columns:</p>
<OL>
<li><B>TABLE_CAT</B> String {@code =>} table catalog </li>
<li><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)</li>
<li><B>TABLE_NAME</B> String {@code =>} table name </li>
<li><B>COLUMN_NAME</B> String {@code =>} column name </li>
<li><B>KEY_SEQ</B> short {@code =>} sequence number within primary key( a value of 1
represents the first column of the primary key, a value of 2 would represent the second column
within the primary key).</li>
<li><B>PK_NAME</B> String {@code =>} primary key name </li>
</OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; ""
retrieves those without a catalog;
<code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; ""
retrieves those without a schema; <code>null</code> means that the schema name
should not be used to narrow the search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws SQLException if a database access error occurs
"""
//MySQL 8 now use 'PRI' in place of 'pri'
String sql =
"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.TABLE_NAME, A.COLUMN_NAME, B.SEQ_IN_INDEX KEY_SEQ, B.INDEX_NAME PK_NAME "
+ " FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.STATISTICS B"
+ " WHERE A.COLUMN_KEY in ('PRI','pri') AND B.INDEX_NAME='PRIMARY' "
+ " AND "
+ catalogCond("A.TABLE_SCHEMA", catalog)
+ " AND "
+ catalogCond("B.TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("A.TABLE_NAME", table)
+ " AND "
+ patternCond("B.TABLE_NAME", table)
+ " AND A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME "
+ " ORDER BY A.COLUMN_NAME";
return executeQuery(sql);
} | java | public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
//MySQL 8 now use 'PRI' in place of 'pri'
String sql =
"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.TABLE_NAME, A.COLUMN_NAME, B.SEQ_IN_INDEX KEY_SEQ, B.INDEX_NAME PK_NAME "
+ " FROM INFORMATION_SCHEMA.COLUMNS A, INFORMATION_SCHEMA.STATISTICS B"
+ " WHERE A.COLUMN_KEY in ('PRI','pri') AND B.INDEX_NAME='PRIMARY' "
+ " AND "
+ catalogCond("A.TABLE_SCHEMA", catalog)
+ " AND "
+ catalogCond("B.TABLE_SCHEMA", catalog)
+ " AND "
+ patternCond("A.TABLE_NAME", table)
+ " AND "
+ patternCond("B.TABLE_NAME", table)
+ " AND A.TABLE_SCHEMA = B.TABLE_SCHEMA AND A.TABLE_NAME = B.TABLE_NAME AND A.COLUMN_NAME = B.COLUMN_NAME "
+ " ORDER BY A.COLUMN_NAME";
return executeQuery(sql);
} | [
"public",
"ResultSet",
"getPrimaryKeys",
"(",
"String",
"catalog",
",",
"String",
"schema",
",",
"String",
"table",
")",
"throws",
"SQLException",
"{",
"//MySQL 8 now use 'PRI' in place of 'pri'",
"String",
"sql",
"=",
"\"SELECT A.TABLE_SCHEMA TABLE_CAT, NULL TABLE_SCHEM, A.T... | Retrieves a description of the given table's primary key columns. They are ordered by
COLUMN_NAME.
<P>Each primary key column description has the following columns:</p>
<OL>
<li><B>TABLE_CAT</B> String {@code =>} table catalog </li>
<li><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)</li>
<li><B>TABLE_NAME</B> String {@code =>} table name </li>
<li><B>COLUMN_NAME</B> String {@code =>} column name </li>
<li><B>KEY_SEQ</B> short {@code =>} sequence number within primary key( a value of 1
represents the first column of the primary key, a value of 2 would represent the second column
within the primary key).</li>
<li><B>PK_NAME</B> String {@code =>} primary key name </li>
</OL>
@param catalog a catalog name; must match the catalog name as it is stored in the database; ""
retrieves those without a catalog;
<code>null</code> means that the catalog name should not be used to narrow the
search
@param schema a schema name; must match the schema name as it is stored in the database; ""
retrieves those without a schema; <code>null</code> means that the schema name
should not be used to narrow the search
@param table a table name; must match the table name as it is stored in the database
@return <code>ResultSet</code> - each row is a primary key column description
@throws SQLException if a database access error occurs | [
"Retrieves",
"a",
"description",
"of",
"the",
"given",
"table",
"s",
"primary",
"key",
"columns",
".",
"They",
"are",
"ordered",
"by",
"COLUMN_NAME",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L555-L574 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntClassMention.java | OntClassMention.setSemanticTypes | public void setSemanticTypes(int i, String v) {
"""
indexed setter for semanticTypes - sets an indexed value - Names or IDs of associated semantic types.
@generated
@param i index in the array to set
@param v value to set into the array
"""
if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null)
jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i);
jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i, v);} | java | public void setSemanticTypes(int i, String v) {
if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null)
jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i);
jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i, v);} | [
"public",
"void",
"setSemanticTypes",
"(",
"int",
"i",
",",
"String",
"v",
")",
"{",
"if",
"(",
"OntClassMention_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"OntClassMention_Type",
")",
"jcasType",
")",
".",
"casFeat_semanticTypes",
"==",
"null",
")",
"jcasType",... | indexed setter for semanticTypes - sets an indexed value - Names or IDs of associated semantic types.
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"semanticTypes",
"-",
"sets",
"an",
"indexed",
"value",
"-",
"Names",
"or",
"IDs",
"of",
"associated",
"semantic",
"types",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntClassMention.java#L183-L187 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java | ApiOvhEmailexchange.organizationName_service_exchangeService_domain_POST | public OvhTask organizationName_service_exchangeService_domain_POST(String organizationName, String exchangeService, Boolean configureAutodiscover, Boolean configureMx, Boolean main, String mxRelay, String name, String organization2010, OvhDomainTypeEnum type) throws IOException {
"""
Create new domain in exchange services
REST: POST /email/exchange/{organizationName}/service/{exchangeService}/domain
@param configureMx [required] If you host domain in OVH we can configure mx record automatically
@param type [required] Type of domain that You want to install
@param name [required] Domain to install on server
@param configureAutodiscover [required] If you host domain in OVH we can configure autodiscover record automatically
@param main [required] This newly created domain will be an organization (Exchange 2010 only)
@param organization2010 [required] If specified, indicates which organization this newly created domain will be part of (Exchange 2010 only)
@param mxRelay [required] If specified, emails to not existing address will be redirected to that domain
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
"""
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/domain";
StringBuilder sb = path(qPath, organizationName, exchangeService);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "configureAutodiscover", configureAutodiscover);
addBody(o, "configureMx", configureMx);
addBody(o, "main", main);
addBody(o, "mxRelay", mxRelay);
addBody(o, "name", name);
addBody(o, "organization2010", organization2010);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask organizationName_service_exchangeService_domain_POST(String organizationName, String exchangeService, Boolean configureAutodiscover, Boolean configureMx, Boolean main, String mxRelay, String name, String organization2010, OvhDomainTypeEnum type) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/domain";
StringBuilder sb = path(qPath, organizationName, exchangeService);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "configureAutodiscover", configureAutodiscover);
addBody(o, "configureMx", configureMx);
addBody(o, "main", main);
addBody(o, "mxRelay", mxRelay);
addBody(o, "name", name);
addBody(o, "organization2010", organization2010);
addBody(o, "type", type);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"organizationName_service_exchangeService_domain_POST",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"Boolean",
"configureAutodiscover",
",",
"Boolean",
"configureMx",
",",
"Boolean",
"main",
",",
"String",
"mxRelay",
",",
... | Create new domain in exchange services
REST: POST /email/exchange/{organizationName}/service/{exchangeService}/domain
@param configureMx [required] If you host domain in OVH we can configure mx record automatically
@param type [required] Type of domain that You want to install
@param name [required] Domain to install on server
@param configureAutodiscover [required] If you host domain in OVH we can configure autodiscover record automatically
@param main [required] This newly created domain will be an organization (Exchange 2010 only)
@param organization2010 [required] If specified, indicates which organization this newly created domain will be part of (Exchange 2010 only)
@param mxRelay [required] If specified, emails to not existing address will be redirected to that domain
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service | [
"Create",
"new",
"domain",
"in",
"exchange",
"services"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L445-L458 |
josueeduardo/snappy | plugin-parent/snappy-loader/src/main/java/io/joshworks/snappy/loader/util/SystemPropertyUtils.java | SystemPropertyUtils.resolvePlaceholders | public static String resolvePlaceholders(Properties properties, String text) {
"""
Resolve ${...} placeholders in the given text, replacing them with corresponding
system property values.
@param properties a properties instance to use in addition to System
@param text the String to resolve
@return the resolved String
@throws IllegalArgumentException if there is an unresolvable placeholder
@see #PLACEHOLDER_PREFIX
@see #PLACEHOLDER_SUFFIX
"""
if (text == null) {
return text;
}
return parseStringValue(properties, text, text, new HashSet<String>());
} | java | public static String resolvePlaceholders(Properties properties, String text) {
if (text == null) {
return text;
}
return parseStringValue(properties, text, text, new HashSet<String>());
} | [
"public",
"static",
"String",
"resolvePlaceholders",
"(",
"Properties",
"properties",
",",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
")",
"{",
"return",
"text",
";",
"}",
"return",
"parseStringValue",
"(",
"properties",
",",
"text",
",",
... | Resolve ${...} placeholders in the given text, replacing them with corresponding
system property values.
@param properties a properties instance to use in addition to System
@param text the String to resolve
@return the resolved String
@throws IllegalArgumentException if there is an unresolvable placeholder
@see #PLACEHOLDER_PREFIX
@see #PLACEHOLDER_SUFFIX | [
"Resolve",
"$",
"{",
"...",
"}",
"placeholders",
"in",
"the",
"given",
"text",
"replacing",
"them",
"with",
"corresponding",
"system",
"property",
"values",
"."
] | train | https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/plugin-parent/snappy-loader/src/main/java/io/joshworks/snappy/loader/util/SystemPropertyUtils.java#L84-L89 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/state/ConstructState.java | ConstructState.addConstructState | public void addConstructState(Constructs construct, ConstructState constructState, String infix) {
"""
See {@link #addConstructState(Constructs, ConstructState, Optional)}. This is a convenience method to pass a
String infix.
"""
addConstructState(construct, constructState, Optional.of(infix));
} | java | public void addConstructState(Constructs construct, ConstructState constructState, String infix) {
addConstructState(construct, constructState, Optional.of(infix));
} | [
"public",
"void",
"addConstructState",
"(",
"Constructs",
"construct",
",",
"ConstructState",
"constructState",
",",
"String",
"infix",
")",
"{",
"addConstructState",
"(",
"construct",
",",
"constructState",
",",
"Optional",
".",
"of",
"(",
"infix",
")",
")",
";... | See {@link #addConstructState(Constructs, ConstructState, Optional)}. This is a convenience method to pass a
String infix. | [
"See",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/state/ConstructState.java#L90-L92 |
killme2008/Metamorphosis | metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java | ResourceUtils.getResourceAsProperties | public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
"""
Returns a resource on the classpath as a Properties object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource
"""
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
} | java | public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
} | [
"public",
"static",
"Properties",
"getResourceAsProperties",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"InputStream",
"in",
"=",
"null",
";",
"Strin... | Returns a resource on the classpath as a Properties object
@param loader
The classloader used to load the resource
@param resource
The resource to find
@throws IOException
If the resource cannot be found or read
@return The resource | [
"Returns",
"a",
"resource",
"on",
"the",
"classpath",
"as",
"a",
"Properties",
"object"
] | train | https://github.com/killme2008/Metamorphosis/blob/1884b10620dbd640aaf85102243ca295703fbb4a/metamorphosis-commons/src/main/java/com/taobao/metamorphosis/utils/ResourceUtils.java#L175-L183 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/CheckoutUrl.java | CheckoutUrl.processDigitalWalletUrl | public static MozuUrl processDigitalWalletUrl(String checkoutId, String digitalWalletType, String responseFields) {
"""
Get Resource Url for ProcessDigitalWallet
@param checkoutId The unique identifier of the checkout.
@param digitalWalletType The type of digital wallet.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/digitalWallet/{digitalWalletType}?responseFields={responseFields}");
formatter.formatUrl("checkoutId", checkoutId);
formatter.formatUrl("digitalWalletType", digitalWalletType);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl processDigitalWalletUrl(String checkoutId, String digitalWalletType, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/digitalWallet/{digitalWalletType}?responseFields={responseFields}");
formatter.formatUrl("checkoutId", checkoutId);
formatter.formatUrl("digitalWalletType", digitalWalletType);
formatter.formatUrl("responseFields", responseFields);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"processDigitalWalletUrl",
"(",
"String",
"checkoutId",
",",
"String",
"digitalWalletType",
",",
"String",
"responseFields",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/checkouts/{checkoutId}/digita... | Get Resource Url for ProcessDigitalWallet
@param checkoutId The unique identifier of the checkout.
@param digitalWalletType The type of digital wallet.
@param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"ProcessDigitalWallet"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/CheckoutUrl.java#L153-L160 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.faulttolerance/src/com/ibm/ws/microprofile/faulttolerance/impl/TimeoutImpl.java | TimeoutImpl.debugTime | @Trivial
private void debugTime(String message, long nanos) {
"""
Output a debug message showing a given relative time, converted from nanos to seconds
@param message
@param nanos
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
FTDebug.debugTime(tc, getDescriptor(), message, nanos);
}
} | java | @Trivial
private void debugTime(String message, long nanos) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
FTDebug.debugTime(tc, getDescriptor(), message, nanos);
}
} | [
"@",
"Trivial",
"private",
"void",
"debugTime",
"(",
"String",
"message",
",",
"long",
"nanos",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"FTDebug",
".",
"debugTime",... | Output a debug message showing a given relative time, converted from nanos to seconds
@param message
@param nanos | [
"Output",
"a",
"debug",
"message",
"showing",
"a",
"given",
"relative",
"time",
"converted",
"from",
"nanos",
"to",
"seconds"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.faulttolerance/src/com/ibm/ws/microprofile/faulttolerance/impl/TimeoutImpl.java#L307-L312 |
alkacon/opencms-core | src/org/opencms/ui/components/CmsUserDataFormLayout.java | CmsUserDataFormLayout.submit | public void submit(CmsUser user, CmsObject cms, Runnable afterWrite) {
"""
Store fields to given user.<p>
@param user User to write information to
@param cms CmsObject
@param afterWrite runnable which gets called after writing user
"""
submit(user, cms, afterWrite, false);
} | java | public void submit(CmsUser user, CmsObject cms, Runnable afterWrite) {
submit(user, cms, afterWrite, false);
} | [
"public",
"void",
"submit",
"(",
"CmsUser",
"user",
",",
"CmsObject",
"cms",
",",
"Runnable",
"afterWrite",
")",
"{",
"submit",
"(",
"user",
",",
"cms",
",",
"afterWrite",
",",
"false",
")",
";",
"}"
] | Store fields to given user.<p>
@param user User to write information to
@param cms CmsObject
@param afterWrite runnable which gets called after writing user | [
"Store",
"fields",
"to",
"given",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsUserDataFormLayout.java#L198-L201 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntRelationMention.java | OntRelationMention.setDomainList | public void setDomainList(int i, Annotation v) {
"""
indexed setter for domainList - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array
"""
if (OntRelationMention_Type.featOkTst && ((OntRelationMention_Type)jcasType).casFeat_domainList == null)
jcasType.jcas.throwFeatMissing("domainList", "de.julielab.jules.types.OntRelationMention");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntRelationMention_Type)jcasType).casFeatCode_domainList), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntRelationMention_Type)jcasType).casFeatCode_domainList), i, jcasType.ll_cas.ll_getFSRef(v));} | java | public void setDomainList(int i, Annotation v) {
if (OntRelationMention_Type.featOkTst && ((OntRelationMention_Type)jcasType).casFeat_domainList == null)
jcasType.jcas.throwFeatMissing("domainList", "de.julielab.jules.types.OntRelationMention");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntRelationMention_Type)jcasType).casFeatCode_domainList), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntRelationMention_Type)jcasType).casFeatCode_domainList), i, jcasType.ll_cas.ll_getFSRef(v));} | [
"public",
"void",
"setDomainList",
"(",
"int",
"i",
",",
"Annotation",
"v",
")",
"{",
"if",
"(",
"OntRelationMention_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"OntRelationMention_Type",
")",
"jcasType",
")",
".",
"casFeat_domainList",
"==",
"null",
")",
"jcasTy... | indexed setter for domainList - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"domainList",
"-",
"sets",
"an",
"indexed",
"value",
"-"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntRelationMention.java#L160-L164 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509DefaultEntryConverter.java | X509DefaultEntryConverter.getConvertedValue | public DERObject getConvertedValue(
DERObjectIdentifier oid,
String value) {
"""
Apply default coversion for the given value depending on the oid
and the character range of the value.
@param oid the object identifier for the DN entry
@param value the value associated with it
@return the ASN.1 equivalent for the string value.
"""
if (value.length() != 0 && value.charAt(0) == '#')
{
try
{
return convertHexEncoded(value, 1);
}
catch (IOException e)
{
throw new RuntimeException("can't recode value for oid " + oid.getId(), e);
}
}
else if (oid.equals(X509Name.EmailAddress))
{
return new DERIA5String(value);
}
else if (canBePrintable(value))
{
return new DERPrintableString(value);
}
else if (canBeUTF8(value))
{
return new DERUTF8String(value);
}
return new DERBMPString(value);
} | java | public DERObject getConvertedValue(
DERObjectIdentifier oid,
String value)
{
if (value.length() != 0 && value.charAt(0) == '#')
{
try
{
return convertHexEncoded(value, 1);
}
catch (IOException e)
{
throw new RuntimeException("can't recode value for oid " + oid.getId(), e);
}
}
else if (oid.equals(X509Name.EmailAddress))
{
return new DERIA5String(value);
}
else if (canBePrintable(value))
{
return new DERPrintableString(value);
}
else if (canBeUTF8(value))
{
return new DERUTF8String(value);
}
return new DERBMPString(value);
} | [
"public",
"DERObject",
"getConvertedValue",
"(",
"DERObjectIdentifier",
"oid",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
".",
"length",
"(",
")",
"!=",
"0",
"&&",
"value",
".",
"charAt",
"(",
"0",
")",
"==",
"'",
"'",
")",
"{",
"try",
"{"... | Apply default coversion for the given value depending on the oid
and the character range of the value.
@param oid the object identifier for the DN entry
@param value the value associated with it
@return the ASN.1 equivalent for the string value. | [
"Apply",
"default",
"coversion",
"for",
"the",
"given",
"value",
"depending",
"on",
"the",
"oid",
"and",
"the",
"character",
"range",
"of",
"the",
"value",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/asn1/x509/X509DefaultEntryConverter.java#L41-L70 |
michael-rapp/AndroidPreferenceActivity | example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java | AppearancePreferenceFragment.createBreadCrumbElevationChangeListener | private OnPreferenceChangeListener createBreadCrumbElevationChangeListener() {
"""
Creates and returns a listener, which allows to adapt the elevation of the bread crumbs, when
the value of the corresponding preference has been changed.
@return The listener, which has been created, as an instance of the type {@link
OnPreferenceChangeListener}
"""
return new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int elevation = Integer.valueOf((String) newValue);
((PreferenceActivity) getActivity()).setBreadCrumbElevation(elevation);
return true;
}
};
} | java | private OnPreferenceChangeListener createBreadCrumbElevationChangeListener() {
return new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int elevation = Integer.valueOf((String) newValue);
((PreferenceActivity) getActivity()).setBreadCrumbElevation(elevation);
return true;
}
};
} | [
"private",
"OnPreferenceChangeListener",
"createBreadCrumbElevationChangeListener",
"(",
")",
"{",
"return",
"new",
"OnPreferenceChangeListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onPreferenceChange",
"(",
"Preference",
"preference",
",",
"Object",
"ne... | Creates and returns a listener, which allows to adapt the elevation of the bread crumbs, when
the value of the corresponding preference has been changed.
@return The listener, which has been created, as an instance of the type {@link
OnPreferenceChangeListener} | [
"Creates",
"and",
"returns",
"a",
"listener",
"which",
"allows",
"to",
"adapt",
"the",
"elevation",
"of",
"the",
"bread",
"crumbs",
"when",
"the",
"value",
"of",
"the",
"corresponding",
"preference",
"has",
"been",
"changed",
"."
] | train | https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java#L128-L139 |
Azure/azure-sdk-for-java | cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/CheckSkuAvailabilitysInner.java | CheckSkuAvailabilitysInner.listAsync | public Observable<CheckSkuAvailabilityResultListInner> listAsync(String location, List<SkuName> skus, Kind kind, String type) {
"""
Check available SKUs.
@param location Resource location.
@param skus The SKU of the resource.
@param kind The Kind of the resource. Possible values include: 'Bing.Autosuggest.v7', 'Bing.CustomSearch', 'Bing.Search.v7', 'Bing.Speech', 'Bing.SpellCheck.v7', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'CustomVision.Prediction', 'CustomVision.Training', 'Emotion', 'Face', 'LUIS', 'QnAMaker', 'SpeakerRecognition', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
@param type The Type of the resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CheckSkuAvailabilityResultListInner object
"""
return listWithServiceResponseAsync(location, skus, kind, type).map(new Func1<ServiceResponse<CheckSkuAvailabilityResultListInner>, CheckSkuAvailabilityResultListInner>() {
@Override
public CheckSkuAvailabilityResultListInner call(ServiceResponse<CheckSkuAvailabilityResultListInner> response) {
return response.body();
}
});
} | java | public Observable<CheckSkuAvailabilityResultListInner> listAsync(String location, List<SkuName> skus, Kind kind, String type) {
return listWithServiceResponseAsync(location, skus, kind, type).map(new Func1<ServiceResponse<CheckSkuAvailabilityResultListInner>, CheckSkuAvailabilityResultListInner>() {
@Override
public CheckSkuAvailabilityResultListInner call(ServiceResponse<CheckSkuAvailabilityResultListInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"CheckSkuAvailabilityResultListInner",
">",
"listAsync",
"(",
"String",
"location",
",",
"List",
"<",
"SkuName",
">",
"skus",
",",
"Kind",
"kind",
",",
"String",
"type",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"locatio... | Check available SKUs.
@param location Resource location.
@param skus The SKU of the resource.
@param kind The Kind of the resource. Possible values include: 'Bing.Autosuggest.v7', 'Bing.CustomSearch', 'Bing.Search.v7', 'Bing.Speech', 'Bing.SpellCheck.v7', 'ComputerVision', 'ContentModerator', 'CustomSpeech', 'CustomVision.Prediction', 'CustomVision.Training', 'Emotion', 'Face', 'LUIS', 'QnAMaker', 'SpeakerRecognition', 'SpeechTranslation', 'TextAnalytics', 'TextTranslation', 'WebLM'
@param type The Type of the resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CheckSkuAvailabilityResultListInner object | [
"Check",
"available",
"SKUs",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/resource-manager/v2017_04_18/src/main/java/com/microsoft/azure/management/cognitiveservices/v2017_04_18/implementation/CheckSkuAvailabilitysInner.java#L107-L114 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/dataformats/json/jackson/AbstractJsonDeserializer.java | AbstractJsonDeserializer.getDoubleParam | protected Double getDoubleParam(String paramName, String errorMessage) throws IOException {
"""
Convenience method for subclasses. Retrieves a double with the given parametername, even if that
parametercontent is actually a string containing a number or a long or an int or... Anything that
can be converted to a double is returned. uses the default parameterhashmap from this deserializer.
@param paramName the name of the parameter
@param errorMessage the errormessage to add to the exception if the param does not exist.
@return a stringparameter with given name. If it does not exist and the errormessage is provided,
an IOException is thrown with that message. if the errormessage is not provided, null is returned.
@throws IOException Exception if the paramname does not exist and an errormessage is provided.
"""
return getDoubleParam(paramName, errorMessage, (Map<String, Object>) inputParams.get());
} | java | protected Double getDoubleParam(String paramName, String errorMessage) throws IOException {
return getDoubleParam(paramName, errorMessage, (Map<String, Object>) inputParams.get());
} | [
"protected",
"Double",
"getDoubleParam",
"(",
"String",
"paramName",
",",
"String",
"errorMessage",
")",
"throws",
"IOException",
"{",
"return",
"getDoubleParam",
"(",
"paramName",
",",
"errorMessage",
",",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"... | Convenience method for subclasses. Retrieves a double with the given parametername, even if that
parametercontent is actually a string containing a number or a long or an int or... Anything that
can be converted to a double is returned. uses the default parameterhashmap from this deserializer.
@param paramName the name of the parameter
@param errorMessage the errormessage to add to the exception if the param does not exist.
@return a stringparameter with given name. If it does not exist and the errormessage is provided,
an IOException is thrown with that message. if the errormessage is not provided, null is returned.
@throws IOException Exception if the paramname does not exist and an errormessage is provided. | [
"Convenience",
"method",
"for",
"subclasses",
".",
"Retrieves",
"a",
"double",
"with",
"the",
"given",
"parametername",
"even",
"if",
"that",
"parametercontent",
"is",
"actually",
"a",
"string",
"containing",
"a",
"number",
"or",
"a",
"long",
"or",
"an",
"int"... | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/AbstractJsonDeserializer.java#L166-L168 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/SuspiciousClusteredSessionSupport.java | SuspiciousClusteredSessionSupport.visitCode | @Override
public void visitCode(Code obj) {
"""
implements the visitor to report on attributes that have changed, without a setAttribute being called on them
@param obj
the currently parsed method
"""
stack.resetForMethodEntry(this);
changedAttributes.clear();
savedAttributes.clear();
super.visitCode(obj);
for (Integer pc : changedAttributes.values()) {
bugReporter.reportBug(new BugInstance(this, BugType.SCSS_SUSPICIOUS_CLUSTERED_SESSION_SUPPORT.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this, pc.intValue()));
}
} | java | @Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
changedAttributes.clear();
savedAttributes.clear();
super.visitCode(obj);
for (Integer pc : changedAttributes.values()) {
bugReporter.reportBug(new BugInstance(this, BugType.SCSS_SUSPICIOUS_CLUSTERED_SESSION_SUPPORT.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this, pc.intValue()));
}
} | [
"@",
"Override",
"public",
"void",
"visitCode",
"(",
"Code",
"obj",
")",
"{",
"stack",
".",
"resetForMethodEntry",
"(",
"this",
")",
";",
"changedAttributes",
".",
"clear",
"(",
")",
";",
"savedAttributes",
".",
"clear",
"(",
")",
";",
"super",
".",
"vis... | implements the visitor to report on attributes that have changed, without a setAttribute being called on them
@param obj
the currently parsed method | [
"implements",
"the",
"visitor",
"to",
"report",
"on",
"attributes",
"that",
"have",
"changed",
"without",
"a",
"setAttribute",
"being",
"called",
"on",
"them"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/SuspiciousClusteredSessionSupport.java#L86-L96 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/GanttChartView.java | GanttChartView.getColumnFontStyle | protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases) {
"""
Retrieve column font details from a block of property data.
@param data property data
@param offset offset into property data
@param fontBases map of font bases
@return ColumnFontStyle instance
"""
int uniqueID = MPPUtility.getInt(data, offset);
FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));
Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));
int style = MPPUtility.getByte(data, offset + 9);
ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));
int change = MPPUtility.getByte(data, offset + 12);
FontBase fontBase = fontBases.get(index);
boolean bold = ((style & 0x01) != 0);
boolean italic = ((style & 0x02) != 0);
boolean underline = ((style & 0x04) != 0);
boolean boldChanged = ((change & 0x01) != 0);
boolean underlineChanged = ((change & 0x02) != 0);
boolean italicChanged = ((change & 0x04) != 0);
boolean colorChanged = ((change & 0x08) != 0);
boolean fontChanged = ((change & 0x10) != 0);
boolean backgroundColorChanged = (uniqueID == -1);
boolean backgroundPatternChanged = (uniqueID == -1);
return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));
} | java | protected TableFontStyle getColumnFontStyle(byte[] data, int offset, Map<Integer, FontBase> fontBases)
{
int uniqueID = MPPUtility.getInt(data, offset);
FieldType fieldType = MPPTaskField.getInstance(MPPUtility.getShort(data, offset + 4));
Integer index = Integer.valueOf(MPPUtility.getByte(data, offset + 8));
int style = MPPUtility.getByte(data, offset + 9);
ColorType color = ColorType.getInstance(MPPUtility.getByte(data, offset + 10));
int change = MPPUtility.getByte(data, offset + 12);
FontBase fontBase = fontBases.get(index);
boolean bold = ((style & 0x01) != 0);
boolean italic = ((style & 0x02) != 0);
boolean underline = ((style & 0x04) != 0);
boolean boldChanged = ((change & 0x01) != 0);
boolean underlineChanged = ((change & 0x02) != 0);
boolean italicChanged = ((change & 0x04) != 0);
boolean colorChanged = ((change & 0x08) != 0);
boolean fontChanged = ((change & 0x10) != 0);
boolean backgroundColorChanged = (uniqueID == -1);
boolean backgroundPatternChanged = (uniqueID == -1);
return (new TableFontStyle(uniqueID, fieldType, fontBase, italic, bold, underline, false, color.getColor(), Color.BLACK, BackgroundPattern.TRANSPARENT, italicChanged, boldChanged, underlineChanged, false, colorChanged, fontChanged, backgroundColorChanged, backgroundPatternChanged));
} | [
"protected",
"TableFontStyle",
"getColumnFontStyle",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"Map",
"<",
"Integer",
",",
"FontBase",
">",
"fontBases",
")",
"{",
"int",
"uniqueID",
"=",
"MPPUtility",
".",
"getInt",
"(",
"data",
",",
"offse... | Retrieve column font details from a block of property data.
@param data property data
@param offset offset into property data
@param fontBases map of font bases
@return ColumnFontStyle instance | [
"Retrieve",
"column",
"font",
"details",
"from",
"a",
"block",
"of",
"property",
"data",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/GanttChartView.java#L1159-L1183 |
jpaoletti/java-presentation-manager | modules/jpm-core/src/main/java/jpaoletti/jpm/security/core/BCrypt.java | BCrypt.gensalt | public static String gensalt(int log_rounds, SecureRandom random) {
"""
Generate a salt for use with the BCrypt.hashpw() method
@param log_rounds the log2 of the number of rounds of
hashing to apply - the work factor therefore increases as
2**log_rounds.
@param random an instance of SecureRandom to use
@return an encoded salt value
"""
StringBuilder rs = new StringBuilder();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10) {
rs.append("0");
}
rs.append(Integer.toString(log_rounds));
rs.append("$");
rs.append(encode_base64(rnd, rnd.length));
return rs.toString();
} | java | public static String gensalt(int log_rounds, SecureRandom random) {
StringBuilder rs = new StringBuilder();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10) {
rs.append("0");
}
rs.append(Integer.toString(log_rounds));
rs.append("$");
rs.append(encode_base64(rnd, rnd.length));
return rs.toString();
} | [
"public",
"static",
"String",
"gensalt",
"(",
"int",
"log_rounds",
",",
"SecureRandom",
"random",
")",
"{",
"StringBuilder",
"rs",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"byte",
"rnd",
"[",
"]",
"=",
"new",
"byte",
"[",
"BCRYPT_SALT_LEN",
"]",
";",
... | Generate a salt for use with the BCrypt.hashpw() method
@param log_rounds the log2 of the number of rounds of
hashing to apply - the work factor therefore increases as
2**log_rounds.
@param random an instance of SecureRandom to use
@return an encoded salt value | [
"Generate",
"a",
"salt",
"for",
"use",
"with",
"the",
"BCrypt",
".",
"hashpw",
"()",
"method"
] | train | https://github.com/jpaoletti/java-presentation-manager/blob/d5aab55638383695db244744b4bfe27c5200e04f/modules/jpm-core/src/main/java/jpaoletti/jpm/security/core/BCrypt.java#L720-L734 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/HsqlLinkedList.java | HsqlLinkedList.add | public void add(int index, Object element) {
"""
Inserts <code>element</code> at <code>index</code>.
@throws IndexOutOfBoundsException if <code>index</code> < 0 or is >
<code>size</code>.
"""
if (index == size()) {
add(element); //Add to the end of this.
}
//If index > size() an exception should be thrown with a slightly
//different message than the exception thrown by getInternal.
else if (index > size()) {
throw new IndexOutOfBoundsException("Index out of bounds: "
+ index + " > " + size());
} else {
Node current = getInternal(index);
Node newNext = new Node(current.data, current.next);
current.data = element;
current.next = newNext;
elementCount++;
//If they inserted at the last valid index, then a new last element
//was created, therfore update the last pointer
if (last == current) {
last = newNext;
}
}
} | java | public void add(int index, Object element) {
if (index == size()) {
add(element); //Add to the end of this.
}
//If index > size() an exception should be thrown with a slightly
//different message than the exception thrown by getInternal.
else if (index > size()) {
throw new IndexOutOfBoundsException("Index out of bounds: "
+ index + " > " + size());
} else {
Node current = getInternal(index);
Node newNext = new Node(current.data, current.next);
current.data = element;
current.next = newNext;
elementCount++;
//If they inserted at the last valid index, then a new last element
//was created, therfore update the last pointer
if (last == current) {
last = newNext;
}
}
} | [
"public",
"void",
"add",
"(",
"int",
"index",
",",
"Object",
"element",
")",
"{",
"if",
"(",
"index",
"==",
"size",
"(",
")",
")",
"{",
"add",
"(",
"element",
")",
";",
"//Add to the end of this.",
"}",
"//If index > size() an exception should be thrown with a s... | Inserts <code>element</code> at <code>index</code>.
@throws IndexOutOfBoundsException if <code>index</code> < 0 or is >
<code>size</code>. | [
"Inserts",
"<code",
">",
"element<",
"/",
"code",
">",
"at",
"<code",
">",
"index<",
"/",
"code",
">",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/HsqlLinkedList.java#L94-L120 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/otm/copy/MetadataObjectCopyStrategy.java | MetadataObjectCopyStrategy.copy | public Object copy(final Object obj, final PersistenceBroker broker) {
"""
Uses an IdentityMap to make sure we don't recurse infinitely on the same object in a cyclic object model.
Proxies
@param obj
@return
"""
return clone(obj, IdentityMapFactory.getIdentityMap(), broker);
} | java | public Object copy(final Object obj, final PersistenceBroker broker)
{
return clone(obj, IdentityMapFactory.getIdentityMap(), broker);
} | [
"public",
"Object",
"copy",
"(",
"final",
"Object",
"obj",
",",
"final",
"PersistenceBroker",
"broker",
")",
"{",
"return",
"clone",
"(",
"obj",
",",
"IdentityMapFactory",
".",
"getIdentityMap",
"(",
")",
",",
"broker",
")",
";",
"}"
] | Uses an IdentityMap to make sure we don't recurse infinitely on the same object in a cyclic object model.
Proxies
@param obj
@return | [
"Uses",
"an",
"IdentityMap",
"to",
"make",
"sure",
"we",
"don",
"t",
"recurse",
"infinitely",
"on",
"the",
"same",
"object",
"in",
"a",
"cyclic",
"object",
"model",
".",
"Proxies"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/otm/copy/MetadataObjectCopyStrategy.java#L48-L51 |
xetorthio/jedis | src/main/java/redis/clients/jedis/BinaryJedis.java | BinaryJedis.hincrBy | @Override
public Long hincrBy(final byte[] key, final byte[] field, final long value) {
"""
Increment the number stored at field in the hash at key by value. If key does not exist, a new
key holding a hash is created. If field does not exist or holds a string, the value is set to 0
before applying the operation. Since the value argument is signed you can use this command to
perform both increments and decrements.
<p>
The range of values supported by HINCRBY is limited to 64 bit signed integers.
<p>
<b>Time complexity:</b> O(1)
@param key
@param field
@param value
@return Integer reply The new value at field after the increment operation.
"""
checkIsInMultiOrPipeline();
client.hincrBy(key, field, value);
return client.getIntegerReply();
} | java | @Override
public Long hincrBy(final byte[] key, final byte[] field, final long value) {
checkIsInMultiOrPipeline();
client.hincrBy(key, field, value);
return client.getIntegerReply();
} | [
"@",
"Override",
"public",
"Long",
"hincrBy",
"(",
"final",
"byte",
"[",
"]",
"key",
",",
"final",
"byte",
"[",
"]",
"field",
",",
"final",
"long",
"value",
")",
"{",
"checkIsInMultiOrPipeline",
"(",
")",
";",
"client",
".",
"hincrBy",
"(",
"key",
",",... | Increment the number stored at field in the hash at key by value. If key does not exist, a new
key holding a hash is created. If field does not exist or holds a string, the value is set to 0
before applying the operation. Since the value argument is signed you can use this command to
perform both increments and decrements.
<p>
The range of values supported by HINCRBY is limited to 64 bit signed integers.
<p>
<b>Time complexity:</b> O(1)
@param key
@param field
@param value
@return Integer reply The new value at field after the increment operation. | [
"Increment",
"the",
"number",
"stored",
"at",
"field",
"in",
"the",
"hash",
"at",
"key",
"by",
"value",
".",
"If",
"key",
"does",
"not",
"exist",
"a",
"new",
"key",
"holding",
"a",
"hash",
"is",
"created",
".",
"If",
"field",
"does",
"not",
"exist",
... | train | https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L990-L995 |
lukas-krecan/JsonUnit | json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java | Configuration.withMatcher | public Configuration withMatcher(String matcherName, Matcher<?> matcher) {
"""
Adds a matcher to be used in ${json-unit.matches:matcherName} macro.
@param matcherName
@param matcher
@return
"""
return new Configuration(tolerance, options, ignorePlaceholder, matchers.with(matcherName, matcher), pathsToBeIgnored, differenceListener);
} | java | public Configuration withMatcher(String matcherName, Matcher<?> matcher) {
return new Configuration(tolerance, options, ignorePlaceholder, matchers.with(matcherName, matcher), pathsToBeIgnored, differenceListener);
} | [
"public",
"Configuration",
"withMatcher",
"(",
"String",
"matcherName",
",",
"Matcher",
"<",
"?",
">",
"matcher",
")",
"{",
"return",
"new",
"Configuration",
"(",
"tolerance",
",",
"options",
",",
"ignorePlaceholder",
",",
"matchers",
".",
"with",
"(",
"matche... | Adds a matcher to be used in ${json-unit.matches:matcherName} macro.
@param matcherName
@param matcher
@return | [
"Adds",
"a",
"matcher",
"to",
"be",
"used",
"in",
"$",
"{",
"json",
"-",
"unit",
".",
"matches",
":",
"matcherName",
"}",
"macro",
"."
] | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit-core/src/main/java/net/javacrumbs/jsonunit/core/Configuration.java#L142-L144 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java | WriterUtils.getWriterFilePath | public static Path getWriterFilePath(State state, int numBranches, int branchId) {
"""
Get the {@link Path} corresponding the the relative file path for a given {@link org.apache.gobblin.writer.DataWriter}.
This method retrieves the value of {@link ConfigurationKeys#WRITER_FILE_PATH} from the given {@link State}. It also
constructs the default value of the {@link ConfigurationKeys#WRITER_FILE_PATH} if not is not specified in the given
{@link State}.
@param state is the {@link State} corresponding to a specific {@link org.apache.gobblin.writer.DataWriter}.
@param numBranches is the total number of branches for the given {@link State}.
@param branchId is the id for the specific branch that the {{@link org.apache.gobblin.writer.DataWriter} will write to.
@return a {@link Path} specifying the relative directory where the {@link org.apache.gobblin.writer.DataWriter} will write to.
"""
if (state.contains(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))) {
return new Path(state.getProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId)));
}
switch (getWriterFilePathType(state)) {
case NAMESPACE_TABLE:
return getNamespaceTableWriterFilePath(state);
case TABLENAME:
return WriterUtils.getTableNameWriterFilePath(state);
default:
return WriterUtils.getDefaultWriterFilePath(state, numBranches, branchId);
}
} | java | public static Path getWriterFilePath(State state, int numBranches, int branchId) {
if (state.contains(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))) {
return new Path(state.getProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId)));
}
switch (getWriterFilePathType(state)) {
case NAMESPACE_TABLE:
return getNamespaceTableWriterFilePath(state);
case TABLENAME:
return WriterUtils.getTableNameWriterFilePath(state);
default:
return WriterUtils.getDefaultWriterFilePath(state, numBranches, branchId);
}
} | [
"public",
"static",
"Path",
"getWriterFilePath",
"(",
"State",
"state",
",",
"int",
"numBranches",
",",
"int",
"branchId",
")",
"{",
"if",
"(",
"state",
".",
"contains",
"(",
"ForkOperatorUtils",
".",
"getPropertyNameForBranch",
"(",
"ConfigurationKeys",
".",
"W... | Get the {@link Path} corresponding the the relative file path for a given {@link org.apache.gobblin.writer.DataWriter}.
This method retrieves the value of {@link ConfigurationKeys#WRITER_FILE_PATH} from the given {@link State}. It also
constructs the default value of the {@link ConfigurationKeys#WRITER_FILE_PATH} if not is not specified in the given
{@link State}.
@param state is the {@link State} corresponding to a specific {@link org.apache.gobblin.writer.DataWriter}.
@param numBranches is the total number of branches for the given {@link State}.
@param branchId is the id for the specific branch that the {{@link org.apache.gobblin.writer.DataWriter} will write to.
@return a {@link Path} specifying the relative directory where the {@link org.apache.gobblin.writer.DataWriter} will write to. | [
"Get",
"the",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java#L155-L170 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/DistributedAvatarFileSystem.java | DistributedAvatarFileSystem.getFileStatus | public FileStatus getFileStatus(final Path f, final boolean useStandby)
throws IOException {
"""
Return the stat information about a file.
@param f path
@param useStandby flag indicating whether to read from standby avatar
@throws FileNotFoundException if the file does not exist.
"""
return new StandbyCaller<FileStatus>() {
@Override
FileStatus call(DistributedFileSystem fs) throws IOException {
return fs.getFileStatus(f);
}
}.callFS(useStandby);
} | java | public FileStatus getFileStatus(final Path f, final boolean useStandby)
throws IOException {
return new StandbyCaller<FileStatus>() {
@Override
FileStatus call(DistributedFileSystem fs) throws IOException {
return fs.getFileStatus(f);
}
}.callFS(useStandby);
} | [
"public",
"FileStatus",
"getFileStatus",
"(",
"final",
"Path",
"f",
",",
"final",
"boolean",
"useStandby",
")",
"throws",
"IOException",
"{",
"return",
"new",
"StandbyCaller",
"<",
"FileStatus",
">",
"(",
")",
"{",
"@",
"Override",
"FileStatus",
"call",
"(",
... | Return the stat information about a file.
@param f path
@param useStandby flag indicating whether to read from standby avatar
@throws FileNotFoundException if the file does not exist. | [
"Return",
"the",
"stat",
"information",
"about",
"a",
"file",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/DistributedAvatarFileSystem.java#L464-L472 |
phax/peppol-directory | peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java | PDIndexerManager.queueWorkItem | @Nonnull
public EChange queueWorkItem (@Nonnull final IParticipantIdentifier aParticipantID,
@Nonnull final EIndexerWorkItemType eType,
@Nonnull @Nonempty final String sOwnerID,
@Nonnull @Nonempty final String sRequestingHost) {
"""
Queue a new work item
@param aParticipantID
Participant ID to use.
@param eType
Action type.
@param sOwnerID
Owner of this action
@param sRequestingHost
Requesting host (IP address)
@return {@link EChange#UNCHANGED} if the item was queued,
{@link EChange#UNCHANGED} if this item is already in the queue!
"""
// Build item
final IIndexerWorkItem aWorkItem = new IndexerWorkItem (aParticipantID, eType, sOwnerID, sRequestingHost);
// And queue it
return _queueUniqueWorkItem (aWorkItem);
} | java | @Nonnull
public EChange queueWorkItem (@Nonnull final IParticipantIdentifier aParticipantID,
@Nonnull final EIndexerWorkItemType eType,
@Nonnull @Nonempty final String sOwnerID,
@Nonnull @Nonempty final String sRequestingHost)
{
// Build item
final IIndexerWorkItem aWorkItem = new IndexerWorkItem (aParticipantID, eType, sOwnerID, sRequestingHost);
// And queue it
return _queueUniqueWorkItem (aWorkItem);
} | [
"@",
"Nonnull",
"public",
"EChange",
"queueWorkItem",
"(",
"@",
"Nonnull",
"final",
"IParticipantIdentifier",
"aParticipantID",
",",
"@",
"Nonnull",
"final",
"EIndexerWorkItemType",
"eType",
",",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sOwnerID",
",",
... | Queue a new work item
@param aParticipantID
Participant ID to use.
@param eType
Action type.
@param sOwnerID
Owner of this action
@param sRequestingHost
Requesting host (IP address)
@return {@link EChange#UNCHANGED} if the item was queued,
{@link EChange#UNCHANGED} if this item is already in the queue! | [
"Queue",
"a",
"new",
"work",
"item"
] | train | https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java#L256-L266 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/MessageAPI.java | MessageAPI.messageMassSendall | public static MessageSendResult messageMassSendall(String access_token, MassMessage massMessage) {
"""
高级群发接口 根据 分组或标签 进行群发
@param access_token access_token
@param massMessage massMessage
@return MessageSendResult
"""
String str = JsonUtil.toJSONString(massMessage);
return messageMassSendall(access_token, str);
} | java | public static MessageSendResult messageMassSendall(String access_token, MassMessage massMessage) {
String str = JsonUtil.toJSONString(massMessage);
return messageMassSendall(access_token, str);
} | [
"public",
"static",
"MessageSendResult",
"messageMassSendall",
"(",
"String",
"access_token",
",",
"MassMessage",
"massMessage",
")",
"{",
"String",
"str",
"=",
"JsonUtil",
".",
"toJSONString",
"(",
"massMessage",
")",
";",
"return",
"messageMassSendall",
"(",
"acce... | 高级群发接口 根据 分组或标签 进行群发
@param access_token access_token
@param massMessage massMessage
@return MessageSendResult | [
"高级群发接口",
"根据",
"分组或标签",
"进行群发"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/MessageAPI.java#L151-L154 |
undertow-io/undertow | core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java | Http2ReceiveListener.handleInitialRequest | void handleInitialRequest(HttpServerExchange initial, Http2Channel channel, byte[] data) {
"""
Handles the initial request when the exchange was started by a HTTP ugprade.
@param initial The initial upgrade request that started the HTTP2 connection
"""
//we have a request
Http2HeadersStreamSinkChannel sink = channel.createInitialUpgradeResponseStream();
final Http2ServerConnection connection = new Http2ServerConnection(channel, sink, undertowOptions, bufferSize, rootHandler);
HeaderMap requestHeaders = new HeaderMap();
for(HeaderValues hv : initial.getRequestHeaders()) {
requestHeaders.putAll(hv.getHeaderName(), hv);
}
final HttpServerExchange exchange = new HttpServerExchange(connection, requestHeaders, sink.getHeaders(), maxEntitySize);
if(initial.getRequestHeaders().contains(Headers.EXPECT)) {
HttpContinue.markContinueResponseSent(exchange);
}
if(initial.getAttachment(HttpAttachments.REQUEST_TRAILERS) != null) {
exchange.putAttachment(HttpAttachments.REQUEST_TRAILERS, initial.getAttachment(HttpAttachments.REQUEST_TRAILERS));
}
Connectors.setRequestStartTime(initial, exchange);
connection.setExchange(exchange);
exchange.setRequestScheme(initial.getRequestScheme());
exchange.setRequestMethod(initial.getRequestMethod());
exchange.setQueryString(initial.getQueryString());
if(data != null) {
Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(data)));
} else {
Connectors.terminateRequest(exchange);
}
String uri = exchange.getQueryString().isEmpty() ? initial.getRequestURI() : initial.getRequestURI() + '?' + exchange.getQueryString();
try {
Connectors.setExchangeRequestPath(exchange, uri, encoding, decode, allowEncodingSlash, decodeBuffer, maxParameters);
} catch (ParameterLimitException e) {
exchange.setStatusCode(StatusCodes.BAD_REQUEST);
exchange.endExchange();
return;
}
handleCommonSetup(sink, exchange, connection);
Connectors.executeRootHandler(rootHandler, exchange);
} | java | void handleInitialRequest(HttpServerExchange initial, Http2Channel channel, byte[] data) {
//we have a request
Http2HeadersStreamSinkChannel sink = channel.createInitialUpgradeResponseStream();
final Http2ServerConnection connection = new Http2ServerConnection(channel, sink, undertowOptions, bufferSize, rootHandler);
HeaderMap requestHeaders = new HeaderMap();
for(HeaderValues hv : initial.getRequestHeaders()) {
requestHeaders.putAll(hv.getHeaderName(), hv);
}
final HttpServerExchange exchange = new HttpServerExchange(connection, requestHeaders, sink.getHeaders(), maxEntitySize);
if(initial.getRequestHeaders().contains(Headers.EXPECT)) {
HttpContinue.markContinueResponseSent(exchange);
}
if(initial.getAttachment(HttpAttachments.REQUEST_TRAILERS) != null) {
exchange.putAttachment(HttpAttachments.REQUEST_TRAILERS, initial.getAttachment(HttpAttachments.REQUEST_TRAILERS));
}
Connectors.setRequestStartTime(initial, exchange);
connection.setExchange(exchange);
exchange.setRequestScheme(initial.getRequestScheme());
exchange.setRequestMethod(initial.getRequestMethod());
exchange.setQueryString(initial.getQueryString());
if(data != null) {
Connectors.ungetRequestBytes(exchange, new ImmediatePooledByteBuffer(ByteBuffer.wrap(data)));
} else {
Connectors.terminateRequest(exchange);
}
String uri = exchange.getQueryString().isEmpty() ? initial.getRequestURI() : initial.getRequestURI() + '?' + exchange.getQueryString();
try {
Connectors.setExchangeRequestPath(exchange, uri, encoding, decode, allowEncodingSlash, decodeBuffer, maxParameters);
} catch (ParameterLimitException e) {
exchange.setStatusCode(StatusCodes.BAD_REQUEST);
exchange.endExchange();
return;
}
handleCommonSetup(sink, exchange, connection);
Connectors.executeRootHandler(rootHandler, exchange);
} | [
"void",
"handleInitialRequest",
"(",
"HttpServerExchange",
"initial",
",",
"Http2Channel",
"channel",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"//we have a request",
"Http2HeadersStreamSinkChannel",
"sink",
"=",
"channel",
".",
"createInitialUpgradeResponseStream",
"(",
... | Handles the initial request when the exchange was started by a HTTP ugprade.
@param initial The initial upgrade request that started the HTTP2 connection | [
"Handles",
"the",
"initial",
"request",
"when",
"the",
"exchange",
"was",
"started",
"by",
"a",
"HTTP",
"ugprade",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/protocol/http2/Http2ReceiveListener.java#L224-L264 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java | XPathContext.createDTMIterator | public DTMIterator createDTMIterator(String xpathString,
PrefixResolver presolver) {
"""
Create a new <code>DTMIterator</code> based on an XPath
<a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
@param xpathString Must be a valid string expressing a
<a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
@param presolver An object that can resolve prefixes to namespace URLs.
@return The newly created <code>DTMIterator</code>.
"""
return m_dtmManager.createDTMIterator(xpathString, presolver);
} | java | public DTMIterator createDTMIterator(String xpathString,
PrefixResolver presolver)
{
return m_dtmManager.createDTMIterator(xpathString, presolver);
} | [
"public",
"DTMIterator",
"createDTMIterator",
"(",
"String",
"xpathString",
",",
"PrefixResolver",
"presolver",
")",
"{",
"return",
"m_dtmManager",
".",
"createDTMIterator",
"(",
"xpathString",
",",
"presolver",
")",
";",
"}"
] | Create a new <code>DTMIterator</code> based on an XPath
<a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
@param xpathString Must be a valid string expressing a
<a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
@param presolver An object that can resolve prefixes to namespace URLs.
@return The newly created <code>DTMIterator</code>. | [
"Create",
"a",
"new",
"<code",
">",
"DTMIterator<",
"/",
"code",
">",
"based",
"on",
"an",
"XPath",
"<a",
"href",
"=",
"http",
":",
"//",
"www",
".",
"w3",
".",
"org",
"/",
"TR",
"/",
"xpath#NT",
"-",
"LocationPath",
">",
"LocationPath<",
"/",
"a",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/XPathContext.java#L259-L263 |
di2e/Argo | ArgoWirelineFormat/src/main/java/ws/argo/wireline/probe/ProbeWrapper.java | ProbeWrapper.addRespondToURL | public void addRespondToURL(String label, String url) {
"""
Add a response URL to the probe.
@param label the string label for the respondTo address
@param url the actual URL string
"""
RespondToURL respondToURL = new RespondToURL();
respondToURL.label = label;
respondToURL.url = url;
respondToURLs.add(respondToURL);
} | java | public void addRespondToURL(String label, String url) {
RespondToURL respondToURL = new RespondToURL();
respondToURL.label = label;
respondToURL.url = url;
respondToURLs.add(respondToURL);
} | [
"public",
"void",
"addRespondToURL",
"(",
"String",
"label",
",",
"String",
"url",
")",
"{",
"RespondToURL",
"respondToURL",
"=",
"new",
"RespondToURL",
"(",
")",
";",
"respondToURL",
".",
"label",
"=",
"label",
";",
"respondToURL",
".",
"url",
"=",
"url",
... | Add a response URL to the probe.
@param label the string label for the respondTo address
@param url the actual URL string | [
"Add",
"a",
"response",
"URL",
"to",
"the",
"probe",
"."
] | train | https://github.com/di2e/Argo/blob/f537a03d2d25fdfecda7999ec10e1da67dc3b8f3/ArgoWirelineFormat/src/main/java/ws/argo/wireline/probe/ProbeWrapper.java#L257-L265 |
AgNO3/jcifs-ng | src/main/java/jcifs/ntlmssp/Type3Message.java | Type3Message.setupMIC | public void setupMIC ( byte[] type1, byte[] type2 ) throws GeneralSecurityException, IOException {
"""
Sets the MIC
@param type1
@param type2
@throws GeneralSecurityException
@throws IOException
"""
byte[] sk = this.masterKey;
if ( sk == null ) {
return;
}
MessageDigest mac = Crypto.getHMACT64(sk);
mac.update(type1);
mac.update(type2);
byte[] type3 = toByteArray();
mac.update(type3);
setMic(mac.digest());
} | java | public void setupMIC ( byte[] type1, byte[] type2 ) throws GeneralSecurityException, IOException {
byte[] sk = this.masterKey;
if ( sk == null ) {
return;
}
MessageDigest mac = Crypto.getHMACT64(sk);
mac.update(type1);
mac.update(type2);
byte[] type3 = toByteArray();
mac.update(type3);
setMic(mac.digest());
} | [
"public",
"void",
"setupMIC",
"(",
"byte",
"[",
"]",
"type1",
",",
"byte",
"[",
"]",
"type2",
")",
"throws",
"GeneralSecurityException",
",",
"IOException",
"{",
"byte",
"[",
"]",
"sk",
"=",
"this",
".",
"masterKey",
";",
"if",
"(",
"sk",
"==",
"null",... | Sets the MIC
@param type1
@param type2
@throws GeneralSecurityException
@throws IOException | [
"Sets",
"the",
"MIC"
] | train | https://github.com/AgNO3/jcifs-ng/blob/0311107a077ea372527ae74839eec8042197332f/src/main/java/jcifs/ntlmssp/Type3Message.java#L297-L308 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/transform/pyramid/PyramidOps.java | PyramidOps.reshapeOutput | public static <O extends ImageGray<O>>
void reshapeOutput( ImagePyramid<?> pyramid , O[] output ) {
"""
Reshapes each image in the array to match the layers in the pyramid
@param pyramid (Input) Image pyramid
@param output (Output) List of images which is to be resized
@param <O> Image type
"""
for( int i = 0; i < output.length; i++ ) {
int w = pyramid.getWidth(i);
int h = pyramid.getHeight(i);
output[i].reshape(w, h);
}
} | java | public static <O extends ImageGray<O>>
void reshapeOutput( ImagePyramid<?> pyramid , O[] output ) {
for( int i = 0; i < output.length; i++ ) {
int w = pyramid.getWidth(i);
int h = pyramid.getHeight(i);
output[i].reshape(w, h);
}
} | [
"public",
"static",
"<",
"O",
"extends",
"ImageGray",
"<",
"O",
">",
">",
"void",
"reshapeOutput",
"(",
"ImagePyramid",
"<",
"?",
">",
"pyramid",
",",
"O",
"[",
"]",
"output",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"output",
"... | Reshapes each image in the array to match the layers in the pyramid
@param pyramid (Input) Image pyramid
@param output (Output) List of images which is to be resized
@param <O> Image type | [
"Reshapes",
"each",
"image",
"in",
"the",
"array",
"to",
"match",
"the",
"layers",
"in",
"the",
"pyramid"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/pyramid/PyramidOps.java#L70-L78 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java | DateFormatUtils.fromString | public static Date fromString(String source, String format) {
"""
Parse a string to {@link Date}, based on the specified {@code format}.
@param source
@param format
@return
"""
try {
ObjectPool<DateFormat> pool = cachedDateFormat.get(format);
try {
DateFormat df = pool.borrowObject();
try {
return df.parse(source);
} finally {
pool.returnObject(df);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | java | public static Date fromString(String source, String format) {
try {
ObjectPool<DateFormat> pool = cachedDateFormat.get(format);
try {
DateFormat df = pool.borrowObject();
try {
return df.parse(source);
} finally {
pool.returnObject(df);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"Date",
"fromString",
"(",
"String",
"source",
",",
"String",
"format",
")",
"{",
"try",
"{",
"ObjectPool",
"<",
"DateFormat",
">",
"pool",
"=",
"cachedDateFormat",
".",
"get",
"(",
"format",
")",
";",
"try",
"{",
"DateFormat",
"df",
... | Parse a string to {@link Date}, based on the specified {@code format}.
@param source
@param format
@return | [
"Parse",
"a",
"string",
"to",
"{",
"@link",
"Date",
"}",
"based",
"on",
"the",
"specified",
"{",
"@code",
"format",
"}",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateFormatUtils.java#L158-L175 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.freshAddress | public Address freshAddress(KeyChain.KeyPurpose purpose, Script.ScriptType outputScriptType, long keyRotationTimeSecs) {
"""
<p>Returns a fresh address for a given {@link KeyChain.KeyPurpose} and of a given
{@link Script.ScriptType}.</p>
<p>This method is meant for when you really need a fallback address. Normally, you should be
using {@link #freshAddress(KeyChain.KeyPurpose)} or
{@link #currentAddress(KeyChain.KeyPurpose)}.</p>
"""
DeterministicKeyChain chain = getActiveKeyChain(outputScriptType, keyRotationTimeSecs);
return Address.fromKey(params, chain.getKey(purpose), outputScriptType);
} | java | public Address freshAddress(KeyChain.KeyPurpose purpose, Script.ScriptType outputScriptType, long keyRotationTimeSecs) {
DeterministicKeyChain chain = getActiveKeyChain(outputScriptType, keyRotationTimeSecs);
return Address.fromKey(params, chain.getKey(purpose), outputScriptType);
} | [
"public",
"Address",
"freshAddress",
"(",
"KeyChain",
".",
"KeyPurpose",
"purpose",
",",
"Script",
".",
"ScriptType",
"outputScriptType",
",",
"long",
"keyRotationTimeSecs",
")",
"{",
"DeterministicKeyChain",
"chain",
"=",
"getActiveKeyChain",
"(",
"outputScriptType",
... | <p>Returns a fresh address for a given {@link KeyChain.KeyPurpose} and of a given
{@link Script.ScriptType}.</p>
<p>This method is meant for when you really need a fallback address. Normally, you should be
using {@link #freshAddress(KeyChain.KeyPurpose)} or
{@link #currentAddress(KeyChain.KeyPurpose)}.</p> | [
"<p",
">",
"Returns",
"a",
"fresh",
"address",
"for",
"a",
"given",
"{"
] | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L368-L371 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowManagedObject.java | PageFlowManagedObject.reinitializeIfNecessary | void reinitializeIfNecessary(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
"""
Internal method to reinitialize only if necessary. The test is whether the ServletContext
reference has been lost.
"""
if (_servletContext == null) {
reinitialize(request, response, servletContext);
}
} | java | void reinitializeIfNecessary(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
{
if (_servletContext == null) {
reinitialize(request, response, servletContext);
}
} | [
"void",
"reinitializeIfNecessary",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"ServletContext",
"servletContext",
")",
"{",
"if",
"(",
"_servletContext",
"==",
"null",
")",
"{",
"reinitialize",
"(",
"request",
",",
"response",
... | Internal method to reinitialize only if necessary. The test is whether the ServletContext
reference has been lost. | [
"Internal",
"method",
"to",
"reinitialize",
"only",
"if",
"necessary",
".",
"The",
"test",
"is",
"whether",
"the",
"ServletContext",
"reference",
"has",
"been",
"lost",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowManagedObject.java#L80-L85 |
stratosphere/stratosphere | stratosphere-java/src/main/java/eu/stratosphere/api/java/ExecutionEnvironment.java | ExecutionEnvironment.generateSequence | public DataSource<Long> generateSequence(long from, long to) {
"""
Creates a new data set that contains a sequence of numbers. The data set will be created in parallel,
so there is no guarantee about the oder of the elements.
@param from The number to start at (inclusive).
@param to The number to stop at (inclusive).
@return A DataSet, containing all number in the {@code [from, to]} interval.
"""
return fromParallelCollection(new NumberSequenceIterator(from, to), BasicTypeInfo.LONG_TYPE_INFO);
} | java | public DataSource<Long> generateSequence(long from, long to) {
return fromParallelCollection(new NumberSequenceIterator(from, to), BasicTypeInfo.LONG_TYPE_INFO);
} | [
"public",
"DataSource",
"<",
"Long",
">",
"generateSequence",
"(",
"long",
"from",
",",
"long",
"to",
")",
"{",
"return",
"fromParallelCollection",
"(",
"new",
"NumberSequenceIterator",
"(",
"from",
",",
"to",
")",
",",
"BasicTypeInfo",
".",
"LONG_TYPE_INFO",
... | Creates a new data set that contains a sequence of numbers. The data set will be created in parallel,
so there is no guarantee about the oder of the elements.
@param from The number to start at (inclusive).
@param to The number to stop at (inclusive).
@return A DataSet, containing all number in the {@code [from, to]} interval. | [
"Creates",
"a",
"new",
"data",
"set",
"that",
"contains",
"a",
"sequence",
"of",
"numbers",
".",
"The",
"data",
"set",
"will",
"be",
"created",
"in",
"parallel",
"so",
"there",
"is",
"no",
"guarantee",
"about",
"the",
"oder",
"of",
"the",
"elements",
"."... | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-java/src/main/java/eu/stratosphere/api/java/ExecutionEnvironment.java#L494-L496 |
anotheria/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java | BaseAJAXMoskitoUIAction.invokeExecute | protected void invokeExecute(final ActionMapping mapping, final FormBean bean, final HttpServletRequest req, final HttpServletResponse res, final JSONResponse jsonResponse)
throws Exception {
"""
Override this method for invoking main action code.
@param mapping
- action mapping
@param bean
- bean
@param req
- request
@param res
- response
@param jsonResponse
- JSON Response
@throws Exception on errors
"""
} | java | protected void invokeExecute(final ActionMapping mapping, final FormBean bean, final HttpServletRequest req, final HttpServletResponse res, final JSONResponse jsonResponse)
throws Exception {
} | [
"protected",
"void",
"invokeExecute",
"(",
"final",
"ActionMapping",
"mapping",
",",
"final",
"FormBean",
"bean",
",",
"final",
"HttpServletRequest",
"req",
",",
"final",
"HttpServletResponse",
"res",
",",
"final",
"JSONResponse",
"jsonResponse",
")",
"throws",
"Exc... | Override this method for invoking main action code.
@param mapping
- action mapping
@param bean
- bean
@param req
- request
@param res
- response
@param jsonResponse
- JSON Response
@throws Exception on errors | [
"Override",
"this",
"method",
"for",
"invoking",
"main",
"action",
"code",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java#L83-L86 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java | WSRdbManagedConnectionImpl.addHandle | private final void addHandle(WSJdbcConnection handle) throws ResourceException {
"""
Add a handle to this ManagedConnection's list of handles.
Signal the JDBC 4.3+ driver that a request is starting.
@param handle the handle to add.
@throws ResourceException if a JDBC 4.3+ driver rejects the beginRequest operation
"""
(numHandlesInUse < handlesInUse.length - 1 ? handlesInUse : resizeHandleList())[numHandlesInUse++] = handle;
if (!inRequest && dsConfig.get().enableBeginEndRequest)
try {
inRequest = true;
mcf.jdbcRuntime.beginRequest(sqlConn);
} catch (SQLException x) {
FFDCFilter.processException(x, getClass().getName(), "548", this);
throw new DataStoreAdapterException("DSA_ERROR", x, getClass());
}
} | java | private final void addHandle(WSJdbcConnection handle) throws ResourceException {
(numHandlesInUse < handlesInUse.length - 1 ? handlesInUse : resizeHandleList())[numHandlesInUse++] = handle;
if (!inRequest && dsConfig.get().enableBeginEndRequest)
try {
inRequest = true;
mcf.jdbcRuntime.beginRequest(sqlConn);
} catch (SQLException x) {
FFDCFilter.processException(x, getClass().getName(), "548", this);
throw new DataStoreAdapterException("DSA_ERROR", x, getClass());
}
} | [
"private",
"final",
"void",
"addHandle",
"(",
"WSJdbcConnection",
"handle",
")",
"throws",
"ResourceException",
"{",
"(",
"numHandlesInUse",
"<",
"handlesInUse",
".",
"length",
"-",
"1",
"?",
"handlesInUse",
":",
"resizeHandleList",
"(",
")",
")",
"[",
"numHandl... | Add a handle to this ManagedConnection's list of handles.
Signal the JDBC 4.3+ driver that a request is starting.
@param handle the handle to add.
@throws ResourceException if a JDBC 4.3+ driver rejects the beginRequest operation | [
"Add",
"a",
"handle",
"to",
"this",
"ManagedConnection",
"s",
"list",
"of",
"handles",
".",
"Signal",
"the",
"JDBC",
"4",
".",
"3",
"+",
"driver",
"that",
"a",
"request",
"is",
"starting",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/WSRdbManagedConnectionImpl.java#L547-L557 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/SelfAssignment.java | SelfAssignment.describeForAssignment | public Description describeForAssignment(AssignmentTree assignmentTree, VisitorState state) {
"""
We expect that the lhs is a field and the rhs is an identifier, specifically a parameter to the
method. We base our suggested fixes on this expectation.
<p>Case 1: If lhs is a field and rhs is an identifier, find a method parameter of the same type
and similar name and suggest it as the rhs. (Guess that they have misspelled the identifier.)
<p>Case 2: If lhs is a field and rhs is not an identifier, find a method parameter of the same
type and similar name and suggest it as the rhs.
<p>Case 3: If lhs is not a field and rhs is an identifier, find a class field of the same type
and similar name and suggest it as the lhs.
<p>Case 4: Otherwise suggest deleting the assignment.
"""
// the statement that is the parent of the self-assignment expression
Tree parent = state.getPath().getParentPath().getLeaf();
// default fix is to delete assignment
Fix fix = SuggestedFix.delete(parent);
ExpressionTree lhs = assignmentTree.getVariable();
ExpressionTree rhs = assignmentTree.getExpression();
// if this is a method invocation, they must be calling checkNotNull()
if (assignmentTree.getExpression().getKind() == METHOD_INVOCATION) {
// change the default fix to be "checkNotNull(x)" instead of "x = checkNotNull(x)"
fix = SuggestedFix.replace(assignmentTree, state.getSourceForNode(rhs));
// new rhs is first argument to checkNotNull()
rhs = stripNullCheck(rhs, state);
}
rhs = skipCast(rhs);
ImmutableList<Fix> exploratoryFieldFixes = ImmutableList.of();
if (lhs.getKind() == MEMBER_SELECT) {
// find a method parameter of the same type and similar name and suggest it
// as the rhs
// rhs should be either identifier or field access
Preconditions.checkState(rhs.getKind() == IDENTIFIER || rhs.getKind() == MEMBER_SELECT);
Type rhsType = ASTHelpers.getType(rhs);
exploratoryFieldFixes =
ReplacementVariableFinder.fixesByReplacingExpressionWithMethodParameter(
rhs, varDecl -> ASTHelpers.isSameType(rhsType, varDecl.type, state), state);
} else if (rhs.getKind() == IDENTIFIER) {
// find a field of the same type and similar name and suggest it as the lhs
// lhs should be identifier
Preconditions.checkState(lhs.getKind() == IDENTIFIER);
Type lhsType = ASTHelpers.getType(lhs);
exploratoryFieldFixes =
ReplacementVariableFinder.fixesByReplacingExpressionWithLocallyDeclaredField(
lhs,
var ->
!Flags.isStatic(var.sym)
&& (var.sym.flags() & Flags.FINAL) == 0
&& ASTHelpers.isSameType(lhsType, var.type, state),
state);
}
if (exploratoryFieldFixes.isEmpty()) {
return describeMatch(assignmentTree, fix);
}
return buildDescription(assignmentTree).addAllFixes(exploratoryFieldFixes).build();
} | java | public Description describeForAssignment(AssignmentTree assignmentTree, VisitorState state) {
// the statement that is the parent of the self-assignment expression
Tree parent = state.getPath().getParentPath().getLeaf();
// default fix is to delete assignment
Fix fix = SuggestedFix.delete(parent);
ExpressionTree lhs = assignmentTree.getVariable();
ExpressionTree rhs = assignmentTree.getExpression();
// if this is a method invocation, they must be calling checkNotNull()
if (assignmentTree.getExpression().getKind() == METHOD_INVOCATION) {
// change the default fix to be "checkNotNull(x)" instead of "x = checkNotNull(x)"
fix = SuggestedFix.replace(assignmentTree, state.getSourceForNode(rhs));
// new rhs is first argument to checkNotNull()
rhs = stripNullCheck(rhs, state);
}
rhs = skipCast(rhs);
ImmutableList<Fix> exploratoryFieldFixes = ImmutableList.of();
if (lhs.getKind() == MEMBER_SELECT) {
// find a method parameter of the same type and similar name and suggest it
// as the rhs
// rhs should be either identifier or field access
Preconditions.checkState(rhs.getKind() == IDENTIFIER || rhs.getKind() == MEMBER_SELECT);
Type rhsType = ASTHelpers.getType(rhs);
exploratoryFieldFixes =
ReplacementVariableFinder.fixesByReplacingExpressionWithMethodParameter(
rhs, varDecl -> ASTHelpers.isSameType(rhsType, varDecl.type, state), state);
} else if (rhs.getKind() == IDENTIFIER) {
// find a field of the same type and similar name and suggest it as the lhs
// lhs should be identifier
Preconditions.checkState(lhs.getKind() == IDENTIFIER);
Type lhsType = ASTHelpers.getType(lhs);
exploratoryFieldFixes =
ReplacementVariableFinder.fixesByReplacingExpressionWithLocallyDeclaredField(
lhs,
var ->
!Flags.isStatic(var.sym)
&& (var.sym.flags() & Flags.FINAL) == 0
&& ASTHelpers.isSameType(lhsType, var.type, state),
state);
}
if (exploratoryFieldFixes.isEmpty()) {
return describeMatch(assignmentTree, fix);
}
return buildDescription(assignmentTree).addAllFixes(exploratoryFieldFixes).build();
} | [
"public",
"Description",
"describeForAssignment",
"(",
"AssignmentTree",
"assignmentTree",
",",
"VisitorState",
"state",
")",
"{",
"// the statement that is the parent of the self-assignment expression",
"Tree",
"parent",
"=",
"state",
".",
"getPath",
"(",
")",
".",
"getPar... | We expect that the lhs is a field and the rhs is an identifier, specifically a parameter to the
method. We base our suggested fixes on this expectation.
<p>Case 1: If lhs is a field and rhs is an identifier, find a method parameter of the same type
and similar name and suggest it as the rhs. (Guess that they have misspelled the identifier.)
<p>Case 2: If lhs is a field and rhs is not an identifier, find a method parameter of the same
type and similar name and suggest it as the rhs.
<p>Case 3: If lhs is not a field and rhs is an identifier, find a class field of the same type
and similar name and suggest it as the lhs.
<p>Case 4: Otherwise suggest deleting the assignment. | [
"We",
"expect",
"that",
"the",
"lhs",
"is",
"a",
"field",
"and",
"the",
"rhs",
"is",
"an",
"identifier",
"specifically",
"a",
"parameter",
"to",
"the",
"method",
".",
"We",
"base",
"our",
"suggested",
"fixes",
"on",
"this",
"expectation",
"."
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/SelfAssignment.java#L168-L221 |
apereo/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/ticket/BaseIdTokenGeneratorService.java | BaseIdTokenGeneratorService.getAuthenticatedProfile | protected CommonProfile getAuthenticatedProfile(final HttpServletRequest request, final HttpServletResponse response) {
"""
Gets authenticated profile.
@param request the request
@param response the response
@return the authenticated profile
"""
val context = new J2EContext(request, response, getConfigurationContext().getSessionStore());
val manager = new ProfileManager<>(context, context.getSessionStore());
val profile = manager.get(true);
if (profile.isEmpty()) {
throw new IllegalArgumentException("Unable to determine the user profile from the context");
}
return profile.get();
} | java | protected CommonProfile getAuthenticatedProfile(final HttpServletRequest request, final HttpServletResponse response) {
val context = new J2EContext(request, response, getConfigurationContext().getSessionStore());
val manager = new ProfileManager<>(context, context.getSessionStore());
val profile = manager.get(true);
if (profile.isEmpty()) {
throw new IllegalArgumentException("Unable to determine the user profile from the context");
}
return profile.get();
} | [
"protected",
"CommonProfile",
"getAuthenticatedProfile",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
")",
"{",
"val",
"context",
"=",
"new",
"J2EContext",
"(",
"request",
",",
"response",
",",
"getConfigurationContext"... | Gets authenticated profile.
@param request the request
@param response the response
@return the authenticated profile | [
"Gets",
"authenticated",
"profile",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/ticket/BaseIdTokenGeneratorService.java#L38-L47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.