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
|
---|---|---|---|---|---|---|---|---|---|---|
jenkinsci/artifactory-plugin
|
src/main/java/org/jfrog/hudson/util/publisher/PublisherFlexible.java
|
PublisherFlexible.isPublisherWrapped
|
public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {
"""
Determines whether a project has the specified publisher type, wrapped by the "Flexible Publish" publisher.
@param project The project
@param type The type of the publisher
@return true if the project contains a publisher of the specified type wrapped by the "Flexible Publish" publisher.
"""
return find(project, type) != null;
}
|
java
|
public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) {
return find(project, type) != null;
}
|
[
"public",
"boolean",
"isPublisherWrapped",
"(",
"AbstractProject",
"<",
"?",
",",
"?",
">",
"project",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"find",
"(",
"project",
",",
"type",
")",
"!=",
"null",
";",
"}"
] |
Determines whether a project has the specified publisher type, wrapped by the "Flexible Publish" publisher.
@param project The project
@param type The type of the publisher
@return true if the project contains a publisher of the specified type wrapped by the "Flexible Publish" publisher.
|
[
"Determines",
"whether",
"a",
"project",
"has",
"the",
"specified",
"publisher",
"type",
"wrapped",
"by",
"the",
"Flexible",
"Publish",
"publisher",
"."
] |
train
|
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/publisher/PublisherFlexible.java#L76-L78
|
osmdroid/osmdroid
|
osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java
|
SphericalUtil.computeOffset
|
public static IGeoPoint computeOffset(IGeoPoint from, double distance, double heading) {
"""
Returns the LatLng resulting from moving a distance from an origin
in the specified heading (expressed in degrees clockwise from north).
@param from The LatLng from which to start.
@param distance The distance to travel.
@param heading The heading in degrees clockwise from north.
"""
distance /= EARTH_RADIUS;
heading = toRadians(heading);
// http://williams.best.vwh.net/avform.htm#LL
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double cosDistance = cos(distance);
double sinDistance = sin(distance);
double sinFromLat = sin(fromLat);
double cosFromLat = cos(fromLat);
double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * cos(heading);
double dLng = atan2(
sinDistance * cosFromLat * sin(heading),
cosDistance - sinFromLat * sinLat);
return new GeoPoint(toDegrees(asin(sinLat)), toDegrees(fromLng + dLng));
}
|
java
|
public static IGeoPoint computeOffset(IGeoPoint from, double distance, double heading) {
distance /= EARTH_RADIUS;
heading = toRadians(heading);
// http://williams.best.vwh.net/avform.htm#LL
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double cosDistance = cos(distance);
double sinDistance = sin(distance);
double sinFromLat = sin(fromLat);
double cosFromLat = cos(fromLat);
double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * cos(heading);
double dLng = atan2(
sinDistance * cosFromLat * sin(heading),
cosDistance - sinFromLat * sinLat);
return new GeoPoint(toDegrees(asin(sinLat)), toDegrees(fromLng + dLng));
}
|
[
"public",
"static",
"IGeoPoint",
"computeOffset",
"(",
"IGeoPoint",
"from",
",",
"double",
"distance",
",",
"double",
"heading",
")",
"{",
"distance",
"/=",
"EARTH_RADIUS",
";",
"heading",
"=",
"toRadians",
"(",
"heading",
")",
";",
"// http://williams.best.vwh.net/avform.htm#LL",
"double",
"fromLat",
"=",
"toRadians",
"(",
"from",
".",
"getLatitude",
"(",
")",
")",
";",
"double",
"fromLng",
"=",
"toRadians",
"(",
"from",
".",
"getLongitude",
"(",
")",
")",
";",
"double",
"cosDistance",
"=",
"cos",
"(",
"distance",
")",
";",
"double",
"sinDistance",
"=",
"sin",
"(",
"distance",
")",
";",
"double",
"sinFromLat",
"=",
"sin",
"(",
"fromLat",
")",
";",
"double",
"cosFromLat",
"=",
"cos",
"(",
"fromLat",
")",
";",
"double",
"sinLat",
"=",
"cosDistance",
"*",
"sinFromLat",
"+",
"sinDistance",
"*",
"cosFromLat",
"*",
"cos",
"(",
"heading",
")",
";",
"double",
"dLng",
"=",
"atan2",
"(",
"sinDistance",
"*",
"cosFromLat",
"*",
"sin",
"(",
"heading",
")",
",",
"cosDistance",
"-",
"sinFromLat",
"*",
"sinLat",
")",
";",
"return",
"new",
"GeoPoint",
"(",
"toDegrees",
"(",
"asin",
"(",
"sinLat",
")",
")",
",",
"toDegrees",
"(",
"fromLng",
"+",
"dLng",
")",
")",
";",
"}"
] |
Returns the LatLng resulting from moving a distance from an origin
in the specified heading (expressed in degrees clockwise from north).
@param from The LatLng from which to start.
@param distance The distance to travel.
@param heading The heading in degrees clockwise from north.
|
[
"Returns",
"the",
"LatLng",
"resulting",
"from",
"moving",
"a",
"distance",
"from",
"an",
"origin",
"in",
"the",
"specified",
"heading",
"(",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"north",
")",
"."
] |
train
|
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L156-L171
|
zafarkhaja/jsemver
|
src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java
|
ExpressionParser.parseWildcardRange
|
private CompositeExpression parseWildcardRange() {
"""
Parses the {@literal <wildcard-range>} non-terminal.
<pre>
{@literal
<wildcard-range> ::= <wildcard>
| <major> "." <wildcard>
| <major> "." <minor> "." <wildcard>
<wildcard> ::= "*" | "x" | "X"
}
</pre>
@return the expression AST
"""
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(0, 0, 0));
}
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(major)).and(lt(versionFor(major + 1)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(WILDCARD);
return gte(versionFor(major, minor)).and(lt(versionFor(major, minor + 1)));
}
|
java
|
private CompositeExpression parseWildcardRange() {
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(0, 0, 0));
}
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(major)).and(lt(versionFor(major + 1)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(WILDCARD);
return gte(versionFor(major, minor)).and(lt(versionFor(major, minor + 1)));
}
|
[
"private",
"CompositeExpression",
"parseWildcardRange",
"(",
")",
"{",
"if",
"(",
"tokens",
".",
"positiveLookahead",
"(",
"WILDCARD",
")",
")",
"{",
"tokens",
".",
"consume",
"(",
")",
";",
"return",
"gte",
"(",
"versionFor",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
";",
"}",
"int",
"major",
"=",
"intOf",
"(",
"consumeNextToken",
"(",
"NUMERIC",
")",
".",
"lexeme",
")",
";",
"consumeNextToken",
"(",
"DOT",
")",
";",
"if",
"(",
"tokens",
".",
"positiveLookahead",
"(",
"WILDCARD",
")",
")",
"{",
"tokens",
".",
"consume",
"(",
")",
";",
"return",
"gte",
"(",
"versionFor",
"(",
"major",
")",
")",
".",
"and",
"(",
"lt",
"(",
"versionFor",
"(",
"major",
"+",
"1",
")",
")",
")",
";",
"}",
"int",
"minor",
"=",
"intOf",
"(",
"consumeNextToken",
"(",
"NUMERIC",
")",
".",
"lexeme",
")",
";",
"consumeNextToken",
"(",
"DOT",
")",
";",
"consumeNextToken",
"(",
"WILDCARD",
")",
";",
"return",
"gte",
"(",
"versionFor",
"(",
"major",
",",
"minor",
")",
")",
".",
"and",
"(",
"lt",
"(",
"versionFor",
"(",
"major",
",",
"minor",
"+",
"1",
")",
")",
")",
";",
"}"
] |
Parses the {@literal <wildcard-range>} non-terminal.
<pre>
{@literal
<wildcard-range> ::= <wildcard>
| <major> "." <wildcard>
| <major> "." <minor> "." <wildcard>
<wildcard> ::= "*" | "x" | "X"
}
</pre>
@return the expression AST
|
[
"Parses",
"the",
"{",
"@literal",
"<wildcard",
"-",
"range",
">",
"}",
"non",
"-",
"terminal",
"."
] |
train
|
https://github.com/zafarkhaja/jsemver/blob/1f4996ea3dab06193c378fd66fd4f8fdc8334cc6/src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java#L314-L331
|
alkacon/opencms-core
|
src/org/opencms/db/CmsDriverManager.java
|
CmsDriverManager.getRoleGroups
|
public Set<CmsGroup> getRoleGroups(CmsDbContext dbc, String roleGroupName, boolean directUsersOnly)
throws CmsException {
"""
Collects the groups which constitute a given role.<p>
@param dbc the database context
@param roleGroupName the group related to the role
@param directUsersOnly if true, only the group belonging to the entry itself wil
@return the set of groups which constitute the role
@throws CmsException if something goes wrong
"""
return getRoleGroupsImpl(dbc, roleGroupName, directUsersOnly, new HashMap<String, Set<CmsGroup>>());
}
|
java
|
public Set<CmsGroup> getRoleGroups(CmsDbContext dbc, String roleGroupName, boolean directUsersOnly)
throws CmsException {
return getRoleGroupsImpl(dbc, roleGroupName, directUsersOnly, new HashMap<String, Set<CmsGroup>>());
}
|
[
"public",
"Set",
"<",
"CmsGroup",
">",
"getRoleGroups",
"(",
"CmsDbContext",
"dbc",
",",
"String",
"roleGroupName",
",",
"boolean",
"directUsersOnly",
")",
"throws",
"CmsException",
"{",
"return",
"getRoleGroupsImpl",
"(",
"dbc",
",",
"roleGroupName",
",",
"directUsersOnly",
",",
"new",
"HashMap",
"<",
"String",
",",
"Set",
"<",
"CmsGroup",
">",
">",
"(",
")",
")",
";",
"}"
] |
Collects the groups which constitute a given role.<p>
@param dbc the database context
@param roleGroupName the group related to the role
@param directUsersOnly if true, only the group belonging to the entry itself wil
@return the set of groups which constitute the role
@throws CmsException if something goes wrong
|
[
"Collects",
"the",
"groups",
"which",
"constitute",
"a",
"given",
"role",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L4617-L4621
|
j-a-w-r/jawr-main-repo
|
jawr-grails/jawr-grails-plugin/src/java/net/jawr/web/resource/bundle/locale/GrailsLocaleUtils.java
|
GrailsLocaleUtils.toBundleName
|
public static String toBundleName(String bundleBaseName, Locale locale) {
"""
Converts the given <code>baseName</code> and <code>locale</code> to the
bundle name. This method is called from the default implementation of the
{@link #newBundle(String, Locale, String, ClassLoader, boolean)
newBundle} and
{@link #needsReload(String, Locale, String, ClassLoader, ResourceBundle, long)
needsReload} methods.
<p>
This implementation returns the following value:
<pre>
baseName + "_" + language + "_" + country + "_" + variant
</pre>
where <code>language</code>, <code>country</code> and
<code>variant</code> are the language, country and variant values of
<code>locale</code>, respectively. Final component values that are empty
Strings are omitted along with the preceding '_'. If all of the values
are empty strings, then <code>baseName</code> is returned.
<p>
For example, if <code>baseName</code> is <code>"baseName"</code> and
<code>locale</code> is <code>Locale("ja", "", "XX")</code>,
then <code>"baseName_ja_ _XX"</code> is returned. If the given
locale is <code>Locale("en")</code>, then <code>"baseName_en"</code> is
returned.
<p>
Overriding this method allows applications to use different conventions
in the organization and packaging of localized resources.
@param baseName
the base name of the resource bundle, a fully qualified class
name
@param locale
the locale for which a resource bundle should be loaded
@return the bundle name for the resource bundle
@exception NullPointerException
if <code>baseName</code> or <code>locale</code> is
<code>null</code>
"""
String baseName = bundleBaseName;
if (!isPluginResoucePath(bundleBaseName)) {
baseName = bundleBaseName.replace('.', '/');
}
if (locale == null) {
return baseName;
}
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (language == "" && country == "" && variant == "") {
return baseName;
}
StringBuffer sb = new StringBuffer(baseName);
sb.append('_');
if (variant != "") {
sb.append(language).append('_').append(country).append('_')
.append(variant);
} else if (country != "") {
sb.append(language).append('_').append(country);
} else {
sb.append(language);
}
return sb.toString();
}
|
java
|
public static String toBundleName(String bundleBaseName, Locale locale) {
String baseName = bundleBaseName;
if (!isPluginResoucePath(bundleBaseName)) {
baseName = bundleBaseName.replace('.', '/');
}
if (locale == null) {
return baseName;
}
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (language == "" && country == "" && variant == "") {
return baseName;
}
StringBuffer sb = new StringBuffer(baseName);
sb.append('_');
if (variant != "") {
sb.append(language).append('_').append(country).append('_')
.append(variant);
} else if (country != "") {
sb.append(language).append('_').append(country);
} else {
sb.append(language);
}
return sb.toString();
}
|
[
"public",
"static",
"String",
"toBundleName",
"(",
"String",
"bundleBaseName",
",",
"Locale",
"locale",
")",
"{",
"String",
"baseName",
"=",
"bundleBaseName",
";",
"if",
"(",
"!",
"isPluginResoucePath",
"(",
"bundleBaseName",
")",
")",
"{",
"baseName",
"=",
"bundleBaseName",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"}",
"if",
"(",
"locale",
"==",
"null",
")",
"{",
"return",
"baseName",
";",
"}",
"String",
"language",
"=",
"locale",
".",
"getLanguage",
"(",
")",
";",
"String",
"country",
"=",
"locale",
".",
"getCountry",
"(",
")",
";",
"String",
"variant",
"=",
"locale",
".",
"getVariant",
"(",
")",
";",
"if",
"(",
"language",
"==",
"\"\"",
"&&",
"country",
"==",
"\"\"",
"&&",
"variant",
"==",
"\"\"",
")",
"{",
"return",
"baseName",
";",
"}",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"baseName",
")",
";",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"if",
"(",
"variant",
"!=",
"\"\"",
")",
"{",
"sb",
".",
"append",
"(",
"language",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"country",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"variant",
")",
";",
"}",
"else",
"if",
"(",
"country",
"!=",
"\"\"",
")",
"{",
"sb",
".",
"append",
"(",
"language",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"country",
")",
";",
"}",
"else",
"{",
"sb",
".",
"append",
"(",
"language",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Converts the given <code>baseName</code> and <code>locale</code> to the
bundle name. This method is called from the default implementation of the
{@link #newBundle(String, Locale, String, ClassLoader, boolean)
newBundle} and
{@link #needsReload(String, Locale, String, ClassLoader, ResourceBundle, long)
needsReload} methods.
<p>
This implementation returns the following value:
<pre>
baseName + "_" + language + "_" + country + "_" + variant
</pre>
where <code>language</code>, <code>country</code> and
<code>variant</code> are the language, country and variant values of
<code>locale</code>, respectively. Final component values that are empty
Strings are omitted along with the preceding '_'. If all of the values
are empty strings, then <code>baseName</code> is returned.
<p>
For example, if <code>baseName</code> is <code>"baseName"</code> and
<code>locale</code> is <code>Locale("ja", "", "XX")</code>,
then <code>"baseName_ja_ _XX"</code> is returned. If the given
locale is <code>Locale("en")</code>, then <code>"baseName_en"</code> is
returned.
<p>
Overriding this method allows applications to use different conventions
in the organization and packaging of localized resources.
@param baseName
the base name of the resource bundle, a fully qualified class
name
@param locale
the locale for which a resource bundle should be loaded
@return the bundle name for the resource bundle
@exception NullPointerException
if <code>baseName</code> or <code>locale</code> is
<code>null</code>
|
[
"Converts",
"the",
"given",
"<code",
">",
"baseName<",
"/",
"code",
">",
"and",
"<code",
">",
"locale<",
"/",
"code",
">",
"to",
"the",
"bundle",
"name",
".",
"This",
"method",
"is",
"called",
"from",
"the",
"default",
"implementation",
"of",
"the",
"{",
"@link",
"#newBundle",
"(",
"String",
"Locale",
"String",
"ClassLoader",
"boolean",
")",
"newBundle",
"}",
"and",
"{",
"@link",
"#needsReload",
"(",
"String",
"Locale",
"String",
"ClassLoader",
"ResourceBundle",
"long",
")",
"needsReload",
"}",
"methods",
"."
] |
train
|
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr-grails/jawr-grails-plugin/src/java/net/jawr/web/resource/bundle/locale/GrailsLocaleUtils.java#L278-L307
|
eclipse/xtext-extras
|
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/XbaseTypeComputer.java
|
XbaseTypeComputer.reassignCheckedType
|
protected ITypeComputationState reassignCheckedType(XExpression condition, /* @Nullable */ XExpression guardedExpression, ITypeComputationState state) {
"""
If the condition is a {@link XInstanceOfExpression type check}, the checked expression
will be automatically casted in the returned state.
"""
if (condition instanceof XInstanceOfExpression) {
XInstanceOfExpression instanceOfExpression = (XInstanceOfExpression) condition;
JvmTypeReference castedType = instanceOfExpression.getType();
if (castedType != null) {
state = state.withTypeCheckpoint(guardedExpression);
JvmIdentifiableElement refinable = getRefinableCandidate(instanceOfExpression.getExpression(), state);
if (refinable != null) {
state.reassignType(refinable, state.getReferenceOwner().toLightweightTypeReference(castedType));
}
}
}
return state;
}
|
java
|
protected ITypeComputationState reassignCheckedType(XExpression condition, /* @Nullable */ XExpression guardedExpression, ITypeComputationState state) {
if (condition instanceof XInstanceOfExpression) {
XInstanceOfExpression instanceOfExpression = (XInstanceOfExpression) condition;
JvmTypeReference castedType = instanceOfExpression.getType();
if (castedType != null) {
state = state.withTypeCheckpoint(guardedExpression);
JvmIdentifiableElement refinable = getRefinableCandidate(instanceOfExpression.getExpression(), state);
if (refinable != null) {
state.reassignType(refinable, state.getReferenceOwner().toLightweightTypeReference(castedType));
}
}
}
return state;
}
|
[
"protected",
"ITypeComputationState",
"reassignCheckedType",
"(",
"XExpression",
"condition",
",",
"/* @Nullable */",
"XExpression",
"guardedExpression",
",",
"ITypeComputationState",
"state",
")",
"{",
"if",
"(",
"condition",
"instanceof",
"XInstanceOfExpression",
")",
"{",
"XInstanceOfExpression",
"instanceOfExpression",
"=",
"(",
"XInstanceOfExpression",
")",
"condition",
";",
"JvmTypeReference",
"castedType",
"=",
"instanceOfExpression",
".",
"getType",
"(",
")",
";",
"if",
"(",
"castedType",
"!=",
"null",
")",
"{",
"state",
"=",
"state",
".",
"withTypeCheckpoint",
"(",
"guardedExpression",
")",
";",
"JvmIdentifiableElement",
"refinable",
"=",
"getRefinableCandidate",
"(",
"instanceOfExpression",
".",
"getExpression",
"(",
")",
",",
"state",
")",
";",
"if",
"(",
"refinable",
"!=",
"null",
")",
"{",
"state",
".",
"reassignType",
"(",
"refinable",
",",
"state",
".",
"getReferenceOwner",
"(",
")",
".",
"toLightweightTypeReference",
"(",
"castedType",
")",
")",
";",
"}",
"}",
"}",
"return",
"state",
";",
"}"
] |
If the condition is a {@link XInstanceOfExpression type check}, the checked expression
will be automatically casted in the returned state.
|
[
"If",
"the",
"condition",
"is",
"a",
"{"
] |
train
|
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/XbaseTypeComputer.java#L279-L292
|
pip-services3-java/pip-services3-components-java
|
src/org/pipservices3/components/config/JsonConfigReader.java
|
JsonConfigReader.readConfig
|
@Override
public ConfigParams readConfig(String correlationId, ConfigParams parameters) throws ApplicationException {
"""
Reads configuration and parameterize it with given values.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param parameters values to parameters the configuration
@return ConfigParams configuration.
@throws ApplicationException when error occured.
"""
Object value = readObject(correlationId, parameters);
return ConfigParams.fromValue(value);
}
|
java
|
@Override
public ConfigParams readConfig(String correlationId, ConfigParams parameters) throws ApplicationException {
Object value = readObject(correlationId, parameters);
return ConfigParams.fromValue(value);
}
|
[
"@",
"Override",
"public",
"ConfigParams",
"readConfig",
"(",
"String",
"correlationId",
",",
"ConfigParams",
"parameters",
")",
"throws",
"ApplicationException",
"{",
"Object",
"value",
"=",
"readObject",
"(",
"correlationId",
",",
"parameters",
")",
";",
"return",
"ConfigParams",
".",
"fromValue",
"(",
"value",
")",
";",
"}"
] |
Reads configuration and parameterize it with given values.
@param correlationId (optional) transaction id to trace execution through
call chain.
@param parameters values to parameters the configuration
@return ConfigParams configuration.
@throws ApplicationException when error occured.
|
[
"Reads",
"configuration",
"and",
"parameterize",
"it",
"with",
"given",
"values",
"."
] |
train
|
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/config/JsonConfigReader.java#L98-L102
|
razorpay/razorpay-android-sample-app
|
app/src/main/java/com/razorpay/sampleapp/PaymentActivity.java
|
PaymentActivity.onPaymentError
|
@SuppressWarnings("unused")
@Override
public void onPaymentError(int code, String response) {
"""
The name of the function has to be
onPaymentError
Wrap your code in try catch, as shown, to ensure that this method runs correctly
"""
try {
Toast.makeText(this, "Payment failed: " + code + " " + response, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, "Exception in onPaymentError", e);
}
}
|
java
|
@SuppressWarnings("unused")
@Override
public void onPaymentError(int code, String response) {
try {
Toast.makeText(this, "Payment failed: " + code + " " + response, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, "Exception in onPaymentError", e);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"@",
"Override",
"public",
"void",
"onPaymentError",
"(",
"int",
"code",
",",
"String",
"response",
")",
"{",
"try",
"{",
"Toast",
".",
"makeText",
"(",
"this",
",",
"\"Payment failed: \"",
"+",
"code",
"+",
"\" \"",
"+",
"response",
",",
"Toast",
".",
"LENGTH_SHORT",
")",
".",
"show",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"Exception in onPaymentError\"",
",",
"e",
")",
";",
"}",
"}"
] |
The name of the function has to be
onPaymentError
Wrap your code in try catch, as shown, to ensure that this method runs correctly
|
[
"The",
"name",
"of",
"the",
"function",
"has",
"to",
"be",
"onPaymentError",
"Wrap",
"your",
"code",
"in",
"try",
"catch",
"as",
"shown",
"to",
"ensure",
"that",
"this",
"method",
"runs",
"correctly"
] |
train
|
https://github.com/razorpay/razorpay-android-sample-app/blob/d49c0da92e25dde71cc402867f37d51a1e02cf1a/app/src/main/java/com/razorpay/sampleapp/PaymentActivity.java#L92-L100
|
petrbouda/joyrest
|
joyrest-oauth2/src/main/java/org/joyrest/oauth2/BasicAuthenticator.java
|
BasicAuthenticator.extractAndDecodeHeader
|
private String[] extractAndDecodeHeader(String header) throws IOException {
"""
Decodes the header into a username and password.
@throws BadCredentialsException if the Basic header is not present or is not valid Base64
"""
byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET);
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
} catch (IllegalArgumentException e) {
throw new BadCredentialsException("Failed to decode basic authentication token");
}
String token = new String(decoded, CREDENTIALS_CHARSET);
int delim = token.indexOf(":");
if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
}
return new String[] {token.substring(0, delim), token.substring(delim + 1)};
}
|
java
|
private String[] extractAndDecodeHeader(String header) throws IOException {
byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET);
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
} catch (IllegalArgumentException e) {
throw new BadCredentialsException("Failed to decode basic authentication token");
}
String token = new String(decoded, CREDENTIALS_CHARSET);
int delim = token.indexOf(":");
if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
}
return new String[] {token.substring(0, delim), token.substring(delim + 1)};
}
|
[
"private",
"String",
"[",
"]",
"extractAndDecodeHeader",
"(",
"String",
"header",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"base64Token",
"=",
"header",
".",
"substring",
"(",
"6",
")",
".",
"getBytes",
"(",
"CREDENTIALS_CHARSET",
")",
";",
"byte",
"[",
"]",
"decoded",
";",
"try",
"{",
"decoded",
"=",
"Base64",
".",
"decode",
"(",
"base64Token",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"new",
"BadCredentialsException",
"(",
"\"Failed to decode basic authentication token\"",
")",
";",
"}",
"String",
"token",
"=",
"new",
"String",
"(",
"decoded",
",",
"CREDENTIALS_CHARSET",
")",
";",
"int",
"delim",
"=",
"token",
".",
"indexOf",
"(",
"\":\"",
")",
";",
"if",
"(",
"delim",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"BadCredentialsException",
"(",
"\"Invalid basic authentication token\"",
")",
";",
"}",
"return",
"new",
"String",
"[",
"]",
"{",
"token",
".",
"substring",
"(",
"0",
",",
"delim",
")",
",",
"token",
".",
"substring",
"(",
"delim",
"+",
"1",
")",
"}",
";",
"}"
] |
Decodes the header into a username and password.
@throws BadCredentialsException if the Basic header is not present or is not valid Base64
|
[
"Decodes",
"the",
"header",
"into",
"a",
"username",
"and",
"password",
"."
] |
train
|
https://github.com/petrbouda/joyrest/blob/58903f06fb7f0b8fdf1ef91318fb48a88bf970e0/joyrest-oauth2/src/main/java/org/joyrest/oauth2/BasicAuthenticator.java#L74-L92
|
apache/flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
|
EmbeddedLeaderService.addContender
|
private void addContender(EmbeddedLeaderElectionService service, LeaderContender contender) {
"""
Callback from leader contenders when they start their service.
"""
synchronized (lock) {
checkState(!shutdown, "leader election service is shut down");
checkState(!service.running, "leader election service is already started");
try {
if (!allLeaderContenders.add(service)) {
throw new IllegalStateException("leader election service was added to this service multiple times");
}
service.contender = contender;
service.running = true;
updateLeader().whenComplete((aVoid, throwable) -> {
if (throwable != null) {
fatalError(throwable);
}
});
}
catch (Throwable t) {
fatalError(t);
}
}
}
|
java
|
private void addContender(EmbeddedLeaderElectionService service, LeaderContender contender) {
synchronized (lock) {
checkState(!shutdown, "leader election service is shut down");
checkState(!service.running, "leader election service is already started");
try {
if (!allLeaderContenders.add(service)) {
throw new IllegalStateException("leader election service was added to this service multiple times");
}
service.contender = contender;
service.running = true;
updateLeader().whenComplete((aVoid, throwable) -> {
if (throwable != null) {
fatalError(throwable);
}
});
}
catch (Throwable t) {
fatalError(t);
}
}
}
|
[
"private",
"void",
"addContender",
"(",
"EmbeddedLeaderElectionService",
"service",
",",
"LeaderContender",
"contender",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"checkState",
"(",
"!",
"shutdown",
",",
"\"leader election service is shut down\"",
")",
";",
"checkState",
"(",
"!",
"service",
".",
"running",
",",
"\"leader election service is already started\"",
")",
";",
"try",
"{",
"if",
"(",
"!",
"allLeaderContenders",
".",
"add",
"(",
"service",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"leader election service was added to this service multiple times\"",
")",
";",
"}",
"service",
".",
"contender",
"=",
"contender",
";",
"service",
".",
"running",
"=",
"true",
";",
"updateLeader",
"(",
")",
".",
"whenComplete",
"(",
"(",
"aVoid",
",",
"throwable",
")",
"->",
"{",
"if",
"(",
"throwable",
"!=",
"null",
")",
"{",
"fatalError",
"(",
"throwable",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"fatalError",
"(",
"t",
")",
";",
"}",
"}",
"}"
] |
Callback from leader contenders when they start their service.
|
[
"Callback",
"from",
"leader",
"contenders",
"when",
"they",
"start",
"their",
"service",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java#L168-L191
|
google/closure-templates
|
java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java
|
GoogRequire.createWithAlias
|
public static GoogRequire createWithAlias(String symbol, String alias) {
"""
Creates a new {@code GoogRequire} that requires the given symbol and aliases it to the given
name: {@code var alias = goog.require('symbol'); }
"""
CodeChunkUtils.checkId(alias);
return new AutoValue_GoogRequire(
symbol,
VariableDeclaration.builder(alias).setRhs(GOOG_REQUIRE.call(stringLiteral(symbol))).build(),
/*isTypeRequire=*/ false);
}
|
java
|
public static GoogRequire createWithAlias(String symbol, String alias) {
CodeChunkUtils.checkId(alias);
return new AutoValue_GoogRequire(
symbol,
VariableDeclaration.builder(alias).setRhs(GOOG_REQUIRE.call(stringLiteral(symbol))).build(),
/*isTypeRequire=*/ false);
}
|
[
"public",
"static",
"GoogRequire",
"createWithAlias",
"(",
"String",
"symbol",
",",
"String",
"alias",
")",
"{",
"CodeChunkUtils",
".",
"checkId",
"(",
"alias",
")",
";",
"return",
"new",
"AutoValue_GoogRequire",
"(",
"symbol",
",",
"VariableDeclaration",
".",
"builder",
"(",
"alias",
")",
".",
"setRhs",
"(",
"GOOG_REQUIRE",
".",
"call",
"(",
"stringLiteral",
"(",
"symbol",
")",
")",
")",
".",
"build",
"(",
")",
",",
"/*isTypeRequire=*/",
"false",
")",
";",
"}"
] |
Creates a new {@code GoogRequire} that requires the given symbol and aliases it to the given
name: {@code var alias = goog.require('symbol'); }
|
[
"Creates",
"a",
"new",
"{"
] |
train
|
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/GoogRequire.java#L58-L64
|
ocelotds/ocelot
|
ocelot-processor/src/main/java/org/ocelotds/FileWriterServices.java
|
FileWriterServices.getFileObjectWriter
|
public Writer getFileObjectWriter(String path, String filename) throws IOException {
"""
Create writer from file path/filename
@param path
@param filename
@return
@throws IOException
"""
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return new FileWriter(new File(dir, filename));
}
|
java
|
public Writer getFileObjectWriter(String path, String filename) throws IOException {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return new FileWriter(new File(dir, filename));
}
|
[
"public",
"Writer",
"getFileObjectWriter",
"(",
"String",
"path",
",",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"File",
"dir",
"=",
"new",
"File",
"(",
"path",
")",
";",
"if",
"(",
"!",
"dir",
".",
"exists",
"(",
")",
")",
"{",
"dir",
".",
"mkdirs",
"(",
")",
";",
"}",
"return",
"new",
"FileWriter",
"(",
"new",
"File",
"(",
"dir",
",",
"filename",
")",
")",
";",
"}"
] |
Create writer from file path/filename
@param path
@param filename
@return
@throws IOException
|
[
"Create",
"writer",
"from",
"file",
"path",
"/",
"filename"
] |
train
|
https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-processor/src/main/java/org/ocelotds/FileWriterServices.java#L87-L93
|
spotify/crtauth-java
|
src/main/java/com/spotify/crtauth/CrtAuthServer.java
|
CrtAuthServer.createFakeFingerprint
|
private Fingerprint createFakeFingerprint(String userName) {
"""
Generate a fake real looking fingerprint for a non-existent user.
@param userName the username to seed the transform with
@return a Fingerprint with bytes that are a function of username and secret
"""
byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode(
this.secret, userName.getBytes(Charsets.UTF_8));
return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6));
}
|
java
|
private Fingerprint createFakeFingerprint(String userName) {
byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode(
this.secret, userName.getBytes(Charsets.UTF_8));
return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6));
}
|
[
"private",
"Fingerprint",
"createFakeFingerprint",
"(",
"String",
"userName",
")",
"{",
"byte",
"[",
"]",
"usernameHmac",
"=",
"CrtAuthCodec",
".",
"getAuthenticationCode",
"(",
"this",
".",
"secret",
",",
"userName",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"return",
"new",
"Fingerprint",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"usernameHmac",
",",
"0",
",",
"6",
")",
")",
";",
"}"
] |
Generate a fake real looking fingerprint for a non-existent user.
@param userName the username to seed the transform with
@return a Fingerprint with bytes that are a function of username and secret
|
[
"Generate",
"a",
"fake",
"real",
"looking",
"fingerprint",
"for",
"a",
"non",
"-",
"existent",
"user",
"."
] |
train
|
https://github.com/spotify/crtauth-java/blob/90f3b40323848740c915b195ad1b547fbeb41700/src/main/java/com/spotify/crtauth/CrtAuthServer.java#L248-L252
|
h2oai/h2o-2
|
src/main/java/water/Job.java
|
Job.waitUntilJobEnded
|
public static void waitUntilJobEnded(Key jobkey, int pollingIntervalMillis) {
"""
Block synchronously waiting for a job to end, success or not.
@param jobkey Job to wait for.
@param pollingIntervalMillis Polling interval sleep time.
"""
while (true) {
if (Job.isEnded(jobkey)) {
return;
}
try { Thread.sleep (pollingIntervalMillis); } catch (Exception ignore) {}
}
}
|
java
|
public static void waitUntilJobEnded(Key jobkey, int pollingIntervalMillis) {
while (true) {
if (Job.isEnded(jobkey)) {
return;
}
try { Thread.sleep (pollingIntervalMillis); } catch (Exception ignore) {}
}
}
|
[
"public",
"static",
"void",
"waitUntilJobEnded",
"(",
"Key",
"jobkey",
",",
"int",
"pollingIntervalMillis",
")",
"{",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"Job",
".",
"isEnded",
"(",
"jobkey",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"pollingIntervalMillis",
")",
";",
"}",
"catch",
"(",
"Exception",
"ignore",
")",
"{",
"}",
"}",
"}"
] |
Block synchronously waiting for a job to end, success or not.
@param jobkey Job to wait for.
@param pollingIntervalMillis Polling interval sleep time.
|
[
"Block",
"synchronously",
"waiting",
"for",
"a",
"job",
"to",
"end",
"success",
"or",
"not",
"."
] |
train
|
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L374-L382
|
RestComm/sipunit
|
src/main/java/org/cafesip/sipunit/SipSession.java
|
SipSession.sendReply
|
public SipTransaction sendReply(SipTransaction transaction, Response response) {
"""
This method sends a stateful response to a previously received request. The returned
SipTransaction object must be used in any subsequent calls to sendReply() for the same received
request, if there are any.
@param transaction The SipTransaction object returned from a previous call to sendReply().
@param response The response to send, as is.
@return A SipTransaction object that must be passed in to any subsequent call to sendReply()
for the same received request, or null if an error was encountered while sending the
response. The calling program doesn't need to do anything with the returned
SipTransaction other than pass it in to a subsequent call to sendReply() for the same
received request.
"""
initErrorInfo();
if ((transaction == null) || (transaction.getServerTransaction() == null)) {
setErrorMessage("Cannot send reply, transaction information is null");
setReturnCode(INVALID_ARGUMENT);
return null;
}
// send the message
try {
SipStack.dumpMessage("Response before sending out through stack", response);
transaction.getServerTransaction().sendResponse(response);
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(EXCEPTION_ENCOUNTERED);
return null;
}
return transaction;
}
|
java
|
public SipTransaction sendReply(SipTransaction transaction, Response response) {
initErrorInfo();
if ((transaction == null) || (transaction.getServerTransaction() == null)) {
setErrorMessage("Cannot send reply, transaction information is null");
setReturnCode(INVALID_ARGUMENT);
return null;
}
// send the message
try {
SipStack.dumpMessage("Response before sending out through stack", response);
transaction.getServerTransaction().sendResponse(response);
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(EXCEPTION_ENCOUNTERED);
return null;
}
return transaction;
}
|
[
"public",
"SipTransaction",
"sendReply",
"(",
"SipTransaction",
"transaction",
",",
"Response",
"response",
")",
"{",
"initErrorInfo",
"(",
")",
";",
"if",
"(",
"(",
"transaction",
"==",
"null",
")",
"||",
"(",
"transaction",
".",
"getServerTransaction",
"(",
")",
"==",
"null",
")",
")",
"{",
"setErrorMessage",
"(",
"\"Cannot send reply, transaction information is null\"",
")",
";",
"setReturnCode",
"(",
"INVALID_ARGUMENT",
")",
";",
"return",
"null",
";",
"}",
"// send the message",
"try",
"{",
"SipStack",
".",
"dumpMessage",
"(",
"\"Response before sending out through stack\"",
",",
"response",
")",
";",
"transaction",
".",
"getServerTransaction",
"(",
")",
".",
"sendResponse",
"(",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"setException",
"(",
"ex",
")",
";",
"setErrorMessage",
"(",
"\"Exception: \"",
"+",
"ex",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\": \"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"setReturnCode",
"(",
"EXCEPTION_ENCOUNTERED",
")",
";",
"return",
"null",
";",
"}",
"return",
"transaction",
";",
"}"
] |
This method sends a stateful response to a previously received request. The returned
SipTransaction object must be used in any subsequent calls to sendReply() for the same received
request, if there are any.
@param transaction The SipTransaction object returned from a previous call to sendReply().
@param response The response to send, as is.
@return A SipTransaction object that must be passed in to any subsequent call to sendReply()
for the same received request, or null if an error was encountered while sending the
response. The calling program doesn't need to do anything with the returned
SipTransaction other than pass it in to a subsequent call to sendReply() for the same
received request.
|
[
"This",
"method",
"sends",
"a",
"stateful",
"response",
"to",
"a",
"previously",
"received",
"request",
".",
"The",
"returned",
"SipTransaction",
"object",
"must",
"be",
"used",
"in",
"any",
"subsequent",
"calls",
"to",
"sendReply",
"()",
"for",
"the",
"same",
"received",
"request",
"if",
"there",
"are",
"any",
"."
] |
train
|
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipSession.java#L1662-L1683
|
beihaifeiwu/dolphin
|
dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java
|
AnnotationUtils.findAnnotation
|
@SuppressWarnings("unchecked")
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
"""
Find a single {@link Annotation} of {@code annotationType} on the
supplied {@link Class}, traversing its interfaces, annotations, and
superclasses if the annotation is not <em>present</em> on the given class
itself.
<p>This method explicitly handles class-level annotations which are not
declared as {@link java.lang.annotation.Inherited inherited} <em>as well
as meta-annotations and annotations on interfaces</em>.
<p>The algorithm operates as follows:
<ol>
<li>Search for the annotation on the given class and return it if found.
<li>Recursively search through all interfaces that the given class declares.
<li>Recursively search through all annotations that the given class declares.
<li>Recursively search through the superclass hierarchy of the given class.
</ol>
<p>Note: in this context, the term <em>recursively</em> means that the search
process continues by returning to step #1 with the current interface,
annotation, or superclass as the class to look for annotations on.
@param clazz the class to look for annotations on
@param annotationType the type of annotation to look for
@return the annotation if found, or {@code null} if not found
"""
AnnotationCacheKey cacheKey = new AnnotationCacheKey(clazz, annotationType);
A result = (A) findAnnotationCache.get(cacheKey);
if (result == null) {
result = findAnnotation(clazz, annotationType, new HashSet<Annotation>());
if (result != null) {
findAnnotationCache.put(cacheKey, result);
}
}
return result;
}
|
java
|
@SuppressWarnings("unchecked")
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
AnnotationCacheKey cacheKey = new AnnotationCacheKey(clazz, annotationType);
A result = (A) findAnnotationCache.get(cacheKey);
if (result == null) {
result = findAnnotation(clazz, annotationType, new HashSet<Annotation>());
if (result != null) {
findAnnotationCache.put(cacheKey, result);
}
}
return result;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"A",
"extends",
"Annotation",
">",
"A",
"findAnnotation",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Class",
"<",
"A",
">",
"annotationType",
")",
"{",
"AnnotationCacheKey",
"cacheKey",
"=",
"new",
"AnnotationCacheKey",
"(",
"clazz",
",",
"annotationType",
")",
";",
"A",
"result",
"=",
"(",
"A",
")",
"findAnnotationCache",
".",
"get",
"(",
"cacheKey",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"result",
"=",
"findAnnotation",
"(",
"clazz",
",",
"annotationType",
",",
"new",
"HashSet",
"<",
"Annotation",
">",
"(",
")",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"findAnnotationCache",
".",
"put",
"(",
"cacheKey",
",",
"result",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Find a single {@link Annotation} of {@code annotationType} on the
supplied {@link Class}, traversing its interfaces, annotations, and
superclasses if the annotation is not <em>present</em> on the given class
itself.
<p>This method explicitly handles class-level annotations which are not
declared as {@link java.lang.annotation.Inherited inherited} <em>as well
as meta-annotations and annotations on interfaces</em>.
<p>The algorithm operates as follows:
<ol>
<li>Search for the annotation on the given class and return it if found.
<li>Recursively search through all interfaces that the given class declares.
<li>Recursively search through all annotations that the given class declares.
<li>Recursively search through the superclass hierarchy of the given class.
</ol>
<p>Note: in this context, the term <em>recursively</em> means that the search
process continues by returning to step #1 with the current interface,
annotation, or superclass as the class to look for annotations on.
@param clazz the class to look for annotations on
@param annotationType the type of annotation to look for
@return the annotation if found, or {@code null} if not found
|
[
"Find",
"a",
"single",
"{"
] |
train
|
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java#L324-L335
|
line/armeria
|
thrift/src/main/java/com/linecorp/armeria/server/thrift/THttpService.java
|
THttpService.newDecorator
|
public static Function<Service<RpcRequest, RpcResponse>, THttpService> newDecorator(
SerializationFormat defaultSerializationFormat) {
"""
Creates a new decorator that supports all thrift protocols and defaults to the specified
{@code defaultSerializationFormat} when the client doesn't specify one.
Currently, the only way to specify a serialization format is by using the HTTP session
protocol and setting the Content-Type header to the appropriate {@link SerializationFormat#mediaType()}.
@param defaultSerializationFormat the default serialization format to use when not specified by the
client
"""
final SerializationFormat[] allowedSerializationFormatArray = newAllowedSerializationFormats(
defaultSerializationFormat,
ThriftSerializationFormats.values());
return delegate -> new THttpService(delegate, allowedSerializationFormatArray);
}
|
java
|
public static Function<Service<RpcRequest, RpcResponse>, THttpService> newDecorator(
SerializationFormat defaultSerializationFormat) {
final SerializationFormat[] allowedSerializationFormatArray = newAllowedSerializationFormats(
defaultSerializationFormat,
ThriftSerializationFormats.values());
return delegate -> new THttpService(delegate, allowedSerializationFormatArray);
}
|
[
"public",
"static",
"Function",
"<",
"Service",
"<",
"RpcRequest",
",",
"RpcResponse",
">",
",",
"THttpService",
">",
"newDecorator",
"(",
"SerializationFormat",
"defaultSerializationFormat",
")",
"{",
"final",
"SerializationFormat",
"[",
"]",
"allowedSerializationFormatArray",
"=",
"newAllowedSerializationFormats",
"(",
"defaultSerializationFormat",
",",
"ThriftSerializationFormats",
".",
"values",
"(",
")",
")",
";",
"return",
"delegate",
"->",
"new",
"THttpService",
"(",
"delegate",
",",
"allowedSerializationFormatArray",
")",
";",
"}"
] |
Creates a new decorator that supports all thrift protocols and defaults to the specified
{@code defaultSerializationFormat} when the client doesn't specify one.
Currently, the only way to specify a serialization format is by using the HTTP session
protocol and setting the Content-Type header to the appropriate {@link SerializationFormat#mediaType()}.
@param defaultSerializationFormat the default serialization format to use when not specified by the
client
|
[
"Creates",
"a",
"new",
"decorator",
"that",
"supports",
"all",
"thrift",
"protocols",
"and",
"defaults",
"to",
"the",
"specified",
"{",
"@code",
"defaultSerializationFormat",
"}",
"when",
"the",
"client",
"doesn",
"t",
"specify",
"one",
".",
"Currently",
"the",
"only",
"way",
"to",
"specify",
"a",
"serialization",
"format",
"is",
"by",
"using",
"the",
"HTTP",
"session",
"protocol",
"and",
"setting",
"the",
"Content",
"-",
"Type",
"header",
"to",
"the",
"appropriate",
"{",
"@link",
"SerializationFormat#mediaType",
"()",
"}",
"."
] |
train
|
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/thrift/src/main/java/com/linecorp/armeria/server/thrift/THttpService.java#L292-L300
|
xvik/generics-resolver
|
src/main/java/ru/vyarus/java/generics/resolver/util/TypeUtils.java
|
TypeUtils.isMoreSpecific
|
public static boolean isMoreSpecific(final Type what, final Type comparingTo) {
"""
Checks if type is more specific than provided one. E.g. {@code ArrayList} is more specific then
{@code List} or {@code List<Integer>} is more specific then {@code List<Object>}.
<p>
Note that comparison logic did not follow all java rules (especially wildcards) as some rules
are not important at runtime.
<p>
Not resolved type variables are resolved to Object. Object is considered as unknown type: everything
is assignable to Object and Object is assignable to everything.
{@code List == List<Object> == List<?> == List<? super Object> == List<? extends Object>}.
<p>
For lower bounded wildcards more specific wildcard contains lower bound: {@code ? extends Number} is
more specific then {@code ? extends Integer}. Also, lower bounded wildcard is always more specific then
Object.
<p>
Not the same as {@link #isAssignable(Type, Type)}. For example:
{@code isAssignable(List, List<String>) == true}, but {@code isMoreSpecific(List, List<String>) == false}.
<p>
Primitive types are checked as wrappers (for example, int is more specific then Number).
@param what type to check
@param comparingTo type to compare to
@return true when provided type is more specific than other type. false otherwise
@throws IllegalArgumentException when types are not compatible
@see ComparatorTypesVisitor for implementation details
@see #isCompatible(Type, Type) use for compatibility check (before) to avoid incompatible types exception
"""
final ComparatorTypesVisitor visitor = new ComparatorTypesVisitor();
TypesWalker.walk(what, comparingTo, visitor);
if (!visitor.isCompatible()) {
throw new IllegalArgumentException(String.format(
"Type %s can't be compared to %s because they are not compatible",
TypeToStringUtils.toStringTypeIgnoringVariables(what),
TypeToStringUtils.toStringTypeIgnoringVariables(comparingTo)));
}
return visitor.isMoreSpecific();
}
|
java
|
public static boolean isMoreSpecific(final Type what, final Type comparingTo) {
final ComparatorTypesVisitor visitor = new ComparatorTypesVisitor();
TypesWalker.walk(what, comparingTo, visitor);
if (!visitor.isCompatible()) {
throw new IllegalArgumentException(String.format(
"Type %s can't be compared to %s because they are not compatible",
TypeToStringUtils.toStringTypeIgnoringVariables(what),
TypeToStringUtils.toStringTypeIgnoringVariables(comparingTo)));
}
return visitor.isMoreSpecific();
}
|
[
"public",
"static",
"boolean",
"isMoreSpecific",
"(",
"final",
"Type",
"what",
",",
"final",
"Type",
"comparingTo",
")",
"{",
"final",
"ComparatorTypesVisitor",
"visitor",
"=",
"new",
"ComparatorTypesVisitor",
"(",
")",
";",
"TypesWalker",
".",
"walk",
"(",
"what",
",",
"comparingTo",
",",
"visitor",
")",
";",
"if",
"(",
"!",
"visitor",
".",
"isCompatible",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"\"Type %s can't be compared to %s because they are not compatible\"",
",",
"TypeToStringUtils",
".",
"toStringTypeIgnoringVariables",
"(",
"what",
")",
",",
"TypeToStringUtils",
".",
"toStringTypeIgnoringVariables",
"(",
"comparingTo",
")",
")",
")",
";",
"}",
"return",
"visitor",
".",
"isMoreSpecific",
"(",
")",
";",
"}"
] |
Checks if type is more specific than provided one. E.g. {@code ArrayList} is more specific then
{@code List} or {@code List<Integer>} is more specific then {@code List<Object>}.
<p>
Note that comparison logic did not follow all java rules (especially wildcards) as some rules
are not important at runtime.
<p>
Not resolved type variables are resolved to Object. Object is considered as unknown type: everything
is assignable to Object and Object is assignable to everything.
{@code List == List<Object> == List<?> == List<? super Object> == List<? extends Object>}.
<p>
For lower bounded wildcards more specific wildcard contains lower bound: {@code ? extends Number} is
more specific then {@code ? extends Integer}. Also, lower bounded wildcard is always more specific then
Object.
<p>
Not the same as {@link #isAssignable(Type, Type)}. For example:
{@code isAssignable(List, List<String>) == true}, but {@code isMoreSpecific(List, List<String>) == false}.
<p>
Primitive types are checked as wrappers (for example, int is more specific then Number).
@param what type to check
@param comparingTo type to compare to
@return true when provided type is more specific than other type. false otherwise
@throws IllegalArgumentException when types are not compatible
@see ComparatorTypesVisitor for implementation details
@see #isCompatible(Type, Type) use for compatibility check (before) to avoid incompatible types exception
|
[
"Checks",
"if",
"type",
"is",
"more",
"specific",
"than",
"provided",
"one",
".",
"E",
".",
"g",
".",
"{",
"@code",
"ArrayList",
"}",
"is",
"more",
"specific",
"then",
"{",
"@code",
"List",
"}",
"or",
"{",
"@code",
"List<Integer",
">",
"}",
"is",
"more",
"specific",
"then",
"{",
"@code",
"List<Object",
">",
"}",
".",
"<p",
">",
"Note",
"that",
"comparison",
"logic",
"did",
"not",
"follow",
"all",
"java",
"rules",
"(",
"especially",
"wildcards",
")",
"as",
"some",
"rules",
"are",
"not",
"important",
"at",
"runtime",
".",
"<p",
">",
"Not",
"resolved",
"type",
"variables",
"are",
"resolved",
"to",
"Object",
".",
"Object",
"is",
"considered",
"as",
"unknown",
"type",
":",
"everything",
"is",
"assignable",
"to",
"Object",
"and",
"Object",
"is",
"assignable",
"to",
"everything",
".",
"{",
"@code",
"List",
"==",
"List<Object",
">",
"==",
"List<?",
">",
"==",
"List<?",
"super",
"Object",
">",
"==",
"List<?",
"extends",
"Object",
">",
"}",
".",
"<p",
">",
"For",
"lower",
"bounded",
"wildcards",
"more",
"specific",
"wildcard",
"contains",
"lower",
"bound",
":",
"{",
"@code",
"?",
"extends",
"Number",
"}",
"is",
"more",
"specific",
"then",
"{",
"@code",
"?",
"extends",
"Integer",
"}",
".",
"Also",
"lower",
"bounded",
"wildcard",
"is",
"always",
"more",
"specific",
"then",
"Object",
".",
"<p",
">",
"Not",
"the",
"same",
"as",
"{",
"@link",
"#isAssignable",
"(",
"Type",
"Type",
")",
"}",
".",
"For",
"example",
":",
"{",
"@code",
"isAssignable",
"(",
"List",
"List<String",
">",
")",
"==",
"true",
"}",
"but",
"{",
"@code",
"isMoreSpecific",
"(",
"List",
"List<String",
">",
")",
"==",
"false",
"}",
".",
"<p",
">",
"Primitive",
"types",
"are",
"checked",
"as",
"wrappers",
"(",
"for",
"example",
"int",
"is",
"more",
"specific",
"then",
"Number",
")",
"."
] |
train
|
https://github.com/xvik/generics-resolver/blob/d7d9d2783265df1178230e8f0b7cb6d853b67a7b/src/main/java/ru/vyarus/java/generics/resolver/util/TypeUtils.java#L75-L86
|
google/error-prone-javac
|
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MethodBuilder.java
|
MethodBuilder.buildSignature
|
public void buildSignature(XMLNode node, Content methodDocTree) {
"""
Build the signature.
@param node the XML element that specifies which components to document
@param methodDocTree the content tree to which the documentation will be added
"""
methodDocTree.addContent(
writer.getSignature((MethodDoc) methods.get(currentMethodIndex)));
}
|
java
|
public void buildSignature(XMLNode node, Content methodDocTree) {
methodDocTree.addContent(
writer.getSignature((MethodDoc) methods.get(currentMethodIndex)));
}
|
[
"public",
"void",
"buildSignature",
"(",
"XMLNode",
"node",
",",
"Content",
"methodDocTree",
")",
"{",
"methodDocTree",
".",
"addContent",
"(",
"writer",
".",
"getSignature",
"(",
"(",
"MethodDoc",
")",
"methods",
".",
"get",
"(",
"currentMethodIndex",
")",
")",
")",
";",
"}"
] |
Build the signature.
@param node the XML element that specifies which components to document
@param methodDocTree the content tree to which the documentation will be added
|
[
"Build",
"the",
"signature",
"."
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MethodBuilder.java#L183-L186
|
apache/incubator-gobblin
|
gobblin-restli/gobblin-throttling-service/gobblin-throttling-service-server/src/main/java/org/apache/gobblin/restli/throttling/DynamicTokenBucket.java
|
DynamicTokenBucket.getPermits
|
public long getPermits(long requestedPermits, long minPermits, long timeoutMillis) {
"""
Request tokens. Like {@link #getPermitsAndDelay(long, long, long)} but block until the wait time passes.
"""
PermitsAndDelay permitsAndDelay = getPermitsAndDelay(requestedPermits, minPermits, timeoutMillis);
if (permitsAndDelay.delay > 0) {
try {
Thread.sleep(permitsAndDelay.delay);
} catch (InterruptedException ie) {
return 0;
}
}
return permitsAndDelay.permits;
}
|
java
|
public long getPermits(long requestedPermits, long minPermits, long timeoutMillis) {
PermitsAndDelay permitsAndDelay = getPermitsAndDelay(requestedPermits, minPermits, timeoutMillis);
if (permitsAndDelay.delay > 0) {
try {
Thread.sleep(permitsAndDelay.delay);
} catch (InterruptedException ie) {
return 0;
}
}
return permitsAndDelay.permits;
}
|
[
"public",
"long",
"getPermits",
"(",
"long",
"requestedPermits",
",",
"long",
"minPermits",
",",
"long",
"timeoutMillis",
")",
"{",
"PermitsAndDelay",
"permitsAndDelay",
"=",
"getPermitsAndDelay",
"(",
"requestedPermits",
",",
"minPermits",
",",
"timeoutMillis",
")",
";",
"if",
"(",
"permitsAndDelay",
".",
"delay",
">",
"0",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"permitsAndDelay",
".",
"delay",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"return",
"0",
";",
"}",
"}",
"return",
"permitsAndDelay",
".",
"permits",
";",
"}"
] |
Request tokens. Like {@link #getPermitsAndDelay(long, long, long)} but block until the wait time passes.
|
[
"Request",
"tokens",
".",
"Like",
"{"
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-throttling-service/gobblin-throttling-service-server/src/main/java/org/apache/gobblin/restli/throttling/DynamicTokenBucket.java#L117-L127
|
Azure/azure-sdk-for-java
|
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java
|
AppsImpl.listWithServiceResponseAsync
|
public Observable<ServiceResponse<List<ApplicationInfoResponse>>> listWithServiceResponseAsync(ListAppsOptionalParameter listOptionalParameter) {
"""
Lists all of the user applications.
@param listOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ApplicationInfoResponse> object
"""
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null;
final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null;
return listWithServiceResponseAsync(skip, take);
}
|
java
|
public Observable<ServiceResponse<List<ApplicationInfoResponse>>> listWithServiceResponseAsync(ListAppsOptionalParameter listOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
final Integer skip = listOptionalParameter != null ? listOptionalParameter.skip() : null;
final Integer take = listOptionalParameter != null ? listOptionalParameter.take() : null;
return listWithServiceResponseAsync(skip, take);
}
|
[
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"ApplicationInfoResponse",
">",
">",
">",
"listWithServiceResponseAsync",
"(",
"ListAppsOptionalParameter",
"listOptionalParameter",
")",
"{",
"if",
"(",
"this",
".",
"client",
".",
"endpoint",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Parameter this.client.endpoint() is required and cannot be null.\"",
")",
";",
"}",
"final",
"Integer",
"skip",
"=",
"listOptionalParameter",
"!=",
"null",
"?",
"listOptionalParameter",
".",
"skip",
"(",
")",
":",
"null",
";",
"final",
"Integer",
"take",
"=",
"listOptionalParameter",
"!=",
"null",
"?",
"listOptionalParameter",
".",
"take",
"(",
")",
":",
"null",
";",
"return",
"listWithServiceResponseAsync",
"(",
"skip",
",",
"take",
")",
";",
"}"
] |
Lists all of the user applications.
@param listOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ApplicationInfoResponse> object
|
[
"Lists",
"all",
"of",
"the",
"user",
"applications",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java#L295-L303
|
albfernandez/itext2
|
src/main/java/com/lowagie/text/Image.java
|
Image.getInstance
|
public static Image getInstance(PdfWriter writer, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
"""
Gets an instance of a Image from a java.awt.Image.
The image is added as a JPEG with a user defined quality.
@param writer
the <CODE>PdfWriter</CODE> object to which the image will be added
@param awtImage
the <CODE>java.awt.Image</CODE> to convert
@param quality
a float value between 0 and 1
@return an object of type <CODE>PdfTemplate</CODE>
@throws BadElementException
on error
@throws IOException
"""
return getInstance(new PdfContentByte(writer), awtImage, quality);
}
|
java
|
public static Image getInstance(PdfWriter writer, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
return getInstance(new PdfContentByte(writer), awtImage, quality);
}
|
[
"public",
"static",
"Image",
"getInstance",
"(",
"PdfWriter",
"writer",
",",
"java",
".",
"awt",
".",
"Image",
"awtImage",
",",
"float",
"quality",
")",
"throws",
"BadElementException",
",",
"IOException",
"{",
"return",
"getInstance",
"(",
"new",
"PdfContentByte",
"(",
"writer",
")",
",",
"awtImage",
",",
"quality",
")",
";",
"}"
] |
Gets an instance of a Image from a java.awt.Image.
The image is added as a JPEG with a user defined quality.
@param writer
the <CODE>PdfWriter</CODE> object to which the image will be added
@param awtImage
the <CODE>java.awt.Image</CODE> to convert
@param quality
a float value between 0 and 1
@return an object of type <CODE>PdfTemplate</CODE>
@throws BadElementException
on error
@throws IOException
|
[
"Gets",
"an",
"instance",
"of",
"a",
"Image",
"from",
"a",
"java",
".",
"awt",
".",
"Image",
".",
"The",
"image",
"is",
"added",
"as",
"a",
"JPEG",
"with",
"a",
"user",
"defined",
"quality",
"."
] |
train
|
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Image.java#L811-L813
|
looly/hutool
|
hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java
|
MailUtil.sendText
|
public static void sendText(String to, String subject, String content, File... files) {
"""
使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br>
多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔
@param to 收件人
@param subject 标题
@param content 正文
@param files 附件列表
@since 3.2.0
"""
send(to, subject, content, false, files);
}
|
java
|
public static void sendText(String to, String subject, String content, File... files) {
send(to, subject, content, false, files);
}
|
[
"public",
"static",
"void",
"sendText",
"(",
"String",
"to",
",",
"String",
"subject",
",",
"String",
"content",
",",
"File",
"...",
"files",
")",
"{",
"send",
"(",
"to",
",",
"subject",
",",
"content",
",",
"false",
",",
"files",
")",
";",
"}"
] |
使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br>
多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔
@param to 收件人
@param subject 标题
@param content 正文
@param files 附件列表
@since 3.2.0
|
[
"使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br",
">",
"多个收件人可以使用逗号“",
"”分隔,也可以通过分号“",
";",
"”分隔"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java#L28-L30
|
looly/hutool
|
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
|
ImgUtil.compress
|
public static void compress(File imageFile, File outFile, float quality) throws IORuntimeException {
"""
压缩图像,输出图像只支持jpg文件
@param imageFile 图像文件
@param outFile 输出文件,只支持jpg文件
@throws IORuntimeException IO异常
@since 4.3.2
"""
Img.from(imageFile).setQuality(quality).write(outFile);
}
|
java
|
public static void compress(File imageFile, File outFile, float quality) throws IORuntimeException {
Img.from(imageFile).setQuality(quality).write(outFile);
}
|
[
"public",
"static",
"void",
"compress",
"(",
"File",
"imageFile",
",",
"File",
"outFile",
",",
"float",
"quality",
")",
"throws",
"IORuntimeException",
"{",
"Img",
".",
"from",
"(",
"imageFile",
")",
".",
"setQuality",
"(",
"quality",
")",
".",
"write",
"(",
"outFile",
")",
";",
"}"
] |
压缩图像,输出图像只支持jpg文件
@param imageFile 图像文件
@param outFile 输出文件,只支持jpg文件
@throws IORuntimeException IO异常
@since 4.3.2
|
[
"压缩图像,输出图像只支持jpg文件"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1130-L1132
|
samskivert/samskivert
|
src/main/java/com/samskivert/swing/util/SwingUtil.java
|
SwingUtil.applyToHierarchy
|
public static void applyToHierarchy (Component comp, ComponentOp op) {
"""
Apply the specified ComponentOp to the supplied component and then all its descendants.
"""
applyToHierarchy(comp, Integer.MAX_VALUE, op);
}
|
java
|
public static void applyToHierarchy (Component comp, ComponentOp op)
{
applyToHierarchy(comp, Integer.MAX_VALUE, op);
}
|
[
"public",
"static",
"void",
"applyToHierarchy",
"(",
"Component",
"comp",
",",
"ComponentOp",
"op",
")",
"{",
"applyToHierarchy",
"(",
"comp",
",",
"Integer",
".",
"MAX_VALUE",
",",
"op",
")",
";",
"}"
] |
Apply the specified ComponentOp to the supplied component and then all its descendants.
|
[
"Apply",
"the",
"specified",
"ComponentOp",
"to",
"the",
"supplied",
"component",
"and",
"then",
"all",
"its",
"descendants",
"."
] |
train
|
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/SwingUtil.java#L276-L279
|
Azure/azure-sdk-for-java
|
batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java
|
TaskOperations.listTasks
|
public PagedList<CloudTask> listTasks(String jobId, DetailLevel detailLevel)
throws BatchErrorException, IOException {
"""
Lists the {@link CloudTask tasks} of the specified job.
@param jobId
The ID of the job.
@param detailLevel
A {@link DetailLevel} used for filtering the list and for
controlling which properties are retrieved from the service.
@return A list of {@link CloudTask} objects.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service.
"""
return listTasks(jobId, detailLevel, null);
}
|
java
|
public PagedList<CloudTask> listTasks(String jobId, DetailLevel detailLevel)
throws BatchErrorException, IOException {
return listTasks(jobId, detailLevel, null);
}
|
[
"public",
"PagedList",
"<",
"CloudTask",
">",
"listTasks",
"(",
"String",
"jobId",
",",
"DetailLevel",
"detailLevel",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"return",
"listTasks",
"(",
"jobId",
",",
"detailLevel",
",",
"null",
")",
";",
"}"
] |
Lists the {@link CloudTask tasks} of the specified job.
@param jobId
The ID of the job.
@param detailLevel
A {@link DetailLevel} used for filtering the list and for
controlling which properties are retrieved from the service.
@return A list of {@link CloudTask} objects.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service.
|
[
"Lists",
"the",
"{",
"@link",
"CloudTask",
"tasks",
"}",
"of",
"the",
"specified",
"job",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java#L418-L421
|
mfornos/humanize
|
humanize-slim/src/main/java/humanize/Humanize.java
|
Humanize.fixLength
|
public static String fixLength(final String text, final int charsNum, final char paddingChar, final boolean left) {
"""
<p>
Pads or truncates a string to a specified length.
</p>
@param text
String to be fixed
@param charsNum
The fixed length in number of chars
@param paddingChar
The padding character
@param left
true for left padding
@return A fixed length string
"""
Preconditions.checkArgument(charsNum > 0, "The number of characters must be greater than zero.");
String str = text == null ? "" : text;
String fmt = String.format("%%%ss", left ? charsNum : -charsNum);
return String.format(fmt, str).substring(0, charsNum).replace(' ', paddingChar);
}
|
java
|
public static String fixLength(final String text, final int charsNum, final char paddingChar, final boolean left)
{
Preconditions.checkArgument(charsNum > 0, "The number of characters must be greater than zero.");
String str = text == null ? "" : text;
String fmt = String.format("%%%ss", left ? charsNum : -charsNum);
return String.format(fmt, str).substring(0, charsNum).replace(' ', paddingChar);
}
|
[
"public",
"static",
"String",
"fixLength",
"(",
"final",
"String",
"text",
",",
"final",
"int",
"charsNum",
",",
"final",
"char",
"paddingChar",
",",
"final",
"boolean",
"left",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"charsNum",
">",
"0",
",",
"\"The number of characters must be greater than zero.\"",
")",
";",
"String",
"str",
"=",
"text",
"==",
"null",
"?",
"\"\"",
":",
"text",
";",
"String",
"fmt",
"=",
"String",
".",
"format",
"(",
"\"%%%ss\"",
",",
"left",
"?",
"charsNum",
":",
"-",
"charsNum",
")",
";",
"return",
"String",
".",
"format",
"(",
"fmt",
",",
"str",
")",
".",
"substring",
"(",
"0",
",",
"charsNum",
")",
".",
"replace",
"(",
"'",
"'",
",",
"paddingChar",
")",
";",
"}"
] |
<p>
Pads or truncates a string to a specified length.
</p>
@param text
String to be fixed
@param charsNum
The fixed length in number of chars
@param paddingChar
The padding character
@param left
true for left padding
@return A fixed length string
|
[
"<p",
">",
"Pads",
"or",
"truncates",
"a",
"string",
"to",
"a",
"specified",
"length",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L822-L830
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/ExternalContextUtils.java
|
ExternalContextUtils._runMethod
|
private static Object _runMethod(Object obj, String methodName) {
"""
Runs a method on an object and returns the result
@param obj the object to run the method on
@param methodName the name of the method
@return the results of the method run
"""
try
{
Method sessionIdMethod = obj.getClass().getMethod(methodName);
return sessionIdMethod.invoke(obj);
}
catch (Exception e)
{
return null;
}
}
|
java
|
private static Object _runMethod(Object obj, String methodName)
{
try
{
Method sessionIdMethod = obj.getClass().getMethod(methodName);
return sessionIdMethod.invoke(obj);
}
catch (Exception e)
{
return null;
}
}
|
[
"private",
"static",
"Object",
"_runMethod",
"(",
"Object",
"obj",
",",
"String",
"methodName",
")",
"{",
"try",
"{",
"Method",
"sessionIdMethod",
"=",
"obj",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"methodName",
")",
";",
"return",
"sessionIdMethod",
".",
"invoke",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] |
Runs a method on an object and returns the result
@param obj the object to run the method on
@param methodName the name of the method
@return the results of the method run
|
[
"Runs",
"a",
"method",
"on",
"an",
"object",
"and",
"returns",
"the",
"result"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/util/ExternalContextUtils.java#L579-L591
|
ManfredTremmel/gwt-commons-lang3
|
src/main/java/org/apache/commons/lang3/ClassUtils.java
|
ClassUtils.getClass
|
@GwtIncompatible("incompatible method")
public static Class<?> getClass(
final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
"""
Returns the class represented by {@code className} using the
{@code classLoader}. This implementation supports the syntaxes
"{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
"{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
@param classLoader the class loader to use to load the class
@param className the class name
@param initialize whether the class must be initialized
@return the class represented by {@code className} using the {@code classLoader}
@throws ClassNotFoundException if the class is not found
"""
try {
Class<?> clazz;
if (namePrimitiveMap.containsKey(className)) {
clazz = namePrimitiveMap.get(className);
} else {
clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
}
return clazz;
} catch (final ClassNotFoundException ex) {
// allow path separators (.) as inner class name separators
final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIndex != -1) {
try {
return getClass(classLoader, className.substring(0, lastDotIndex) +
INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
initialize);
} catch (final ClassNotFoundException ex2) { // NOPMD
// ignore exception
}
}
throw ex;
}
}
|
java
|
@GwtIncompatible("incompatible method")
public static Class<?> getClass(
final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
try {
Class<?> clazz;
if (namePrimitiveMap.containsKey(className)) {
clazz = namePrimitiveMap.get(className);
} else {
clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
}
return clazz;
} catch (final ClassNotFoundException ex) {
// allow path separators (.) as inner class name separators
final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIndex != -1) {
try {
return getClass(classLoader, className.substring(0, lastDotIndex) +
INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
initialize);
} catch (final ClassNotFoundException ex2) { // NOPMD
// ignore exception
}
}
throw ex;
}
}
|
[
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"public",
"static",
"Class",
"<",
"?",
">",
"getClass",
"(",
"final",
"ClassLoader",
"classLoader",
",",
"final",
"String",
"className",
",",
"final",
"boolean",
"initialize",
")",
"throws",
"ClassNotFoundException",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"clazz",
";",
"if",
"(",
"namePrimitiveMap",
".",
"containsKey",
"(",
"className",
")",
")",
"{",
"clazz",
"=",
"namePrimitiveMap",
".",
"get",
"(",
"className",
")",
";",
"}",
"else",
"{",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"toCanonicalName",
"(",
"className",
")",
",",
"initialize",
",",
"classLoader",
")",
";",
"}",
"return",
"clazz",
";",
"}",
"catch",
"(",
"final",
"ClassNotFoundException",
"ex",
")",
"{",
"// allow path separators (.) as inner class name separators",
"final",
"int",
"lastDotIndex",
"=",
"className",
".",
"lastIndexOf",
"(",
"PACKAGE_SEPARATOR_CHAR",
")",
";",
"if",
"(",
"lastDotIndex",
"!=",
"-",
"1",
")",
"{",
"try",
"{",
"return",
"getClass",
"(",
"classLoader",
",",
"className",
".",
"substring",
"(",
"0",
",",
"lastDotIndex",
")",
"+",
"INNER_CLASS_SEPARATOR_CHAR",
"+",
"className",
".",
"substring",
"(",
"lastDotIndex",
"+",
"1",
")",
",",
"initialize",
")",
";",
"}",
"catch",
"(",
"final",
"ClassNotFoundException",
"ex2",
")",
"{",
"// NOPMD",
"// ignore exception",
"}",
"}",
"throw",
"ex",
";",
"}",
"}"
] |
Returns the class represented by {@code className} using the
{@code classLoader}. This implementation supports the syntaxes
"{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
"{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
@param classLoader the class loader to use to load the class
@param className the class name
@param initialize whether the class must be initialized
@return the class represented by {@code className} using the {@code classLoader}
@throws ClassNotFoundException if the class is not found
|
[
"Returns",
"the",
"class",
"represented",
"by",
"{",
"@code",
"className",
"}",
"using",
"the",
"{",
"@code",
"classLoader",
"}",
".",
"This",
"implementation",
"supports",
"the",
"syntaxes",
"{",
"@code",
"java",
".",
"util",
".",
"Map",
".",
"Entry",
"[]",
"}",
"{",
"@code",
"java",
".",
"util",
".",
"Map$Entry",
"[]",
"}",
"{",
"@code",
"[",
"Ljava",
".",
"util",
".",
"Map",
".",
"Entry",
";",
"}",
"and",
"{",
"@code",
"[",
"Ljava",
".",
"util",
".",
"Map$Entry",
";",
"}",
"."
] |
train
|
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ClassUtils.java#L996-L1023
|
Ellzord/JALSE
|
src/main/java/jalse/entities/Entities.java
|
Entities.walkEntityTree
|
public static void walkEntityTree(final EntityContainer container, final EntityVisitor visitor) {
"""
Walks through all entities (recursive and breadth-first). Walking can be stopped or filtered
based on the visit result returned.
This is equivalent to {@code walkEntityTree(container, Integer.MAX_VALUE, visitor)}
@param container
Entity container.
@param visitor
Entity visitor.
@see EntityVisitor
"""
walkEntityTree(container, Integer.MAX_VALUE, visitor);
}
|
java
|
public static void walkEntityTree(final EntityContainer container, final EntityVisitor visitor) {
walkEntityTree(container, Integer.MAX_VALUE, visitor);
}
|
[
"public",
"static",
"void",
"walkEntityTree",
"(",
"final",
"EntityContainer",
"container",
",",
"final",
"EntityVisitor",
"visitor",
")",
"{",
"walkEntityTree",
"(",
"container",
",",
"Integer",
".",
"MAX_VALUE",
",",
"visitor",
")",
";",
"}"
] |
Walks through all entities (recursive and breadth-first). Walking can be stopped or filtered
based on the visit result returned.
This is equivalent to {@code walkEntityTree(container, Integer.MAX_VALUE, visitor)}
@param container
Entity container.
@param visitor
Entity visitor.
@see EntityVisitor
|
[
"Walks",
"through",
"all",
"entities",
"(",
"recursive",
"and",
"breadth",
"-",
"first",
")",
".",
"Walking",
"can",
"be",
"stopped",
"or",
"filtered",
"based",
"on",
"the",
"visit",
"result",
"returned",
"."
] |
train
|
https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/Entities.java#L502-L504
|
BioPAX/Paxtools
|
pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java
|
PatternBox.chemicalAffectsProteinThroughControl
|
public static Pattern chemicalAffectsProteinThroughControl() {
"""
A small molecule controls an interaction of which the protein is a participant.
@return pattern
"""
Pattern p = new Pattern(SmallMoleculeReference.class, "controller SMR");
p.add(erToPE(), "controller SMR", "controller simple PE");
p.add(notGeneric(), "controller simple PE");
p.add(linkToComplex(), "controller simple PE", "controller PE");
p.add(peToControl(), "controller PE", "Control");
p.add(controlToInter(), "Control", "Interaction");
p.add(new NOT(participantER()), "Interaction", "controller SMR");
p.add(participant(), "Interaction", "affected PE");
p.add(linkToSpecific(), "affected PE", "affected simple PE");
p.add(new Type(SequenceEntity.class), "affected simple PE");
p.add(peToER(), "affected simple PE", "affected generic ER");
p.add(linkedER(false), "affected generic ER", "affected ER");
return p;
}
|
java
|
public static Pattern chemicalAffectsProteinThroughControl()
{
Pattern p = new Pattern(SmallMoleculeReference.class, "controller SMR");
p.add(erToPE(), "controller SMR", "controller simple PE");
p.add(notGeneric(), "controller simple PE");
p.add(linkToComplex(), "controller simple PE", "controller PE");
p.add(peToControl(), "controller PE", "Control");
p.add(controlToInter(), "Control", "Interaction");
p.add(new NOT(participantER()), "Interaction", "controller SMR");
p.add(participant(), "Interaction", "affected PE");
p.add(linkToSpecific(), "affected PE", "affected simple PE");
p.add(new Type(SequenceEntity.class), "affected simple PE");
p.add(peToER(), "affected simple PE", "affected generic ER");
p.add(linkedER(false), "affected generic ER", "affected ER");
return p;
}
|
[
"public",
"static",
"Pattern",
"chemicalAffectsProteinThroughControl",
"(",
")",
"{",
"Pattern",
"p",
"=",
"new",
"Pattern",
"(",
"SmallMoleculeReference",
".",
"class",
",",
"\"controller SMR\"",
")",
";",
"p",
".",
"add",
"(",
"erToPE",
"(",
")",
",",
"\"controller SMR\"",
",",
"\"controller simple PE\"",
")",
";",
"p",
".",
"add",
"(",
"notGeneric",
"(",
")",
",",
"\"controller simple PE\"",
")",
";",
"p",
".",
"add",
"(",
"linkToComplex",
"(",
")",
",",
"\"controller simple PE\"",
",",
"\"controller PE\"",
")",
";",
"p",
".",
"add",
"(",
"peToControl",
"(",
")",
",",
"\"controller PE\"",
",",
"\"Control\"",
")",
";",
"p",
".",
"add",
"(",
"controlToInter",
"(",
")",
",",
"\"Control\"",
",",
"\"Interaction\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"NOT",
"(",
"participantER",
"(",
")",
")",
",",
"\"Interaction\"",
",",
"\"controller SMR\"",
")",
";",
"p",
".",
"add",
"(",
"participant",
"(",
")",
",",
"\"Interaction\"",
",",
"\"affected PE\"",
")",
";",
"p",
".",
"add",
"(",
"linkToSpecific",
"(",
")",
",",
"\"affected PE\"",
",",
"\"affected simple PE\"",
")",
";",
"p",
".",
"add",
"(",
"new",
"Type",
"(",
"SequenceEntity",
".",
"class",
")",
",",
"\"affected simple PE\"",
")",
";",
"p",
".",
"add",
"(",
"peToER",
"(",
")",
",",
"\"affected simple PE\"",
",",
"\"affected generic ER\"",
")",
";",
"p",
".",
"add",
"(",
"linkedER",
"(",
"false",
")",
",",
"\"affected generic ER\"",
",",
"\"affected ER\"",
")",
";",
"return",
"p",
";",
"}"
] |
A small molecule controls an interaction of which the protein is a participant.
@return pattern
|
[
"A",
"small",
"molecule",
"controls",
"an",
"interaction",
"of",
"which",
"the",
"protein",
"is",
"a",
"participant",
"."
] |
train
|
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L548-L563
|
bazaarvoice/ostrich
|
core/src/main/java/com/bazaarvoice/ostrich/pool/ServicePool.java
|
ServicePool.executeOnEndPoint
|
<R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback)
throws Exception {
"""
Execute a callback on a specific end point.
<p/>
NOTE: This method is package private specifically so that {@link AsyncServicePool} can call it.
"""
ServiceHandle<S> handle = null;
try {
handle = _serviceCache.checkOut(endPoint);
Timer.Context timer = _callbackExecutionTime.time();
try {
return callback.call(handle.getService());
} finally {
timer.stop();
}
} catch (NoCachedInstancesAvailableException e) {
LOG.info("Service cache exhausted. End point: {}", endPoint, e);
// Don't mark an end point as bad just because there are no cached end points for it.
throw e;
} catch (Exception e) {
if (_serviceFactory.isRetriableException(e)) {
// This is a known and supported exception indicating that something went wrong somewhere in the service
// layer while trying to communicate with the end point. These errors are often transient, so we
// enqueue a health check for the end point and mark it as unavailable for the time being.
markEndPointAsBad(endPoint);
LOG.info("Bad end point discovered. End point: {}", endPoint, e);
}
throw e;
} finally {
if (handle != null) {
try {
_serviceCache.checkIn(handle);
} catch (Exception e) {
// This should never happen, but log just in case.
LOG.warn("Error returning end point to cache. End point: {}, {}",
endPoint, e.toString());
LOG.debug("Exception", e);
}
}
}
}
|
java
|
<R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback)
throws Exception {
ServiceHandle<S> handle = null;
try {
handle = _serviceCache.checkOut(endPoint);
Timer.Context timer = _callbackExecutionTime.time();
try {
return callback.call(handle.getService());
} finally {
timer.stop();
}
} catch (NoCachedInstancesAvailableException e) {
LOG.info("Service cache exhausted. End point: {}", endPoint, e);
// Don't mark an end point as bad just because there are no cached end points for it.
throw e;
} catch (Exception e) {
if (_serviceFactory.isRetriableException(e)) {
// This is a known and supported exception indicating that something went wrong somewhere in the service
// layer while trying to communicate with the end point. These errors are often transient, so we
// enqueue a health check for the end point and mark it as unavailable for the time being.
markEndPointAsBad(endPoint);
LOG.info("Bad end point discovered. End point: {}", endPoint, e);
}
throw e;
} finally {
if (handle != null) {
try {
_serviceCache.checkIn(handle);
} catch (Exception e) {
// This should never happen, but log just in case.
LOG.warn("Error returning end point to cache. End point: {}, {}",
endPoint, e.toString());
LOG.debug("Exception", e);
}
}
}
}
|
[
"<",
"R",
">",
"R",
"executeOnEndPoint",
"(",
"ServiceEndPoint",
"endPoint",
",",
"ServiceCallback",
"<",
"S",
",",
"R",
">",
"callback",
")",
"throws",
"Exception",
"{",
"ServiceHandle",
"<",
"S",
">",
"handle",
"=",
"null",
";",
"try",
"{",
"handle",
"=",
"_serviceCache",
".",
"checkOut",
"(",
"endPoint",
")",
";",
"Timer",
".",
"Context",
"timer",
"=",
"_callbackExecutionTime",
".",
"time",
"(",
")",
";",
"try",
"{",
"return",
"callback",
".",
"call",
"(",
"handle",
".",
"getService",
"(",
")",
")",
";",
"}",
"finally",
"{",
"timer",
".",
"stop",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"NoCachedInstancesAvailableException",
"e",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Service cache exhausted. End point: {}\"",
",",
"endPoint",
",",
"e",
")",
";",
"// Don't mark an end point as bad just because there are no cached end points for it.",
"throw",
"e",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"_serviceFactory",
".",
"isRetriableException",
"(",
"e",
")",
")",
"{",
"// This is a known and supported exception indicating that something went wrong somewhere in the service",
"// layer while trying to communicate with the end point. These errors are often transient, so we",
"// enqueue a health check for the end point and mark it as unavailable for the time being.",
"markEndPointAsBad",
"(",
"endPoint",
")",
";",
"LOG",
".",
"info",
"(",
"\"Bad end point discovered. End point: {}\"",
",",
"endPoint",
",",
"e",
")",
";",
"}",
"throw",
"e",
";",
"}",
"finally",
"{",
"if",
"(",
"handle",
"!=",
"null",
")",
"{",
"try",
"{",
"_serviceCache",
".",
"checkIn",
"(",
"handle",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// This should never happen, but log just in case.",
"LOG",
".",
"warn",
"(",
"\"Error returning end point to cache. End point: {}, {}\"",
",",
"endPoint",
",",
"e",
".",
"toString",
"(",
")",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Exception\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}"
] |
Execute a callback on a specific end point.
<p/>
NOTE: This method is package private specifically so that {@link AsyncServicePool} can call it.
|
[
"Execute",
"a",
"callback",
"on",
"a",
"specific",
"end",
"point",
".",
"<p",
"/",
">",
"NOTE",
":",
"This",
"method",
"is",
"package",
"private",
"specifically",
"so",
"that",
"{"
] |
train
|
https://github.com/bazaarvoice/ostrich/blob/13591867870ab23445253f11fc872662a8028191/core/src/main/java/com/bazaarvoice/ostrich/pool/ServicePool.java#L295-L333
|
fabric8io/kubernetes-client
|
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RollingUpdater.java
|
RollingUpdater.waitUntilDeleted
|
private void waitUntilDeleted(final String namespace, final String name) {
"""
Since k8s v1.4.x, rc/rs deletes are asynchronous.
Lets wait until the resource is actually deleted in the server
"""
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Runnable waitTillDeletedPoller = () -> {
try {
T res = resources().inNamespace(namespace).withName(name).get();
if (res == null) {
countDownLatch.countDown();
}
} catch (KubernetesClientException e) {
if (e.getCode() == 404) {
countDownLatch.countDown();
}
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
executor.shutdown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
poller.cancel(true);
logger.cancel(true);
executor.shutdown();
LOG.warn("Still found deleted resource {} in namespace: {} after waiting for {} seconds so giving up",
name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
}
}
|
java
|
private void waitUntilDeleted(final String namespace, final String name) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Runnable waitTillDeletedPoller = () -> {
try {
T res = resources().inNamespace(namespace).withName(name).get();
if (res == null) {
countDownLatch.countDown();
}
} catch (KubernetesClientException e) {
if (e.getCode() == 404) {
countDownLatch.countDown();
}
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
executor.shutdown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
poller.cancel(true);
logger.cancel(true);
executor.shutdown();
LOG.warn("Still found deleted resource {} in namespace: {} after waiting for {} seconds so giving up",
name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
}
}
|
[
"private",
"void",
"waitUntilDeleted",
"(",
"final",
"String",
"namespace",
",",
"final",
"String",
"name",
")",
"{",
"final",
"CountDownLatch",
"countDownLatch",
"=",
"new",
"CountDownLatch",
"(",
"1",
")",
";",
"final",
"Runnable",
"waitTillDeletedPoller",
"=",
"(",
")",
"->",
"{",
"try",
"{",
"T",
"res",
"=",
"resources",
"(",
")",
".",
"inNamespace",
"(",
"namespace",
")",
".",
"withName",
"(",
"name",
")",
".",
"get",
"(",
")",
";",
"if",
"(",
"res",
"==",
"null",
")",
"{",
"countDownLatch",
".",
"countDown",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"KubernetesClientException",
"e",
")",
"{",
"if",
"(",
"e",
".",
"getCode",
"(",
")",
"==",
"404",
")",
"{",
"countDownLatch",
".",
"countDown",
"(",
")",
";",
"}",
"}",
"}",
";",
"ScheduledExecutorService",
"executor",
"=",
"Executors",
".",
"newSingleThreadScheduledExecutor",
"(",
")",
";",
"ScheduledFuture",
"poller",
"=",
"executor",
".",
"scheduleWithFixedDelay",
"(",
"waitTillDeletedPoller",
",",
"0",
",",
"5",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"ScheduledFuture",
"logger",
"=",
"executor",
".",
"scheduleWithFixedDelay",
"(",
"(",
")",
"->",
"LOG",
".",
"debug",
"(",
"\"Found resource {}/{} not yet deleted on server, so waiting...\"",
",",
"namespace",
",",
"name",
")",
",",
"0",
",",
"loggingIntervalMillis",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"try",
"{",
"countDownLatch",
".",
"await",
"(",
"DEFAULT_SERVER_GC_WAIT_TIMEOUT",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"executor",
".",
"shutdown",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"poller",
".",
"cancel",
"(",
"true",
")",
";",
"logger",
".",
"cancel",
"(",
"true",
")",
";",
"executor",
".",
"shutdown",
"(",
")",
";",
"LOG",
".",
"warn",
"(",
"\"Still found deleted resource {} in namespace: {} after waiting for {} seconds so giving up\"",
",",
"name",
",",
"namespace",
",",
"TimeUnit",
".",
"MILLISECONDS",
".",
"toSeconds",
"(",
"DEFAULT_SERVER_GC_WAIT_TIMEOUT",
")",
")",
";",
"}",
"}"
] |
Since k8s v1.4.x, rc/rs deletes are asynchronous.
Lets wait until the resource is actually deleted in the server
|
[
"Since",
"k8s",
"v1",
".",
"4",
".",
"x",
"rc",
"/",
"rs",
"deletes",
"are",
"asynchronous",
".",
"Lets",
"wait",
"until",
"the",
"resource",
"is",
"actually",
"deleted",
"in",
"the",
"server"
] |
train
|
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/RollingUpdater.java#L218-L248
|
zalando-stups/java-sproc-wrapper
|
src/main/java/de/zalando/typemapper/parser/postgres/RowMapper.java
|
RowMapper.mapRow
|
public final Element mapRow(final ResultSet rs, final String columnName) throws SQLException {
"""
@param rs
@param columnName
@return
@throws java.sql.SQLException
"""
final Element element = new Element();
List<String> l;
try {
l = ParseUtils.postgresROW2StringList(rs.getString(columnName));
} catch (RowParserException e) {
throw new SQLException(e);
}
element.setRowList(l);
return element;
}
|
java
|
public final Element mapRow(final ResultSet rs, final String columnName) throws SQLException {
final Element element = new Element();
List<String> l;
try {
l = ParseUtils.postgresROW2StringList(rs.getString(columnName));
} catch (RowParserException e) {
throw new SQLException(e);
}
element.setRowList(l);
return element;
}
|
[
"public",
"final",
"Element",
"mapRow",
"(",
"final",
"ResultSet",
"rs",
",",
"final",
"String",
"columnName",
")",
"throws",
"SQLException",
"{",
"final",
"Element",
"element",
"=",
"new",
"Element",
"(",
")",
";",
"List",
"<",
"String",
">",
"l",
";",
"try",
"{",
"l",
"=",
"ParseUtils",
".",
"postgresROW2StringList",
"(",
"rs",
".",
"getString",
"(",
"columnName",
")",
")",
";",
"}",
"catch",
"(",
"RowParserException",
"e",
")",
"{",
"throw",
"new",
"SQLException",
"(",
"e",
")",
";",
"}",
"element",
".",
"setRowList",
"(",
"l",
")",
";",
"return",
"element",
";",
"}"
] |
@param rs
@param columnName
@return
@throws java.sql.SQLException
|
[
"@param",
"rs",
"@param",
"columnName"
] |
train
|
https://github.com/zalando-stups/java-sproc-wrapper/blob/b86a6243e83e8ea33d1a46e9dbac8c79082dc0ec/src/main/java/de/zalando/typemapper/parser/postgres/RowMapper.java#L31-L42
|
Netflix/spectator
|
spectator-api/src/main/java/com/netflix/spectator/api/Utils.java
|
Utils.getTagValue
|
public static String getTagValue(Iterable<Tag> tags, String k) {
"""
Returns the value associated with with a given key or null if no such key is present in the
set of tags.
@param tags
Set of tags to search.
@param k
Key to search for.
@return
Value for the key or null if the key is not present.
"""
Preconditions.checkNotNull(tags, "tags");
Preconditions.checkNotNull(k, "key");
for (Tag t : tags) {
if (k.equals(t.key())) {
return t.value();
}
}
return null;
}
|
java
|
public static String getTagValue(Iterable<Tag> tags, String k) {
Preconditions.checkNotNull(tags, "tags");
Preconditions.checkNotNull(k, "key");
for (Tag t : tags) {
if (k.equals(t.key())) {
return t.value();
}
}
return null;
}
|
[
"public",
"static",
"String",
"getTagValue",
"(",
"Iterable",
"<",
"Tag",
">",
"tags",
",",
"String",
"k",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"tags",
",",
"\"tags\"",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"k",
",",
"\"key\"",
")",
";",
"for",
"(",
"Tag",
"t",
":",
"tags",
")",
"{",
"if",
"(",
"k",
".",
"equals",
"(",
"t",
".",
"key",
"(",
")",
")",
")",
"{",
"return",
"t",
".",
"value",
"(",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Returns the value associated with with a given key or null if no such key is present in the
set of tags.
@param tags
Set of tags to search.
@param k
Key to search for.
@return
Value for the key or null if the key is not present.
|
[
"Returns",
"the",
"value",
"associated",
"with",
"with",
"a",
"given",
"key",
"or",
"null",
"if",
"no",
"such",
"key",
"is",
"present",
"in",
"the",
"set",
"of",
"tags",
"."
] |
train
|
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/Utils.java#L113-L122
|
deeplearning4j/deeplearning4j
|
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/RandomProjection.java
|
RandomProjection.gaussianRandomMatrix
|
private INDArray gaussianRandomMatrix(long[] shape, Random rng) {
"""
Generate a dense Gaussian random matrix.
The n' components of the random matrix are drawn from
N(0, 1.0 / n').
@param shape
@param rng
@return
"""
Nd4j.checkShapeValues(shape);
INDArray res = Nd4j.create(shape);
GaussianDistribution op1 = new GaussianDistribution(res, 0.0, 1.0 / Math.sqrt(shape[0]));
Nd4j.getExecutioner().exec(op1, rng);
return res;
}
|
java
|
private INDArray gaussianRandomMatrix(long[] shape, Random rng){
Nd4j.checkShapeValues(shape);
INDArray res = Nd4j.create(shape);
GaussianDistribution op1 = new GaussianDistribution(res, 0.0, 1.0 / Math.sqrt(shape[0]));
Nd4j.getExecutioner().exec(op1, rng);
return res;
}
|
[
"private",
"INDArray",
"gaussianRandomMatrix",
"(",
"long",
"[",
"]",
"shape",
",",
"Random",
"rng",
")",
"{",
"Nd4j",
".",
"checkShapeValues",
"(",
"shape",
")",
";",
"INDArray",
"res",
"=",
"Nd4j",
".",
"create",
"(",
"shape",
")",
";",
"GaussianDistribution",
"op1",
"=",
"new",
"GaussianDistribution",
"(",
"res",
",",
"0.0",
",",
"1.0",
"/",
"Math",
".",
"sqrt",
"(",
"shape",
"[",
"0",
"]",
")",
")",
";",
"Nd4j",
".",
"getExecutioner",
"(",
")",
".",
"exec",
"(",
"op1",
",",
"rng",
")",
";",
"return",
"res",
";",
"}"
] |
Generate a dense Gaussian random matrix.
The n' components of the random matrix are drawn from
N(0, 1.0 / n').
@param shape
@param rng
@return
|
[
"Generate",
"a",
"dense",
"Gaussian",
"random",
"matrix",
"."
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/RandomProjection.java#L132-L139
|
Azure/azure-sdk-for-java
|
recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupWorkloadItemsInner.java
|
BackupWorkloadItemsInner.listAsync
|
public Observable<Page<WorkloadItemResourceInner>> listAsync(final String vaultName, final String resourceGroupName, final String fabricName, final String containerName) {
"""
Provides a pageable list of workload item of a specific container according to the query filter and the pagination parameters.
@param vaultName The name of the recovery services vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param fabricName Fabric name associated with the container.
@param containerName Name of the container.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<WorkloadItemResourceInner> object
"""
return listWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName)
.map(new Func1<ServiceResponse<Page<WorkloadItemResourceInner>>, Page<WorkloadItemResourceInner>>() {
@Override
public Page<WorkloadItemResourceInner> call(ServiceResponse<Page<WorkloadItemResourceInner>> response) {
return response.body();
}
});
}
|
java
|
public Observable<Page<WorkloadItemResourceInner>> listAsync(final String vaultName, final String resourceGroupName, final String fabricName, final String containerName) {
return listWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName)
.map(new Func1<ServiceResponse<Page<WorkloadItemResourceInner>>, Page<WorkloadItemResourceInner>>() {
@Override
public Page<WorkloadItemResourceInner> call(ServiceResponse<Page<WorkloadItemResourceInner>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Page",
"<",
"WorkloadItemResourceInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"vaultName",
",",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"fabricName",
",",
"final",
"String",
"containerName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"vaultName",
",",
"resourceGroupName",
",",
"fabricName",
",",
"containerName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"WorkloadItemResourceInner",
">",
">",
",",
"Page",
"<",
"WorkloadItemResourceInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"WorkloadItemResourceInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"WorkloadItemResourceInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Provides a pageable list of workload item of a specific container according to the query filter and the pagination parameters.
@param vaultName The name of the recovery services vault.
@param resourceGroupName The name of the resource group where the recovery services vault is present.
@param fabricName Fabric name associated with the container.
@param containerName Name of the container.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<WorkloadItemResourceInner> object
|
[
"Provides",
"a",
"pageable",
"list",
"of",
"workload",
"item",
"of",
"a",
"specific",
"container",
"according",
"to",
"the",
"query",
"filter",
"and",
"the",
"pagination",
"parameters",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/recoveryservices.backup/resource-manager/v2017_07_01/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2017_07_01/implementation/BackupWorkloadItemsInner.java#L124-L132
|
nguyenq/tess4j
|
src/main/java/net/sourceforge/tess4j/util/PdfUtilities.java
|
PdfUtilities.splitPdf
|
public static void splitPdf(String inputPdfFile, String outputPdfFile, String firstPage, String lastPage) {
"""
Splits PDF.
@deprecated As of Release 3.0.
@param inputPdfFile input file
@param outputPdfFile output file
@param firstPage begin page
@param lastPage end page
"""
if (firstPage.trim().isEmpty()) {
firstPage = "0";
}
if (lastPage.trim().isEmpty()) {
lastPage = "0";
}
splitPdf(new File(inputPdfFile), new File(outputPdfFile), Integer.parseInt(firstPage), Integer.parseInt(lastPage));
}
|
java
|
public static void splitPdf(String inputPdfFile, String outputPdfFile, String firstPage, String lastPage) {
if (firstPage.trim().isEmpty()) {
firstPage = "0";
}
if (lastPage.trim().isEmpty()) {
lastPage = "0";
}
splitPdf(new File(inputPdfFile), new File(outputPdfFile), Integer.parseInt(firstPage), Integer.parseInt(lastPage));
}
|
[
"public",
"static",
"void",
"splitPdf",
"(",
"String",
"inputPdfFile",
",",
"String",
"outputPdfFile",
",",
"String",
"firstPage",
",",
"String",
"lastPage",
")",
"{",
"if",
"(",
"firstPage",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"firstPage",
"=",
"\"0\"",
";",
"}",
"if",
"(",
"lastPage",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"lastPage",
"=",
"\"0\"",
";",
"}",
"splitPdf",
"(",
"new",
"File",
"(",
"inputPdfFile",
")",
",",
"new",
"File",
"(",
"outputPdfFile",
")",
",",
"Integer",
".",
"parseInt",
"(",
"firstPage",
")",
",",
"Integer",
".",
"parseInt",
"(",
"lastPage",
")",
")",
";",
"}"
] |
Splits PDF.
@deprecated As of Release 3.0.
@param inputPdfFile input file
@param outputPdfFile output file
@param firstPage begin page
@param lastPage end page
|
[
"Splits",
"PDF",
"."
] |
train
|
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/PdfUtilities.java#L82-L91
|
goldmansachs/gs-collections
|
collections/src/main/java/com/gs/collections/impl/utility/ListIterate.java
|
ListIterate.forEach
|
public static <T> void forEach(List<T> list, int from, int to, Procedure<? super T> procedure) {
"""
Iterates over the section of the list covered by the specified indexes. The indexes are both inclusive. If the
from is less than the to, the list is iterated in forward order. If the from is greater than the to, then the
list is iterated in the reverse order.
<p>
<pre>e.g.
MutableList<People> people = FastList.newListWith(ted, mary, bob, sally);
ListIterate.forEach(people, 0, 1, new Procedure<Person>()
{
public void value(Person person)
{
LOGGER.info(person.getName());
}
});
</pre>
<p>
This code would output ted and mary's names.
"""
ListIterate.rangeCheck(from, to, list.size());
if (list instanceof RandomAccess)
{
RandomAccessListIterate.forEach(list, from, to, procedure);
}
else
{
if (from <= to)
{
ListIterator<T> iterator = list.listIterator(from);
for (int i = from; i <= to; i++)
{
procedure.value(iterator.next());
}
}
else
{
ListIterator<T> iterator = list.listIterator(from + 1);
for (int i = from; i >= to; i--)
{
procedure.value(iterator.previous());
}
}
}
}
|
java
|
public static <T> void forEach(List<T> list, int from, int to, Procedure<? super T> procedure)
{
ListIterate.rangeCheck(from, to, list.size());
if (list instanceof RandomAccess)
{
RandomAccessListIterate.forEach(list, from, to, procedure);
}
else
{
if (from <= to)
{
ListIterator<T> iterator = list.listIterator(from);
for (int i = from; i <= to; i++)
{
procedure.value(iterator.next());
}
}
else
{
ListIterator<T> iterator = list.listIterator(from + 1);
for (int i = from; i >= to; i--)
{
procedure.value(iterator.previous());
}
}
}
}
|
[
"public",
"static",
"<",
"T",
">",
"void",
"forEach",
"(",
"List",
"<",
"T",
">",
"list",
",",
"int",
"from",
",",
"int",
"to",
",",
"Procedure",
"<",
"?",
"super",
"T",
">",
"procedure",
")",
"{",
"ListIterate",
".",
"rangeCheck",
"(",
"from",
",",
"to",
",",
"list",
".",
"size",
"(",
")",
")",
";",
"if",
"(",
"list",
"instanceof",
"RandomAccess",
")",
"{",
"RandomAccessListIterate",
".",
"forEach",
"(",
"list",
",",
"from",
",",
"to",
",",
"procedure",
")",
";",
"}",
"else",
"{",
"if",
"(",
"from",
"<=",
"to",
")",
"{",
"ListIterator",
"<",
"T",
">",
"iterator",
"=",
"list",
".",
"listIterator",
"(",
"from",
")",
";",
"for",
"(",
"int",
"i",
"=",
"from",
";",
"i",
"<=",
"to",
";",
"i",
"++",
")",
"{",
"procedure",
".",
"value",
"(",
"iterator",
".",
"next",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"ListIterator",
"<",
"T",
">",
"iterator",
"=",
"list",
".",
"listIterator",
"(",
"from",
"+",
"1",
")",
";",
"for",
"(",
"int",
"i",
"=",
"from",
";",
"i",
">=",
"to",
";",
"i",
"--",
")",
"{",
"procedure",
".",
"value",
"(",
"iterator",
".",
"previous",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
Iterates over the section of the list covered by the specified indexes. The indexes are both inclusive. If the
from is less than the to, the list is iterated in forward order. If the from is greater than the to, then the
list is iterated in the reverse order.
<p>
<pre>e.g.
MutableList<People> people = FastList.newListWith(ted, mary, bob, sally);
ListIterate.forEach(people, 0, 1, new Procedure<Person>()
{
public void value(Person person)
{
LOGGER.info(person.getName());
}
});
</pre>
<p>
This code would output ted and mary's names.
|
[
"Iterates",
"over",
"the",
"section",
"of",
"the",
"list",
"covered",
"by",
"the",
"specified",
"indexes",
".",
"The",
"indexes",
"are",
"both",
"inclusive",
".",
"If",
"the",
"from",
"is",
"less",
"than",
"the",
"to",
"the",
"list",
"is",
"iterated",
"in",
"forward",
"order",
".",
"If",
"the",
"from",
"is",
"greater",
"than",
"the",
"to",
"then",
"the",
"list",
"is",
"iterated",
"in",
"the",
"reverse",
"order",
".",
"<p",
">",
"<pre",
">",
"e",
".",
"g",
".",
"MutableList<People",
">",
"people",
"=",
"FastList",
".",
"newListWith",
"(",
"ted",
"mary",
"bob",
"sally",
")",
";",
"ListIterate",
".",
"forEach",
"(",
"people",
"0",
"1",
"new",
"Procedure<Person",
">",
"()",
"{",
"public",
"void",
"value",
"(",
"Person",
"person",
")",
"{",
"LOGGER",
".",
"info",
"(",
"person",
".",
"getName",
"()",
")",
";",
"}",
"}",
")",
";",
"<",
"/",
"pre",
">",
"<p",
">",
"This",
"code",
"would",
"output",
"ted",
"and",
"mary",
"s",
"names",
"."
] |
train
|
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/ListIterate.java#L706-L733
|
matthewhorridge/owlapi-gwt
|
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyDomainAxiomImpl_CustomFieldSerializer.java
|
OWLDataPropertyDomainAxiomImpl_CustomFieldSerializer.deserializeInstance
|
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataPropertyDomainAxiomImpl instance) throws SerializationException {
"""
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
"""
deserialize(streamReader, instance);
}
|
java
|
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataPropertyDomainAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
}
|
[
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLDataPropertyDomainAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] |
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
|
[
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] |
train
|
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataPropertyDomainAxiomImpl_CustomFieldSerializer.java#L98-L101
|
moparisthebest/beehive
|
beehive-netui-core/src/main/java/org/apache/beehive/netui/script/el/tokens/ExpressionToken.java
|
ExpressionToken.parseIndex
|
protected final int parseIndex(String indexString) {
"""
Attempt to convert a String indexString into an integer index.
@param indexString the index string
@return the converted integer
"""
try {
return Integer.parseInt(indexString);
} catch(Exception e) {
String msg = "Error converting \"" + indexString + "\" into an integer. Cause: " + e;
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
}
|
java
|
protected final int parseIndex(String indexString) {
try {
return Integer.parseInt(indexString);
} catch(Exception e) {
String msg = "Error converting \"" + indexString + "\" into an integer. Cause: " + e;
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
}
|
[
"protected",
"final",
"int",
"parseIndex",
"(",
"String",
"indexString",
")",
"{",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"indexString",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"msg",
"=",
"\"Error converting \\\"\"",
"+",
"indexString",
"+",
"\"\\\" into an integer. Cause: \"",
"+",
"e",
";",
"LOGGER",
".",
"error",
"(",
"msg",
",",
"e",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"msg",
",",
"e",
")",
";",
"}",
"}"
] |
Attempt to convert a String indexString into an integer index.
@param indexString the index string
@return the converted integer
|
[
"Attempt",
"to",
"convert",
"a",
"String",
"indexString",
"into",
"an",
"integer",
"index",
"."
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/script/el/tokens/ExpressionToken.java#L236-L244
|
andi12/msbuild-maven-plugin
|
msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/AbstractMSBuildPluginMojo.java
|
AbstractMSBuildPluginMojo.getRelativeFile
|
protected File getRelativeFile( File baseDir, File targetFile ) throws IOException {
"""
Compute the relative path portion from a path and a base directory.
If basedir and target are the same "." is returned.
For example: Given C:\foo\bar and C:\foo\bar\baz this method will return baz
@param baseDir the base directory
@param targetFile the path to express as relative to basedir
@return the relative portion of the path between basedir and target
@throws IOException if the target is not basedir or a subpath of basedir
"""
String baseDirStr = baseDir.getPath();
String targetDirStr = targetFile.getPath();
if ( targetDirStr.equals( baseDirStr ) )
{
return new File( "." );
}
else if ( targetDirStr.startsWith( baseDirStr + File.separator ) ) // add slash to ensure directory
{
return new File( targetDirStr.substring( baseDirStr.length() + 1 ) ); // + slash char
}
throw new IOException( "Unable to relativize " + targetDirStr + " to " + baseDir );
}
|
java
|
protected File getRelativeFile( File baseDir, File targetFile ) throws IOException
{
String baseDirStr = baseDir.getPath();
String targetDirStr = targetFile.getPath();
if ( targetDirStr.equals( baseDirStr ) )
{
return new File( "." );
}
else if ( targetDirStr.startsWith( baseDirStr + File.separator ) ) // add slash to ensure directory
{
return new File( targetDirStr.substring( baseDirStr.length() + 1 ) ); // + slash char
}
throw new IOException( "Unable to relativize " + targetDirStr + " to " + baseDir );
}
|
[
"protected",
"File",
"getRelativeFile",
"(",
"File",
"baseDir",
",",
"File",
"targetFile",
")",
"throws",
"IOException",
"{",
"String",
"baseDirStr",
"=",
"baseDir",
".",
"getPath",
"(",
")",
";",
"String",
"targetDirStr",
"=",
"targetFile",
".",
"getPath",
"(",
")",
";",
"if",
"(",
"targetDirStr",
".",
"equals",
"(",
"baseDirStr",
")",
")",
"{",
"return",
"new",
"File",
"(",
"\".\"",
")",
";",
"}",
"else",
"if",
"(",
"targetDirStr",
".",
"startsWith",
"(",
"baseDirStr",
"+",
"File",
".",
"separator",
")",
")",
"// add slash to ensure directory",
"{",
"return",
"new",
"File",
"(",
"targetDirStr",
".",
"substring",
"(",
"baseDirStr",
".",
"length",
"(",
")",
"+",
"1",
")",
")",
";",
"// + slash char",
"}",
"throw",
"new",
"IOException",
"(",
"\"Unable to relativize \"",
"+",
"targetDirStr",
"+",
"\" to \"",
"+",
"baseDir",
")",
";",
"}"
] |
Compute the relative path portion from a path and a base directory.
If basedir and target are the same "." is returned.
For example: Given C:\foo\bar and C:\foo\bar\baz this method will return baz
@param baseDir the base directory
@param targetFile the path to express as relative to basedir
@return the relative portion of the path between basedir and target
@throws IOException if the target is not basedir or a subpath of basedir
|
[
"Compute",
"the",
"relative",
"path",
"portion",
"from",
"a",
"path",
"and",
"a",
"base",
"directory",
".",
"If",
"basedir",
"and",
"target",
"are",
"the",
"same",
".",
"is",
"returned",
".",
"For",
"example",
":",
"Given",
"C",
":",
"\\",
"foo",
"\\",
"bar",
"and",
"C",
":",
"\\",
"foo",
"\\",
"bar",
"\\",
"baz",
"this",
"method",
"will",
"return",
"baz"
] |
train
|
https://github.com/andi12/msbuild-maven-plugin/blob/224159c15efba20d482f8c630f7947339b1a1b86/msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/AbstractMSBuildPluginMojo.java#L215-L230
|
lessthanoptimal/BoofCV
|
main/boofcv-recognition/src/main/java/boofcv/alg/scene/ClassifierKNearestNeighborsBow.java
|
ClassifierKNearestNeighborsBow.setClassificationData
|
public void setClassificationData(List<HistogramScene> memory , int numScenes ) {
"""
Provides a set of labeled word histograms to use to classify a new image
@param memory labeled histograms
"""
nn.setPoints(memory, false);
scenes = new double[ numScenes ];
}
|
java
|
public void setClassificationData(List<HistogramScene> memory , int numScenes ) {
nn.setPoints(memory, false);
scenes = new double[ numScenes ];
}
|
[
"public",
"void",
"setClassificationData",
"(",
"List",
"<",
"HistogramScene",
">",
"memory",
",",
"int",
"numScenes",
")",
"{",
"nn",
".",
"setPoints",
"(",
"memory",
",",
"false",
")",
";",
"scenes",
"=",
"new",
"double",
"[",
"numScenes",
"]",
";",
"}"
] |
Provides a set of labeled word histograms to use to classify a new image
@param memory labeled histograms
|
[
"Provides",
"a",
"set",
"of",
"labeled",
"word",
"histograms",
"to",
"use",
"to",
"classify",
"a",
"new",
"image"
] |
train
|
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/scene/ClassifierKNearestNeighborsBow.java#L98-L103
|
lagom/lagom
|
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/RequestHeader.java
|
RequestHeader.withMethod
|
public RequestHeader withMethod(Method method) {
"""
Return a copy of this request header with the given method set.
@param method The method to set.
@return A copy of this request header.
"""
return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, principal, headers, lowercaseHeaders);
}
|
java
|
public RequestHeader withMethod(Method method) {
return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, principal, headers, lowercaseHeaders);
}
|
[
"public",
"RequestHeader",
"withMethod",
"(",
"Method",
"method",
")",
"{",
"return",
"new",
"RequestHeader",
"(",
"method",
",",
"uri",
",",
"protocol",
",",
"acceptedResponseProtocols",
",",
"principal",
",",
"headers",
",",
"lowercaseHeaders",
")",
";",
"}"
] |
Return a copy of this request header with the given method set.
@param method The method to set.
@return A copy of this request header.
|
[
"Return",
"a",
"copy",
"of",
"this",
"request",
"header",
"with",
"the",
"given",
"method",
"set",
"."
] |
train
|
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/RequestHeader.java#L92-L94
|
OpenTSDB/opentsdb
|
src/core/TSDB.java
|
TSDB.getUID
|
public byte[] getUID(final UniqueIdType type, final String name) {
"""
Attempts to find the UID matching a given name
@param type The type of UID
@param name The name to search for
@throws IllegalArgumentException if the type is not valid
@throws NoSuchUniqueName if the name was not found
@since 2.0
"""
try {
return getUIDAsync(type, name).join();
} catch (NoSuchUniqueName e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
LOG.error("Unexpected exception", e);
throw new RuntimeException(e);
}
}
|
java
|
public byte[] getUID(final UniqueIdType type, final String name) {
try {
return getUIDAsync(type, name).join();
} catch (NoSuchUniqueName e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
LOG.error("Unexpected exception", e);
throw new RuntimeException(e);
}
}
|
[
"public",
"byte",
"[",
"]",
"getUID",
"(",
"final",
"UniqueIdType",
"type",
",",
"final",
"String",
"name",
")",
"{",
"try",
"{",
"return",
"getUIDAsync",
"(",
"type",
",",
"name",
")",
".",
"join",
"(",
")",
";",
"}",
"catch",
"(",
"NoSuchUniqueName",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Unexpected exception\"",
",",
"e",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Attempts to find the UID matching a given name
@param type The type of UID
@param name The name to search for
@throws IllegalArgumentException if the type is not valid
@throws NoSuchUniqueName if the name was not found
@since 2.0
|
[
"Attempts",
"to",
"find",
"the",
"UID",
"matching",
"a",
"given",
"name"
] |
train
|
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/TSDB.java#L667-L678
|
feedzai/pdb
|
src/main/java/com/feedzai/commons/sql/abstraction/dml/dialect/SqlBuilder.java
|
SqlBuilder.notIn
|
public static Expression notIn(final Expression e1, final Expression e2) {
"""
The NOT IN expression.
@param e1 The first expression.
@param e2 The second expression.
@return The expression.
"""
return new RepeatDelimiter(NOTIN, e1.isEnclosed() ? e1 : e1.enclose(), e2.isEnclosed() ? e2 : e2.enclose());
}
|
java
|
public static Expression notIn(final Expression e1, final Expression e2) {
return new RepeatDelimiter(NOTIN, e1.isEnclosed() ? e1 : e1.enclose(), e2.isEnclosed() ? e2 : e2.enclose());
}
|
[
"public",
"static",
"Expression",
"notIn",
"(",
"final",
"Expression",
"e1",
",",
"final",
"Expression",
"e2",
")",
"{",
"return",
"new",
"RepeatDelimiter",
"(",
"NOTIN",
",",
"e1",
".",
"isEnclosed",
"(",
")",
"?",
"e1",
":",
"e1",
".",
"enclose",
"(",
")",
",",
"e2",
".",
"isEnclosed",
"(",
")",
"?",
"e2",
":",
"e2",
".",
"enclose",
"(",
")",
")",
";",
"}"
] |
The NOT IN expression.
@param e1 The first expression.
@param e2 The second expression.
@return The expression.
|
[
"The",
"NOT",
"IN",
"expression",
"."
] |
train
|
https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/dml/dialect/SqlBuilder.java#L694-L696
|
EdwardRaff/JSAT
|
JSAT/src/jsat/utils/ListUtils.java
|
ListUtils.randomSample
|
public static <T> void randomSample(List<T> source, List<T> dest, int samples) {
"""
Obtains a random sample without replacement from a source list and places
it in the destination list. This is done without modifying the source list.
@param <T> the list content type involved
@param source the source of values to randomly sample from
@param dest the list to store the random samples in. The list does not
need to be empty for the sampling to work correctly
@param samples the number of samples to select from the source
@throws IllegalArgumentException if the sample size is not positive or l
arger than the source population.
"""
randomSample(source, dest, samples, RandomUtil.getRandom());
}
|
java
|
public static <T> void randomSample(List<T> source, List<T> dest, int samples)
{
randomSample(source, dest, samples, RandomUtil.getRandom());
}
|
[
"public",
"static",
"<",
"T",
">",
"void",
"randomSample",
"(",
"List",
"<",
"T",
">",
"source",
",",
"List",
"<",
"T",
">",
"dest",
",",
"int",
"samples",
")",
"{",
"randomSample",
"(",
"source",
",",
"dest",
",",
"samples",
",",
"RandomUtil",
".",
"getRandom",
"(",
")",
")",
";",
"}"
] |
Obtains a random sample without replacement from a source list and places
it in the destination list. This is done without modifying the source list.
@param <T> the list content type involved
@param source the source of values to randomly sample from
@param dest the list to store the random samples in. The list does not
need to be empty for the sampling to work correctly
@param samples the number of samples to select from the source
@throws IllegalArgumentException if the sample size is not positive or l
arger than the source population.
|
[
"Obtains",
"a",
"random",
"sample",
"without",
"replacement",
"from",
"a",
"source",
"list",
"and",
"places",
"it",
"in",
"the",
"destination",
"list",
".",
"This",
"is",
"done",
"without",
"modifying",
"the",
"source",
"list",
"."
] |
train
|
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/ListUtils.java#L237-L240
|
temyers/cucumber-jvm-parallel-plugin
|
src/main/java/com/github/timm/cucumber/generate/CucumberITGeneratorByScenario.java
|
CucumberITGeneratorByScenario.setFeatureFileLocation
|
private void setFeatureFileLocation(final File file, final Location location) {
"""
Sets the feature file location based on the given file. The full file path is trimmed to only include the
featuresDirectory. E.g. /myproject/src/test/resources/features/feature1.feature will be saved as
features/feature1.feature
@param file The feature file
"""
featureFileLocation = normalizePathSeparator(file).concat(":" + location.getLine());
}
|
java
|
private void setFeatureFileLocation(final File file, final Location location) {
featureFileLocation = normalizePathSeparator(file).concat(":" + location.getLine());
}
|
[
"private",
"void",
"setFeatureFileLocation",
"(",
"final",
"File",
"file",
",",
"final",
"Location",
"location",
")",
"{",
"featureFileLocation",
"=",
"normalizePathSeparator",
"(",
"file",
")",
".",
"concat",
"(",
"\":\"",
"+",
"location",
".",
"getLine",
"(",
")",
")",
";",
"}"
] |
Sets the feature file location based on the given file. The full file path is trimmed to only include the
featuresDirectory. E.g. /myproject/src/test/resources/features/feature1.feature will be saved as
features/feature1.feature
@param file The feature file
|
[
"Sets",
"the",
"feature",
"file",
"location",
"based",
"on",
"the",
"given",
"file",
".",
"The",
"full",
"file",
"path",
"is",
"trimmed",
"to",
"only",
"include",
"the",
"featuresDirectory",
".",
"E",
".",
"g",
".",
"/",
"myproject",
"/",
"src",
"/",
"test",
"/",
"resources",
"/",
"features",
"/",
"feature1",
".",
"feature",
"will",
"be",
"saved",
"as",
"features",
"/",
"feature1",
".",
"feature"
] |
train
|
https://github.com/temyers/cucumber-jvm-parallel-plugin/blob/931628fc1e2822be667ec216e10e706993974aa4/src/main/java/com/github/timm/cucumber/generate/CucumberITGeneratorByScenario.java#L197-L199
|
Azure/azure-sdk-for-java
|
datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java
|
ProjectsInner.listAsync
|
public Observable<Page<ProjectInner>> listAsync(final String groupName, final String serviceName) {
"""
Get projects in a service.
The project resource is a nested resource representing a stored migration project. This method returns a list of projects owned by a service resource.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ProjectInner> object
"""
return listWithServiceResponseAsync(groupName, serviceName)
.map(new Func1<ServiceResponse<Page<ProjectInner>>, Page<ProjectInner>>() {
@Override
public Page<ProjectInner> call(ServiceResponse<Page<ProjectInner>> response) {
return response.body();
}
});
}
|
java
|
public Observable<Page<ProjectInner>> listAsync(final String groupName, final String serviceName) {
return listWithServiceResponseAsync(groupName, serviceName)
.map(new Func1<ServiceResponse<Page<ProjectInner>>, Page<ProjectInner>>() {
@Override
public Page<ProjectInner> call(ServiceResponse<Page<ProjectInner>> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"Page",
"<",
"ProjectInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"groupName",
",",
"final",
"String",
"serviceName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectInner",
">",
">",
",",
"Page",
"<",
"ProjectInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"ProjectInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"ProjectInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Get projects in a service.
The project resource is a nested resource representing a stored migration project. This method returns a list of projects owned by a service resource.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ProjectInner> object
|
[
"Get",
"projects",
"in",
"a",
"service",
".",
"The",
"project",
"resource",
"is",
"a",
"nested",
"resource",
"representing",
"a",
"stored",
"migration",
"project",
".",
"This",
"method",
"returns",
"a",
"list",
"of",
"projects",
"owned",
"by",
"a",
"service",
"resource",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java#L143-L151
|
nguillaumin/slick2d-maven
|
slick2d-core/src/main/java/org/newdawn/slick/SpriteSheet.java
|
SpriteSheet.getSprite
|
public Image getSprite(int x, int y) {
"""
Get a sprite at a particular cell on the sprite sheet
@param x The x position of the cell on the sprite sheet
@param y The y position of the cell on the sprite sheet
@return The single image from the sprite sheet
"""
target.init();
initImpl();
if ((x < 0) || (x >= subImages.length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
if ((y < 0) || (y >= subImages[0].length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
return target.getSubImage(x*(tw+spacing) + margin, y*(th+spacing) + margin,tw,th);
}
|
java
|
public Image getSprite(int x, int y) {
target.init();
initImpl();
if ((x < 0) || (x >= subImages.length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
if ((y < 0) || (y >= subImages[0].length)) {
throw new RuntimeException("SubImage out of sheet bounds: "+x+","+y);
}
return target.getSubImage(x*(tw+spacing) + margin, y*(th+spacing) + margin,tw,th);
}
|
[
"public",
"Image",
"getSprite",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"target",
".",
"init",
"(",
")",
";",
"initImpl",
"(",
")",
";",
"if",
"(",
"(",
"x",
"<",
"0",
")",
"||",
"(",
"x",
">=",
"subImages",
".",
"length",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"SubImage out of sheet bounds: \"",
"+",
"x",
"+",
"\",\"",
"+",
"y",
")",
";",
"}",
"if",
"(",
"(",
"y",
"<",
"0",
")",
"||",
"(",
"y",
">=",
"subImages",
"[",
"0",
"]",
".",
"length",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"SubImage out of sheet bounds: \"",
"+",
"x",
"+",
"\",\"",
"+",
"y",
")",
";",
"}",
"return",
"target",
".",
"getSubImage",
"(",
"x",
"*",
"(",
"tw",
"+",
"spacing",
")",
"+",
"margin",
",",
"y",
"*",
"(",
"th",
"+",
"spacing",
")",
"+",
"margin",
",",
"tw",
",",
"th",
")",
";",
"}"
] |
Get a sprite at a particular cell on the sprite sheet
@param x The x position of the cell on the sprite sheet
@param y The y position of the cell on the sprite sheet
@return The single image from the sprite sheet
|
[
"Get",
"a",
"sprite",
"at",
"a",
"particular",
"cell",
"on",
"the",
"sprite",
"sheet"
] |
train
|
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/SpriteSheet.java#L218-L230
|
smartsheet-platform/smartsheet-java-sdk
|
src/main/java/com/smartsheet/api/internal/oauth/OAuthFlowImpl.java
|
OAuthFlowImpl.newAuthorizationURL
|
public String newAuthorizationURL(EnumSet<AccessScope> scopes, String state) {
"""
Generate a new authorization URL.
Exceptions: - IllegalArgumentException : if scopes is null/empty
@param scopes the scopes
@param state an arbitrary string that will be returned to your app; intended to be used by you to ensure that
this redirect is indeed from an OAuth flow that you initiated
@return the authorization URL
@throws UnsupportedEncodingException the unsupported encoding exception
"""
Util.throwIfNull(scopes);
if(state == null){state = "";}
// Build a map of parameters for the URL
HashMap<String,Object> params = new HashMap<String, Object>();
params.put("response_type", "code");
params.put("client_id", clientId);
params.put("redirect_uri", redirectURL);
params.put("state", state);
StringBuilder scopeBuffer = new StringBuilder();
for(AccessScope scope : scopes) {
scopeBuffer.append(scope.name()+",");
}
params.put("scope",scopeBuffer.substring(0,scopeBuffer.length()-1));
// Generate the URL with the parameters
return QueryUtil.generateUrl(authorizationURL, params);
}
|
java
|
public String newAuthorizationURL(EnumSet<AccessScope> scopes, String state) {
Util.throwIfNull(scopes);
if(state == null){state = "";}
// Build a map of parameters for the URL
HashMap<String,Object> params = new HashMap<String, Object>();
params.put("response_type", "code");
params.put("client_id", clientId);
params.put("redirect_uri", redirectURL);
params.put("state", state);
StringBuilder scopeBuffer = new StringBuilder();
for(AccessScope scope : scopes) {
scopeBuffer.append(scope.name()+",");
}
params.put("scope",scopeBuffer.substring(0,scopeBuffer.length()-1));
// Generate the URL with the parameters
return QueryUtil.generateUrl(authorizationURL, params);
}
|
[
"public",
"String",
"newAuthorizationURL",
"(",
"EnumSet",
"<",
"AccessScope",
">",
"scopes",
",",
"String",
"state",
")",
"{",
"Util",
".",
"throwIfNull",
"(",
"scopes",
")",
";",
"if",
"(",
"state",
"==",
"null",
")",
"{",
"state",
"=",
"\"\"",
";",
"}",
"// Build a map of parameters for the URL",
"HashMap",
"<",
"String",
",",
"Object",
">",
"params",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"params",
".",
"put",
"(",
"\"response_type\"",
",",
"\"code\"",
")",
";",
"params",
".",
"put",
"(",
"\"client_id\"",
",",
"clientId",
")",
";",
"params",
".",
"put",
"(",
"\"redirect_uri\"",
",",
"redirectURL",
")",
";",
"params",
".",
"put",
"(",
"\"state\"",
",",
"state",
")",
";",
"StringBuilder",
"scopeBuffer",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"AccessScope",
"scope",
":",
"scopes",
")",
"{",
"scopeBuffer",
".",
"append",
"(",
"scope",
".",
"name",
"(",
")",
"+",
"\",\"",
")",
";",
"}",
"params",
".",
"put",
"(",
"\"scope\"",
",",
"scopeBuffer",
".",
"substring",
"(",
"0",
",",
"scopeBuffer",
".",
"length",
"(",
")",
"-",
"1",
")",
")",
";",
"// Generate the URL with the parameters",
"return",
"QueryUtil",
".",
"generateUrl",
"(",
"authorizationURL",
",",
"params",
")",
";",
"}"
] |
Generate a new authorization URL.
Exceptions: - IllegalArgumentException : if scopes is null/empty
@param scopes the scopes
@param state an arbitrary string that will be returned to your app; intended to be used by you to ensure that
this redirect is indeed from an OAuth flow that you initiated
@return the authorization URL
@throws UnsupportedEncodingException the unsupported encoding exception
|
[
"Generate",
"a",
"new",
"authorization",
"URL",
"."
] |
train
|
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/oauth/OAuthFlowImpl.java#L136-L155
|
Waikato/moa
|
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
|
MTree.getNearestByRange
|
public Query getNearestByRange(DATA queryData, double range) {
"""
Performs a nearest-neighbors query on the M-Tree, constrained by distance.
@param queryData The query data object.
@param range The maximum distance from {@code queryData} to fetched
neighbors.
@return A {@link Query} object used to iterate on the results.
"""
return getNearest(queryData, range, Integer.MAX_VALUE);
}
|
java
|
public Query getNearestByRange(DATA queryData, double range) {
return getNearest(queryData, range, Integer.MAX_VALUE);
}
|
[
"public",
"Query",
"getNearestByRange",
"(",
"DATA",
"queryData",
",",
"double",
"range",
")",
"{",
"return",
"getNearest",
"(",
"queryData",
",",
"range",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"}"
] |
Performs a nearest-neighbors query on the M-Tree, constrained by distance.
@param queryData The query data object.
@param range The maximum distance from {@code queryData} to fetched
neighbors.
@return A {@link Query} object used to iterate on the results.
|
[
"Performs",
"a",
"nearest",
"-",
"neighbors",
"query",
"on",
"the",
"M",
"-",
"Tree",
"constrained",
"by",
"distance",
"."
] |
train
|
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L410-L412
|
kmi/iserve
|
iserve-discovery-api/src/main/java/uk/ac/open/kmi/iserve/discovery/api/impl/AbstractMatcher.java
|
AbstractMatcher.listMatchesAtMostOfType
|
@Override
public Table<URI, URI, MatchResult> listMatchesAtMostOfType(Set<URI> origins, MatchType maxType) {
"""
Obtain all the matching resources that have a MatchTyoe with the URIs of {@code origin} of the type provided (inclusive) or less.
@param origins URIs to match
@param maxType the maximum MatchType we want to obtain
@return a {@link com.google.common.collect.Table} with the result of the matching indexed by origin URI and then destination URI.
"""
return listMatchesWithinRange(origins, this.matchTypesSupported.getLowest(), maxType);
}
|
java
|
@Override
public Table<URI, URI, MatchResult> listMatchesAtMostOfType(Set<URI> origins, MatchType maxType) {
return listMatchesWithinRange(origins, this.matchTypesSupported.getLowest(), maxType);
}
|
[
"@",
"Override",
"public",
"Table",
"<",
"URI",
",",
"URI",
",",
"MatchResult",
">",
"listMatchesAtMostOfType",
"(",
"Set",
"<",
"URI",
">",
"origins",
",",
"MatchType",
"maxType",
")",
"{",
"return",
"listMatchesWithinRange",
"(",
"origins",
",",
"this",
".",
"matchTypesSupported",
".",
"getLowest",
"(",
")",
",",
"maxType",
")",
";",
"}"
] |
Obtain all the matching resources that have a MatchTyoe with the URIs of {@code origin} of the type provided (inclusive) or less.
@param origins URIs to match
@param maxType the maximum MatchType we want to obtain
@return a {@link com.google.common.collect.Table} with the result of the matching indexed by origin URI and then destination URI.
|
[
"Obtain",
"all",
"the",
"matching",
"resources",
"that",
"have",
"a",
"MatchTyoe",
"with",
"the",
"URIs",
"of",
"{",
"@code",
"origin",
"}",
"of",
"the",
"type",
"provided",
"(",
"inclusive",
")",
"or",
"less",
"."
] |
train
|
https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-discovery-api/src/main/java/uk/ac/open/kmi/iserve/discovery/api/impl/AbstractMatcher.java#L135-L138
|
sebastiangraf/perfidix
|
src/main/java/org/perfidix/ouput/asciitable/NiceTable.java
|
NiceTable.updateColumnWidth
|
void updateColumnWidth(final int index, final int newSize) {
"""
Performs an update on the column lengths.
@param index
the index of the column
@param newSize
the new size of the column
"""
columnLengths[index] = Math.max(columnLengths[index], newSize);
}
|
java
|
void updateColumnWidth(final int index, final int newSize) {
columnLengths[index] = Math.max(columnLengths[index], newSize);
}
|
[
"void",
"updateColumnWidth",
"(",
"final",
"int",
"index",
",",
"final",
"int",
"newSize",
")",
"{",
"columnLengths",
"[",
"index",
"]",
"=",
"Math",
".",
"max",
"(",
"columnLengths",
"[",
"index",
"]",
",",
"newSize",
")",
";",
"}"
] |
Performs an update on the column lengths.
@param index
the index of the column
@param newSize
the new size of the column
|
[
"Performs",
"an",
"update",
"on",
"the",
"column",
"lengths",
"."
] |
train
|
https://github.com/sebastiangraf/perfidix/blob/f13aa793b6a3055215ed4edbb946c1bb5d564886/src/main/java/org/perfidix/ouput/asciitable/NiceTable.java#L167-L169
|
voldemort/voldemort
|
src/java/voldemort/utils/ReflectUtils.java
|
ReflectUtils.getMethod
|
public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {
"""
Get the named method from the class
@param c The class to get the method from
@param name The method name
@param argTypes The argument types
@return The method
"""
try {
return c.getMethod(name, argTypes);
} catch(NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
|
java
|
public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {
try {
return c.getMethod(name, argTypes);
} catch(NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
|
[
"public",
"static",
"<",
"T",
">",
"Method",
"getMethod",
"(",
"Class",
"<",
"T",
">",
"c",
",",
"String",
"name",
",",
"Class",
"<",
"?",
">",
"...",
"argTypes",
")",
"{",
"try",
"{",
"return",
"c",
".",
"getMethod",
"(",
"name",
",",
"argTypes",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"e",
")",
";",
"}",
"}"
] |
Get the named method from the class
@param c The class to get the method from
@param name The method name
@param argTypes The argument types
@return The method
|
[
"Get",
"the",
"named",
"method",
"from",
"the",
"class"
] |
train
|
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/ReflectUtils.java#L160-L166
|
apache/incubator-gobblin
|
gobblin-api/src/main/java/org/apache/gobblin/configuration/WorkUnitState.java
|
WorkUnitState.getActualHighWatermark
|
public <T extends Watermark> T getActualHighWatermark(Class<T> watermarkClass, Gson gson) {
"""
Get the actual high {@link Watermark}. If the {@code WorkUnitState} does not contain the actual high watermark
(which may be caused by task failures), the low watermark in the corresponding {@link WorkUnit} will be returned.
@param watermarkClass the watermark class for this {@code WorkUnitState}.
@param gson a {@link Gson} object used to deserialize the watermark.
@return the actual high watermark in this {@code WorkUnitState}. null is returned if this {@code WorkUnitState}
does not contain an actual high watermark, and the corresponding {@code WorkUnit} does not contain a low
watermark.
"""
JsonElement json = getActualHighWatermark();
if (json == null) {
json = this.workUnit.getLowWatermark();
if (json == null) {
return null;
}
}
return gson.fromJson(json, watermarkClass);
}
|
java
|
public <T extends Watermark> T getActualHighWatermark(Class<T> watermarkClass, Gson gson) {
JsonElement json = getActualHighWatermark();
if (json == null) {
json = this.workUnit.getLowWatermark();
if (json == null) {
return null;
}
}
return gson.fromJson(json, watermarkClass);
}
|
[
"public",
"<",
"T",
"extends",
"Watermark",
">",
"T",
"getActualHighWatermark",
"(",
"Class",
"<",
"T",
">",
"watermarkClass",
",",
"Gson",
"gson",
")",
"{",
"JsonElement",
"json",
"=",
"getActualHighWatermark",
"(",
")",
";",
"if",
"(",
"json",
"==",
"null",
")",
"{",
"json",
"=",
"this",
".",
"workUnit",
".",
"getLowWatermark",
"(",
")",
";",
"if",
"(",
"json",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"}",
"return",
"gson",
".",
"fromJson",
"(",
"json",
",",
"watermarkClass",
")",
";",
"}"
] |
Get the actual high {@link Watermark}. If the {@code WorkUnitState} does not contain the actual high watermark
(which may be caused by task failures), the low watermark in the corresponding {@link WorkUnit} will be returned.
@param watermarkClass the watermark class for this {@code WorkUnitState}.
@param gson a {@link Gson} object used to deserialize the watermark.
@return the actual high watermark in this {@code WorkUnitState}. null is returned if this {@code WorkUnitState}
does not contain an actual high watermark, and the corresponding {@code WorkUnit} does not contain a low
watermark.
|
[
"Get",
"the",
"actual",
"high",
"{",
"@link",
"Watermark",
"}",
".",
"If",
"the",
"{",
"@code",
"WorkUnitState",
"}",
"does",
"not",
"contain",
"the",
"actual",
"high",
"watermark",
"(",
"which",
"may",
"be",
"caused",
"by",
"task",
"failures",
")",
"the",
"low",
"watermark",
"in",
"the",
"corresponding",
"{",
"@link",
"WorkUnit",
"}",
"will",
"be",
"returned",
"."
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/WorkUnitState.java#L218-L227
|
deeplearning4j/deeplearning4j
|
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
|
SameDiff.addPropertyToResolve
|
public void addPropertyToResolve(DifferentialFunction forFunction, String arrayName) {
"""
Adds a property that needs to be resolve for later.
These variables are typically values that are arrays
that are named but have an unknown value till execution time.
<p>
This is very common for model import.
@param forFunction the function to add the property to resolve for
@param arrayName the array name
"""
if (!propertiesToResolve.containsKey(forFunction.getOwnName())) {
List<String> newVal = new ArrayList<>();
newVal.add(arrayName);
propertiesToResolve.put(forFunction.getOwnName(), newVal);
} else {
List<String> newVal = propertiesToResolve.get(forFunction.getOwnName());
newVal.add(arrayName);
}
}
|
java
|
public void addPropertyToResolve(DifferentialFunction forFunction, String arrayName) {
if (!propertiesToResolve.containsKey(forFunction.getOwnName())) {
List<String> newVal = new ArrayList<>();
newVal.add(arrayName);
propertiesToResolve.put(forFunction.getOwnName(), newVal);
} else {
List<String> newVal = propertiesToResolve.get(forFunction.getOwnName());
newVal.add(arrayName);
}
}
|
[
"public",
"void",
"addPropertyToResolve",
"(",
"DifferentialFunction",
"forFunction",
",",
"String",
"arrayName",
")",
"{",
"if",
"(",
"!",
"propertiesToResolve",
".",
"containsKey",
"(",
"forFunction",
".",
"getOwnName",
"(",
")",
")",
")",
"{",
"List",
"<",
"String",
">",
"newVal",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"newVal",
".",
"add",
"(",
"arrayName",
")",
";",
"propertiesToResolve",
".",
"put",
"(",
"forFunction",
".",
"getOwnName",
"(",
")",
",",
"newVal",
")",
";",
"}",
"else",
"{",
"List",
"<",
"String",
">",
"newVal",
"=",
"propertiesToResolve",
".",
"get",
"(",
"forFunction",
".",
"getOwnName",
"(",
")",
")",
";",
"newVal",
".",
"add",
"(",
"arrayName",
")",
";",
"}",
"}"
] |
Adds a property that needs to be resolve for later.
These variables are typically values that are arrays
that are named but have an unknown value till execution time.
<p>
This is very common for model import.
@param forFunction the function to add the property to resolve for
@param arrayName the array name
|
[
"Adds",
"a",
"property",
"that",
"needs",
"to",
"be",
"resolve",
"for",
"later",
".",
"These",
"variables",
"are",
"typically",
"values",
"that",
"are",
"arrays",
"that",
"are",
"named",
"but",
"have",
"an",
"unknown",
"value",
"till",
"execution",
"time",
".",
"<p",
">",
"This",
"is",
"very",
"common",
"for",
"model",
"import",
"."
] |
train
|
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L975-L984
|
alkacon/opencms-core
|
src-setup/org/opencms/setup/CmsSetupDb.java
|
CmsSetupDb.setConnection
|
public void setConnection(String DbDriver, String DbConStr, String DbConStrParams, String DbUser, String DbPwd) {
"""
Creates a new internal connection to the database.<p>
@param DbDriver JDBC driver class name
@param DbConStr JDBC connect URL
@param DbConStrParams JDBC connect URL params, or null
@param DbUser JDBC database user
@param DbPwd JDBC database password
"""
setConnection(DbDriver, DbConStr, DbConStrParams, DbUser, DbPwd, true);
}
|
java
|
public void setConnection(String DbDriver, String DbConStr, String DbConStrParams, String DbUser, String DbPwd) {
setConnection(DbDriver, DbConStr, DbConStrParams, DbUser, DbPwd, true);
}
|
[
"public",
"void",
"setConnection",
"(",
"String",
"DbDriver",
",",
"String",
"DbConStr",
",",
"String",
"DbConStrParams",
",",
"String",
"DbUser",
",",
"String",
"DbPwd",
")",
"{",
"setConnection",
"(",
"DbDriver",
",",
"DbConStr",
",",
"DbConStrParams",
",",
"DbUser",
",",
"DbPwd",
",",
"true",
")",
";",
"}"
] |
Creates a new internal connection to the database.<p>
@param DbDriver JDBC driver class name
@param DbConStr JDBC connect URL
@param DbConStrParams JDBC connect URL params, or null
@param DbUser JDBC database user
@param DbPwd JDBC database password
|
[
"Creates",
"a",
"new",
"internal",
"connection",
"to",
"the",
"database",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupDb.java#L486-L489
|
dmurph/jgoogleanalyticstracker
|
src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java
|
JGoogleAnalyticsTracker.trackEvent
|
public void trackEvent(String argCategory, String argAction, String argLabel, Integer argValue) {
"""
Tracks an event. To provide more info about the page, use
{@link #makeCustomRequest(AnalyticsRequestData)}.
@param argCategory
required
@param argAction
required
@param argLabel
optional
@param argValue
optional
"""
AnalyticsRequestData data = new AnalyticsRequestData();
data.setEventCategory(argCategory);
data.setEventAction(argAction);
data.setEventLabel(argLabel);
data.setEventValue(argValue);
makeCustomRequest(data);
}
|
java
|
public void trackEvent(String argCategory, String argAction, String argLabel, Integer argValue) {
AnalyticsRequestData data = new AnalyticsRequestData();
data.setEventCategory(argCategory);
data.setEventAction(argAction);
data.setEventLabel(argLabel);
data.setEventValue(argValue);
makeCustomRequest(data);
}
|
[
"public",
"void",
"trackEvent",
"(",
"String",
"argCategory",
",",
"String",
"argAction",
",",
"String",
"argLabel",
",",
"Integer",
"argValue",
")",
"{",
"AnalyticsRequestData",
"data",
"=",
"new",
"AnalyticsRequestData",
"(",
")",
";",
"data",
".",
"setEventCategory",
"(",
"argCategory",
")",
";",
"data",
".",
"setEventAction",
"(",
"argAction",
")",
";",
"data",
".",
"setEventLabel",
"(",
"argLabel",
")",
";",
"data",
".",
"setEventValue",
"(",
"argValue",
")",
";",
"makeCustomRequest",
"(",
"data",
")",
";",
"}"
] |
Tracks an event. To provide more info about the page, use
{@link #makeCustomRequest(AnalyticsRequestData)}.
@param argCategory
required
@param argAction
required
@param argLabel
optional
@param argValue
optional
|
[
"Tracks",
"an",
"event",
".",
"To",
"provide",
"more",
"info",
"about",
"the",
"page",
"use",
"{",
"@link",
"#makeCustomRequest",
"(",
"AnalyticsRequestData",
")",
"}",
"."
] |
train
|
https://github.com/dmurph/jgoogleanalyticstracker/blob/69f68caf8e09a53e6f6076477bf05b84bc80e386/src/main/java/com/dmurph/tracking/JGoogleAnalyticsTracker.java#L393-L401
|
eurekaclinical/protempa
|
protempa-framework/src/main/java/org/protempa/proposition/CopyPropositionVisitor.java
|
CopyPropositionVisitor.setReferences
|
public void setReferences(Map<String, List<UniqueId>> references) {
"""
Overrides the references for copies made with this visitor.
@param references a map of reference name to reference pairs, or
<code>null</code> to use the original proposition's value for this field.
"""
if (references != null) {
this.references = new HashMap<>(references);
} else {
this.references = null;
}
}
|
java
|
public void setReferences(Map<String, List<UniqueId>> references) {
if (references != null) {
this.references = new HashMap<>(references);
} else {
this.references = null;
}
}
|
[
"public",
"void",
"setReferences",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"UniqueId",
">",
">",
"references",
")",
"{",
"if",
"(",
"references",
"!=",
"null",
")",
"{",
"this",
".",
"references",
"=",
"new",
"HashMap",
"<>",
"(",
"references",
")",
";",
"}",
"else",
"{",
"this",
".",
"references",
"=",
"null",
";",
"}",
"}"
] |
Overrides the references for copies made with this visitor.
@param references a map of reference name to reference pairs, or
<code>null</code> to use the original proposition's value for this field.
|
[
"Overrides",
"the",
"references",
"for",
"copies",
"made",
"with",
"this",
"visitor",
"."
] |
train
|
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/proposition/CopyPropositionVisitor.java#L98-L104
|
hyperledger/fabric-sdk-java
|
src/main/java/org/hyperledger/fabric/sdk/idemix/IdemixUtils.java
|
IdemixUtils.transformFromProto
|
static ECP2 transformFromProto(Idemix.ECP2 w) {
"""
Returns an amcl.BN256.ECP2 on input of an ECP2 protobuf object.
@param w a protobuf object representing an ECP2
@return a ECP2 created from the protobuf object
"""
byte[] valuexa = w.getXa().toByteArray();
byte[] valuexb = w.getXb().toByteArray();
byte[] valueya = w.getYa().toByteArray();
byte[] valueyb = w.getYb().toByteArray();
FP2 valuex = new FP2(BIG.fromBytes(valuexa), BIG.fromBytes(valuexb));
FP2 valuey = new FP2(BIG.fromBytes(valueya), BIG.fromBytes(valueyb));
return new ECP2(valuex, valuey);
}
|
java
|
static ECP2 transformFromProto(Idemix.ECP2 w) {
byte[] valuexa = w.getXa().toByteArray();
byte[] valuexb = w.getXb().toByteArray();
byte[] valueya = w.getYa().toByteArray();
byte[] valueyb = w.getYb().toByteArray();
FP2 valuex = new FP2(BIG.fromBytes(valuexa), BIG.fromBytes(valuexb));
FP2 valuey = new FP2(BIG.fromBytes(valueya), BIG.fromBytes(valueyb));
return new ECP2(valuex, valuey);
}
|
[
"static",
"ECP2",
"transformFromProto",
"(",
"Idemix",
".",
"ECP2",
"w",
")",
"{",
"byte",
"[",
"]",
"valuexa",
"=",
"w",
".",
"getXa",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"byte",
"[",
"]",
"valuexb",
"=",
"w",
".",
"getXb",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"byte",
"[",
"]",
"valueya",
"=",
"w",
".",
"getYa",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"byte",
"[",
"]",
"valueyb",
"=",
"w",
".",
"getYb",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"FP2",
"valuex",
"=",
"new",
"FP2",
"(",
"BIG",
".",
"fromBytes",
"(",
"valuexa",
")",
",",
"BIG",
".",
"fromBytes",
"(",
"valuexb",
")",
")",
";",
"FP2",
"valuey",
"=",
"new",
"FP2",
"(",
"BIG",
".",
"fromBytes",
"(",
"valueya",
")",
",",
"BIG",
".",
"fromBytes",
"(",
"valueyb",
")",
")",
";",
"return",
"new",
"ECP2",
"(",
"valuex",
",",
"valuey",
")",
";",
"}"
] |
Returns an amcl.BN256.ECP2 on input of an ECP2 protobuf object.
@param w a protobuf object representing an ECP2
@return a ECP2 created from the protobuf object
|
[
"Returns",
"an",
"amcl",
".",
"BN256",
".",
"ECP2",
"on",
"input",
"of",
"an",
"ECP2",
"protobuf",
"object",
"."
] |
train
|
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/idemix/IdemixUtils.java#L198-L206
|
petergeneric/stdlib
|
stdlib/src/main/java/com/peterphi/std/crypto/digest/DigestHelper.java
|
DigestHelper.sha1hmac
|
public static String sha1hmac(String key, String plaintext, int encoding) {
"""
Performs HMAC-SHA1 on the UTF-8 byte representation of strings, returning the hexidecimal hash as a result
@param key
@param plaintext
@return
"""
byte[] signature = sha1hmac(key.getBytes(), plaintext.getBytes());
return encode(signature, encoding);
}
|
java
|
public static String sha1hmac(String key, String plaintext, int encoding)
{
byte[] signature = sha1hmac(key.getBytes(), plaintext.getBytes());
return encode(signature, encoding);
}
|
[
"public",
"static",
"String",
"sha1hmac",
"(",
"String",
"key",
",",
"String",
"plaintext",
",",
"int",
"encoding",
")",
"{",
"byte",
"[",
"]",
"signature",
"=",
"sha1hmac",
"(",
"key",
".",
"getBytes",
"(",
")",
",",
"plaintext",
".",
"getBytes",
"(",
")",
")",
";",
"return",
"encode",
"(",
"signature",
",",
"encoding",
")",
";",
"}"
] |
Performs HMAC-SHA1 on the UTF-8 byte representation of strings, returning the hexidecimal hash as a result
@param key
@param plaintext
@return
|
[
"Performs",
"HMAC",
"-",
"SHA1",
"on",
"the",
"UTF",
"-",
"8",
"byte",
"representation",
"of",
"strings",
"returning",
"the",
"hexidecimal",
"hash",
"as",
"a",
"result"
] |
train
|
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/crypto/digest/DigestHelper.java#L56-L61
|
alkacon/opencms-core
|
src/org/opencms/security/CmsPrincipal.java
|
CmsPrincipal.getDisplayName
|
public String getDisplayName(CmsObject cms, Locale locale, I_CmsGroupNameTranslation translation)
throws CmsException {
"""
Returns the translated display name of this principal if it is a group and the display name otherwise.<p>
@param cms the current CMS context
@param locale the locale
@param translation the group name translation to use
@return the translated display name
@throws CmsException if something goes wrong
"""
if (!isGroup() || (translation == null)) {
return getDisplayName(cms, locale);
}
return Messages.get().getBundle(locale).key(
Messages.GUI_PRINCIPAL_DISPLAY_NAME_2,
translation.translateGroupName(getName(), false),
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, getOuFqn()).getDisplayName(locale));
}
|
java
|
public String getDisplayName(CmsObject cms, Locale locale, I_CmsGroupNameTranslation translation)
throws CmsException {
if (!isGroup() || (translation == null)) {
return getDisplayName(cms, locale);
}
return Messages.get().getBundle(locale).key(
Messages.GUI_PRINCIPAL_DISPLAY_NAME_2,
translation.translateGroupName(getName(), false),
OpenCms.getOrgUnitManager().readOrganizationalUnit(cms, getOuFqn()).getDisplayName(locale));
}
|
[
"public",
"String",
"getDisplayName",
"(",
"CmsObject",
"cms",
",",
"Locale",
"locale",
",",
"I_CmsGroupNameTranslation",
"translation",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isGroup",
"(",
")",
"||",
"(",
"translation",
"==",
"null",
")",
")",
"{",
"return",
"getDisplayName",
"(",
"cms",
",",
"locale",
")",
";",
"}",
"return",
"Messages",
".",
"get",
"(",
")",
".",
"getBundle",
"(",
"locale",
")",
".",
"key",
"(",
"Messages",
".",
"GUI_PRINCIPAL_DISPLAY_NAME_2",
",",
"translation",
".",
"translateGroupName",
"(",
"getName",
"(",
")",
",",
"false",
")",
",",
"OpenCms",
".",
"getOrgUnitManager",
"(",
")",
".",
"readOrganizationalUnit",
"(",
"cms",
",",
"getOuFqn",
"(",
")",
")",
".",
"getDisplayName",
"(",
"locale",
")",
")",
";",
"}"
] |
Returns the translated display name of this principal if it is a group and the display name otherwise.<p>
@param cms the current CMS context
@param locale the locale
@param translation the group name translation to use
@return the translated display name
@throws CmsException if something goes wrong
|
[
"Returns",
"the",
"translated",
"display",
"name",
"of",
"this",
"principal",
"if",
"it",
"is",
"a",
"group",
"and",
"the",
"display",
"name",
"otherwise",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsPrincipal.java#L427-L437
|
wildfly/wildfly-core
|
server/src/main/java/org/jboss/as/server/deployment/reflect/DeploymentReflectionIndex.java
|
DeploymentReflectionIndex.getClassIndex
|
@SuppressWarnings( {
"""
Get the (possibly cached) index for a given class.
@param clazz the class
@return the index
""""unchecked"})
public synchronized ClassReflectionIndex getClassIndex(Class clazz) {
try {
ClassReflectionIndex index = classes.get(clazz);
if (index == null) {
final SecurityManager sm = System.getSecurityManager();
if (sm == null) {
index = new ClassReflectionIndex(clazz, this);
} else {
index = AccessController.doPrivileged((PrivilegedAction<ClassReflectionIndex>) () -> new ClassReflectionIndex(clazz, this));
}
classes.put(clazz, index);
}
return index;
} catch (Throwable e) {
throw ServerLogger.ROOT_LOGGER.errorGettingReflectiveInformation(clazz, clazz.getClassLoader(), e);
}
}
|
java
|
@SuppressWarnings({"unchecked"})
public synchronized ClassReflectionIndex getClassIndex(Class clazz) {
try {
ClassReflectionIndex index = classes.get(clazz);
if (index == null) {
final SecurityManager sm = System.getSecurityManager();
if (sm == null) {
index = new ClassReflectionIndex(clazz, this);
} else {
index = AccessController.doPrivileged((PrivilegedAction<ClassReflectionIndex>) () -> new ClassReflectionIndex(clazz, this));
}
classes.put(clazz, index);
}
return index;
} catch (Throwable e) {
throw ServerLogger.ROOT_LOGGER.errorGettingReflectiveInformation(clazz, clazz.getClassLoader(), e);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
"}",
")",
"public",
"synchronized",
"ClassReflectionIndex",
"getClassIndex",
"(",
"Class",
"clazz",
")",
"{",
"try",
"{",
"ClassReflectionIndex",
"index",
"=",
"classes",
".",
"get",
"(",
"clazz",
")",
";",
"if",
"(",
"index",
"==",
"null",
")",
"{",
"final",
"SecurityManager",
"sm",
"=",
"System",
".",
"getSecurityManager",
"(",
")",
";",
"if",
"(",
"sm",
"==",
"null",
")",
"{",
"index",
"=",
"new",
"ClassReflectionIndex",
"(",
"clazz",
",",
"this",
")",
";",
"}",
"else",
"{",
"index",
"=",
"AccessController",
".",
"doPrivileged",
"(",
"(",
"PrivilegedAction",
"<",
"ClassReflectionIndex",
">",
")",
"(",
")",
"->",
"new",
"ClassReflectionIndex",
"(",
"clazz",
",",
"this",
")",
")",
";",
"}",
"classes",
".",
"put",
"(",
"clazz",
",",
"index",
")",
";",
"}",
"return",
"index",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"ServerLogger",
".",
"ROOT_LOGGER",
".",
"errorGettingReflectiveInformation",
"(",
"clazz",
",",
"clazz",
".",
"getClassLoader",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] |
Get the (possibly cached) index for a given class.
@param clazz the class
@return the index
|
[
"Get",
"the",
"(",
"possibly",
"cached",
")",
"index",
"for",
"a",
"given",
"class",
"."
] |
train
|
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/reflect/DeploymentReflectionIndex.java#L63-L80
|
Azure/azure-sdk-for-java
|
compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/DisksInner.java
|
DisksInner.beginCreateOrUpdate
|
public DiskInner beginCreateOrUpdate(String resourceGroupName, String diskName, DiskInner disk) {
"""
Creates or updates a disk.
@param resourceGroupName The name of the resource group.
@param diskName The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
@param disk Disk object supplied in the body of the Put disk operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DiskInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, diskName, disk).toBlocking().single().body();
}
|
java
|
public DiskInner beginCreateOrUpdate(String resourceGroupName, String diskName, DiskInner disk) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, diskName, disk).toBlocking().single().body();
}
|
[
"public",
"DiskInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"diskName",
",",
"DiskInner",
"disk",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"diskName",
",",
"disk",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Creates or updates a disk.
@param resourceGroupName The name of the resource group.
@param diskName The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters.
@param disk Disk object supplied in the body of the Put disk operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DiskInner object if successful.
|
[
"Creates",
"or",
"updates",
"a",
"disk",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/DisksInner.java#L221-L223
|
gallandarakhneorg/afc
|
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/Vector2dfx.java
|
Vector2dfx.lengthProperty
|
public ReadOnlyDoubleProperty lengthProperty() {
"""
Replies the property that represents the length of the vector.
@return the length property
"""
if (this.lengthProperty == null) {
this.lengthProperty = new ReadOnlyDoubleWrapper(this, MathFXAttributeNames.LENGTH);
this.lengthProperty.bind(Bindings.createDoubleBinding(() ->
Math.sqrt(lengthSquaredProperty().doubleValue()), lengthSquaredProperty()));
}
return this.lengthProperty.getReadOnlyProperty();
}
|
java
|
public ReadOnlyDoubleProperty lengthProperty() {
if (this.lengthProperty == null) {
this.lengthProperty = new ReadOnlyDoubleWrapper(this, MathFXAttributeNames.LENGTH);
this.lengthProperty.bind(Bindings.createDoubleBinding(() ->
Math.sqrt(lengthSquaredProperty().doubleValue()), lengthSquaredProperty()));
}
return this.lengthProperty.getReadOnlyProperty();
}
|
[
"public",
"ReadOnlyDoubleProperty",
"lengthProperty",
"(",
")",
"{",
"if",
"(",
"this",
".",
"lengthProperty",
"==",
"null",
")",
"{",
"this",
".",
"lengthProperty",
"=",
"new",
"ReadOnlyDoubleWrapper",
"(",
"this",
",",
"MathFXAttributeNames",
".",
"LENGTH",
")",
";",
"this",
".",
"lengthProperty",
".",
"bind",
"(",
"Bindings",
".",
"createDoubleBinding",
"(",
"(",
")",
"->",
"Math",
".",
"sqrt",
"(",
"lengthSquaredProperty",
"(",
")",
".",
"doubleValue",
"(",
")",
")",
",",
"lengthSquaredProperty",
"(",
")",
")",
")",
";",
"}",
"return",
"this",
".",
"lengthProperty",
".",
"getReadOnlyProperty",
"(",
")",
";",
"}"
] |
Replies the property that represents the length of the vector.
@return the length property
|
[
"Replies",
"the",
"property",
"that",
"represents",
"the",
"length",
"of",
"the",
"vector",
"."
] |
train
|
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d2/dfx/Vector2dfx.java#L170-L177
|
Azure/azure-sdk-for-java
|
devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java
|
ControllersInner.listConnectionDetails
|
public ControllerConnectionDetailsListInner listConnectionDetails(String resourceGroupName, String name) {
"""
Lists connection details for an Azure Dev Spaces Controller.
Lists connection details for the underlying container resources of an Azure Dev Spaces Controller.
@param resourceGroupName Resource group to which the resource belongs.
@param name Name of the resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ControllerConnectionDetailsListInner object if successful.
"""
return listConnectionDetailsWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
}
|
java
|
public ControllerConnectionDetailsListInner listConnectionDetails(String resourceGroupName, String name) {
return listConnectionDetailsWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body();
}
|
[
"public",
"ControllerConnectionDetailsListInner",
"listConnectionDetails",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
")",
"{",
"return",
"listConnectionDetailsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Lists connection details for an Azure Dev Spaces Controller.
Lists connection details for the underlying container resources of an Azure Dev Spaces Controller.
@param resourceGroupName Resource group to which the resource belongs.
@param name Name of the resource.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ControllerConnectionDetailsListInner object if successful.
|
[
"Lists",
"connection",
"details",
"for",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
".",
"Lists",
"connection",
"details",
"for",
"the",
"underlying",
"container",
"resources",
"of",
"an",
"Azure",
"Dev",
"Spaces",
"Controller",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/devspaces/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/devspaces/v2018_06_01_preview/implementation/ControllersInner.java#L976-L978
|
netscaler/nitro
|
src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmsessionaction.java
|
tmsessionaction.get
|
public static tmsessionaction get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch tmsessionaction resource of given name .
"""
tmsessionaction obj = new tmsessionaction();
obj.set_name(name);
tmsessionaction response = (tmsessionaction) obj.get_resource(service);
return response;
}
|
java
|
public static tmsessionaction get(nitro_service service, String name) throws Exception{
tmsessionaction obj = new tmsessionaction();
obj.set_name(name);
tmsessionaction response = (tmsessionaction) obj.get_resource(service);
return response;
}
|
[
"public",
"static",
"tmsessionaction",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"tmsessionaction",
"obj",
"=",
"new",
"tmsessionaction",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"tmsessionaction",
"response",
"=",
"(",
"tmsessionaction",
")",
"obj",
".",
"get_resource",
"(",
"service",
")",
";",
"return",
"response",
";",
"}"
] |
Use this API to fetch tmsessionaction resource of given name .
|
[
"Use",
"this",
"API",
"to",
"fetch",
"tmsessionaction",
"resource",
"of",
"given",
"name",
"."
] |
train
|
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmsessionaction.java#L522-L527
|
Whiley/WhileyCompiler
|
src/main/java/wyc/io/WhileyFileParser.java
|
WhileyFileParser.parseAndOrExpression
|
private Expr parseAndOrExpression(EnclosingScope scope, boolean terminated) {
"""
Parse a logical expression of the form:
<pre>
Expr ::= ConditionExpr [ ( "&&" | "||" ) Expr]
</pre>
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return
"""
checkNotEof();
int start = index;
Expr lhs = parseBitwiseOrExpression(scope, terminated);
Token lookahead = tryAndMatch(terminated, LogicalAnd, LogicalOr);
if (lookahead != null) {
switch (lookahead.kind) {
case LogicalAnd: {
Expr rhs = parseExpression(scope, terminated);
lhs = annotateSourceLocation(new Expr.LogicalAnd(new Tuple<>(lhs, rhs)),start);
break;
}
case LogicalOr: {
Expr rhs = parseExpression(scope, terminated);
lhs = annotateSourceLocation(new Expr.LogicalOr(new Tuple<>(lhs, rhs)), start);
break;
}
default:
throw new RuntimeException("deadcode"); // dead-code
}
}
return lhs;
}
|
java
|
private Expr parseAndOrExpression(EnclosingScope scope, boolean terminated) {
checkNotEof();
int start = index;
Expr lhs = parseBitwiseOrExpression(scope, terminated);
Token lookahead = tryAndMatch(terminated, LogicalAnd, LogicalOr);
if (lookahead != null) {
switch (lookahead.kind) {
case LogicalAnd: {
Expr rhs = parseExpression(scope, terminated);
lhs = annotateSourceLocation(new Expr.LogicalAnd(new Tuple<>(lhs, rhs)),start);
break;
}
case LogicalOr: {
Expr rhs = parseExpression(scope, terminated);
lhs = annotateSourceLocation(new Expr.LogicalOr(new Tuple<>(lhs, rhs)), start);
break;
}
default:
throw new RuntimeException("deadcode"); // dead-code
}
}
return lhs;
}
|
[
"private",
"Expr",
"parseAndOrExpression",
"(",
"EnclosingScope",
"scope",
",",
"boolean",
"terminated",
")",
"{",
"checkNotEof",
"(",
")",
";",
"int",
"start",
"=",
"index",
";",
"Expr",
"lhs",
"=",
"parseBitwiseOrExpression",
"(",
"scope",
",",
"terminated",
")",
";",
"Token",
"lookahead",
"=",
"tryAndMatch",
"(",
"terminated",
",",
"LogicalAnd",
",",
"LogicalOr",
")",
";",
"if",
"(",
"lookahead",
"!=",
"null",
")",
"{",
"switch",
"(",
"lookahead",
".",
"kind",
")",
"{",
"case",
"LogicalAnd",
":",
"{",
"Expr",
"rhs",
"=",
"parseExpression",
"(",
"scope",
",",
"terminated",
")",
";",
"lhs",
"=",
"annotateSourceLocation",
"(",
"new",
"Expr",
".",
"LogicalAnd",
"(",
"new",
"Tuple",
"<>",
"(",
"lhs",
",",
"rhs",
")",
")",
",",
"start",
")",
";",
"break",
";",
"}",
"case",
"LogicalOr",
":",
"{",
"Expr",
"rhs",
"=",
"parseExpression",
"(",
"scope",
",",
"terminated",
")",
";",
"lhs",
"=",
"annotateSourceLocation",
"(",
"new",
"Expr",
".",
"LogicalOr",
"(",
"new",
"Tuple",
"<>",
"(",
"lhs",
",",
"rhs",
")",
")",
",",
"start",
")",
";",
"break",
";",
"}",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"deadcode\"",
")",
";",
"// dead-code",
"}",
"}",
"return",
"lhs",
";",
"}"
] |
Parse a logical expression of the form:
<pre>
Expr ::= ConditionExpr [ ( "&&" | "||" ) Expr]
</pre>
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return
|
[
"Parse",
"a",
"logical",
"expression",
"of",
"the",
"form",
":"
] |
train
|
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L1712-L1734
|
svenkubiak/mangooio
|
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
|
Validator.expectMin
|
public void expectMin(String name, double minLength, String message) {
"""
Validates a given field to have a minimum length
@param name The field to check
@param minLength The minimum length
@param message A custom error message instead of the default one
"""
String value = Optional.ofNullable(get(name)).orElse("");
if (StringUtils.isNumeric(value)) {
if (Double.parseDouble(value) < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
} else {
if (value.length() < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
}
}
|
java
|
public void expectMin(String name, double minLength, String message) {
String value = Optional.ofNullable(get(name)).orElse("");
if (StringUtils.isNumeric(value)) {
if (Double.parseDouble(value) < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
} else {
if (value.length() < minLength) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength)));
}
}
}
|
[
"public",
"void",
"expectMin",
"(",
"String",
"name",
",",
"double",
"minLength",
",",
"String",
"message",
")",
"{",
"String",
"value",
"=",
"Optional",
".",
"ofNullable",
"(",
"get",
"(",
"name",
")",
")",
".",
"orElse",
"(",
"\"\"",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNumeric",
"(",
"value",
")",
")",
"{",
"if",
"(",
"Double",
".",
"parseDouble",
"(",
"value",
")",
"<",
"minLength",
")",
"{",
"addError",
"(",
"name",
",",
"Optional",
".",
"ofNullable",
"(",
"message",
")",
".",
"orElse",
"(",
"messages",
".",
"get",
"(",
"Validation",
".",
"MIN_KEY",
".",
"name",
"(",
")",
",",
"name",
",",
"minLength",
")",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"value",
".",
"length",
"(",
")",
"<",
"minLength",
")",
"{",
"addError",
"(",
"name",
",",
"Optional",
".",
"ofNullable",
"(",
"message",
")",
".",
"orElse",
"(",
"messages",
".",
"get",
"(",
"Validation",
".",
"MIN_KEY",
".",
"name",
"(",
")",
",",
"name",
",",
"minLength",
")",
")",
")",
";",
"}",
"}",
"}"
] |
Validates a given field to have a minimum length
@param name The field to check
@param minLength The minimum length
@param message A custom error message instead of the default one
|
[
"Validates",
"a",
"given",
"field",
"to",
"have",
"a",
"minimum",
"length"
] |
train
|
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L96-L108
|
xcesco/kripton
|
kripton-processor/src/main/java/com/abubusoft/kripton/processor/BindDataSourceSubProcessor.java
|
BindDataSourceSubProcessor.analyzeSecondRound
|
public boolean analyzeSecondRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
"""
Analyze second round.
@param annotations
the annotations
@param roundEnv
the round env
@return true, if successful
"""
parseBindType(roundEnv);
// Put all @BindTable elements in beanElements
for (Element item : roundEnv.getElementsAnnotatedWith(BindSqlType.class)) {
if (item.getKind() != ElementKind.CLASS) {
String msg = String.format("%s %s, only class can be annotated with @%s annotation", item.getKind(),
item, BindSqlType.class.getSimpleName());
throw (new InvalidKindForAnnotationException(msg));
}
globalBeanElements.put(item.toString(), (TypeElement) item);
}
// generate dao
Set<? extends Element> generatedDaos = roundEnv.getElementsAnnotatedWith(BindGeneratedDao.class);
for (Element item : generatedDaos) {
String keyToReplace = AnnotationUtility.extractAsClassName(item, BindGeneratedDao.class,
AnnotationAttributeType.DAO);
globalDaoElements.put(keyToReplace, (TypeElement) item);
globalDaoGenerated.add(keyToReplace);
}
return false;
}
|
java
|
public boolean analyzeSecondRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
parseBindType(roundEnv);
// Put all @BindTable elements in beanElements
for (Element item : roundEnv.getElementsAnnotatedWith(BindSqlType.class)) {
if (item.getKind() != ElementKind.CLASS) {
String msg = String.format("%s %s, only class can be annotated with @%s annotation", item.getKind(),
item, BindSqlType.class.getSimpleName());
throw (new InvalidKindForAnnotationException(msg));
}
globalBeanElements.put(item.toString(), (TypeElement) item);
}
// generate dao
Set<? extends Element> generatedDaos = roundEnv.getElementsAnnotatedWith(BindGeneratedDao.class);
for (Element item : generatedDaos) {
String keyToReplace = AnnotationUtility.extractAsClassName(item, BindGeneratedDao.class,
AnnotationAttributeType.DAO);
globalDaoElements.put(keyToReplace, (TypeElement) item);
globalDaoGenerated.add(keyToReplace);
}
return false;
}
|
[
"public",
"boolean",
"analyzeSecondRound",
"(",
"Set",
"<",
"?",
"extends",
"TypeElement",
">",
"annotations",
",",
"RoundEnvironment",
"roundEnv",
")",
"{",
"parseBindType",
"(",
"roundEnv",
")",
";",
"// Put all @BindTable elements in beanElements",
"for",
"(",
"Element",
"item",
":",
"roundEnv",
".",
"getElementsAnnotatedWith",
"(",
"BindSqlType",
".",
"class",
")",
")",
"{",
"if",
"(",
"item",
".",
"getKind",
"(",
")",
"!=",
"ElementKind",
".",
"CLASS",
")",
"{",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"%s %s, only class can be annotated with @%s annotation\"",
",",
"item",
".",
"getKind",
"(",
")",
",",
"item",
",",
"BindSqlType",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
";",
"throw",
"(",
"new",
"InvalidKindForAnnotationException",
"(",
"msg",
")",
")",
";",
"}",
"globalBeanElements",
".",
"put",
"(",
"item",
".",
"toString",
"(",
")",
",",
"(",
"TypeElement",
")",
"item",
")",
";",
"}",
"// generate dao",
"Set",
"<",
"?",
"extends",
"Element",
">",
"generatedDaos",
"=",
"roundEnv",
".",
"getElementsAnnotatedWith",
"(",
"BindGeneratedDao",
".",
"class",
")",
";",
"for",
"(",
"Element",
"item",
":",
"generatedDaos",
")",
"{",
"String",
"keyToReplace",
"=",
"AnnotationUtility",
".",
"extractAsClassName",
"(",
"item",
",",
"BindGeneratedDao",
".",
"class",
",",
"AnnotationAttributeType",
".",
"DAO",
")",
";",
"globalDaoElements",
".",
"put",
"(",
"keyToReplace",
",",
"(",
"TypeElement",
")",
"item",
")",
";",
"globalDaoGenerated",
".",
"add",
"(",
"keyToReplace",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Analyze second round.
@param annotations
the annotations
@param roundEnv
the round env
@return true, if successful
|
[
"Analyze",
"second",
"round",
"."
] |
train
|
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/BindDataSourceSubProcessor.java#L561-L584
|
cdk/cdk
|
storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java
|
CxSmilesParser.processCoords
|
private static boolean processCoords(CharIter iter, CxSmilesState state) {
"""
Coordinates are written between parenthesis. The z-coord may be omitted '(0,1,),(2,3,)'.
@param iter input characters, iterator is progressed by this method
@param state output CXSMILES state
@return parse was a success (or not)
"""
if (state.atomCoords == null)
state.atomCoords = new ArrayList<>();
while (iter.hasNext()) {
// end of coordinate list
if (iter.curr() == ')') {
iter.next();
iter.nextIf(','); // optional
return true;
}
double x = readDouble(iter);
if (!iter.nextIf(','))
return false;
double y = readDouble(iter);
if (!iter.nextIf(','))
return false;
double z = readDouble(iter);
iter.nextIf(';');
state.coordFlag = state.coordFlag || z != 0;
state.atomCoords.add(new double[]{x, y, z});
}
return false;
}
|
java
|
private static boolean processCoords(CharIter iter, CxSmilesState state) {
if (state.atomCoords == null)
state.atomCoords = new ArrayList<>();
while (iter.hasNext()) {
// end of coordinate list
if (iter.curr() == ')') {
iter.next();
iter.nextIf(','); // optional
return true;
}
double x = readDouble(iter);
if (!iter.nextIf(','))
return false;
double y = readDouble(iter);
if (!iter.nextIf(','))
return false;
double z = readDouble(iter);
iter.nextIf(';');
state.coordFlag = state.coordFlag || z != 0;
state.atomCoords.add(new double[]{x, y, z});
}
return false;
}
|
[
"private",
"static",
"boolean",
"processCoords",
"(",
"CharIter",
"iter",
",",
"CxSmilesState",
"state",
")",
"{",
"if",
"(",
"state",
".",
"atomCoords",
"==",
"null",
")",
"state",
".",
"atomCoords",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"// end of coordinate list",
"if",
"(",
"iter",
".",
"curr",
"(",
")",
"==",
"'",
"'",
")",
"{",
"iter",
".",
"next",
"(",
")",
";",
"iter",
".",
"nextIf",
"(",
"'",
"'",
")",
";",
"// optional",
"return",
"true",
";",
"}",
"double",
"x",
"=",
"readDouble",
"(",
"iter",
")",
";",
"if",
"(",
"!",
"iter",
".",
"nextIf",
"(",
"'",
"'",
")",
")",
"return",
"false",
";",
"double",
"y",
"=",
"readDouble",
"(",
"iter",
")",
";",
"if",
"(",
"!",
"iter",
".",
"nextIf",
"(",
"'",
"'",
")",
")",
"return",
"false",
";",
"double",
"z",
"=",
"readDouble",
"(",
"iter",
")",
";",
"iter",
".",
"nextIf",
"(",
"'",
"'",
")",
";",
"state",
".",
"coordFlag",
"=",
"state",
".",
"coordFlag",
"||",
"z",
"!=",
"0",
";",
"state",
".",
"atomCoords",
".",
"add",
"(",
"new",
"double",
"[",
"]",
"{",
"x",
",",
"y",
",",
"z",
"}",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Coordinates are written between parenthesis. The z-coord may be omitted '(0,1,),(2,3,)'.
@param iter input characters, iterator is progressed by this method
@param state output CXSMILES state
@return parse was a success (or not)
|
[
"Coordinates",
"are",
"written",
"between",
"parenthesis",
".",
"The",
"z",
"-",
"coord",
"may",
"be",
"omitted",
"(",
"0",
"1",
")",
"(",
"2",
"3",
")",
"."
] |
train
|
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java#L154-L179
|
knowm/XChange
|
xchange-ripple/src/main/java/org/knowm/xchange/ripple/RippleAdapters.java
|
RippleAdapters.adaptOpenOrders
|
public static OpenOrders adaptOpenOrders(
final RippleAccountOrders rippleOrders, final int scale) {
"""
Adapts a Ripple Account Orders object to an XChange OpenOrders object Counterparties set in
additional data since there is no other way of the application receiving this information.
"""
final List<LimitOrder> list = new ArrayList<>(rippleOrders.getOrders().size());
for (final RippleAccountOrdersBody order : rippleOrders.getOrders()) {
final OrderType orderType;
final RippleAmount baseAmount;
final RippleAmount counterAmount;
if (order.getType().equals("buy")) {
// buying: we receive base and pay with counter, taker receives counter and pays with base
counterAmount = order.getTakerGets();
baseAmount = order.getTakerPays();
orderType = OrderType.BID;
} else {
// selling: we receive counter and pay with base, taker receives base and pays with counter
baseAmount = order.getTakerGets();
counterAmount = order.getTakerPays();
orderType = OrderType.ASK;
}
final String baseSymbol = baseAmount.getCurrency();
final String counterSymbol = counterAmount.getCurrency();
// need to provide rounding scale to prevent ArithmeticException
final BigDecimal price =
counterAmount
.getValue()
.divide(baseAmount.getValue(), scale, RoundingMode.HALF_UP)
.stripTrailingZeros();
final CurrencyPair pair = new CurrencyPair(baseSymbol, counterSymbol);
final RippleLimitOrder xchangeOrder =
(RippleLimitOrder)
new RippleLimitOrder.Builder(orderType, pair)
.baseCounterparty(baseAmount.getCounterparty())
.counterCounterparty(counterAmount.getCounterparty())
.id(Long.toString(order.getSequence()))
.limitPrice(price)
.timestamp(null)
.originalAmount(baseAmount.getValue())
.build();
list.add(xchangeOrder);
}
return new OpenOrders(list);
}
|
java
|
public static OpenOrders adaptOpenOrders(
final RippleAccountOrders rippleOrders, final int scale) {
final List<LimitOrder> list = new ArrayList<>(rippleOrders.getOrders().size());
for (final RippleAccountOrdersBody order : rippleOrders.getOrders()) {
final OrderType orderType;
final RippleAmount baseAmount;
final RippleAmount counterAmount;
if (order.getType().equals("buy")) {
// buying: we receive base and pay with counter, taker receives counter and pays with base
counterAmount = order.getTakerGets();
baseAmount = order.getTakerPays();
orderType = OrderType.BID;
} else {
// selling: we receive counter and pay with base, taker receives base and pays with counter
baseAmount = order.getTakerGets();
counterAmount = order.getTakerPays();
orderType = OrderType.ASK;
}
final String baseSymbol = baseAmount.getCurrency();
final String counterSymbol = counterAmount.getCurrency();
// need to provide rounding scale to prevent ArithmeticException
final BigDecimal price =
counterAmount
.getValue()
.divide(baseAmount.getValue(), scale, RoundingMode.HALF_UP)
.stripTrailingZeros();
final CurrencyPair pair = new CurrencyPair(baseSymbol, counterSymbol);
final RippleLimitOrder xchangeOrder =
(RippleLimitOrder)
new RippleLimitOrder.Builder(orderType, pair)
.baseCounterparty(baseAmount.getCounterparty())
.counterCounterparty(counterAmount.getCounterparty())
.id(Long.toString(order.getSequence()))
.limitPrice(price)
.timestamp(null)
.originalAmount(baseAmount.getValue())
.build();
list.add(xchangeOrder);
}
return new OpenOrders(list);
}
|
[
"public",
"static",
"OpenOrders",
"adaptOpenOrders",
"(",
"final",
"RippleAccountOrders",
"rippleOrders",
",",
"final",
"int",
"scale",
")",
"{",
"final",
"List",
"<",
"LimitOrder",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
"rippleOrders",
".",
"getOrders",
"(",
")",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"final",
"RippleAccountOrdersBody",
"order",
":",
"rippleOrders",
".",
"getOrders",
"(",
")",
")",
"{",
"final",
"OrderType",
"orderType",
";",
"final",
"RippleAmount",
"baseAmount",
";",
"final",
"RippleAmount",
"counterAmount",
";",
"if",
"(",
"order",
".",
"getType",
"(",
")",
".",
"equals",
"(",
"\"buy\"",
")",
")",
"{",
"// buying: we receive base and pay with counter, taker receives counter and pays with base",
"counterAmount",
"=",
"order",
".",
"getTakerGets",
"(",
")",
";",
"baseAmount",
"=",
"order",
".",
"getTakerPays",
"(",
")",
";",
"orderType",
"=",
"OrderType",
".",
"BID",
";",
"}",
"else",
"{",
"// selling: we receive counter and pay with base, taker receives base and pays with counter",
"baseAmount",
"=",
"order",
".",
"getTakerGets",
"(",
")",
";",
"counterAmount",
"=",
"order",
".",
"getTakerPays",
"(",
")",
";",
"orderType",
"=",
"OrderType",
".",
"ASK",
";",
"}",
"final",
"String",
"baseSymbol",
"=",
"baseAmount",
".",
"getCurrency",
"(",
")",
";",
"final",
"String",
"counterSymbol",
"=",
"counterAmount",
".",
"getCurrency",
"(",
")",
";",
"// need to provide rounding scale to prevent ArithmeticException",
"final",
"BigDecimal",
"price",
"=",
"counterAmount",
".",
"getValue",
"(",
")",
".",
"divide",
"(",
"baseAmount",
".",
"getValue",
"(",
")",
",",
"scale",
",",
"RoundingMode",
".",
"HALF_UP",
")",
".",
"stripTrailingZeros",
"(",
")",
";",
"final",
"CurrencyPair",
"pair",
"=",
"new",
"CurrencyPair",
"(",
"baseSymbol",
",",
"counterSymbol",
")",
";",
"final",
"RippleLimitOrder",
"xchangeOrder",
"=",
"(",
"RippleLimitOrder",
")",
"new",
"RippleLimitOrder",
".",
"Builder",
"(",
"orderType",
",",
"pair",
")",
".",
"baseCounterparty",
"(",
"baseAmount",
".",
"getCounterparty",
"(",
")",
")",
".",
"counterCounterparty",
"(",
"counterAmount",
".",
"getCounterparty",
"(",
")",
")",
".",
"id",
"(",
"Long",
".",
"toString",
"(",
"order",
".",
"getSequence",
"(",
")",
")",
")",
".",
"limitPrice",
"(",
"price",
")",
".",
"timestamp",
"(",
"null",
")",
".",
"originalAmount",
"(",
"baseAmount",
".",
"getValue",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"list",
".",
"add",
"(",
"xchangeOrder",
")",
";",
"}",
"return",
"new",
"OpenOrders",
"(",
"list",
")",
";",
"}"
] |
Adapts a Ripple Account Orders object to an XChange OpenOrders object Counterparties set in
additional data since there is no other way of the application receiving this information.
|
[
"Adapts",
"a",
"Ripple",
"Account",
"Orders",
"object",
"to",
"an",
"XChange",
"OpenOrders",
"object",
"Counterparties",
"set",
"in",
"additional",
"data",
"since",
"there",
"is",
"no",
"other",
"way",
"of",
"the",
"application",
"receiving",
"this",
"information",
"."
] |
train
|
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-ripple/src/main/java/org/knowm/xchange/ripple/RippleAdapters.java#L203-L249
|
Waikato/moa
|
moa/src/main/java/moa/classifiers/core/attributeclassobservers/FIMTDDNumericAttributeClassObserver.java
|
FIMTDDNumericAttributeClassObserver.searchForBestSplitOption
|
protected AttributeSplitSuggestion searchForBestSplitOption(Node currentNode, AttributeSplitSuggestion currentBestOption, SplitCriterion criterion, int attIndex) {
"""
Implementation of the FindBestSplit algorithm from E.Ikonomovska et al.
"""
// Return null if the current node is null or we have finished looking through all the possible splits
if (currentNode == null || countRightTotal == 0.0) {
return currentBestOption;
}
if (currentNode.left != null) {
currentBestOption = searchForBestSplitOption(currentNode.left, currentBestOption, criterion, attIndex);
}
sumTotalLeft += currentNode.leftStatistics.getValue(1);
sumTotalRight -= currentNode.leftStatistics.getValue(1);
sumSqTotalLeft += currentNode.leftStatistics.getValue(2);
sumSqTotalRight -= currentNode.leftStatistics.getValue(2);
countLeftTotal += currentNode.leftStatistics.getValue(0);
countRightTotal -= currentNode.leftStatistics.getValue(0);
double[][] postSplitDists = new double[][]{{countLeftTotal, sumTotalLeft, sumSqTotalLeft}, {countRightTotal, sumTotalRight, sumSqTotalRight}};
double[] preSplitDist = new double[]{(countLeftTotal + countRightTotal), (sumTotalLeft + sumTotalRight), (sumSqTotalLeft + sumSqTotalRight)};
double merit = criterion.getMeritOfSplit(preSplitDist, postSplitDists);
if ((currentBestOption == null) || (merit > currentBestOption.merit)) {
currentBestOption = new AttributeSplitSuggestion(
new NumericAttributeBinaryTest(attIndex,
currentNode.cut_point, true), postSplitDists, merit);
}
if (currentNode.right != null) {
currentBestOption = searchForBestSplitOption(currentNode.right, currentBestOption, criterion, attIndex);
}
sumTotalLeft -= currentNode.leftStatistics.getValue(1);
sumTotalRight += currentNode.leftStatistics.getValue(1);
sumSqTotalLeft -= currentNode.leftStatistics.getValue(2);
sumSqTotalRight += currentNode.leftStatistics.getValue(2);
countLeftTotal -= currentNode.leftStatistics.getValue(0);
countRightTotal += currentNode.leftStatistics.getValue(0);
return currentBestOption;
}
|
java
|
protected AttributeSplitSuggestion searchForBestSplitOption(Node currentNode, AttributeSplitSuggestion currentBestOption, SplitCriterion criterion, int attIndex) {
// Return null if the current node is null or we have finished looking through all the possible splits
if (currentNode == null || countRightTotal == 0.0) {
return currentBestOption;
}
if (currentNode.left != null) {
currentBestOption = searchForBestSplitOption(currentNode.left, currentBestOption, criterion, attIndex);
}
sumTotalLeft += currentNode.leftStatistics.getValue(1);
sumTotalRight -= currentNode.leftStatistics.getValue(1);
sumSqTotalLeft += currentNode.leftStatistics.getValue(2);
sumSqTotalRight -= currentNode.leftStatistics.getValue(2);
countLeftTotal += currentNode.leftStatistics.getValue(0);
countRightTotal -= currentNode.leftStatistics.getValue(0);
double[][] postSplitDists = new double[][]{{countLeftTotal, sumTotalLeft, sumSqTotalLeft}, {countRightTotal, sumTotalRight, sumSqTotalRight}};
double[] preSplitDist = new double[]{(countLeftTotal + countRightTotal), (sumTotalLeft + sumTotalRight), (sumSqTotalLeft + sumSqTotalRight)};
double merit = criterion.getMeritOfSplit(preSplitDist, postSplitDists);
if ((currentBestOption == null) || (merit > currentBestOption.merit)) {
currentBestOption = new AttributeSplitSuggestion(
new NumericAttributeBinaryTest(attIndex,
currentNode.cut_point, true), postSplitDists, merit);
}
if (currentNode.right != null) {
currentBestOption = searchForBestSplitOption(currentNode.right, currentBestOption, criterion, attIndex);
}
sumTotalLeft -= currentNode.leftStatistics.getValue(1);
sumTotalRight += currentNode.leftStatistics.getValue(1);
sumSqTotalLeft -= currentNode.leftStatistics.getValue(2);
sumSqTotalRight += currentNode.leftStatistics.getValue(2);
countLeftTotal -= currentNode.leftStatistics.getValue(0);
countRightTotal += currentNode.leftStatistics.getValue(0);
return currentBestOption;
}
|
[
"protected",
"AttributeSplitSuggestion",
"searchForBestSplitOption",
"(",
"Node",
"currentNode",
",",
"AttributeSplitSuggestion",
"currentBestOption",
",",
"SplitCriterion",
"criterion",
",",
"int",
"attIndex",
")",
"{",
"// Return null if the current node is null or we have finished looking through all the possible splits",
"if",
"(",
"currentNode",
"==",
"null",
"||",
"countRightTotal",
"==",
"0.0",
")",
"{",
"return",
"currentBestOption",
";",
"}",
"if",
"(",
"currentNode",
".",
"left",
"!=",
"null",
")",
"{",
"currentBestOption",
"=",
"searchForBestSplitOption",
"(",
"currentNode",
".",
"left",
",",
"currentBestOption",
",",
"criterion",
",",
"attIndex",
")",
";",
"}",
"sumTotalLeft",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"1",
")",
";",
"sumTotalRight",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"1",
")",
";",
"sumSqTotalLeft",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"2",
")",
";",
"sumSqTotalRight",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"2",
")",
";",
"countLeftTotal",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"0",
")",
";",
"countRightTotal",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"0",
")",
";",
"double",
"[",
"]",
"[",
"]",
"postSplitDists",
"=",
"new",
"double",
"[",
"]",
"[",
"]",
"{",
"{",
"countLeftTotal",
",",
"sumTotalLeft",
",",
"sumSqTotalLeft",
"}",
",",
"{",
"countRightTotal",
",",
"sumTotalRight",
",",
"sumSqTotalRight",
"}",
"}",
";",
"double",
"[",
"]",
"preSplitDist",
"=",
"new",
"double",
"[",
"]",
"{",
"(",
"countLeftTotal",
"+",
"countRightTotal",
")",
",",
"(",
"sumTotalLeft",
"+",
"sumTotalRight",
")",
",",
"(",
"sumSqTotalLeft",
"+",
"sumSqTotalRight",
")",
"}",
";",
"double",
"merit",
"=",
"criterion",
".",
"getMeritOfSplit",
"(",
"preSplitDist",
",",
"postSplitDists",
")",
";",
"if",
"(",
"(",
"currentBestOption",
"==",
"null",
")",
"||",
"(",
"merit",
">",
"currentBestOption",
".",
"merit",
")",
")",
"{",
"currentBestOption",
"=",
"new",
"AttributeSplitSuggestion",
"(",
"new",
"NumericAttributeBinaryTest",
"(",
"attIndex",
",",
"currentNode",
".",
"cut_point",
",",
"true",
")",
",",
"postSplitDists",
",",
"merit",
")",
";",
"}",
"if",
"(",
"currentNode",
".",
"right",
"!=",
"null",
")",
"{",
"currentBestOption",
"=",
"searchForBestSplitOption",
"(",
"currentNode",
".",
"right",
",",
"currentBestOption",
",",
"criterion",
",",
"attIndex",
")",
";",
"}",
"sumTotalLeft",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"1",
")",
";",
"sumTotalRight",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"1",
")",
";",
"sumSqTotalLeft",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"2",
")",
";",
"sumSqTotalRight",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"2",
")",
";",
"countLeftTotal",
"-=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"0",
")",
";",
"countRightTotal",
"+=",
"currentNode",
".",
"leftStatistics",
".",
"getValue",
"(",
"0",
")",
";",
"return",
"currentBestOption",
";",
"}"
] |
Implementation of the FindBestSplit algorithm from E.Ikonomovska et al.
|
[
"Implementation",
"of",
"the",
"FindBestSplit",
"algorithm",
"from",
"E",
".",
"Ikonomovska",
"et",
"al",
"."
] |
train
|
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/core/attributeclassobservers/FIMTDDNumericAttributeClassObserver.java#L148-L187
|
allure-framework/allure1
|
allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java
|
AllureResultsUtils.writeAttachmentWithErrorMessage
|
public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) {
"""
Write throwable as attachment.
@param throwable to write
@param title title of attachment
@return Created {@link ru.yandex.qatools.allure.model.Attachment}
"""
String message = throwable.getMessage();
try {
return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title);
} catch (Exception e) {
e.addSuppressed(throwable);
LOGGER.error(String.format("Can't write attachment \"%s\"", title), e);
}
return new Attachment();
}
|
java
|
public static Attachment writeAttachmentWithErrorMessage(Throwable throwable, String title) {
String message = throwable.getMessage();
try {
return writeAttachment(message.getBytes(CONFIG.getAttachmentsEncoding()), title);
} catch (Exception e) {
e.addSuppressed(throwable);
LOGGER.error(String.format("Can't write attachment \"%s\"", title), e);
}
return new Attachment();
}
|
[
"public",
"static",
"Attachment",
"writeAttachmentWithErrorMessage",
"(",
"Throwable",
"throwable",
",",
"String",
"title",
")",
"{",
"String",
"message",
"=",
"throwable",
".",
"getMessage",
"(",
")",
";",
"try",
"{",
"return",
"writeAttachment",
"(",
"message",
".",
"getBytes",
"(",
"CONFIG",
".",
"getAttachmentsEncoding",
"(",
")",
")",
",",
"title",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"addSuppressed",
"(",
"throwable",
")",
";",
"LOGGER",
".",
"error",
"(",
"String",
".",
"format",
"(",
"\"Can't write attachment \\\"%s\\\"\"",
",",
"title",
")",
",",
"e",
")",
";",
"}",
"return",
"new",
"Attachment",
"(",
")",
";",
"}"
] |
Write throwable as attachment.
@param throwable to write
@param title title of attachment
@return Created {@link ru.yandex.qatools.allure.model.Attachment}
|
[
"Write",
"throwable",
"as",
"attachment",
"."
] |
train
|
https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java#L243-L252
|
brianwhu/xillium
|
data/src/main/java/org/xillium/data/CachedResultSet.java
|
CachedResultSet.chooseFields
|
public static <T> CachedResultSet chooseFields(Collection<T> collection, String... columns) {
"""
Retrieves the rows from a collection of Objects, where a subset of the objects' (of type T) <i>public fields</i> are taken as result set columns.
@param <T> the type of the objects in the collection
@param collection a collection of objects
@param columns names of a select subset of each object's public fields
@return the result set from the list of objects
"""
CachedResultSet rs = new CachedResultSet(columns, new ArrayList<Object[]>());
for (T object: collection) {
Object[] row = new Object[columns.length];
for (int i = 0; i < columns.length; ++i) {
try {
Object value = Beans.getKnownField(object.getClass(), columns[i]).get(object);
if (value != null) {
if (value.getClass().isArray()) {
row[i] = Strings.join(value, ';');
} else {
row[i] = value.toString();
}
} else {
row[i] = null;
}
} catch (Exception x) {
row[i] = null;
}
}
rs.rows.add(row);
}
return rs;
}
|
java
|
public static <T> CachedResultSet chooseFields(Collection<T> collection, String... columns) {
CachedResultSet rs = new CachedResultSet(columns, new ArrayList<Object[]>());
for (T object: collection) {
Object[] row = new Object[columns.length];
for (int i = 0; i < columns.length; ++i) {
try {
Object value = Beans.getKnownField(object.getClass(), columns[i]).get(object);
if (value != null) {
if (value.getClass().isArray()) {
row[i] = Strings.join(value, ';');
} else {
row[i] = value.toString();
}
} else {
row[i] = null;
}
} catch (Exception x) {
row[i] = null;
}
}
rs.rows.add(row);
}
return rs;
}
|
[
"public",
"static",
"<",
"T",
">",
"CachedResultSet",
"chooseFields",
"(",
"Collection",
"<",
"T",
">",
"collection",
",",
"String",
"...",
"columns",
")",
"{",
"CachedResultSet",
"rs",
"=",
"new",
"CachedResultSet",
"(",
"columns",
",",
"new",
"ArrayList",
"<",
"Object",
"[",
"]",
">",
"(",
")",
")",
";",
"for",
"(",
"T",
"object",
":",
"collection",
")",
"{",
"Object",
"[",
"]",
"row",
"=",
"new",
"Object",
"[",
"columns",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"columns",
".",
"length",
";",
"++",
"i",
")",
"{",
"try",
"{",
"Object",
"value",
"=",
"Beans",
".",
"getKnownField",
"(",
"object",
".",
"getClass",
"(",
")",
",",
"columns",
"[",
"i",
"]",
")",
".",
"get",
"(",
"object",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"if",
"(",
"value",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"row",
"[",
"i",
"]",
"=",
"Strings",
".",
"join",
"(",
"value",
",",
"'",
"'",
")",
";",
"}",
"else",
"{",
"row",
"[",
"i",
"]",
"=",
"value",
".",
"toString",
"(",
")",
";",
"}",
"}",
"else",
"{",
"row",
"[",
"i",
"]",
"=",
"null",
";",
"}",
"}",
"catch",
"(",
"Exception",
"x",
")",
"{",
"row",
"[",
"i",
"]",
"=",
"null",
";",
"}",
"}",
"rs",
".",
"rows",
".",
"add",
"(",
"row",
")",
";",
"}",
"return",
"rs",
";",
"}"
] |
Retrieves the rows from a collection of Objects, where a subset of the objects' (of type T) <i>public fields</i> are taken as result set columns.
@param <T> the type of the objects in the collection
@param collection a collection of objects
@param columns names of a select subset of each object's public fields
@return the result set from the list of objects
|
[
"Retrieves",
"the",
"rows",
"from",
"a",
"collection",
"of",
"Objects",
"where",
"a",
"subset",
"of",
"the",
"objects",
"(",
"of",
"type",
"T",
")",
"<i",
">",
"public",
"fields<",
"/",
"i",
">",
"are",
"taken",
"as",
"result",
"set",
"columns",
"."
] |
train
|
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/data/src/main/java/org/xillium/data/CachedResultSet.java#L148-L172
|
FlyingHe/UtilsMaven
|
src/main/java/com/github/flyinghe/tools/DBUtils.java
|
DBUtils.transformMapListToBeanList
|
private static <T> List<T> transformMapListToBeanList(Class<T> clazz, List<Map<String, Object>> listProperties)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
"""
将所有记录包装成T类对象,并将所有T类对象放入一个数组中并返回,传入的T类的定义必须符合JavaBean规范,
因为本函数是调用T类对象的setter器来给对象赋值的
@param clazz T类的类对象
@param listProperties 所有记录
@return 返回所有被实例化的对象的数组,若没有对象,返回一个空数组
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException
"""
// 存放被实例化的T类对象
T bean = null;
// 存放所有被实例化的对象
List<T> list = new ArrayList<T>();
// 将实例化的对象放入List数组中
if (listProperties.size() != 0) {
Iterator<Map<String, Object>> iter = listProperties.iterator();
while (iter.hasNext()) {
// 实例化T类对象
bean = clazz.newInstance();
// 遍历每条记录的字段,并给T类实例化对象属性赋值
for (Map.Entry<String, Object> entry : iter.next().entrySet()) {
BeanUtils.setProperty(bean, entry.getKey(), entry.getValue());
}
// 将赋过值的T类对象放入数组中
list.add(bean);
}
}
return list;
}
|
java
|
private static <T> List<T> transformMapListToBeanList(Class<T> clazz, List<Map<String, Object>> listProperties)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
// 存放被实例化的T类对象
T bean = null;
// 存放所有被实例化的对象
List<T> list = new ArrayList<T>();
// 将实例化的对象放入List数组中
if (listProperties.size() != 0) {
Iterator<Map<String, Object>> iter = listProperties.iterator();
while (iter.hasNext()) {
// 实例化T类对象
bean = clazz.newInstance();
// 遍历每条记录的字段,并给T类实例化对象属性赋值
for (Map.Entry<String, Object> entry : iter.next().entrySet()) {
BeanUtils.setProperty(bean, entry.getKey(), entry.getValue());
}
// 将赋过值的T类对象放入数组中
list.add(bean);
}
}
return list;
}
|
[
"private",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"transformMapListToBeanList",
"(",
"Class",
"<",
"T",
">",
"clazz",
",",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"listProperties",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"// 存放被实例化的T类对象",
"T",
"bean",
"=",
"null",
";",
"// 存放所有被实例化的对象",
"List",
"<",
"T",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"T",
">",
"(",
")",
";",
"// 将实例化的对象放入List数组中",
"if",
"(",
"listProperties",
".",
"size",
"(",
")",
"!=",
"0",
")",
"{",
"Iterator",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"iter",
"=",
"listProperties",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"// 实例化T类对象",
"bean",
"=",
"clazz",
".",
"newInstance",
"(",
")",
";",
"// 遍历每条记录的字段,并给T类实例化对象属性赋值",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"iter",
".",
"next",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"BeanUtils",
".",
"setProperty",
"(",
"bean",
",",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"// 将赋过值的T类对象放入数组中",
"list",
".",
"add",
"(",
"bean",
")",
";",
"}",
"}",
"return",
"list",
";",
"}"
] |
将所有记录包装成T类对象,并将所有T类对象放入一个数组中并返回,传入的T类的定义必须符合JavaBean规范,
因为本函数是调用T类对象的setter器来给对象赋值的
@param clazz T类的类对象
@param listProperties 所有记录
@return 返回所有被实例化的对象的数组,若没有对象,返回一个空数组
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException
|
[
"将所有记录包装成T类对象,并将所有T类对象放入一个数组中并返回,传入的T类的定义必须符合JavaBean规范,",
"因为本函数是调用T类对象的setter器来给对象赋值的"
] |
train
|
https://github.com/FlyingHe/UtilsMaven/blob/d9605b7bfe0c28a05289252e12d163e114080b4a/src/main/java/com/github/flyinghe/tools/DBUtils.java#L181-L203
|
Alluxio/alluxio
|
core/server/common/src/main/java/alluxio/underfs/AbstractUfsManager.java
|
AbstractUfsManager.getOrAdd
|
private UnderFileSystem getOrAdd(AlluxioURI ufsUri, UnderFileSystemConfiguration ufsConf) {
"""
Return a UFS instance if it already exists in the cache, otherwise, creates a new instance and
return this.
@param ufsUri the UFS path
@param ufsConf the UFS configuration
@return the UFS instance
"""
Key key = new Key(ufsUri, ufsConf.getMountSpecificConf());
UnderFileSystem cachedFs = mUnderFileSystemMap.get(key);
if (cachedFs != null) {
return cachedFs;
}
// On cache miss, synchronize the creation to ensure ufs is only created once
synchronized (mLock) {
cachedFs = mUnderFileSystemMap.get(key);
if (cachedFs != null) {
return cachedFs;
}
UnderFileSystem fs = UnderFileSystem.Factory.create(ufsUri.toString(), ufsConf);
// Detect whether to use managed blocking on UFS operations.
boolean useManagedBlocking = fs.isObjectStorage();
if (ufsConf.isSet(PropertyKey.UNDERFS_RUN_WITH_MANAGEDBLOCKING)) {
useManagedBlocking = ufsConf.getBoolean(PropertyKey.UNDERFS_RUN_WITH_MANAGEDBLOCKING);
}
// Wrap UFS under managed blocking forwarder if required.
if (useManagedBlocking) {
fs = new ManagedBlockingUfsForwarder(fs);
}
mUnderFileSystemMap.putIfAbsent(key, fs);
mCloser.register(fs);
try {
connectUfs(fs);
} catch (IOException e) {
LOG.warn("Failed to perform initial connect to UFS {}: {}", ufsUri, e.getMessage());
}
return fs;
}
}
|
java
|
private UnderFileSystem getOrAdd(AlluxioURI ufsUri, UnderFileSystemConfiguration ufsConf) {
Key key = new Key(ufsUri, ufsConf.getMountSpecificConf());
UnderFileSystem cachedFs = mUnderFileSystemMap.get(key);
if (cachedFs != null) {
return cachedFs;
}
// On cache miss, synchronize the creation to ensure ufs is only created once
synchronized (mLock) {
cachedFs = mUnderFileSystemMap.get(key);
if (cachedFs != null) {
return cachedFs;
}
UnderFileSystem fs = UnderFileSystem.Factory.create(ufsUri.toString(), ufsConf);
// Detect whether to use managed blocking on UFS operations.
boolean useManagedBlocking = fs.isObjectStorage();
if (ufsConf.isSet(PropertyKey.UNDERFS_RUN_WITH_MANAGEDBLOCKING)) {
useManagedBlocking = ufsConf.getBoolean(PropertyKey.UNDERFS_RUN_WITH_MANAGEDBLOCKING);
}
// Wrap UFS under managed blocking forwarder if required.
if (useManagedBlocking) {
fs = new ManagedBlockingUfsForwarder(fs);
}
mUnderFileSystemMap.putIfAbsent(key, fs);
mCloser.register(fs);
try {
connectUfs(fs);
} catch (IOException e) {
LOG.warn("Failed to perform initial connect to UFS {}: {}", ufsUri, e.getMessage());
}
return fs;
}
}
|
[
"private",
"UnderFileSystem",
"getOrAdd",
"(",
"AlluxioURI",
"ufsUri",
",",
"UnderFileSystemConfiguration",
"ufsConf",
")",
"{",
"Key",
"key",
"=",
"new",
"Key",
"(",
"ufsUri",
",",
"ufsConf",
".",
"getMountSpecificConf",
"(",
")",
")",
";",
"UnderFileSystem",
"cachedFs",
"=",
"mUnderFileSystemMap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"cachedFs",
"!=",
"null",
")",
"{",
"return",
"cachedFs",
";",
"}",
"// On cache miss, synchronize the creation to ensure ufs is only created once",
"synchronized",
"(",
"mLock",
")",
"{",
"cachedFs",
"=",
"mUnderFileSystemMap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"cachedFs",
"!=",
"null",
")",
"{",
"return",
"cachedFs",
";",
"}",
"UnderFileSystem",
"fs",
"=",
"UnderFileSystem",
".",
"Factory",
".",
"create",
"(",
"ufsUri",
".",
"toString",
"(",
")",
",",
"ufsConf",
")",
";",
"// Detect whether to use managed blocking on UFS operations.",
"boolean",
"useManagedBlocking",
"=",
"fs",
".",
"isObjectStorage",
"(",
")",
";",
"if",
"(",
"ufsConf",
".",
"isSet",
"(",
"PropertyKey",
".",
"UNDERFS_RUN_WITH_MANAGEDBLOCKING",
")",
")",
"{",
"useManagedBlocking",
"=",
"ufsConf",
".",
"getBoolean",
"(",
"PropertyKey",
".",
"UNDERFS_RUN_WITH_MANAGEDBLOCKING",
")",
";",
"}",
"// Wrap UFS under managed blocking forwarder if required.",
"if",
"(",
"useManagedBlocking",
")",
"{",
"fs",
"=",
"new",
"ManagedBlockingUfsForwarder",
"(",
"fs",
")",
";",
"}",
"mUnderFileSystemMap",
".",
"putIfAbsent",
"(",
"key",
",",
"fs",
")",
";",
"mCloser",
".",
"register",
"(",
"fs",
")",
";",
"try",
"{",
"connectUfs",
"(",
"fs",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"Failed to perform initial connect to UFS {}: {}\"",
",",
"ufsUri",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"return",
"fs",
";",
"}",
"}"
] |
Return a UFS instance if it already exists in the cache, otherwise, creates a new instance and
return this.
@param ufsUri the UFS path
@param ufsConf the UFS configuration
@return the UFS instance
|
[
"Return",
"a",
"UFS",
"instance",
"if",
"it",
"already",
"exists",
"in",
"the",
"cache",
"otherwise",
"creates",
"a",
"new",
"instance",
"and",
"return",
"this",
"."
] |
train
|
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/underfs/AbstractUfsManager.java#L116-L149
|
openengsb/openengsb
|
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java
|
TransformationPerformer.transformObject
|
public Object transformObject(TransformationDescription description, Object source) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
"""
Transforms the given object based on the given TransformationDescription.
"""
return transformObject(description, source, null);
}
|
java
|
public Object transformObject(TransformationDescription description, Object source) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
return transformObject(description, source, null);
}
|
[
"public",
"Object",
"transformObject",
"(",
"TransformationDescription",
"description",
",",
"Object",
"source",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
",",
"ClassNotFoundException",
"{",
"return",
"transformObject",
"(",
"description",
",",
"source",
",",
"null",
")",
";",
"}"
] |
Transforms the given object based on the given TransformationDescription.
|
[
"Transforms",
"the",
"given",
"object",
"based",
"on",
"the",
"given",
"TransformationDescription",
"."
] |
train
|
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/performer/TransformationPerformer.java#L81-L84
|
timols/java-gitlab-api
|
src/main/java/org/gitlab/api/http/Query.java
|
Query.appendIf
|
public <T> Query appendIf(final String name, final T value) throws UnsupportedEncodingException {
"""
Conditionally append a parameter to the query
if the value of the parameter is not null
@param name Parameter name
@param value Parameter value
@return this
@throws java.io.UnsupportedEncodingException If the provided value cannot be URL Encoded
"""
if (value != null) {
append(name, value.toString());
}
return this;
}
|
java
|
public <T> Query appendIf(final String name, final T value) throws UnsupportedEncodingException {
if (value != null) {
append(name, value.toString());
}
return this;
}
|
[
"public",
"<",
"T",
">",
"Query",
"appendIf",
"(",
"final",
"String",
"name",
",",
"final",
"T",
"value",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"append",
"(",
"name",
",",
"value",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Conditionally append a parameter to the query
if the value of the parameter is not null
@param name Parameter name
@param value Parameter value
@return this
@throws java.io.UnsupportedEncodingException If the provided value cannot be URL Encoded
|
[
"Conditionally",
"append",
"a",
"parameter",
"to",
"the",
"query",
"if",
"the",
"value",
"of",
"the",
"parameter",
"is",
"not",
"null"
] |
train
|
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/http/Query.java#L54-L59
|
spotbugs/spotbugs
|
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CFG.java
|
CFG.getLocationAtEntry
|
public Location getLocationAtEntry() {
"""
Get the Location representing the entry to the CFG. Note that this is a
"fake" Location, and shouldn't be relied on to yield source line
information.
@return Location at entry to CFG
"""
InstructionHandle handle = getEntry().getFirstInstruction();
assert handle != null;
return new Location(handle, getEntry());
}
|
java
|
public Location getLocationAtEntry() {
InstructionHandle handle = getEntry().getFirstInstruction();
assert handle != null;
return new Location(handle, getEntry());
}
|
[
"public",
"Location",
"getLocationAtEntry",
"(",
")",
"{",
"InstructionHandle",
"handle",
"=",
"getEntry",
"(",
")",
".",
"getFirstInstruction",
"(",
")",
";",
"assert",
"handle",
"!=",
"null",
";",
"return",
"new",
"Location",
"(",
"handle",
",",
"getEntry",
"(",
")",
")",
";",
"}"
] |
Get the Location representing the entry to the CFG. Note that this is a
"fake" Location, and shouldn't be relied on to yield source line
information.
@return Location at entry to CFG
|
[
"Get",
"the",
"Location",
"representing",
"the",
"entry",
"to",
"the",
"CFG",
".",
"Note",
"that",
"this",
"is",
"a",
"fake",
"Location",
"and",
"shouldn",
"t",
"be",
"relied",
"on",
"to",
"yield",
"source",
"line",
"information",
"."
] |
train
|
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CFG.java#L612-L616
|
JodaOrg/joda-time
|
src/main/java/org/joda/time/LocalDateTime.java
|
LocalDateTime.withTime
|
public LocalDateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) {
"""
Returns a copy of this datetime with the specified time,
retaining the date fields.
<p>
If the time is already the time passed in, then <code>this</code> is returned.
<p>
To set a single field use the properties, for example:
<pre>
LocalDateTime set = dt.hourOfDay().setCopy(6);
</pre>
@param hourOfDay the hour of the day
@param minuteOfHour the minute of the hour
@param secondOfMinute the second of the minute
@param millisOfSecond the millisecond of the second
@return a copy of this datetime with a different time
@throws IllegalArgumentException if any value if invalid
"""
Chronology chrono = getChronology();
long instant = getLocalMillis();
instant = chrono.hourOfDay().set(instant, hourOfDay);
instant = chrono.minuteOfHour().set(instant, minuteOfHour);
instant = chrono.secondOfMinute().set(instant, secondOfMinute);
instant = chrono.millisOfSecond().set(instant, millisOfSecond);
return withLocalMillis(instant);
}
|
java
|
public LocalDateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) {
Chronology chrono = getChronology();
long instant = getLocalMillis();
instant = chrono.hourOfDay().set(instant, hourOfDay);
instant = chrono.minuteOfHour().set(instant, minuteOfHour);
instant = chrono.secondOfMinute().set(instant, secondOfMinute);
instant = chrono.millisOfSecond().set(instant, millisOfSecond);
return withLocalMillis(instant);
}
|
[
"public",
"LocalDateTime",
"withTime",
"(",
"int",
"hourOfDay",
",",
"int",
"minuteOfHour",
",",
"int",
"secondOfMinute",
",",
"int",
"millisOfSecond",
")",
"{",
"Chronology",
"chrono",
"=",
"getChronology",
"(",
")",
";",
"long",
"instant",
"=",
"getLocalMillis",
"(",
")",
";",
"instant",
"=",
"chrono",
".",
"hourOfDay",
"(",
")",
".",
"set",
"(",
"instant",
",",
"hourOfDay",
")",
";",
"instant",
"=",
"chrono",
".",
"minuteOfHour",
"(",
")",
".",
"set",
"(",
"instant",
",",
"minuteOfHour",
")",
";",
"instant",
"=",
"chrono",
".",
"secondOfMinute",
"(",
")",
".",
"set",
"(",
"instant",
",",
"secondOfMinute",
")",
";",
"instant",
"=",
"chrono",
".",
"millisOfSecond",
"(",
")",
".",
"set",
"(",
"instant",
",",
"millisOfSecond",
")",
";",
"return",
"withLocalMillis",
"(",
"instant",
")",
";",
"}"
] |
Returns a copy of this datetime with the specified time,
retaining the date fields.
<p>
If the time is already the time passed in, then <code>this</code> is returned.
<p>
To set a single field use the properties, for example:
<pre>
LocalDateTime set = dt.hourOfDay().setCopy(6);
</pre>
@param hourOfDay the hour of the day
@param minuteOfHour the minute of the hour
@param secondOfMinute the second of the minute
@param millisOfSecond the millisecond of the second
@return a copy of this datetime with a different time
@throws IllegalArgumentException if any value if invalid
|
[
"Returns",
"a",
"copy",
"of",
"this",
"datetime",
"with",
"the",
"specified",
"time",
"retaining",
"the",
"date",
"fields",
".",
"<p",
">",
"If",
"the",
"time",
"is",
"already",
"the",
"time",
"passed",
"in",
"then",
"<code",
">",
"this<",
"/",
"code",
">",
"is",
"returned",
".",
"<p",
">",
"To",
"set",
"a",
"single",
"field",
"use",
"the",
"properties",
"for",
"example",
":",
"<pre",
">",
"LocalDateTime",
"set",
"=",
"dt",
".",
"hourOfDay",
"()",
".",
"setCopy",
"(",
"6",
")",
";",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/LocalDateTime.java#L937-L945
|
cubedtear/aritzh
|
aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/ARGBColorUtil.java
|
ARGBColorUtil.getColor
|
public static int getColor(final int alpha, final int red, final int green, final int blue) {
"""
Gets a color composed of the specified channels. All values must be between 0 and 255, both inclusive
@param alpha The alpha channel [0-255]
@param red The red channel [0-255]
@param green The green channel [0-255]
@param blue The blue channel [0-255]
@return The color composed of the specified channels
"""
return (alpha << ALPHA_SHIFT) | (red << RED_SHIFT) | (green << GREEN_SHIFT) | blue;
}
|
java
|
public static int getColor(final int alpha, final int red, final int green, final int blue) {
return (alpha << ALPHA_SHIFT) | (red << RED_SHIFT) | (green << GREEN_SHIFT) | blue;
}
|
[
"public",
"static",
"int",
"getColor",
"(",
"final",
"int",
"alpha",
",",
"final",
"int",
"red",
",",
"final",
"int",
"green",
",",
"final",
"int",
"blue",
")",
"{",
"return",
"(",
"alpha",
"<<",
"ALPHA_SHIFT",
")",
"|",
"(",
"red",
"<<",
"RED_SHIFT",
")",
"|",
"(",
"green",
"<<",
"GREEN_SHIFT",
")",
"|",
"blue",
";",
"}"
] |
Gets a color composed of the specified channels. All values must be between 0 and 255, both inclusive
@param alpha The alpha channel [0-255]
@param red The red channel [0-255]
@param green The green channel [0-255]
@param blue The blue channel [0-255]
@return The color composed of the specified channels
|
[
"Gets",
"a",
"color",
"composed",
"of",
"the",
"specified",
"channels",
".",
"All",
"values",
"must",
"be",
"between",
"0",
"and",
"255",
"both",
"inclusive"
] |
train
|
https://github.com/cubedtear/aritzh/blob/bc7493447a1a6088c4a7306ca4d0f0c20278364f/aritzh-core/src/main/java/io/github/aritzhack/aritzh/util/ARGBColorUtil.java#L114-L116
|
tweea/matrixjavalib-main-common
|
src/main/java/net/matrix/util/Collections3.java
|
Collections3.convertToString
|
public static String convertToString(final Collection collection, final String prefix, final String postfix) {
"""
转换 Collection 所有元素(通过 toString())为 String,每个元素的前面加入 prefix,后面加入
postfix,如<div>mymessage</div>。
@param collection
来源集合
@param prefix
前缀
@param postfix
后缀
@return 组合字符串
"""
StringBuilder builder = new StringBuilder();
for (Object o : collection) {
builder.append(prefix).append(o).append(postfix);
}
return builder.toString();
}
|
java
|
public static String convertToString(final Collection collection, final String prefix, final String postfix) {
StringBuilder builder = new StringBuilder();
for (Object o : collection) {
builder.append(prefix).append(o).append(postfix);
}
return builder.toString();
}
|
[
"public",
"static",
"String",
"convertToString",
"(",
"final",
"Collection",
"collection",
",",
"final",
"String",
"prefix",
",",
"final",
"String",
"postfix",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Object",
"o",
":",
"collection",
")",
"{",
"builder",
".",
"append",
"(",
"prefix",
")",
".",
"append",
"(",
"o",
")",
".",
"append",
"(",
"postfix",
")",
";",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] |
转换 Collection 所有元素(通过 toString())为 String,每个元素的前面加入 prefix,后面加入
postfix,如<div>mymessage</div>。
@param collection
来源集合
@param prefix
前缀
@param postfix
后缀
@return 组合字符串
|
[
"转换",
"Collection",
"所有元素(通过",
"toString",
"()",
")为",
"String,每个元素的前面加入",
"prefix,后面加入",
"postfix,如<div",
">",
"mymessage<",
"/",
"div",
">",
"。"
] |
train
|
https://github.com/tweea/matrixjavalib-main-common/blob/ac8f98322a422e3ef76c3e12d47b98268cec7006/src/main/java/net/matrix/util/Collections3.java#L105-L111
|
MariaDB/mariadb-connector-j
|
src/main/java/org/mariadb/jdbc/internal/com/read/Buffer.java
|
Buffer.readString
|
public String readString(final int numberOfBytes) {
"""
Read String with defined length.
@param numberOfBytes raw data length.
@return String value
"""
position += numberOfBytes;
return new String(buf, position - numberOfBytes, numberOfBytes);
}
|
java
|
public String readString(final int numberOfBytes) {
position += numberOfBytes;
return new String(buf, position - numberOfBytes, numberOfBytes);
}
|
[
"public",
"String",
"readString",
"(",
"final",
"int",
"numberOfBytes",
")",
"{",
"position",
"+=",
"numberOfBytes",
";",
"return",
"new",
"String",
"(",
"buf",
",",
"position",
"-",
"numberOfBytes",
",",
"numberOfBytes",
")",
";",
"}"
] |
Read String with defined length.
@param numberOfBytes raw data length.
@return String value
|
[
"Read",
"String",
"with",
"defined",
"length",
"."
] |
train
|
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/Buffer.java#L134-L137
|
sshtools/j2ssh-maverick
|
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java
|
SftpSubsystemChannel.changePermissions
|
public void changePermissions(String filename, String permissions)
throws SftpStatusException, SshException {
"""
Change the permissions of a file.
@param filename
the path to the file.
@param permissions
a string containing the permissions, for example "rw-r--r--"
@throws SftpStatusException
, SshException
"""
SftpFileAttributes attrs = new SftpFileAttributes(this,
SftpFileAttributes.SSH_FILEXFER_TYPE_UNKNOWN);
attrs.setPermissions(permissions);
setAttributes(filename, attrs);
}
|
java
|
public void changePermissions(String filename, String permissions)
throws SftpStatusException, SshException {
SftpFileAttributes attrs = new SftpFileAttributes(this,
SftpFileAttributes.SSH_FILEXFER_TYPE_UNKNOWN);
attrs.setPermissions(permissions);
setAttributes(filename, attrs);
}
|
[
"public",
"void",
"changePermissions",
"(",
"String",
"filename",
",",
"String",
"permissions",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"SftpFileAttributes",
"attrs",
"=",
"new",
"SftpFileAttributes",
"(",
"this",
",",
"SftpFileAttributes",
".",
"SSH_FILEXFER_TYPE_UNKNOWN",
")",
";",
"attrs",
".",
"setPermissions",
"(",
"permissions",
")",
";",
"setAttributes",
"(",
"filename",
",",
"attrs",
")",
";",
"}"
] |
Change the permissions of a file.
@param filename
the path to the file.
@param permissions
a string containing the permissions, for example "rw-r--r--"
@throws SftpStatusException
, SshException
|
[
"Change",
"the",
"permissions",
"of",
"a",
"file",
"."
] |
train
|
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpSubsystemChannel.java#L446-L454
|
alkacon/opencms-core
|
src/org/opencms/ui/apps/git/CmsGitCheckin.java
|
CmsGitCheckin.addConfigurationIfValid
|
private void addConfigurationIfValid(final Collection<CmsGitConfiguration> configurations, final File configFile) {
"""
Adds the configuration from <code>configFile</code> to the {@link Collection} of {@link CmsGitConfiguration},
if a valid configuration is read. Otherwise it logs the failure.
@param configurations Collection of configurations where the new configuration should be added.
@param configFile file to read the new configuration from.
"""
CmsGitConfiguration config = null;
try {
if (configFile.isFile()) {
config = new CmsGitConfiguration(configFile);
if (config.isValid()) {
configurations.add(config);
} else {
throw new Exception(
"Could not read git configuration file" + config.getConfigurationFile().getAbsolutePath());
}
}
} catch (NullPointerException npe) {
LOG.error("Could not read git configuration.", npe);
} catch (Exception e) {
String file = (null != config)
&& (null != config.getConfigurationFile())
&& (null != config.getConfigurationFile().getAbsolutePath())
? config.getConfigurationFile().getAbsolutePath()
: "<unknown>";
LOG.warn("Trying to read invalid git configuration from " + file + ".", e);
}
}
|
java
|
private void addConfigurationIfValid(final Collection<CmsGitConfiguration> configurations, final File configFile) {
CmsGitConfiguration config = null;
try {
if (configFile.isFile()) {
config = new CmsGitConfiguration(configFile);
if (config.isValid()) {
configurations.add(config);
} else {
throw new Exception(
"Could not read git configuration file" + config.getConfigurationFile().getAbsolutePath());
}
}
} catch (NullPointerException npe) {
LOG.error("Could not read git configuration.", npe);
} catch (Exception e) {
String file = (null != config)
&& (null != config.getConfigurationFile())
&& (null != config.getConfigurationFile().getAbsolutePath())
? config.getConfigurationFile().getAbsolutePath()
: "<unknown>";
LOG.warn("Trying to read invalid git configuration from " + file + ".", e);
}
}
|
[
"private",
"void",
"addConfigurationIfValid",
"(",
"final",
"Collection",
"<",
"CmsGitConfiguration",
">",
"configurations",
",",
"final",
"File",
"configFile",
")",
"{",
"CmsGitConfiguration",
"config",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"configFile",
".",
"isFile",
"(",
")",
")",
"{",
"config",
"=",
"new",
"CmsGitConfiguration",
"(",
"configFile",
")",
";",
"if",
"(",
"config",
".",
"isValid",
"(",
")",
")",
"{",
"configurations",
".",
"add",
"(",
"config",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"Could not read git configuration file\"",
"+",
"config",
".",
"getConfigurationFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"NullPointerException",
"npe",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Could not read git configuration.\"",
",",
"npe",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"file",
"=",
"(",
"null",
"!=",
"config",
")",
"&&",
"(",
"null",
"!=",
"config",
".",
"getConfigurationFile",
"(",
")",
")",
"&&",
"(",
"null",
"!=",
"config",
".",
"getConfigurationFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
"?",
"config",
".",
"getConfigurationFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
":",
"\"<unknown>\"",
";",
"LOG",
".",
"warn",
"(",
"\"Trying to read invalid git configuration from \"",
"+",
"file",
"+",
"\".\"",
",",
"e",
")",
";",
"}",
"}"
] |
Adds the configuration from <code>configFile</code> to the {@link Collection} of {@link CmsGitConfiguration},
if a valid configuration is read. Otherwise it logs the failure.
@param configurations Collection of configurations where the new configuration should be added.
@param configFile file to read the new configuration from.
|
[
"Adds",
"the",
"configuration",
"from",
"<code",
">",
"configFile<",
"/",
"code",
">",
"to",
"the",
"{"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/git/CmsGitCheckin.java#L529-L552
|
wmdietl/jsr308-langtools
|
src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
|
HtmlDocletWriter.isTypeInProfile
|
public boolean isTypeInProfile(ClassDoc cd, int profileValue) {
"""
Check if a type belongs to a profile.
@param cd the classDoc object that needs to be checked
@param profileValue the profile in which the type needs to be checked
@return true if the type is in the profile
"""
return (configuration.profiles.getProfile(getTypeNameForProfile(cd)) <= profileValue);
}
|
java
|
public boolean isTypeInProfile(ClassDoc cd, int profileValue) {
return (configuration.profiles.getProfile(getTypeNameForProfile(cd)) <= profileValue);
}
|
[
"public",
"boolean",
"isTypeInProfile",
"(",
"ClassDoc",
"cd",
",",
"int",
"profileValue",
")",
"{",
"return",
"(",
"configuration",
".",
"profiles",
".",
"getProfile",
"(",
"getTypeNameForProfile",
"(",
"cd",
")",
")",
"<=",
"profileValue",
")",
";",
"}"
] |
Check if a type belongs to a profile.
@param cd the classDoc object that needs to be checked
@param profileValue the profile in which the type needs to be checked
@return true if the type is in the profile
|
[
"Check",
"if",
"a",
"type",
"belongs",
"to",
"a",
"profile",
"."
] |
train
|
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L332-L334
|
linkedin/PalDB
|
paldb/src/main/java/com/linkedin/paldb/api/Configuration.java
|
Configuration.getInt
|
public int getInt(String key, int defaultValue) {
"""
Gets the int value for <code>key</code> or <code>defaultValue</code> if not found.
@param key key to get value for
@param defaultValue default value if key not found
@return value or <code>defaultValue</code> if not found
"""
if (containsKey(key)) {
return Integer.parseInt(get(key));
} else {
return defaultValue;
}
}
|
java
|
public int getInt(String key, int defaultValue) {
if (containsKey(key)) {
return Integer.parseInt(get(key));
} else {
return defaultValue;
}
}
|
[
"public",
"int",
"getInt",
"(",
"String",
"key",
",",
"int",
"defaultValue",
")",
"{",
"if",
"(",
"containsKey",
"(",
"key",
")",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"get",
"(",
"key",
")",
")",
";",
"}",
"else",
"{",
"return",
"defaultValue",
";",
"}",
"}"
] |
Gets the int value for <code>key</code> or <code>defaultValue</code> if not found.
@param key key to get value for
@param defaultValue default value if key not found
@return value or <code>defaultValue</code> if not found
|
[
"Gets",
"the",
"int",
"value",
"for",
"<code",
">",
"key<",
"/",
"code",
">",
"or",
"<code",
">",
"defaultValue<",
"/",
"code",
">",
"if",
"not",
"found",
"."
] |
train
|
https://github.com/linkedin/PalDB/blob/d05ccdd3f67855eb2675dbd82599f19aa7a9f650/paldb/src/main/java/com/linkedin/paldb/api/Configuration.java#L258-L264
|
IBM/ibm-cos-sdk-java
|
ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/aspera/transfer/AsperaLibraryLoader.java
|
AsperaLibraryLoader.loadLibrary
|
public static void loadLibrary(File extractedPath, List<String> candidates) {
"""
Loads a dynamic library into the JVM from a list of candidates
@param extractedPath The base directory where candidate dynamic libraries reside
@param candidates A list of candidate dynamic library names for various platforms
@return true if one of the candidate libraries was loaded successfully, else false
"""
for (String lib : candidates) {
File libPath = new File(extractedPath, lib);
String absPath = libPath.getAbsolutePath();
log.debug("Attempting to load dynamic library: " + absPath);
try {
System.load(absPath);
log.info("Loaded dynamic library: " + absPath);
return;
} catch (UnsatisfiedLinkError e) {
log.debug("Unable to load dynamic library: " + absPath, e);
}
}
throw new RuntimeException("Failed to load Aspera dynamic library from candidates " + candidates + " at location: " + extractedPath);
}
|
java
|
public static void loadLibrary(File extractedPath, List<String> candidates) {
for (String lib : candidates) {
File libPath = new File(extractedPath, lib);
String absPath = libPath.getAbsolutePath();
log.debug("Attempting to load dynamic library: " + absPath);
try {
System.load(absPath);
log.info("Loaded dynamic library: " + absPath);
return;
} catch (UnsatisfiedLinkError e) {
log.debug("Unable to load dynamic library: " + absPath, e);
}
}
throw new RuntimeException("Failed to load Aspera dynamic library from candidates " + candidates + " at location: " + extractedPath);
}
|
[
"public",
"static",
"void",
"loadLibrary",
"(",
"File",
"extractedPath",
",",
"List",
"<",
"String",
">",
"candidates",
")",
"{",
"for",
"(",
"String",
"lib",
":",
"candidates",
")",
"{",
"File",
"libPath",
"=",
"new",
"File",
"(",
"extractedPath",
",",
"lib",
")",
";",
"String",
"absPath",
"=",
"libPath",
".",
"getAbsolutePath",
"(",
")",
";",
"log",
".",
"debug",
"(",
"\"Attempting to load dynamic library: \"",
"+",
"absPath",
")",
";",
"try",
"{",
"System",
".",
"load",
"(",
"absPath",
")",
";",
"log",
".",
"info",
"(",
"\"Loaded dynamic library: \"",
"+",
"absPath",
")",
";",
"return",
";",
"}",
"catch",
"(",
"UnsatisfiedLinkError",
"e",
")",
"{",
"log",
".",
"debug",
"(",
"\"Unable to load dynamic library: \"",
"+",
"absPath",
",",
"e",
")",
";",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to load Aspera dynamic library from candidates \"",
"+",
"candidates",
"+",
"\" at location: \"",
"+",
"extractedPath",
")",
";",
"}"
] |
Loads a dynamic library into the JVM from a list of candidates
@param extractedPath The base directory where candidate dynamic libraries reside
@param candidates A list of candidate dynamic library names for various platforms
@return true if one of the candidate libraries was loaded successfully, else false
|
[
"Loads",
"a",
"dynamic",
"library",
"into",
"the",
"JVM",
"from",
"a",
"list",
"of",
"candidates"
] |
train
|
https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/aspera/transfer/AsperaLibraryLoader.java#L201-L215
|
RestComm/jss7
|
m3ua/impl/src/main/java/org/restcomm/protocols/ss7/m3ua/impl/router/ServerM3UARouter.java
|
ServerM3UARouter.addRk
|
public void addRk(RoutingKey rk, AsImpl asImpl) throws Exception {
"""
<p>
Create a Tree structure adding the reference to passed As. The Tree is created starting from {@link DPCNode} as parent
node containing 'n' {@link OPCNode} leafs where 'n' is list of OPC passed. For each {@link OPCNode} there will be 'm'
{@link SINode} leafs where 'm' is number of Service Indicator passed.
</p>
<p>
DPC is mandatory while OPC and SI list are optional. If OPC or SI is not passed the wild card '-1' leaf will be added to
parent node
</p>
@param rk
@param asImpl
@throws Exception
"""
int dpc = rk.getDestinationPointCodes()[0].getPointCode();
OPCList[] opcArray = rk.getOPCLists();
int[] opcIntArr = null;
if (opcArray == null) {
opcIntArr = new int[] { -1 };
} else {
opcIntArr = opcArray[0].getPointCodes();
}
ServiceIndicators[] siArray = rk.getServiceIndicators();
short[] siShortArr = null;
if (siArray == null) {
siShortArr = new short[] { -1 };
} else {
siShortArr = siArray[0].getIndicators();
}
for (FastList.Node<DPCNode> n = dpcList.head(), end = dpcList.tail(); (n = n.getNext()) != end;) {
DPCNode dpcNode = n.getValue();
if (dpcNode.dpc == dpc) {
this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
return;
}
}
DPCNode dpcNode = new DPCNode(dpc);
this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
this.dpcList.add(dpcNode);
}
|
java
|
public void addRk(RoutingKey rk, AsImpl asImpl) throws Exception {
int dpc = rk.getDestinationPointCodes()[0].getPointCode();
OPCList[] opcArray = rk.getOPCLists();
int[] opcIntArr = null;
if (opcArray == null) {
opcIntArr = new int[] { -1 };
} else {
opcIntArr = opcArray[0].getPointCodes();
}
ServiceIndicators[] siArray = rk.getServiceIndicators();
short[] siShortArr = null;
if (siArray == null) {
siShortArr = new short[] { -1 };
} else {
siShortArr = siArray[0].getIndicators();
}
for (FastList.Node<DPCNode> n = dpcList.head(), end = dpcList.tail(); (n = n.getNext()) != end;) {
DPCNode dpcNode = n.getValue();
if (dpcNode.dpc == dpc) {
this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
return;
}
}
DPCNode dpcNode = new DPCNode(dpc);
this.addSi(dpcNode, opcIntArr, siShortArr, asImpl);
this.dpcList.add(dpcNode);
}
|
[
"public",
"void",
"addRk",
"(",
"RoutingKey",
"rk",
",",
"AsImpl",
"asImpl",
")",
"throws",
"Exception",
"{",
"int",
"dpc",
"=",
"rk",
".",
"getDestinationPointCodes",
"(",
")",
"[",
"0",
"]",
".",
"getPointCode",
"(",
")",
";",
"OPCList",
"[",
"]",
"opcArray",
"=",
"rk",
".",
"getOPCLists",
"(",
")",
";",
"int",
"[",
"]",
"opcIntArr",
"=",
"null",
";",
"if",
"(",
"opcArray",
"==",
"null",
")",
"{",
"opcIntArr",
"=",
"new",
"int",
"[",
"]",
"{",
"-",
"1",
"}",
";",
"}",
"else",
"{",
"opcIntArr",
"=",
"opcArray",
"[",
"0",
"]",
".",
"getPointCodes",
"(",
")",
";",
"}",
"ServiceIndicators",
"[",
"]",
"siArray",
"=",
"rk",
".",
"getServiceIndicators",
"(",
")",
";",
"short",
"[",
"]",
"siShortArr",
"=",
"null",
";",
"if",
"(",
"siArray",
"==",
"null",
")",
"{",
"siShortArr",
"=",
"new",
"short",
"[",
"]",
"{",
"-",
"1",
"}",
";",
"}",
"else",
"{",
"siShortArr",
"=",
"siArray",
"[",
"0",
"]",
".",
"getIndicators",
"(",
")",
";",
"}",
"for",
"(",
"FastList",
".",
"Node",
"<",
"DPCNode",
">",
"n",
"=",
"dpcList",
".",
"head",
"(",
")",
",",
"end",
"=",
"dpcList",
".",
"tail",
"(",
")",
";",
"(",
"n",
"=",
"n",
".",
"getNext",
"(",
")",
")",
"!=",
"end",
";",
")",
"{",
"DPCNode",
"dpcNode",
"=",
"n",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"dpcNode",
".",
"dpc",
"==",
"dpc",
")",
"{",
"this",
".",
"addSi",
"(",
"dpcNode",
",",
"opcIntArr",
",",
"siShortArr",
",",
"asImpl",
")",
";",
"return",
";",
"}",
"}",
"DPCNode",
"dpcNode",
"=",
"new",
"DPCNode",
"(",
"dpc",
")",
";",
"this",
".",
"addSi",
"(",
"dpcNode",
",",
"opcIntArr",
",",
"siShortArr",
",",
"asImpl",
")",
";",
"this",
".",
"dpcList",
".",
"add",
"(",
"dpcNode",
")",
";",
"}"
] |
<p>
Create a Tree structure adding the reference to passed As. The Tree is created starting from {@link DPCNode} as parent
node containing 'n' {@link OPCNode} leafs where 'n' is list of OPC passed. For each {@link OPCNode} there will be 'm'
{@link SINode} leafs where 'm' is number of Service Indicator passed.
</p>
<p>
DPC is mandatory while OPC and SI list are optional. If OPC or SI is not passed the wild card '-1' leaf will be added to
parent node
</p>
@param rk
@param asImpl
@throws Exception
|
[
"<p",
">",
"Create",
"a",
"Tree",
"structure",
"adding",
"the",
"reference",
"to",
"passed",
"As",
".",
"The",
"Tree",
"is",
"created",
"starting",
"from",
"{",
"@link",
"DPCNode",
"}",
"as",
"parent",
"node",
"containing",
"n",
"{",
"@link",
"OPCNode",
"}",
"leafs",
"where",
"n",
"is",
"list",
"of",
"OPC",
"passed",
".",
"For",
"each",
"{",
"@link",
"OPCNode",
"}",
"there",
"will",
"be",
"m",
"{",
"@link",
"SINode",
"}",
"leafs",
"where",
"m",
"is",
"number",
"of",
"Service",
"Indicator",
"passed",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/m3ua/impl/src/main/java/org/restcomm/protocols/ss7/m3ua/impl/router/ServerM3UARouter.java#L69-L100
|
alexnederlof/Jasper-report-maven-plugin
|
src/main/java/com/alexnederlof/jasperreport/JasperReporter.java
|
JasperReporter.jrxmlFilesToCompile
|
protected Set<File> jrxmlFilesToCompile(SourceMapping mapping) throws MojoExecutionException {
"""
Determines source files to be compiled.
@param mapping The source files
@return set of jxml files to compile
@throws MojoExecutionException When there's trouble with the input
"""
if (!sourceDirectory.isDirectory()) {
String message = sourceDirectory.getName() + " is not a directory";
if (failOnMissingSourceDirectory) {
throw new IllegalArgumentException(message);
}
else {
log.warn(message + ", skip JasperReports reports compiling.");
return Collections.emptySet();
}
}
try {
SourceInclusionScanner scanner = createSourceInclusionScanner();
scanner.addSourceMapping(mapping);
return scanner.getIncludedSources(sourceDirectory, outputDirectory);
}
catch (InclusionScanException e) {
throw new MojoExecutionException("Error scanning source root: \'" + sourceDirectory + "\'.", e);
}
}
|
java
|
protected Set<File> jrxmlFilesToCompile(SourceMapping mapping) throws MojoExecutionException {
if (!sourceDirectory.isDirectory()) {
String message = sourceDirectory.getName() + " is not a directory";
if (failOnMissingSourceDirectory) {
throw new IllegalArgumentException(message);
}
else {
log.warn(message + ", skip JasperReports reports compiling.");
return Collections.emptySet();
}
}
try {
SourceInclusionScanner scanner = createSourceInclusionScanner();
scanner.addSourceMapping(mapping);
return scanner.getIncludedSources(sourceDirectory, outputDirectory);
}
catch (InclusionScanException e) {
throw new MojoExecutionException("Error scanning source root: \'" + sourceDirectory + "\'.", e);
}
}
|
[
"protected",
"Set",
"<",
"File",
">",
"jrxmlFilesToCompile",
"(",
"SourceMapping",
"mapping",
")",
"throws",
"MojoExecutionException",
"{",
"if",
"(",
"!",
"sourceDirectory",
".",
"isDirectory",
"(",
")",
")",
"{",
"String",
"message",
"=",
"sourceDirectory",
".",
"getName",
"(",
")",
"+",
"\" is not a directory\"",
";",
"if",
"(",
"failOnMissingSourceDirectory",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
";",
"}",
"else",
"{",
"log",
".",
"warn",
"(",
"message",
"+",
"\", skip JasperReports reports compiling.\"",
")",
";",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"}",
"}",
"try",
"{",
"SourceInclusionScanner",
"scanner",
"=",
"createSourceInclusionScanner",
"(",
")",
";",
"scanner",
".",
"addSourceMapping",
"(",
"mapping",
")",
";",
"return",
"scanner",
".",
"getIncludedSources",
"(",
"sourceDirectory",
",",
"outputDirectory",
")",
";",
"}",
"catch",
"(",
"InclusionScanException",
"e",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Error scanning source root: \\'\"",
"+",
"sourceDirectory",
"+",
"\"\\'.\"",
",",
"e",
")",
";",
"}",
"}"
] |
Determines source files to be compiled.
@param mapping The source files
@return set of jxml files to compile
@throws MojoExecutionException When there's trouble with the input
|
[
"Determines",
"source",
"files",
"to",
"be",
"compiled",
"."
] |
train
|
https://github.com/alexnederlof/Jasper-report-maven-plugin/blob/481c50c6db360ec71693034b6b9a2c1eb63277d8/src/main/java/com/alexnederlof/jasperreport/JasperReporter.java#L229-L249
|
VoltDB/voltdb
|
third_party/java/src/org/HdrHistogram_voltpatches/Histogram.java
|
Histogram.decodeFromCompressedByteBuffer
|
public static Histogram decodeFromCompressedByteBuffer(final ByteBuffer buffer,
final long minBarForHighestTrackableValue) throws DataFormatException {
"""
Construct a new histogram by decoding it from a compressed form in a ByteBuffer.
@param buffer The buffer to decode from
@param minBarForHighestTrackableValue Force highestTrackableValue to be set at least this high
@return The newly constructed histogram
@throws DataFormatException on error parsing/decompressing the buffer
"""
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestTrackableValue);
}
|
java
|
public static Histogram decodeFromCompressedByteBuffer(final ByteBuffer buffer,
final long minBarForHighestTrackableValue) throws DataFormatException {
return decodeFromCompressedByteBuffer(buffer, Histogram.class, minBarForHighestTrackableValue);
}
|
[
"public",
"static",
"Histogram",
"decodeFromCompressedByteBuffer",
"(",
"final",
"ByteBuffer",
"buffer",
",",
"final",
"long",
"minBarForHighestTrackableValue",
")",
"throws",
"DataFormatException",
"{",
"return",
"decodeFromCompressedByteBuffer",
"(",
"buffer",
",",
"Histogram",
".",
"class",
",",
"minBarForHighestTrackableValue",
")",
";",
"}"
] |
Construct a new histogram by decoding it from a compressed form in a ByteBuffer.
@param buffer The buffer to decode from
@param minBarForHighestTrackableValue Force highestTrackableValue to be set at least this high
@return The newly constructed histogram
@throws DataFormatException on error parsing/decompressing the buffer
|
[
"Construct",
"a",
"new",
"histogram",
"by",
"decoding",
"it",
"from",
"a",
"compressed",
"form",
"in",
"a",
"ByteBuffer",
"."
] |
train
|
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/HdrHistogram_voltpatches/Histogram.java#L251-L254
|
Azure/azure-sdk-for-java
|
datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java
|
AccountsInner.deleteFirewallRule
|
public void deleteFirewallRule(String resourceGroupName, String accountName, String firewallRuleName) {
"""
Deletes the specified firewall rule from the specified Data Lake Store account.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Store account.
@param accountName The name of the Data Lake Store account from which to delete the firewall rule.
@param firewallRuleName The name of the firewall rule to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
deleteFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, firewallRuleName).toBlocking().single().body();
}
|
java
|
public void deleteFirewallRule(String resourceGroupName, String accountName, String firewallRuleName) {
deleteFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, firewallRuleName).toBlocking().single().body();
}
|
[
"public",
"void",
"deleteFirewallRule",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"String",
"firewallRuleName",
")",
"{",
"deleteFirewallRuleWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
"firewallRuleName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] |
Deletes the specified firewall rule from the specified Data Lake Store account.
@param resourceGroupName The name of the Azure resource group that contains the Data Lake Store account.
@param accountName The name of the Data Lake Store account from which to delete the firewall rule.
@param firewallRuleName The name of the firewall rule to delete.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
|
[
"Deletes",
"the",
"specified",
"firewall",
"rule",
"from",
"the",
"specified",
"Data",
"Lake",
"Store",
"account",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java#L149-L151
|
crnk-project/crnk-framework
|
crnk-setup/crnk-setup-rs/src/main/java/io/crnk/rs/JsonApiResponseFilter.java
|
JsonApiResponseFilter.filter
|
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
"""
Creates JSON API responses for custom JAX-RS actions returning Crnk resources.
"""
Object response = responseContext.getEntity();
if (response == null) {
if (feature.getBoot().isNullDataResponseEnabled()) {
Document document = new Document();
document.setData(Nullable.nullValue());
responseContext.setEntity(document);
responseContext.setStatus(Response.Status.OK.getStatusCode());
responseContext.getHeaders().put("Content-Type",
Collections.singletonList(JsonApiMediaType.APPLICATION_JSON_API));
}
return;
}
// only modify responses which contain a single or a list of Crnk resources
Optional<RegistryEntry> registryEntry = getRegistryEntry(response);
if (registryEntry.isPresent()) {
CrnkBoot boot = feature.getBoot();
DocumentMapper documentMapper = boot.getDocumentMapper();
HttpRequestContextProvider httpRequestContextProvider = boot.getModuleRegistry().getHttpRequestContextProvider();
try {
HttpRequestContext context = new HttpRequestContextBaseAdapter(new JaxrsRequestContext(requestContext,
feature));
httpRequestContextProvider.onRequestStarted(context);
JsonApiResponse jsonApiResponse = new JsonApiResponse();
jsonApiResponse.setEntity(response);
// use the Crnk document mapper to create a JSON API response
DocumentMappingConfig mappingConfig = new DocumentMappingConfig();
ResourceInformation resourceInformation = registryEntry.get().getResourceInformation();
Map<String, Set<String>> jsonApiParameters = context.getRequestParameters().entrySet()
.stream()
.filter(entry -> isJsonApiParameter(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
QuerySpecUrlMapper urlMapper = feature.getBoot().getUrlMapper();
QuerySpec querySpec = urlMapper.deserialize(resourceInformation, jsonApiParameters);
ResourceRegistry resourceRegistry = feature.getBoot().getResourceRegistry();
QueryAdapter queryAdapter = new QuerySpecAdapter(querySpec, resourceRegistry, context.getQueryContext());
responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, queryAdapter, mappingConfig).get());
responseContext.getHeaders().put("Content-Type",
Collections.singletonList(JsonApiMediaType.APPLICATION_JSON_API));
} finally {
httpRequestContextProvider.onRequestFinished();
}
} else if (isJsonApiResponse(responseContext) && !doNotWrap(response)) {
Document document = new Document();
document.setData(Nullable.of(response));
responseContext.setEntity(document);
}
}
|
java
|
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
Object response = responseContext.getEntity();
if (response == null) {
if (feature.getBoot().isNullDataResponseEnabled()) {
Document document = new Document();
document.setData(Nullable.nullValue());
responseContext.setEntity(document);
responseContext.setStatus(Response.Status.OK.getStatusCode());
responseContext.getHeaders().put("Content-Type",
Collections.singletonList(JsonApiMediaType.APPLICATION_JSON_API));
}
return;
}
// only modify responses which contain a single or a list of Crnk resources
Optional<RegistryEntry> registryEntry = getRegistryEntry(response);
if (registryEntry.isPresent()) {
CrnkBoot boot = feature.getBoot();
DocumentMapper documentMapper = boot.getDocumentMapper();
HttpRequestContextProvider httpRequestContextProvider = boot.getModuleRegistry().getHttpRequestContextProvider();
try {
HttpRequestContext context = new HttpRequestContextBaseAdapter(new JaxrsRequestContext(requestContext,
feature));
httpRequestContextProvider.onRequestStarted(context);
JsonApiResponse jsonApiResponse = new JsonApiResponse();
jsonApiResponse.setEntity(response);
// use the Crnk document mapper to create a JSON API response
DocumentMappingConfig mappingConfig = new DocumentMappingConfig();
ResourceInformation resourceInformation = registryEntry.get().getResourceInformation();
Map<String, Set<String>> jsonApiParameters = context.getRequestParameters().entrySet()
.stream()
.filter(entry -> isJsonApiParameter(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
QuerySpecUrlMapper urlMapper = feature.getBoot().getUrlMapper();
QuerySpec querySpec = urlMapper.deserialize(resourceInformation, jsonApiParameters);
ResourceRegistry resourceRegistry = feature.getBoot().getResourceRegistry();
QueryAdapter queryAdapter = new QuerySpecAdapter(querySpec, resourceRegistry, context.getQueryContext());
responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, queryAdapter, mappingConfig).get());
responseContext.getHeaders().put("Content-Type",
Collections.singletonList(JsonApiMediaType.APPLICATION_JSON_API));
} finally {
httpRequestContextProvider.onRequestFinished();
}
} else if (isJsonApiResponse(responseContext) && !doNotWrap(response)) {
Document document = new Document();
document.setData(Nullable.of(response));
responseContext.setEntity(document);
}
}
|
[
"@",
"Override",
"public",
"void",
"filter",
"(",
"ContainerRequestContext",
"requestContext",
",",
"ContainerResponseContext",
"responseContext",
")",
"{",
"Object",
"response",
"=",
"responseContext",
".",
"getEntity",
"(",
")",
";",
"if",
"(",
"response",
"==",
"null",
")",
"{",
"if",
"(",
"feature",
".",
"getBoot",
"(",
")",
".",
"isNullDataResponseEnabled",
"(",
")",
")",
"{",
"Document",
"document",
"=",
"new",
"Document",
"(",
")",
";",
"document",
".",
"setData",
"(",
"Nullable",
".",
"nullValue",
"(",
")",
")",
";",
"responseContext",
".",
"setEntity",
"(",
"document",
")",
";",
"responseContext",
".",
"setStatus",
"(",
"Response",
".",
"Status",
".",
"OK",
".",
"getStatusCode",
"(",
")",
")",
";",
"responseContext",
".",
"getHeaders",
"(",
")",
".",
"put",
"(",
"\"Content-Type\"",
",",
"Collections",
".",
"singletonList",
"(",
"JsonApiMediaType",
".",
"APPLICATION_JSON_API",
")",
")",
";",
"}",
"return",
";",
"}",
"// only modify responses which contain a single or a list of Crnk resources",
"Optional",
"<",
"RegistryEntry",
">",
"registryEntry",
"=",
"getRegistryEntry",
"(",
"response",
")",
";",
"if",
"(",
"registryEntry",
".",
"isPresent",
"(",
")",
")",
"{",
"CrnkBoot",
"boot",
"=",
"feature",
".",
"getBoot",
"(",
")",
";",
"DocumentMapper",
"documentMapper",
"=",
"boot",
".",
"getDocumentMapper",
"(",
")",
";",
"HttpRequestContextProvider",
"httpRequestContextProvider",
"=",
"boot",
".",
"getModuleRegistry",
"(",
")",
".",
"getHttpRequestContextProvider",
"(",
")",
";",
"try",
"{",
"HttpRequestContext",
"context",
"=",
"new",
"HttpRequestContextBaseAdapter",
"(",
"new",
"JaxrsRequestContext",
"(",
"requestContext",
",",
"feature",
")",
")",
";",
"httpRequestContextProvider",
".",
"onRequestStarted",
"(",
"context",
")",
";",
"JsonApiResponse",
"jsonApiResponse",
"=",
"new",
"JsonApiResponse",
"(",
")",
";",
"jsonApiResponse",
".",
"setEntity",
"(",
"response",
")",
";",
"// use the Crnk document mapper to create a JSON API response",
"DocumentMappingConfig",
"mappingConfig",
"=",
"new",
"DocumentMappingConfig",
"(",
")",
";",
"ResourceInformation",
"resourceInformation",
"=",
"registryEntry",
".",
"get",
"(",
")",
".",
"getResourceInformation",
"(",
")",
";",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"jsonApiParameters",
"=",
"context",
".",
"getRequestParameters",
"(",
")",
".",
"entrySet",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"entry",
"->",
"isJsonApiParameter",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toMap",
"(",
"Map",
".",
"Entry",
"::",
"getKey",
",",
"Map",
".",
"Entry",
"::",
"getValue",
")",
")",
";",
"QuerySpecUrlMapper",
"urlMapper",
"=",
"feature",
".",
"getBoot",
"(",
")",
".",
"getUrlMapper",
"(",
")",
";",
"QuerySpec",
"querySpec",
"=",
"urlMapper",
".",
"deserialize",
"(",
"resourceInformation",
",",
"jsonApiParameters",
")",
";",
"ResourceRegistry",
"resourceRegistry",
"=",
"feature",
".",
"getBoot",
"(",
")",
".",
"getResourceRegistry",
"(",
")",
";",
"QueryAdapter",
"queryAdapter",
"=",
"new",
"QuerySpecAdapter",
"(",
"querySpec",
",",
"resourceRegistry",
",",
"context",
".",
"getQueryContext",
"(",
")",
")",
";",
"responseContext",
".",
"setEntity",
"(",
"documentMapper",
".",
"toDocument",
"(",
"jsonApiResponse",
",",
"queryAdapter",
",",
"mappingConfig",
")",
".",
"get",
"(",
")",
")",
";",
"responseContext",
".",
"getHeaders",
"(",
")",
".",
"put",
"(",
"\"Content-Type\"",
",",
"Collections",
".",
"singletonList",
"(",
"JsonApiMediaType",
".",
"APPLICATION_JSON_API",
")",
")",
";",
"}",
"finally",
"{",
"httpRequestContextProvider",
".",
"onRequestFinished",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isJsonApiResponse",
"(",
"responseContext",
")",
"&&",
"!",
"doNotWrap",
"(",
"response",
")",
")",
"{",
"Document",
"document",
"=",
"new",
"Document",
"(",
")",
";",
"document",
".",
"setData",
"(",
"Nullable",
".",
"of",
"(",
"response",
")",
")",
";",
"responseContext",
".",
"setEntity",
"(",
"document",
")",
";",
"}",
"}"
] |
Creates JSON API responses for custom JAX-RS actions returning Crnk resources.
|
[
"Creates",
"JSON",
"API",
"responses",
"for",
"custom",
"JAX",
"-",
"RS",
"actions",
"returning",
"Crnk",
"resources",
"."
] |
train
|
https://github.com/crnk-project/crnk-framework/blob/2fd3ef9a991788d46fd2e83b43c8ea37cbaf8681/crnk-setup/crnk-setup-rs/src/main/java/io/crnk/rs/JsonApiResponseFilter.java#L54-L107
|
vanilladb/vanillacore
|
src/main/java/org/vanilladb/core/storage/record/RecordPage.java
|
RecordPage.getVal
|
public Constant getVal(String fldName) {
"""
Returns the value stored in the specified field of this record.
@param fldName
the name of the field.
@return the constant stored in that field
"""
int position = fieldPos(fldName);
return getVal(position, ti.schema().type(fldName));
}
|
java
|
public Constant getVal(String fldName) {
int position = fieldPos(fldName);
return getVal(position, ti.schema().type(fldName));
}
|
[
"public",
"Constant",
"getVal",
"(",
"String",
"fldName",
")",
"{",
"int",
"position",
"=",
"fieldPos",
"(",
"fldName",
")",
";",
"return",
"getVal",
"(",
"position",
",",
"ti",
".",
"schema",
"(",
")",
".",
"type",
"(",
"fldName",
")",
")",
";",
"}"
] |
Returns the value stored in the specified field of this record.
@param fldName
the name of the field.
@return the constant stored in that field
|
[
"Returns",
"the",
"value",
"stored",
"in",
"the",
"specified",
"field",
"of",
"this",
"record",
"."
] |
train
|
https://github.com/vanilladb/vanillacore/blob/d9a34e876b1b83226036d1fa982a614bbef59bd1/src/main/java/org/vanilladb/core/storage/record/RecordPage.java#L187-L190
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.isEqualOrNull
|
private static boolean isEqualOrNull(String left, String right) {
"""
Compares two strings for equality; if both strings are null they are
considered equal.
@param left the first string to compare
@param right the second string to compare
@return true if the strings are equal or if they are both null; otherwise
false.
"""
return (left != null && left.equals(right)) || (left == null && right == null);
}
|
java
|
private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
}
|
[
"private",
"static",
"boolean",
"isEqualOrNull",
"(",
"String",
"left",
",",
"String",
"right",
")",
"{",
"return",
"(",
"left",
"!=",
"null",
"&&",
"left",
".",
"equals",
"(",
"right",
")",
")",
"||",
"(",
"left",
"==",
"null",
"&&",
"right",
"==",
"null",
")",
";",
"}"
] |
Compares two strings for equality; if both strings are null they are
considered equal.
@param left the first string to compare
@param right the second string to compare
@return true if the strings are equal or if they are both null; otherwise
false.
|
[
"Compares",
"two",
"strings",
"for",
"equality",
";",
"if",
"both",
"strings",
"are",
"null",
"they",
"are",
"considered",
"equal",
"."
] |
train
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L698-L700
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.logging.core/src/com/ibm/ejs/ras/TraceNLS.java
|
TraceNLS.getTraceNLS
|
public static TraceNLS getTraceNLS(Class<?> caller, String bundleName) {
"""
Retrieve a TraceNLS instance for the specified ResourceBundle.
<p>
If the specified ResourceBundle is not found, a TraceNLS object is
returned. Subsequent method calls on that instance will return a "bundle
not found" message as appropriate.
<p>
@param caller
Class object requesting the NLS bundle instance
@param bundleName
the package-qualified name of the ResourceBundle. The caller
MUST guarantee that this is not null.
<p>
@return a TraceNLS object. Null is never returned.
"""
if (resolver == null)
resolver = TraceNLSResolver.getInstance();
// TODO: CACHE
return new TraceNLS(caller, bundleName);
}
|
java
|
public static TraceNLS getTraceNLS(Class<?> caller, String bundleName) {
if (resolver == null)
resolver = TraceNLSResolver.getInstance();
// TODO: CACHE
return new TraceNLS(caller, bundleName);
}
|
[
"public",
"static",
"TraceNLS",
"getTraceNLS",
"(",
"Class",
"<",
"?",
">",
"caller",
",",
"String",
"bundleName",
")",
"{",
"if",
"(",
"resolver",
"==",
"null",
")",
"resolver",
"=",
"TraceNLSResolver",
".",
"getInstance",
"(",
")",
";",
"// TODO: CACHE",
"return",
"new",
"TraceNLS",
"(",
"caller",
",",
"bundleName",
")",
";",
"}"
] |
Retrieve a TraceNLS instance for the specified ResourceBundle.
<p>
If the specified ResourceBundle is not found, a TraceNLS object is
returned. Subsequent method calls on that instance will return a "bundle
not found" message as appropriate.
<p>
@param caller
Class object requesting the NLS bundle instance
@param bundleName
the package-qualified name of the ResourceBundle. The caller
MUST guarantee that this is not null.
<p>
@return a TraceNLS object. Null is never returned.
|
[
"Retrieve",
"a",
"TraceNLS",
"instance",
"for",
"the",
"specified",
"ResourceBundle",
".",
"<p",
">",
"If",
"the",
"specified",
"ResourceBundle",
"is",
"not",
"found",
"a",
"TraceNLS",
"object",
"is",
"returned",
".",
"Subsequent",
"method",
"calls",
"on",
"that",
"instance",
"will",
"return",
"a",
"bundle",
"not",
"found",
"message",
"as",
"appropriate",
".",
"<p",
">"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ejs/ras/TraceNLS.java#L101-L106
|
zackpollard/JavaTelegramBot-API
|
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
|
TelegramBot.editInlineMessageReplyMarkup
|
public boolean editInlineMessageReplyMarkup(String inlineMessageId, InlineReplyMarkup inlineReplyMarkup) {
"""
This allows you to edit the InlineReplyMarkup of any inline message that you have sent previously. (The inline
message must have an InlineReplyMarkup object attached in order to be editable)
@param inlineMessageId The ID of the inline message you want to edit
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return True if the edit succeeded, otherwise False
"""
if(inlineMessageId != null && inlineReplyMarkup != null) {
JSONObject jsonResponse = this.editMessageReplyMarkup(null, null, inlineMessageId, inlineReplyMarkup);
if(jsonResponse != null) {
if(jsonResponse.getBoolean("result")) return true;
}
}
return false;
}
|
java
|
public boolean editInlineMessageReplyMarkup(String inlineMessageId, InlineReplyMarkup inlineReplyMarkup) {
if(inlineMessageId != null && inlineReplyMarkup != null) {
JSONObject jsonResponse = this.editMessageReplyMarkup(null, null, inlineMessageId, inlineReplyMarkup);
if(jsonResponse != null) {
if(jsonResponse.getBoolean("result")) return true;
}
}
return false;
}
|
[
"public",
"boolean",
"editInlineMessageReplyMarkup",
"(",
"String",
"inlineMessageId",
",",
"InlineReplyMarkup",
"inlineReplyMarkup",
")",
"{",
"if",
"(",
"inlineMessageId",
"!=",
"null",
"&&",
"inlineReplyMarkup",
"!=",
"null",
")",
"{",
"JSONObject",
"jsonResponse",
"=",
"this",
".",
"editMessageReplyMarkup",
"(",
"null",
",",
"null",
",",
"inlineMessageId",
",",
"inlineReplyMarkup",
")",
";",
"if",
"(",
"jsonResponse",
"!=",
"null",
")",
"{",
"if",
"(",
"jsonResponse",
".",
"getBoolean",
"(",
"\"result\"",
")",
")",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
This allows you to edit the InlineReplyMarkup of any inline message that you have sent previously. (The inline
message must have an InlineReplyMarkup object attached in order to be editable)
@param inlineMessageId The ID of the inline message you want to edit
@param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message
@return True if the edit succeeded, otherwise False
|
[
"This",
"allows",
"you",
"to",
"edit",
"the",
"InlineReplyMarkup",
"of",
"any",
"inline",
"message",
"that",
"you",
"have",
"sent",
"previously",
".",
"(",
"The",
"inline",
"message",
"must",
"have",
"an",
"InlineReplyMarkup",
"object",
"attached",
"in",
"order",
"to",
"be",
"editable",
")"
] |
train
|
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L882-L895
|
lessthanoptimal/ejml
|
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
|
CommonOps_DDRM.concatRowsMulti
|
public static DMatrixRMaj concatRowsMulti(DMatrixRMaj ...m ) {
"""
<p>Concatinates all the matrices together along their columns. If the rows do not match the upper elements
are set to zero.</p>
A = [ m[0] ; ... ; m[n-1] ]
@param m Set of matrices
@return Resulting matrix
"""
int rows = 0;
int cols = 0;
for (int i = 0; i < m.length; i++) {
rows += m[i].numRows;
cols = Math.max(cols,m[i].numCols);
}
DMatrixRMaj R = new DMatrixRMaj(rows,cols);
int row = 0;
for (int i = 0; i < m.length; i++) {
insert(m[i],R,row,0);
row += m[i].numRows;
}
return R;
}
|
java
|
public static DMatrixRMaj concatRowsMulti(DMatrixRMaj ...m ) {
int rows = 0;
int cols = 0;
for (int i = 0; i < m.length; i++) {
rows += m[i].numRows;
cols = Math.max(cols,m[i].numCols);
}
DMatrixRMaj R = new DMatrixRMaj(rows,cols);
int row = 0;
for (int i = 0; i < m.length; i++) {
insert(m[i],R,row,0);
row += m[i].numRows;
}
return R;
}
|
[
"public",
"static",
"DMatrixRMaj",
"concatRowsMulti",
"(",
"DMatrixRMaj",
"...",
"m",
")",
"{",
"int",
"rows",
"=",
"0",
";",
"int",
"cols",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m",
".",
"length",
";",
"i",
"++",
")",
"{",
"rows",
"+=",
"m",
"[",
"i",
"]",
".",
"numRows",
";",
"cols",
"=",
"Math",
".",
"max",
"(",
"cols",
",",
"m",
"[",
"i",
"]",
".",
"numCols",
")",
";",
"}",
"DMatrixRMaj",
"R",
"=",
"new",
"DMatrixRMaj",
"(",
"rows",
",",
"cols",
")",
";",
"int",
"row",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m",
".",
"length",
";",
"i",
"++",
")",
"{",
"insert",
"(",
"m",
"[",
"i",
"]",
",",
"R",
",",
"row",
",",
"0",
")",
";",
"row",
"+=",
"m",
"[",
"i",
"]",
".",
"numRows",
";",
"}",
"return",
"R",
";",
"}"
] |
<p>Concatinates all the matrices together along their columns. If the rows do not match the upper elements
are set to zero.</p>
A = [ m[0] ; ... ; m[n-1] ]
@param m Set of matrices
@return Resulting matrix
|
[
"<p",
">",
"Concatinates",
"all",
"the",
"matrices",
"together",
"along",
"their",
"columns",
".",
"If",
"the",
"rows",
"do",
"not",
"match",
"the",
"upper",
"elements",
"are",
"set",
"to",
"zero",
".",
"<",
"/",
"p",
">"
] |
train
|
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L2857-L2874
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.