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
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UniversalTimeScale.java | UniversalTimeScale.toBigDecimal | public static BigDecimal toBigDecimal(long universalTime, int timeScale) {
"""
Convert a datetime from the universal time scale to a <code>BigDecimal</code> in the given time scale.
@param universalTime The datetime in the universal time scale
@param timeScale The time scale to convert to
@return The datetime converted to the given time scale
"""
TimeScaleData data = getTimeScaleData(timeScale);
BigDecimal universal = new BigDecimal(universalTime);
BigDecimal units = new BigDecimal(data.units);
BigDecimal epochOffset = new BigDecimal(data.epochOffset);
return universal.divide(units, BigDecimal.ROUND_HALF_UP).subtract(epochOffset);
} | java | public static BigDecimal toBigDecimal(long universalTime, int timeScale)
{
TimeScaleData data = getTimeScaleData(timeScale);
BigDecimal universal = new BigDecimal(universalTime);
BigDecimal units = new BigDecimal(data.units);
BigDecimal epochOffset = new BigDecimal(data.epochOffset);
return universal.divide(units, BigDecimal.ROUND_HALF_UP).subtract(epochOffset);
} | [
"public",
"static",
"BigDecimal",
"toBigDecimal",
"(",
"long",
"universalTime",
",",
"int",
"timeScale",
")",
"{",
"TimeScaleData",
"data",
"=",
"getTimeScaleData",
"(",
"timeScale",
")",
";",
"BigDecimal",
"universal",
"=",
"new",
"BigDecimal",
"(",
"universalTime",
")",
";",
"BigDecimal",
"units",
"=",
"new",
"BigDecimal",
"(",
"data",
".",
"units",
")",
";",
"BigDecimal",
"epochOffset",
"=",
"new",
"BigDecimal",
"(",
"data",
".",
"epochOffset",
")",
";",
"return",
"universal",
".",
"divide",
"(",
"units",
",",
"BigDecimal",
".",
"ROUND_HALF_UP",
")",
".",
"subtract",
"(",
"epochOffset",
")",
";",
"}"
] | Convert a datetime from the universal time scale to a <code>BigDecimal</code> in the given time scale.
@param universalTime The datetime in the universal time scale
@param timeScale The time scale to convert to
@return The datetime converted to the given time scale | [
"Convert",
"a",
"datetime",
"from",
"the",
"universal",
"time",
"scale",
"to",
"a",
"<code",
">",
"BigDecimal<",
"/",
"code",
">",
"in",
"the",
"given",
"time",
"scale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UniversalTimeScale.java#L467-L475 |
JavaMoney/jsr354-ri | moneta-core/src/main/java/org/javamoney/moneta/spi/MoneyUtils.java | MoneyUtils.getMathContext | public static MathContext getMathContext(MonetaryContext monetaryContext, RoundingMode defaultMode) {
"""
Evaluates the {@link MathContext} from the given {@link MonetaryContext}.
@param monetaryContext the {@link MonetaryContext}
@param defaultMode the default {@link RoundingMode}, to be used if no one is set
in {@link MonetaryContext}.
@return the corresponding {@link MathContext}
"""
MathContext ctx = monetaryContext.get(MathContext.class);
if (Objects.nonNull(ctx)) {
return ctx;
}
RoundingMode roundingMode = monetaryContext.get(RoundingMode.class);
if (roundingMode == null) {
roundingMode = Optional.ofNullable(defaultMode).orElse(HALF_EVEN);
}
return new MathContext(monetaryContext.getPrecision(), roundingMode);
} | java | public static MathContext getMathContext(MonetaryContext monetaryContext, RoundingMode defaultMode) {
MathContext ctx = monetaryContext.get(MathContext.class);
if (Objects.nonNull(ctx)) {
return ctx;
}
RoundingMode roundingMode = monetaryContext.get(RoundingMode.class);
if (roundingMode == null) {
roundingMode = Optional.ofNullable(defaultMode).orElse(HALF_EVEN);
}
return new MathContext(monetaryContext.getPrecision(), roundingMode);
} | [
"public",
"static",
"MathContext",
"getMathContext",
"(",
"MonetaryContext",
"monetaryContext",
",",
"RoundingMode",
"defaultMode",
")",
"{",
"MathContext",
"ctx",
"=",
"monetaryContext",
".",
"get",
"(",
"MathContext",
".",
"class",
")",
";",
"if",
"(",
"Objects",
".",
"nonNull",
"(",
"ctx",
")",
")",
"{",
"return",
"ctx",
";",
"}",
"RoundingMode",
"roundingMode",
"=",
"monetaryContext",
".",
"get",
"(",
"RoundingMode",
".",
"class",
")",
";",
"if",
"(",
"roundingMode",
"==",
"null",
")",
"{",
"roundingMode",
"=",
"Optional",
".",
"ofNullable",
"(",
"defaultMode",
")",
".",
"orElse",
"(",
"HALF_EVEN",
")",
";",
"}",
"return",
"new",
"MathContext",
"(",
"monetaryContext",
".",
"getPrecision",
"(",
")",
",",
"roundingMode",
")",
";",
"}"
] | Evaluates the {@link MathContext} from the given {@link MonetaryContext}.
@param monetaryContext the {@link MonetaryContext}
@param defaultMode the default {@link RoundingMode}, to be used if no one is set
in {@link MonetaryContext}.
@return the corresponding {@link MathContext} | [
"Evaluates",
"the",
"{",
"@link",
"MathContext",
"}",
"from",
"the",
"given",
"{",
"@link",
"MonetaryContext",
"}",
"."
] | train | https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/spi/MoneyUtils.java#L127-L137 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Marker.java | Marker.getAs | public <T> T getAs(String name, Class<T> returnType) {
"""
Returns the value for {@code name} coerced to the given type, T.
@param <T> the return type
@param name the String name of the value to return
@param returnType The return type, which must be assignable from Long,
Integer, String, or Object
@return the Object stored for {@code name} coerced to a T
@throws ClassCastException if the return type is unknown
"""
return Conversions.convert(get(name), returnType);
} | java | public <T> T getAs(String name, Class<T> returnType) {
return Conversions.convert(get(name), returnType);
} | [
"public",
"<",
"T",
">",
"T",
"getAs",
"(",
"String",
"name",
",",
"Class",
"<",
"T",
">",
"returnType",
")",
"{",
"return",
"Conversions",
".",
"convert",
"(",
"get",
"(",
"name",
")",
",",
"returnType",
")",
";",
"}"
] | Returns the value for {@code name} coerced to the given type, T.
@param <T> the return type
@param name the String name of the value to return
@param returnType The return type, which must be assignable from Long,
Integer, String, or Object
@return the Object stored for {@code name} coerced to a T
@throws ClassCastException if the return type is unknown | [
"Returns",
"the",
"value",
"for",
"{",
"@code",
"name",
"}",
"coerced",
"to",
"the",
"given",
"type",
"T",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Marker.java#L93-L95 |
dadoonet/elasticsearch-beyonder | src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java | TemplateElasticsearchUpdater.removeTemplate | @Deprecated
public static void removeTemplate(Client client, String template) {
"""
Remove a template
@param client Elasticsearch client
@param template template name
@deprecated Will be removed when we don't support TransportClient anymore
"""
logger.trace("removeTemplate({})", template);
client.admin().indices().prepareDeleteTemplate(template).get();
logger.trace("/removeTemplate({})", template);
} | java | @Deprecated
public static void removeTemplate(Client client, String template) {
logger.trace("removeTemplate({})", template);
client.admin().indices().prepareDeleteTemplate(template).get();
logger.trace("/removeTemplate({})", template);
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"removeTemplate",
"(",
"Client",
"client",
",",
"String",
"template",
")",
"{",
"logger",
".",
"trace",
"(",
"\"removeTemplate({})\"",
",",
"template",
")",
";",
"client",
".",
"admin",
"(",
")",
".",
"indices",
"(",
")",
".",
"prepareDeleteTemplate",
"(",
"template",
")",
".",
"get",
"(",
")",
";",
"logger",
".",
"trace",
"(",
"\"/removeTemplate({})\"",
",",
"template",
")",
";",
"}"
] | Remove a template
@param client Elasticsearch client
@param template template name
@deprecated Will be removed when we don't support TransportClient anymore | [
"Remove",
"a",
"template"
] | train | https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L142-L147 |
Addicticks/httpsupload | src/main/java/com/addicticks/net/httpsupload/SSLUtils.java | SSLUtils.setNoValidate | public static void setNoValidate(HttpsURLConnection connection, String[] acceptedIssuers) {
"""
Changes the HTTPS connection so that it will not validate the endpoint's
certificates. Also it will not require the URL hostname to match the
common name presented by the endpoint's certificate. This method should
be called <i>before</i> a connection is made on the {@code connection}
object.
<p>
This method is equivalent to <code>--no-check-certificate</code> option when
using the Unix/Linux <code>wget</code> command line tool.
<p>
As an additional feature the issuer of the certificate can be checked
to match (any of) a certain string. If - for example - you create
a self-signed certificate then you decide the 'issuer organization'
yourself and the issuer organization name you used when you created the
certificate can then be validated here. This provides a
little extra security than simply accepting any type of certificate.
@param connection connection to change (must not yet be connected)
@param acceptedIssuers accept only a certificate from one of these issuer
organizations. Checks against the Organization (O) field in the 'Issued
By' section of the server's certficate. This parameter provides some
minimal security. A {@code null} means all issuer organizations are
accepted.
"""
SSLContext sc;
try {
// Using "SSL" below means protocols: SSLv3, TLSv1
sc = SSLContext.getInstance("SSL");
sc.init(null, getNonValidatingTrustManagers(acceptedIssuers), new java.security.SecureRandom());
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(SSLUtils.ALLHOSTSVALID_HOSTNAMEVERIFIER);
} catch (NoSuchAlgorithmException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Algorithm SSL not found.", ex);
} catch (KeyManagementException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Error initializing SSL security context.", ex);
}
} | java | public static void setNoValidate(HttpsURLConnection connection, String[] acceptedIssuers) {
SSLContext sc;
try {
// Using "SSL" below means protocols: SSLv3, TLSv1
sc = SSLContext.getInstance("SSL");
sc.init(null, getNonValidatingTrustManagers(acceptedIssuers), new java.security.SecureRandom());
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(SSLUtils.ALLHOSTSVALID_HOSTNAMEVERIFIER);
} catch (NoSuchAlgorithmException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Algorithm SSL not found.", ex);
} catch (KeyManagementException ex) {
// Don't think this will ever happen. Hence we do not forward it.
LOGGER.log(Level.SEVERE, "Error initializing SSL security context.", ex);
}
} | [
"public",
"static",
"void",
"setNoValidate",
"(",
"HttpsURLConnection",
"connection",
",",
"String",
"[",
"]",
"acceptedIssuers",
")",
"{",
"SSLContext",
"sc",
";",
"try",
"{",
"// Using \"SSL\" below means protocols: SSLv3, TLSv1\r",
"sc",
"=",
"SSLContext",
".",
"getInstance",
"(",
"\"SSL\"",
")",
";",
"sc",
".",
"init",
"(",
"null",
",",
"getNonValidatingTrustManagers",
"(",
"acceptedIssuers",
")",
",",
"new",
"java",
".",
"security",
".",
"SecureRandom",
"(",
")",
")",
";",
"connection",
".",
"setSSLSocketFactory",
"(",
"sc",
".",
"getSocketFactory",
"(",
")",
")",
";",
"connection",
".",
"setHostnameVerifier",
"(",
"SSLUtils",
".",
"ALLHOSTSVALID_HOSTNAMEVERIFIER",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"ex",
")",
"{",
"// Don't think this will ever happen. Hence we do not forward it.\r",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Algorithm SSL not found.\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"KeyManagementException",
"ex",
")",
"{",
"// Don't think this will ever happen. Hence we do not forward it.\r",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Error initializing SSL security context.\"",
",",
"ex",
")",
";",
"}",
"}"
] | Changes the HTTPS connection so that it will not validate the endpoint's
certificates. Also it will not require the URL hostname to match the
common name presented by the endpoint's certificate. This method should
be called <i>before</i> a connection is made on the {@code connection}
object.
<p>
This method is equivalent to <code>--no-check-certificate</code> option when
using the Unix/Linux <code>wget</code> command line tool.
<p>
As an additional feature the issuer of the certificate can be checked
to match (any of) a certain string. If - for example - you create
a self-signed certificate then you decide the 'issuer organization'
yourself and the issuer organization name you used when you created the
certificate can then be validated here. This provides a
little extra security than simply accepting any type of certificate.
@param connection connection to change (must not yet be connected)
@param acceptedIssuers accept only a certificate from one of these issuer
organizations. Checks against the Organization (O) field in the 'Issued
By' section of the server's certficate. This parameter provides some
minimal security. A {@code null} means all issuer organizations are
accepted. | [
"Changes",
"the",
"HTTPS",
"connection",
"so",
"that",
"it",
"will",
"not",
"validate",
"the",
"endpoint",
"s",
"certificates",
".",
"Also",
"it",
"will",
"not",
"require",
"the",
"URL",
"hostname",
"to",
"match",
"the",
"common",
"name",
"presented",
"by",
"the",
"endpoint",
"s",
"certificate",
".",
"This",
"method",
"should",
"be",
"called",
"<i",
">",
"before<",
"/",
"i",
">",
"a",
"connection",
"is",
"made",
"on",
"the",
"{",
"@code",
"connection",
"}",
"object",
"."
] | train | https://github.com/Addicticks/httpsupload/blob/261a8e63ec923482a74ffe1352024c1900c55a55/src/main/java/com/addicticks/net/httpsupload/SSLUtils.java#L94-L109 |
quattor/pan | panc/src/main/java/org/quattor/pan/statement/IncludeStatement.java | IncludeStatement.executeWithNamedTemplate | protected void executeWithNamedTemplate(Context context, String name)
throws EvaluationException {
"""
This is a utility method which performs an include from a fixed template
name. The validity of the name should be checked by the subclass; this
avoids unnecessary regular expression matching.
@param context
evaluation context to use
@param name
fixed template name
@throws EvaluationException
"""
assert (context != null);
assert (name != null);
Template template = null;
boolean runStatic = false;
try {
template = context.localLoad(name);
if (template == null) {
template = context.globalLoad(name);
runStatic = true;
}
} catch (EvaluationException ee) {
throw ee.addExceptionInfo(getSourceRange(), context);
}
// Check that the template was actually loaded.
if (template == null) {
throw new EvaluationException("failed to load template: " + name,
getSourceRange());
}
TemplateType includeeType = context.getCurrentTemplate().type;
TemplateType includedType = template.type;
// Check that the template types are correct for the inclusion.
if (!Template.checkValidInclude(includeeType, includedType)) {
throw new EvaluationException(includeeType
+ " template cannot include " + includedType + " template",
getSourceRange());
}
// Push the template, execute it, then pop it from the stack.
// Template loops will be caught by the call depth check when pushing
// the template.
context.pushTemplate(template, getSourceRange(), Level.INFO,
includedType.toString());
template.execute(context, runStatic);
context.popTemplate(Level.INFO, includedType.toString());
} | java | protected void executeWithNamedTemplate(Context context, String name)
throws EvaluationException {
assert (context != null);
assert (name != null);
Template template = null;
boolean runStatic = false;
try {
template = context.localLoad(name);
if (template == null) {
template = context.globalLoad(name);
runStatic = true;
}
} catch (EvaluationException ee) {
throw ee.addExceptionInfo(getSourceRange(), context);
}
// Check that the template was actually loaded.
if (template == null) {
throw new EvaluationException("failed to load template: " + name,
getSourceRange());
}
TemplateType includeeType = context.getCurrentTemplate().type;
TemplateType includedType = template.type;
// Check that the template types are correct for the inclusion.
if (!Template.checkValidInclude(includeeType, includedType)) {
throw new EvaluationException(includeeType
+ " template cannot include " + includedType + " template",
getSourceRange());
}
// Push the template, execute it, then pop it from the stack.
// Template loops will be caught by the call depth check when pushing
// the template.
context.pushTemplate(template, getSourceRange(), Level.INFO,
includedType.toString());
template.execute(context, runStatic);
context.popTemplate(Level.INFO, includedType.toString());
} | [
"protected",
"void",
"executeWithNamedTemplate",
"(",
"Context",
"context",
",",
"String",
"name",
")",
"throws",
"EvaluationException",
"{",
"assert",
"(",
"context",
"!=",
"null",
")",
";",
"assert",
"(",
"name",
"!=",
"null",
")",
";",
"Template",
"template",
"=",
"null",
";",
"boolean",
"runStatic",
"=",
"false",
";",
"try",
"{",
"template",
"=",
"context",
".",
"localLoad",
"(",
"name",
")",
";",
"if",
"(",
"template",
"==",
"null",
")",
"{",
"template",
"=",
"context",
".",
"globalLoad",
"(",
"name",
")",
";",
"runStatic",
"=",
"true",
";",
"}",
"}",
"catch",
"(",
"EvaluationException",
"ee",
")",
"{",
"throw",
"ee",
".",
"addExceptionInfo",
"(",
"getSourceRange",
"(",
")",
",",
"context",
")",
";",
"}",
"// Check that the template was actually loaded.",
"if",
"(",
"template",
"==",
"null",
")",
"{",
"throw",
"new",
"EvaluationException",
"(",
"\"failed to load template: \"",
"+",
"name",
",",
"getSourceRange",
"(",
")",
")",
";",
"}",
"TemplateType",
"includeeType",
"=",
"context",
".",
"getCurrentTemplate",
"(",
")",
".",
"type",
";",
"TemplateType",
"includedType",
"=",
"template",
".",
"type",
";",
"// Check that the template types are correct for the inclusion.",
"if",
"(",
"!",
"Template",
".",
"checkValidInclude",
"(",
"includeeType",
",",
"includedType",
")",
")",
"{",
"throw",
"new",
"EvaluationException",
"(",
"includeeType",
"+",
"\" template cannot include \"",
"+",
"includedType",
"+",
"\" template\"",
",",
"getSourceRange",
"(",
")",
")",
";",
"}",
"// Push the template, execute it, then pop it from the stack.",
"// Template loops will be caught by the call depth check when pushing",
"// the template.",
"context",
".",
"pushTemplate",
"(",
"template",
",",
"getSourceRange",
"(",
")",
",",
"Level",
".",
"INFO",
",",
"includedType",
".",
"toString",
"(",
")",
")",
";",
"template",
".",
"execute",
"(",
"context",
",",
"runStatic",
")",
";",
"context",
".",
"popTemplate",
"(",
"Level",
".",
"INFO",
",",
"includedType",
".",
"toString",
"(",
")",
")",
";",
"}"
] | This is a utility method which performs an include from a fixed template
name. The validity of the name should be checked by the subclass; this
avoids unnecessary regular expression matching.
@param context
evaluation context to use
@param name
fixed template name
@throws EvaluationException | [
"This",
"is",
"a",
"utility",
"method",
"which",
"performs",
"an",
"include",
"from",
"a",
"fixed",
"template",
"name",
".",
"The",
"validity",
"of",
"the",
"name",
"should",
"be",
"checked",
"by",
"the",
"subclass",
";",
"this",
"avoids",
"unnecessary",
"regular",
"expression",
"matching",
"."
] | train | https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/statement/IncludeStatement.java#L122-L165 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java | SqlBuilderHelper.generateLogForSQL | static void generateLogForSQL(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
"""
<p>
Generate log for where conditions.
</p>
<h2>pre conditions</h2>
<p>
required variable are:
</p>
<ul>
<li>_sqlBuilder</li>
<li>_projectionBuffer</li> *
</ul>
<h2>post conditions</h2>
<p>
created variables are:</li>
<ul>
<li>_sql</li>
</ul>
@param method
the method
@param methodBuilder
the method builder
"""
// manage log
if (method.getParent().getParent().generateLog) {
methodBuilder.addCode("\n// manage log\n");
methodBuilder.addStatement("$T.info(_sql)", Logger.class);
}
} | java | static void generateLogForSQL(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
// manage log
if (method.getParent().getParent().generateLog) {
methodBuilder.addCode("\n// manage log\n");
methodBuilder.addStatement("$T.info(_sql)", Logger.class);
}
} | [
"static",
"void",
"generateLogForSQL",
"(",
"SQLiteModelMethod",
"method",
",",
"MethodSpec",
".",
"Builder",
"methodBuilder",
")",
"{",
"// manage log",
"if",
"(",
"method",
".",
"getParent",
"(",
")",
".",
"getParent",
"(",
")",
".",
"generateLog",
")",
"{",
"methodBuilder",
".",
"addCode",
"(",
"\"\\n// manage log\\n\"",
")",
";",
"methodBuilder",
".",
"addStatement",
"(",
"\"$T.info(_sql)\"",
",",
"Logger",
".",
"class",
")",
";",
"}",
"}"
] | <p>
Generate log for where conditions.
</p>
<h2>pre conditions</h2>
<p>
required variable are:
</p>
<ul>
<li>_sqlBuilder</li>
<li>_projectionBuffer</li> *
</ul>
<h2>post conditions</h2>
<p>
created variables are:</li>
<ul>
<li>_sql</li>
</ul>
@param method
the method
@param methodBuilder
the method builder | [
"<p",
">",
"Generate",
"log",
"for",
"where",
"conditions",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/SqlBuilderHelper.java#L313-L319 |
vdurmont/semver4j | src/main/java/com/vdurmont/semver4j/Requirement.java | Requirement.addParentheses | private static List<Token> addParentheses(List<Token> tokens) {
"""
Return parenthesized expression, giving lowest priority to OR operator
@param tokens the tokens contained in the requirement string
@return the tokens with parenthesis
"""
List<Token> result = new ArrayList<Token>();
result.add(new Token(TokenType.OPENING, "("));
for (Token token : tokens) {
if (token.type == TokenType.OR) {
result.add(new Token(TokenType.CLOSING, ")"));
result.add(token);
result.add(new Token(TokenType.OPENING, "("));
} else {
result.add(token);
}
}
result.add(new Token(TokenType.CLOSING, ")"));
return result;
} | java | private static List<Token> addParentheses(List<Token> tokens) {
List<Token> result = new ArrayList<Token>();
result.add(new Token(TokenType.OPENING, "("));
for (Token token : tokens) {
if (token.type == TokenType.OR) {
result.add(new Token(TokenType.CLOSING, ")"));
result.add(token);
result.add(new Token(TokenType.OPENING, "("));
} else {
result.add(token);
}
}
result.add(new Token(TokenType.CLOSING, ")"));
return result;
} | [
"private",
"static",
"List",
"<",
"Token",
">",
"addParentheses",
"(",
"List",
"<",
"Token",
">",
"tokens",
")",
"{",
"List",
"<",
"Token",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"Token",
">",
"(",
")",
";",
"result",
".",
"add",
"(",
"new",
"Token",
"(",
"TokenType",
".",
"OPENING",
",",
"\"(\"",
")",
")",
";",
"for",
"(",
"Token",
"token",
":",
"tokens",
")",
"{",
"if",
"(",
"token",
".",
"type",
"==",
"TokenType",
".",
"OR",
")",
"{",
"result",
".",
"add",
"(",
"new",
"Token",
"(",
"TokenType",
".",
"CLOSING",
",",
"\")\"",
")",
")",
";",
"result",
".",
"add",
"(",
"token",
")",
";",
"result",
".",
"add",
"(",
"new",
"Token",
"(",
"TokenType",
".",
"OPENING",
",",
"\"(\"",
")",
")",
";",
"}",
"else",
"{",
"result",
".",
"add",
"(",
"token",
")",
";",
"}",
"}",
"result",
".",
"add",
"(",
"new",
"Token",
"(",
"TokenType",
".",
"CLOSING",
",",
"\")\"",
")",
")",
";",
"return",
"result",
";",
"}"
] | Return parenthesized expression, giving lowest priority to OR operator
@param tokens the tokens contained in the requirement string
@return the tokens with parenthesis | [
"Return",
"parenthesized",
"expression",
"giving",
"lowest",
"priority",
"to",
"OR",
"operator"
] | train | https://github.com/vdurmont/semver4j/blob/3f0266e4985ac29e9da482e04001ed15fad6c3e2/src/main/java/com/vdurmont/semver4j/Requirement.java#L194-L208 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java | CalibratedCurves.getCloneShifted | public CalibratedCurves getCloneShifted(Map<String,Double> shifts) throws SolverException, CloneNotSupportedException {
"""
Returns the set curves calibrated to "shifted" market data, that is,
the market date of <code>this</code> object, modified by the shifts
provided to this methods.
@param shifts A map of shifts associating each symbol with a shifts. If symbols are not part of this map, they remain unshifted.
@return A new set of calibrated curves, calibrated to shifted market data.
@throws SolverException The likely cause of this exception is a failure of the solver used in the calibration.
@throws CloneNotSupportedException The likely cause of this exception is the inability to clone or modify a curve.
"""
// Clone calibration specs, shifting the desired symbol
List<CalibrationSpec> calibrationSpecsShifted = new ArrayList<>();
for(CalibrationSpec calibrationSpec : calibrationSpecs) {
if(shifts.containsKey(calibrationSpec)) {
calibrationSpecsShifted.add(calibrationSpec.getCloneShifted(shifts.get(calibrationSpec)));
}
else {
calibrationSpecsShifted.add(calibrationSpec);
}
}
return new CalibratedCurves(calibrationSpecsShifted, model, evaluationTime, calibrationAccuracy);
} | java | public CalibratedCurves getCloneShifted(Map<String,Double> shifts) throws SolverException, CloneNotSupportedException {
// Clone calibration specs, shifting the desired symbol
List<CalibrationSpec> calibrationSpecsShifted = new ArrayList<>();
for(CalibrationSpec calibrationSpec : calibrationSpecs) {
if(shifts.containsKey(calibrationSpec)) {
calibrationSpecsShifted.add(calibrationSpec.getCloneShifted(shifts.get(calibrationSpec)));
}
else {
calibrationSpecsShifted.add(calibrationSpec);
}
}
return new CalibratedCurves(calibrationSpecsShifted, model, evaluationTime, calibrationAccuracy);
} | [
"public",
"CalibratedCurves",
"getCloneShifted",
"(",
"Map",
"<",
"String",
",",
"Double",
">",
"shifts",
")",
"throws",
"SolverException",
",",
"CloneNotSupportedException",
"{",
"// Clone calibration specs, shifting the desired symbol",
"List",
"<",
"CalibrationSpec",
">",
"calibrationSpecsShifted",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"CalibrationSpec",
"calibrationSpec",
":",
"calibrationSpecs",
")",
"{",
"if",
"(",
"shifts",
".",
"containsKey",
"(",
"calibrationSpec",
")",
")",
"{",
"calibrationSpecsShifted",
".",
"add",
"(",
"calibrationSpec",
".",
"getCloneShifted",
"(",
"shifts",
".",
"get",
"(",
"calibrationSpec",
")",
")",
")",
";",
"}",
"else",
"{",
"calibrationSpecsShifted",
".",
"add",
"(",
"calibrationSpec",
")",
";",
"}",
"}",
"return",
"new",
"CalibratedCurves",
"(",
"calibrationSpecsShifted",
",",
"model",
",",
"evaluationTime",
",",
"calibrationAccuracy",
")",
";",
"}"
] | Returns the set curves calibrated to "shifted" market data, that is,
the market date of <code>this</code> object, modified by the shifts
provided to this methods.
@param shifts A map of shifts associating each symbol with a shifts. If symbols are not part of this map, they remain unshifted.
@return A new set of calibrated curves, calibrated to shifted market data.
@throws SolverException The likely cause of this exception is a failure of the solver used in the calibration.
@throws CloneNotSupportedException The likely cause of this exception is the inability to clone or modify a curve. | [
"Returns",
"the",
"set",
"curves",
"calibrated",
"to",
"shifted",
"market",
"data",
"that",
"is",
"the",
"market",
"date",
"of",
"<code",
">",
"this<",
"/",
"code",
">",
"object",
"modified",
"by",
"the",
"shifts",
"provided",
"to",
"this",
"methods",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/calibration/CalibratedCurves.java#L593-L606 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java | ExtensionHttpSessions.getHttpSessionsSite | public HttpSessionsSite getHttpSessionsSite(String site, boolean createIfNeeded) {
"""
Gets the http sessions for a particular site. The behaviour when a {@link HttpSessionsSite}
does not exist is defined by the {@code createIfNeeded} parameter.
@param site the site. This parameter has to be formed as defined in the
{@link ExtensionHttpSessions} class documentation. However, if the protocol is
missing, a default protocol of 80 is used.
@param createIfNeeded whether a new {@link HttpSessionsSite} object is created if one does
not exist
@return the http sessions site container, or null one does not exist and createIfNeeded is
false
"""
// Add a default port
if (!site.contains(":")) {
site = site + (":80");
}
synchronized (sessionLock) {
if (sessions == null) {
if (!createIfNeeded) {
return null;
}
sessions = new HashMap<>();
}
HttpSessionsSite hss = sessions.get(site);
if (hss == null) {
if (!createIfNeeded)
return null;
hss = new HttpSessionsSite(this, site);
sessions.put(site, hss);
}
return hss;
}
} | java | public HttpSessionsSite getHttpSessionsSite(String site, boolean createIfNeeded) {
// Add a default port
if (!site.contains(":")) {
site = site + (":80");
}
synchronized (sessionLock) {
if (sessions == null) {
if (!createIfNeeded) {
return null;
}
sessions = new HashMap<>();
}
HttpSessionsSite hss = sessions.get(site);
if (hss == null) {
if (!createIfNeeded)
return null;
hss = new HttpSessionsSite(this, site);
sessions.put(site, hss);
}
return hss;
}
} | [
"public",
"HttpSessionsSite",
"getHttpSessionsSite",
"(",
"String",
"site",
",",
"boolean",
"createIfNeeded",
")",
"{",
"// Add a default port",
"if",
"(",
"!",
"site",
".",
"contains",
"(",
"\":\"",
")",
")",
"{",
"site",
"=",
"site",
"+",
"(",
"\":80\"",
")",
";",
"}",
"synchronized",
"(",
"sessionLock",
")",
"{",
"if",
"(",
"sessions",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"createIfNeeded",
")",
"{",
"return",
"null",
";",
"}",
"sessions",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"}",
"HttpSessionsSite",
"hss",
"=",
"sessions",
".",
"get",
"(",
"site",
")",
";",
"if",
"(",
"hss",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"createIfNeeded",
")",
"return",
"null",
";",
"hss",
"=",
"new",
"HttpSessionsSite",
"(",
"this",
",",
"site",
")",
";",
"sessions",
".",
"put",
"(",
"site",
",",
"hss",
")",
";",
"}",
"return",
"hss",
";",
"}",
"}"
] | Gets the http sessions for a particular site. The behaviour when a {@link HttpSessionsSite}
does not exist is defined by the {@code createIfNeeded} parameter.
@param site the site. This parameter has to be formed as defined in the
{@link ExtensionHttpSessions} class documentation. However, if the protocol is
missing, a default protocol of 80 is used.
@param createIfNeeded whether a new {@link HttpSessionsSite} object is created if one does
not exist
@return the http sessions site container, or null one does not exist and createIfNeeded is
false | [
"Gets",
"the",
"http",
"sessions",
"for",
"a",
"particular",
"site",
".",
"The",
"behaviour",
"when",
"a",
"{",
"@link",
"HttpSessionsSite",
"}",
"does",
"not",
"exist",
"is",
"defined",
"by",
"the",
"{",
"@code",
"createIfNeeded",
"}",
"parameter",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java#L499-L520 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ProcedureExtensions.java | ProcedureExtensions.curry | @Pure
public static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,
final P1 argument) {
"""
Curries a procedure that takes five arguments.
@param procedure
the original procedure. May not be <code>null</code>.
@param argument
the fixed first argument of {@code procedure}.
@return a procedure that takes four arguments. Never <code>null</code>.
"""
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure4<P2, P3, P4, P5>() {
@Override
public void apply(P2 p2, P3 p3, P4 p4, P5 p5) {
procedure.apply(argument, p2, p3, p4, p5);
}
};
} | java | @Pure
public static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,
final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure4<P2, P3, P4, P5>() {
@Override
public void apply(P2 p2, P3 p3, P4 p4, P5 p5) {
procedure.apply(argument, p2, p3, p4, p5);
}
};
} | [
"@",
"Pure",
"public",
"static",
"<",
"P1",
",",
"P2",
",",
"P3",
",",
"P4",
",",
"P5",
">",
"Procedure4",
"<",
"P2",
",",
"P3",
",",
"P4",
",",
"P5",
">",
"curry",
"(",
"final",
"Procedure5",
"<",
"?",
"super",
"P1",
",",
"?",
"super",
"P2",
",",
"?",
"super",
"P3",
",",
"?",
"super",
"P4",
",",
"?",
"super",
"P5",
">",
"procedure",
",",
"final",
"P1",
"argument",
")",
"{",
"if",
"(",
"procedure",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"procedure\"",
")",
";",
"return",
"new",
"Procedure4",
"<",
"P2",
",",
"P3",
",",
"P4",
",",
"P5",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"apply",
"(",
"P2",
"p2",
",",
"P3",
"p3",
",",
"P4",
"p4",
",",
"P5",
"p5",
")",
"{",
"procedure",
".",
"apply",
"(",
"argument",
",",
"p2",
",",
"p3",
",",
"p4",
",",
"p5",
")",
";",
"}",
"}",
";",
"}"
] | Curries a procedure that takes five arguments.
@param procedure
the original procedure. May not be <code>null</code>.
@param argument
the fixed first argument of {@code procedure}.
@return a procedure that takes four arguments. Never <code>null</code>. | [
"Curries",
"a",
"procedure",
"that",
"takes",
"five",
"arguments",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/ProcedureExtensions.java#L122-L133 |
bushidowallet/bushido-java-service | bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PublicKeyRing.java | PublicKeyRing.addPublicKey | public void addPublicKey(PublicKey key, NetworkParameters network) {
"""
Add a public key to the key ring.
@param key public key
@param network Bitcoin network to talk to
"""
Address address = Address.fromStandardPublicKey(key, network);
_addresses.add(address);
_addressSet.add(address);
_publicKeys.put(address, key);
} | java | public void addPublicKey(PublicKey key, NetworkParameters network) {
Address address = Address.fromStandardPublicKey(key, network);
_addresses.add(address);
_addressSet.add(address);
_publicKeys.put(address, key);
} | [
"public",
"void",
"addPublicKey",
"(",
"PublicKey",
"key",
",",
"NetworkParameters",
"network",
")",
"{",
"Address",
"address",
"=",
"Address",
".",
"fromStandardPublicKey",
"(",
"key",
",",
"network",
")",
";",
"_addresses",
".",
"add",
"(",
"address",
")",
";",
"_addressSet",
".",
"add",
"(",
"address",
")",
";",
"_publicKeys",
".",
"put",
"(",
"address",
",",
"key",
")",
";",
"}"
] | Add a public key to the key ring.
@param key public key
@param network Bitcoin network to talk to | [
"Add",
"a",
"public",
"key",
"to",
"the",
"key",
"ring",
"."
] | train | https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PublicKeyRing.java#L25-L30 |
sniggle/simple-pgp | simple-pgp-api/src/main/java/me/sniggle/pgp/crypt/internal/BaseKeyPairGenerator.java | BaseKeyPairGenerator.generateKeyPair | public boolean generateKeyPair(String userId, String password, OutputStream publicKey, OutputStream secrectKey) {
"""
@see KeyPairGenerator#generateKeyPair(String, String, OutputStream, OutputStream)
@param userId
the user id for the PGP key pair
@param password
the password used to secure the secret (private) key
@param publicKey
the target stream for the public key
@param secrectKey
the target stream for the secret (private) key
@return
"""
LOGGER.trace("generateKeyPair(String, String, OutputStream, OutputStream)");
LOGGER.trace("User ID: {}, Password: ********, Public Key: {}, Secret Key: {}", userId, publicKey == null ? "not set" : "set", secrectKey == null ? "not set" : "set");
return generateKeyPair(userId, password, DEFAULT_KEY_SIZE, publicKey, secrectKey);
} | java | public boolean generateKeyPair(String userId, String password, OutputStream publicKey, OutputStream secrectKey) {
LOGGER.trace("generateKeyPair(String, String, OutputStream, OutputStream)");
LOGGER.trace("User ID: {}, Password: ********, Public Key: {}, Secret Key: {}", userId, publicKey == null ? "not set" : "set", secrectKey == null ? "not set" : "set");
return generateKeyPair(userId, password, DEFAULT_KEY_SIZE, publicKey, secrectKey);
} | [
"public",
"boolean",
"generateKeyPair",
"(",
"String",
"userId",
",",
"String",
"password",
",",
"OutputStream",
"publicKey",
",",
"OutputStream",
"secrectKey",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"generateKeyPair(String, String, OutputStream, OutputStream)\"",
")",
";",
"LOGGER",
".",
"trace",
"(",
"\"User ID: {}, Password: ********, Public Key: {}, Secret Key: {}\"",
",",
"userId",
",",
"publicKey",
"==",
"null",
"?",
"\"not set\"",
":",
"\"set\"",
",",
"secrectKey",
"==",
"null",
"?",
"\"not set\"",
":",
"\"set\"",
")",
";",
"return",
"generateKeyPair",
"(",
"userId",
",",
"password",
",",
"DEFAULT_KEY_SIZE",
",",
"publicKey",
",",
"secrectKey",
")",
";",
"}"
] | @see KeyPairGenerator#generateKeyPair(String, String, OutputStream, OutputStream)
@param userId
the user id for the PGP key pair
@param password
the password used to secure the secret (private) key
@param publicKey
the target stream for the public key
@param secrectKey
the target stream for the secret (private) key
@return | [
"@see",
"KeyPairGenerator#generateKeyPair",
"(",
"String",
"String",
"OutputStream",
"OutputStream",
")"
] | train | https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-api/src/main/java/me/sniggle/pgp/crypt/internal/BaseKeyPairGenerator.java#L120-L124 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/NetworkConfig.java | NetworkConfig.createAllOrderers | private void createAllOrderers() throws NetworkConfigurationException {
"""
Creates Node instances representing all the orderers defined in the config file
"""
// Sanity check
if (orderers != null) {
throw new NetworkConfigurationException("INTERNAL ERROR: orderers has already been initialized!");
}
orderers = new HashMap<>();
// orderers is a JSON object containing a nested object for each orderers
JsonObject jsonOrderers = getJsonObject(jsonConfig, "orderers");
if (jsonOrderers != null) {
for (Entry<String, JsonValue> entry : jsonOrderers.entrySet()) {
String ordererName = entry.getKey();
JsonObject jsonOrderer = getJsonValueAsObject(entry.getValue());
if (jsonOrderer == null) {
throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
}
Node orderer = createNode(ordererName, jsonOrderer, "url");
if (orderer == null) {
throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
}
orderers.put(ordererName, orderer);
}
}
} | java | private void createAllOrderers() throws NetworkConfigurationException {
// Sanity check
if (orderers != null) {
throw new NetworkConfigurationException("INTERNAL ERROR: orderers has already been initialized!");
}
orderers = new HashMap<>();
// orderers is a JSON object containing a nested object for each orderers
JsonObject jsonOrderers = getJsonObject(jsonConfig, "orderers");
if (jsonOrderers != null) {
for (Entry<String, JsonValue> entry : jsonOrderers.entrySet()) {
String ordererName = entry.getKey();
JsonObject jsonOrderer = getJsonValueAsObject(entry.getValue());
if (jsonOrderer == null) {
throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
}
Node orderer = createNode(ordererName, jsonOrderer, "url");
if (orderer == null) {
throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
}
orderers.put(ordererName, orderer);
}
}
} | [
"private",
"void",
"createAllOrderers",
"(",
")",
"throws",
"NetworkConfigurationException",
"{",
"// Sanity check",
"if",
"(",
"orderers",
"!=",
"null",
")",
"{",
"throw",
"new",
"NetworkConfigurationException",
"(",
"\"INTERNAL ERROR: orderers has already been initialized!\"",
")",
";",
"}",
"orderers",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"// orderers is a JSON object containing a nested object for each orderers",
"JsonObject",
"jsonOrderers",
"=",
"getJsonObject",
"(",
"jsonConfig",
",",
"\"orderers\"",
")",
";",
"if",
"(",
"jsonOrderers",
"!=",
"null",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"JsonValue",
">",
"entry",
":",
"jsonOrderers",
".",
"entrySet",
"(",
")",
")",
"{",
"String",
"ordererName",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"JsonObject",
"jsonOrderer",
"=",
"getJsonValueAsObject",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"jsonOrderer",
"==",
"null",
")",
"{",
"throw",
"new",
"NetworkConfigurationException",
"(",
"format",
"(",
"\"Error loading config. Invalid orderer entry: %s\"",
",",
"ordererName",
")",
")",
";",
"}",
"Node",
"orderer",
"=",
"createNode",
"(",
"ordererName",
",",
"jsonOrderer",
",",
"\"url\"",
")",
";",
"if",
"(",
"orderer",
"==",
"null",
")",
"{",
"throw",
"new",
"NetworkConfigurationException",
"(",
"format",
"(",
"\"Error loading config. Invalid orderer entry: %s\"",
",",
"ordererName",
")",
")",
";",
"}",
"orderers",
".",
"put",
"(",
"ordererName",
",",
"orderer",
")",
";",
"}",
"}",
"}"
] | Creates Node instances representing all the orderers defined in the config file | [
"Creates",
"Node",
"instances",
"representing",
"all",
"the",
"orderers",
"defined",
"in",
"the",
"config",
"file"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/NetworkConfig.java#L501-L531 |
GoSimpleLLC/nbvcxz | src/main/java/me/gosimple/nbvcxz/Nbvcxz.java | Nbvcxz.getBestCombination | private List<Match> getBestCombination(final Configuration configuration, final String password) {
"""
Returns the best combination of matches based on multiple methods. We run the password through the
{@code findGoodEnoughCombination} method test to see if is considered "random". If it isn't, we
run it through the {@code findBestCombination} method, which is much more expensive for large
passwords.
@param configuration the configuration
@param password the password
@return the best list of matches, sorted by start index.
"""
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i));
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches);
Collections.sort(matches, comparator);
return matches;
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches);
}
catch (TimeoutException e)
{
return good_enough_matches;
}
} | java | private List<Match> getBestCombination(final Configuration configuration, final String password)
{
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i));
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches);
Collections.sort(matches, comparator);
return matches;
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches);
}
catch (TimeoutException e)
{
return good_enough_matches;
}
} | [
"private",
"List",
"<",
"Match",
">",
"getBestCombination",
"(",
"final",
"Configuration",
"configuration",
",",
"final",
"String",
"password",
")",
"{",
"this",
".",
"best_matches",
".",
"clear",
"(",
")",
";",
"this",
".",
"best_matches_length",
"=",
"0",
";",
"final",
"List",
"<",
"Match",
">",
"all_matches",
"=",
"getAllMatches",
"(",
"configuration",
",",
"password",
")",
";",
"final",
"Map",
"<",
"Integer",
",",
"Match",
">",
"brute_force_matches",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"password",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"brute_force_matches",
".",
"put",
"(",
"i",
",",
"createBruteForceMatch",
"(",
"password",
",",
"configuration",
",",
"i",
")",
")",
";",
"}",
"final",
"List",
"<",
"Match",
">",
"good_enough_matches",
"=",
"findGoodEnoughCombination",
"(",
"password",
",",
"all_matches",
",",
"brute_force_matches",
")",
";",
"if",
"(",
"all_matches",
"==",
"null",
"||",
"all_matches",
".",
"size",
"(",
")",
"==",
"0",
"||",
"isRandom",
"(",
"password",
",",
"good_enough_matches",
")",
")",
"{",
"List",
"<",
"Match",
">",
"matches",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"backfillBruteForce",
"(",
"password",
",",
"brute_force_matches",
",",
"matches",
")",
";",
"Collections",
".",
"sort",
"(",
"matches",
",",
"comparator",
")",
";",
"return",
"matches",
";",
"}",
"Collections",
".",
"sort",
"(",
"all_matches",
",",
"comparator",
")",
";",
"try",
"{",
"return",
"findBestCombination",
"(",
"password",
",",
"all_matches",
",",
"brute_force_matches",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"return",
"good_enough_matches",
";",
"}",
"}"
] | Returns the best combination of matches based on multiple methods. We run the password through the
{@code findGoodEnoughCombination} method test to see if is considered "random". If it isn't, we
run it through the {@code findBestCombination} method, which is much more expensive for large
passwords.
@param configuration the configuration
@param password the password
@return the best list of matches, sorted by start index. | [
"Returns",
"the",
"best",
"combination",
"of",
"matches",
"based",
"on",
"multiple",
"methods",
".",
"We",
"run",
"the",
"password",
"through",
"the",
"{",
"@code",
"findGoodEnoughCombination",
"}",
"method",
"test",
"to",
"see",
"if",
"is",
"considered",
"random",
".",
"If",
"it",
"isn",
"t",
"we",
"run",
"it",
"through",
"the",
"{",
"@code",
"findBestCombination",
"}",
"method",
"which",
"is",
"much",
"more",
"expensive",
"for",
"large",
"passwords",
"."
] | train | https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/Nbvcxz.java#L262-L292 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.getAt | @SuppressWarnings("unchecked")
public static List<Long> getAt(long[] array, ObjectRange range) {
"""
Support the subscript operator with an ObjectRange for a long array
@param array a long array
@param range an ObjectRange indicating the indices for the items to retrieve
@return list of the retrieved longs
@since 1.0
"""
return primitiveArrayGet(array, range);
} | java | @SuppressWarnings("unchecked")
public static List<Long> getAt(long[] array, ObjectRange range) {
return primitiveArrayGet(array, range);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"List",
"<",
"Long",
">",
"getAt",
"(",
"long",
"[",
"]",
"array",
",",
"ObjectRange",
"range",
")",
"{",
"return",
"primitiveArrayGet",
"(",
"array",
",",
"range",
")",
";",
"}"
] | Support the subscript operator with an ObjectRange for a long array
@param array a long array
@param range an ObjectRange indicating the indices for the items to retrieve
@return list of the retrieved longs
@since 1.0 | [
"Support",
"the",
"subscript",
"operator",
"with",
"an",
"ObjectRange",
"for",
"a",
"long",
"array"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13886-L13889 |
google/closure-templates | java/src/com/google/template/soy/data/SanitizedContents.java | SanitizedContents.constantJs | public static SanitizedContent constantJs(@CompileTimeConstant final String constant) {
"""
Wraps an assumed-safe JS constant.
<p>This only accepts compile-time constants, based on the assumption that scripts that are
controlled by the application (and not user input) are considered safe.
"""
return fromConstant(constant, ContentKind.JS, Dir.LTR);
} | java | public static SanitizedContent constantJs(@CompileTimeConstant final String constant) {
return fromConstant(constant, ContentKind.JS, Dir.LTR);
} | [
"public",
"static",
"SanitizedContent",
"constantJs",
"(",
"@",
"CompileTimeConstant",
"final",
"String",
"constant",
")",
"{",
"return",
"fromConstant",
"(",
"constant",
",",
"ContentKind",
".",
"JS",
",",
"Dir",
".",
"LTR",
")",
";",
"}"
] | Wraps an assumed-safe JS constant.
<p>This only accepts compile-time constants, based on the assumption that scripts that are
controlled by the application (and not user input) are considered safe. | [
"Wraps",
"an",
"assumed",
"-",
"safe",
"JS",
"constant",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SanitizedContents.java#L228-L230 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java | SVGPath.relativeEllipticalArc | public SVGPath relativeEllipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) {
"""
Elliptical arc curve to the given relative coordinates.
@param rxy radius
@param ar x-axis-rotation
@param la large arc flag, if angle >= 180 deg
@param sp sweep flag, if arc will be drawn in positive-angle direction
@param xy new coordinates
"""
return append(PATH_ARC_RELATIVE).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
} | java | public SVGPath relativeEllipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC_RELATIVE).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
} | [
"public",
"SVGPath",
"relativeEllipticalArc",
"(",
"double",
"[",
"]",
"rxy",
",",
"double",
"ar",
",",
"double",
"la",
",",
"double",
"sp",
",",
"double",
"[",
"]",
"xy",
")",
"{",
"return",
"append",
"(",
"PATH_ARC_RELATIVE",
")",
".",
"append",
"(",
"rxy",
"[",
"0",
"]",
")",
".",
"append",
"(",
"rxy",
"[",
"1",
"]",
")",
".",
"append",
"(",
"ar",
")",
".",
"append",
"(",
"la",
")",
".",
"append",
"(",
"sp",
")",
".",
"append",
"(",
"xy",
"[",
"0",
"]",
")",
".",
"append",
"(",
"xy",
"[",
"1",
"]",
")",
";",
"}"
] | Elliptical arc curve to the given relative coordinates.
@param rxy radius
@param ar x-axis-rotation
@param la large arc flag, if angle >= 180 deg
@param sp sweep flag, if arc will be drawn in positive-angle direction
@param xy new coordinates | [
"Elliptical",
"arc",
"curve",
"to",
"the",
"given",
"relative",
"coordinates",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L618-L620 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java | AbstractQueryProtocol.readErrorPacket | private SQLException readErrorPacket(Buffer buffer, Results results) {
"""
Read ERR_Packet.
@param buffer current buffer
@param results result object
@return SQLException if sub-result connection fail
@see <a href="https://mariadb.com/kb/en/mariadb/err_packet/">ERR_Packet</a>
"""
removeHasMoreResults();
this.hasWarnings = false;
buffer.skipByte();
final int errorNumber = buffer.readShort();
String message;
String sqlState;
if (buffer.readByte() == '#') {
sqlState = new String(buffer.readRawBytes(5));
message = buffer.readStringNullEnd(StandardCharsets.UTF_8);
} else {
// Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections')
buffer.position -= 1;
message = new String(buffer.buf, buffer.position, buffer.limit - buffer.position,
StandardCharsets.UTF_8);
sqlState = "HY000";
}
results.addStatsError(false);
//force current status to in transaction to ensure rollback/commit, since command may have issue a transaction
serverStatus |= ServerStatus.IN_TRANSACTION;
removeActiveStreamingResult();
return new SQLException(message, sqlState, errorNumber);
} | java | private SQLException readErrorPacket(Buffer buffer, Results results) {
removeHasMoreResults();
this.hasWarnings = false;
buffer.skipByte();
final int errorNumber = buffer.readShort();
String message;
String sqlState;
if (buffer.readByte() == '#') {
sqlState = new String(buffer.readRawBytes(5));
message = buffer.readStringNullEnd(StandardCharsets.UTF_8);
} else {
// Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections')
buffer.position -= 1;
message = new String(buffer.buf, buffer.position, buffer.limit - buffer.position,
StandardCharsets.UTF_8);
sqlState = "HY000";
}
results.addStatsError(false);
//force current status to in transaction to ensure rollback/commit, since command may have issue a transaction
serverStatus |= ServerStatus.IN_TRANSACTION;
removeActiveStreamingResult();
return new SQLException(message, sqlState, errorNumber);
} | [
"private",
"SQLException",
"readErrorPacket",
"(",
"Buffer",
"buffer",
",",
"Results",
"results",
")",
"{",
"removeHasMoreResults",
"(",
")",
";",
"this",
".",
"hasWarnings",
"=",
"false",
";",
"buffer",
".",
"skipByte",
"(",
")",
";",
"final",
"int",
"errorNumber",
"=",
"buffer",
".",
"readShort",
"(",
")",
";",
"String",
"message",
";",
"String",
"sqlState",
";",
"if",
"(",
"buffer",
".",
"readByte",
"(",
")",
"==",
"'",
"'",
")",
"{",
"sqlState",
"=",
"new",
"String",
"(",
"buffer",
".",
"readRawBytes",
"(",
"5",
")",
")",
";",
"message",
"=",
"buffer",
".",
"readStringNullEnd",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"}",
"else",
"{",
"// Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections')",
"buffer",
".",
"position",
"-=",
"1",
";",
"message",
"=",
"new",
"String",
"(",
"buffer",
".",
"buf",
",",
"buffer",
".",
"position",
",",
"buffer",
".",
"limit",
"-",
"buffer",
".",
"position",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"sqlState",
"=",
"\"HY000\"",
";",
"}",
"results",
".",
"addStatsError",
"(",
"false",
")",
";",
"//force current status to in transaction to ensure rollback/commit, since command may have issue a transaction",
"serverStatus",
"|=",
"ServerStatus",
".",
"IN_TRANSACTION",
";",
"removeActiveStreamingResult",
"(",
")",
";",
"return",
"new",
"SQLException",
"(",
"message",
",",
"sqlState",
",",
"errorNumber",
")",
";",
"}"
] | Read ERR_Packet.
@param buffer current buffer
@param results result object
@return SQLException if sub-result connection fail
@see <a href="https://mariadb.com/kb/en/mariadb/err_packet/">ERR_Packet</a> | [
"Read",
"ERR_Packet",
"."
] | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1571-L1595 |
PistoiaHELM/HELM2NotationToolkit | src/main/java/org/helm/notation2/tools/ChangeObjects.java | ChangeObjects.generateGroupElement | private static String generateGroupElement(String id, List<Double> list) {
"""
method to generate the MonomerNotationGroupElement in String format
@param id
@param list
@return MonomerNotationGroupElement in String format
"""
StringBuilder sb = new StringBuilder();
if (list.size() == 1) {
if (list.get(0) == -1.0) {
sb.append(id + ":");
sb.append("?" + "-");
} else if (list.get(0) == 1.0) {
sb.append(id + ":");
} else {
sb.append(id + ":" + list.get(0) + "-");
}
} else {
sb.append(id + ":");
for (Double item : list) {
sb.append(item + "-");
}
}
sb.setLength(sb.length() - 1);
return sb.toString();
} | java | private static String generateGroupElement(String id, List<Double> list) {
StringBuilder sb = new StringBuilder();
if (list.size() == 1) {
if (list.get(0) == -1.0) {
sb.append(id + ":");
sb.append("?" + "-");
} else if (list.get(0) == 1.0) {
sb.append(id + ":");
} else {
sb.append(id + ":" + list.get(0) + "-");
}
} else {
sb.append(id + ":");
for (Double item : list) {
sb.append(item + "-");
}
}
sb.setLength(sb.length() - 1);
return sb.toString();
} | [
"private",
"static",
"String",
"generateGroupElement",
"(",
"String",
"id",
",",
"List",
"<",
"Double",
">",
"list",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"list",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"if",
"(",
"list",
".",
"get",
"(",
"0",
")",
"==",
"-",
"1.0",
")",
"{",
"sb",
".",
"append",
"(",
"id",
"+",
"\":\"",
")",
";",
"sb",
".",
"append",
"(",
"\"?\"",
"+",
"\"-\"",
")",
";",
"}",
"else",
"if",
"(",
"list",
".",
"get",
"(",
"0",
")",
"==",
"1.0",
")",
"{",
"sb",
".",
"append",
"(",
"id",
"+",
"\":\"",
")",
";",
"}",
"else",
"{",
"sb",
".",
"append",
"(",
"id",
"+",
"\":\"",
"+",
"list",
".",
"get",
"(",
"0",
")",
"+",
"\"-\"",
")",
";",
"}",
"}",
"else",
"{",
"sb",
".",
"append",
"(",
"id",
"+",
"\":\"",
")",
";",
"for",
"(",
"Double",
"item",
":",
"list",
")",
"{",
"sb",
".",
"append",
"(",
"item",
"+",
"\"-\"",
")",
";",
"}",
"}",
"sb",
".",
"setLength",
"(",
"sb",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | method to generate the MonomerNotationGroupElement in String format
@param id
@param list
@return MonomerNotationGroupElement in String format | [
"method",
"to",
"generate",
"the",
"MonomerNotationGroupElement",
"in",
"String",
"format"
] | train | https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/ChangeObjects.java#L777-L798 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/util/Scheduler.java | Scheduler.durationMS | public static long durationMS(LocalDateTime start,LocalDateTime end) {
"""
The time between two dates
@param start the begin time
@param end the finish time
@return duration in milliseconds
"""
if(start == null || end == null)
{
return 0;
}
return Duration.between(start, end).toMillis();
} | java | public static long durationMS(LocalDateTime start,LocalDateTime end)
{
if(start == null || end == null)
{
return 0;
}
return Duration.between(start, end).toMillis();
} | [
"public",
"static",
"long",
"durationMS",
"(",
"LocalDateTime",
"start",
",",
"LocalDateTime",
"end",
")",
"{",
"if",
"(",
"start",
"==",
"null",
"||",
"end",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"return",
"Duration",
".",
"between",
"(",
"start",
",",
"end",
")",
".",
"toMillis",
"(",
")",
";",
"}"
] | The time between two dates
@param start the begin time
@param end the finish time
@return duration in milliseconds | [
"The",
"time",
"between",
"two",
"dates"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Scheduler.java#L85-L93 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java | DateUtil.ceiling | public static DateTime ceiling(Date date, DateField dateField) {
"""
修改日期为某个时间字段结束时间
@param date {@link Date}
@param dateField 时间字段
@return {@link DateTime}
@since 4.5.7
"""
return new DateTime(ceiling(calendar(date), dateField));
} | java | public static DateTime ceiling(Date date, DateField dateField) {
return new DateTime(ceiling(calendar(date), dateField));
} | [
"public",
"static",
"DateTime",
"ceiling",
"(",
"Date",
"date",
",",
"DateField",
"dateField",
")",
"{",
"return",
"new",
"DateTime",
"(",
"ceiling",
"(",
"calendar",
"(",
"date",
")",
",",
"dateField",
")",
")",
";",
"}"
] | 修改日期为某个时间字段结束时间
@param date {@link Date}
@param dateField 时间字段
@return {@link DateTime}
@since 4.5.7 | [
"修改日期为某个时间字段结束时间"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L803-L805 |
ontop/ontop | engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/rewriting/impl/TreeWitnessRewriter.java | TreeWitnessRewriter.getHeadAtom | private Function getHeadAtom(String base, String suffix, List<Term> arguments) {
"""
/*
returns an atom with given arguments and the predicate name formed by the given URI basis and string fragment
"""
Predicate predicate = datalogFactory.getSubqueryPredicate(base + suffix, arguments.size());
return termFactory.getFunction(predicate, arguments);
} | java | private Function getHeadAtom(String base, String suffix, List<Term> arguments) {
Predicate predicate = datalogFactory.getSubqueryPredicate(base + suffix, arguments.size());
return termFactory.getFunction(predicate, arguments);
} | [
"private",
"Function",
"getHeadAtom",
"(",
"String",
"base",
",",
"String",
"suffix",
",",
"List",
"<",
"Term",
">",
"arguments",
")",
"{",
"Predicate",
"predicate",
"=",
"datalogFactory",
".",
"getSubqueryPredicate",
"(",
"base",
"+",
"suffix",
",",
"arguments",
".",
"size",
"(",
")",
")",
";",
"return",
"termFactory",
".",
"getFunction",
"(",
"predicate",
",",
"arguments",
")",
";",
"}"
] | /*
returns an atom with given arguments and the predicate name formed by the given URI basis and string fragment | [
"/",
"*",
"returns",
"an",
"atom",
"with",
"given",
"arguments",
"and",
"the",
"predicate",
"name",
"formed",
"by",
"the",
"given",
"URI",
"basis",
"and",
"string",
"fragment"
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/engine/reformulation/core/src/main/java/it/unibz/inf/ontop/answering/reformulation/rewriting/impl/TreeWitnessRewriter.java#L128-L131 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java | ULocale.getDisplayVariant | public static String getDisplayVariant(String localeID, ULocale displayLocale) {
"""
<strong>[icu]</strong> Returns a locale's variant localized for display in the provided locale.
This is a cover for the ICU4C API.
@param localeID the id of the locale whose variant will be displayed.
@param displayLocale the locale in which to display the name.
@return the localized variant name.
"""
return getDisplayVariantInternal(new ULocale(localeID), displayLocale);
} | java | public static String getDisplayVariant(String localeID, ULocale displayLocale) {
return getDisplayVariantInternal(new ULocale(localeID), displayLocale);
} | [
"public",
"static",
"String",
"getDisplayVariant",
"(",
"String",
"localeID",
",",
"ULocale",
"displayLocale",
")",
"{",
"return",
"getDisplayVariantInternal",
"(",
"new",
"ULocale",
"(",
"localeID",
")",
",",
"displayLocale",
")",
";",
"}"
] | <strong>[icu]</strong> Returns a locale's variant localized for display in the provided locale.
This is a cover for the ICU4C API.
@param localeID the id of the locale whose variant will be displayed.
@param displayLocale the locale in which to display the name.
@return the localized variant name. | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"a",
"locale",
"s",
"variant",
"localized",
"for",
"display",
"in",
"the",
"provided",
"locale",
".",
"This",
"is",
"a",
"cover",
"for",
"the",
"ICU4C",
"API",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/ULocale.java#L1652-L1654 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.replaceEntries | public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) {
"""
Copies an existing ZIP file and replaces the given entries in it.
@param zip
an existing ZIP file (only read).
@param entries
new ZIP entries to be replaced with.
@param destZip
new ZIP file created.
@return <code>true</code> if at least one entry was replaced.
"""
if (log.isDebugEnabled()) {
log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + ".");
}
final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries);
final int entryCount = entryByPath.size();
try {
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip)));
try {
final Set<String> names = new HashSet<String>();
iterate(zip, new ZipEntryCallback() {
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
if (names.add(zipEntry.getName())) {
ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName());
if (entry != null) {
addEntry(entry, out);
}
else {
ZipEntryUtil.copyEntry(zipEntry, in, out);
}
}
else if (log.isDebugEnabled()) {
log.debug("Duplicate entry: {}", zipEntry.getName());
}
}
});
}
finally {
IOUtils.closeQuietly(out);
}
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
return entryByPath.size() < entryCount;
} | java | public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) {
if (log.isDebugEnabled()) {
log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + ".");
}
final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries);
final int entryCount = entryByPath.size();
try {
final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip)));
try {
final Set<String> names = new HashSet<String>();
iterate(zip, new ZipEntryCallback() {
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
if (names.add(zipEntry.getName())) {
ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName());
if (entry != null) {
addEntry(entry, out);
}
else {
ZipEntryUtil.copyEntry(zipEntry, in, out);
}
}
else if (log.isDebugEnabled()) {
log.debug("Duplicate entry: {}", zipEntry.getName());
}
}
});
}
finally {
IOUtils.closeQuietly(out);
}
}
catch (IOException e) {
ZipExceptionUtil.rethrow(e);
}
return entryByPath.size() < entryCount;
} | [
"public",
"static",
"boolean",
"replaceEntries",
"(",
"File",
"zip",
",",
"ZipEntrySource",
"[",
"]",
"entries",
",",
"File",
"destZip",
")",
"{",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Copying '\"",
"+",
"zip",
"+",
"\"' to '\"",
"+",
"destZip",
"+",
"\"' and replacing entries \"",
"+",
"Arrays",
".",
"asList",
"(",
"entries",
")",
"+",
"\".\"",
")",
";",
"}",
"final",
"Map",
"<",
"String",
",",
"ZipEntrySource",
">",
"entryByPath",
"=",
"entriesByPath",
"(",
"entries",
")",
";",
"final",
"int",
"entryCount",
"=",
"entryByPath",
".",
"size",
"(",
")",
";",
"try",
"{",
"final",
"ZipOutputStream",
"out",
"=",
"new",
"ZipOutputStream",
"(",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"destZip",
")",
")",
")",
";",
"try",
"{",
"final",
"Set",
"<",
"String",
">",
"names",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"iterate",
"(",
"zip",
",",
"new",
"ZipEntryCallback",
"(",
")",
"{",
"public",
"void",
"process",
"(",
"InputStream",
"in",
",",
"ZipEntry",
"zipEntry",
")",
"throws",
"IOException",
"{",
"if",
"(",
"names",
".",
"add",
"(",
"zipEntry",
".",
"getName",
"(",
")",
")",
")",
"{",
"ZipEntrySource",
"entry",
"=",
"(",
"ZipEntrySource",
")",
"entryByPath",
".",
"remove",
"(",
"zipEntry",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"entry",
"!=",
"null",
")",
"{",
"addEntry",
"(",
"entry",
",",
"out",
")",
";",
"}",
"else",
"{",
"ZipEntryUtil",
".",
"copyEntry",
"(",
"zipEntry",
",",
"in",
",",
"out",
")",
";",
"}",
"}",
"else",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Duplicate entry: {}\"",
",",
"zipEntry",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"out",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"ZipExceptionUtil",
".",
"rethrow",
"(",
"e",
")",
";",
"}",
"return",
"entryByPath",
".",
"size",
"(",
")",
"<",
"entryCount",
";",
"}"
] | Copies an existing ZIP file and replaces the given entries in it.
@param zip
an existing ZIP file (only read).
@param entries
new ZIP entries to be replaced with.
@param destZip
new ZIP file created.
@return <code>true</code> if at least one entry was replaced. | [
"Copies",
"an",
"existing",
"ZIP",
"file",
"and",
"replaces",
"the",
"given",
"entries",
"in",
"it",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2626-L2662 |
jhg023/SimpleNet | src/main/java/simplenet/packet/Packet.java | Packet.putDouble | public Packet putDouble(double d, ByteOrder order) {
"""
Writes a single {@code double} with the specified {@link ByteOrder} to this {@link Packet}'s payload.
@param d A {@code double}.
@param order The internal byte order of the {@code double}.
@return The {@link Packet} to allow for chained writes.
@see #putLong(long, ByteOrder)
"""
return putLong(Double.doubleToRawLongBits(d), order);
} | java | public Packet putDouble(double d, ByteOrder order) {
return putLong(Double.doubleToRawLongBits(d), order);
} | [
"public",
"Packet",
"putDouble",
"(",
"double",
"d",
",",
"ByteOrder",
"order",
")",
"{",
"return",
"putLong",
"(",
"Double",
".",
"doubleToRawLongBits",
"(",
"d",
")",
",",
"order",
")",
";",
"}"
] | Writes a single {@code double} with the specified {@link ByteOrder} to this {@link Packet}'s payload.
@param d A {@code double}.
@param order The internal byte order of the {@code double}.
@return The {@link Packet} to allow for chained writes.
@see #putLong(long, ByteOrder) | [
"Writes",
"a",
"single",
"{",
"@code",
"double",
"}",
"with",
"the",
"specified",
"{",
"@link",
"ByteOrder",
"}",
"to",
"this",
"{",
"@link",
"Packet",
"}",
"s",
"payload",
"."
] | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/packet/Packet.java#L185-L187 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/LabelsApi.java | LabelsApi.createLabel | public Label createLabel(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException {
"""
Create a label
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param name the name for the label
@param color the color for the label
@param description the description for the label
@param priority the priority for the label
@return the created Label instance
@throws GitLabApiException if any exception occurs
"""
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("color", color, true)
.withParam("description", description)
.withParam("priority", priority);
Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "labels");
return (response.readEntity(Label.class));
} | java | public Label createLabel(Object projectIdOrPath, String name, String color, String description, Integer priority) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("color", color, true)
.withParam("description", description)
.withParam("priority", priority);
Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "labels");
return (response.readEntity(Label.class));
} | [
"public",
"Label",
"createLabel",
"(",
"Object",
"projectIdOrPath",
",",
"String",
"name",
",",
"String",
"color",
",",
"String",
"description",
",",
"Integer",
"priority",
")",
"throws",
"GitLabApiException",
"{",
"GitLabApiForm",
"formData",
"=",
"new",
"GitLabApiForm",
"(",
")",
".",
"withParam",
"(",
"\"name\"",
",",
"name",
",",
"true",
")",
".",
"withParam",
"(",
"\"color\"",
",",
"color",
",",
"true",
")",
".",
"withParam",
"(",
"\"description\"",
",",
"description",
")",
".",
"withParam",
"(",
"\"priority\"",
",",
"priority",
")",
";",
"Response",
"response",
"=",
"post",
"(",
"Response",
".",
"Status",
".",
"CREATED",
",",
"formData",
",",
"\"projects\"",
",",
"getProjectIdOrPath",
"(",
"projectIdOrPath",
")",
",",
"\"labels\"",
")",
";",
"return",
"(",
"response",
".",
"readEntity",
"(",
"Label",
".",
"class",
")",
")",
";",
"}"
] | Create a label
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param name the name for the label
@param color the color for the label
@param description the description for the label
@param priority the priority for the label
@return the created Label instance
@throws GitLabApiException if any exception occurs | [
"Create",
"a",
"label"
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/LabelsApi.java#L119-L128 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getSasDefinitionsAsync | public Observable<Page<SasDefinitionItem>> getSasDefinitionsAsync(final String vaultBaseUrl, final String storageAccountName, final Integer maxresults) {
"""
List storage SAS definitions for the given storage account. This operation requires the storage/listsas permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SasDefinitionItem> object
"""
return getSasDefinitionsWithServiceResponseAsync(vaultBaseUrl, storageAccountName, maxresults)
.map(new Func1<ServiceResponse<Page<SasDefinitionItem>>, Page<SasDefinitionItem>>() {
@Override
public Page<SasDefinitionItem> call(ServiceResponse<Page<SasDefinitionItem>> response) {
return response.body();
}
});
} | java | public Observable<Page<SasDefinitionItem>> getSasDefinitionsAsync(final String vaultBaseUrl, final String storageAccountName, final Integer maxresults) {
return getSasDefinitionsWithServiceResponseAsync(vaultBaseUrl, storageAccountName, maxresults)
.map(new Func1<ServiceResponse<Page<SasDefinitionItem>>, Page<SasDefinitionItem>>() {
@Override
public Page<SasDefinitionItem> call(ServiceResponse<Page<SasDefinitionItem>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"SasDefinitionItem",
">",
">",
"getSasDefinitionsAsync",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"String",
"storageAccountName",
",",
"final",
"Integer",
"maxresults",
")",
"{",
"return",
"getSasDefinitionsWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName",
",",
"maxresults",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"SasDefinitionItem",
">",
">",
",",
"Page",
"<",
"SasDefinitionItem",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Page",
"<",
"SasDefinitionItem",
">",
"call",
"(",
"ServiceResponse",
"<",
"Page",
"<",
"SasDefinitionItem",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | List storage SAS definitions for the given storage account. This operation requires the storage/listsas permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@param maxresults Maximum number of results to return in a page. If not specified the service will return up to 25 results.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<SasDefinitionItem> object | [
"List",
"storage",
"SAS",
"definitions",
"for",
"the",
"given",
"storage",
"account",
".",
"This",
"operation",
"requires",
"the",
"storage",
"/",
"listsas",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L10543-L10551 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/CrashReportingUtil.java | CrashReportingUtil.writeMemoryCrashDump | public static void writeMemoryCrashDump(@NonNull Model net, @NonNull Throwable e) {
"""
Generate and write the crash dump to the crash dump root directory (by default, the working directory).
Naming convention for crash dump files: "dl4j-memory-crash-dump-<timestamp>_<thread-id>.txt"
@param net Net to generate the crash dump for. May not be null
@param e Throwable/exception. Stack trace will be included in the network output
"""
if(!crashDumpsEnabled){
return;
}
long now = System.currentTimeMillis();
long tid = Thread.currentThread().getId(); //Also add thread ID to avoid name clashes (parallel wrapper, etc)
String threadName = Thread.currentThread().getName();
crashDumpRootDirectory.mkdirs();
File f = new File(crashDumpRootDirectory, "dl4j-memory-crash-dump-" + now + "_" + tid + ".txt");
StringBuilder sb = new StringBuilder();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sb.append("Deeplearning4j OOM Exception Encountered for ").append(net.getClass().getSimpleName()).append("\n")
.append(f("Timestamp: ", sdf.format(now)))
.append(f("Thread ID", tid))
.append(f("Thread Name", threadName))
.append("\n\n");
sb.append("Stack Trace:\n")
.append(ExceptionUtils.getStackTrace(e));
try{
sb.append("\n\n");
sb.append(generateMemoryStatus(net, -1, (InputType[])null));
} catch (Throwable t){
sb.append("<Error generating network memory status information section>")
.append(ExceptionUtils.getStackTrace(t));
}
String toWrite = sb.toString();
try{
FileUtils.writeStringToFile(f, toWrite);
} catch (IOException e2){
log.error("Error writing memory crash dump information to disk: {}", f.getAbsolutePath(), e2);
}
log.error(">>> Out of Memory Exception Detected. Memory crash dump written to: {}", f.getAbsolutePath());
log.warn("Memory crash dump reporting can be disabled with CrashUtil.crashDumpsEnabled(false) or using system " +
"property -D" + DL4JSystemProperties.CRASH_DUMP_ENABLED_PROPERTY + "=false");
log.warn("Memory crash dump reporting output location can be set with CrashUtil.crashDumpOutputDirectory(File) or using system " +
"property -D" + DL4JSystemProperties.CRASH_DUMP_OUTPUT_DIRECTORY_PROPERTY + "=<path>");
} | java | public static void writeMemoryCrashDump(@NonNull Model net, @NonNull Throwable e){
if(!crashDumpsEnabled){
return;
}
long now = System.currentTimeMillis();
long tid = Thread.currentThread().getId(); //Also add thread ID to avoid name clashes (parallel wrapper, etc)
String threadName = Thread.currentThread().getName();
crashDumpRootDirectory.mkdirs();
File f = new File(crashDumpRootDirectory, "dl4j-memory-crash-dump-" + now + "_" + tid + ".txt");
StringBuilder sb = new StringBuilder();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sb.append("Deeplearning4j OOM Exception Encountered for ").append(net.getClass().getSimpleName()).append("\n")
.append(f("Timestamp: ", sdf.format(now)))
.append(f("Thread ID", tid))
.append(f("Thread Name", threadName))
.append("\n\n");
sb.append("Stack Trace:\n")
.append(ExceptionUtils.getStackTrace(e));
try{
sb.append("\n\n");
sb.append(generateMemoryStatus(net, -1, (InputType[])null));
} catch (Throwable t){
sb.append("<Error generating network memory status information section>")
.append(ExceptionUtils.getStackTrace(t));
}
String toWrite = sb.toString();
try{
FileUtils.writeStringToFile(f, toWrite);
} catch (IOException e2){
log.error("Error writing memory crash dump information to disk: {}", f.getAbsolutePath(), e2);
}
log.error(">>> Out of Memory Exception Detected. Memory crash dump written to: {}", f.getAbsolutePath());
log.warn("Memory crash dump reporting can be disabled with CrashUtil.crashDumpsEnabled(false) or using system " +
"property -D" + DL4JSystemProperties.CRASH_DUMP_ENABLED_PROPERTY + "=false");
log.warn("Memory crash dump reporting output location can be set with CrashUtil.crashDumpOutputDirectory(File) or using system " +
"property -D" + DL4JSystemProperties.CRASH_DUMP_OUTPUT_DIRECTORY_PROPERTY + "=<path>");
} | [
"public",
"static",
"void",
"writeMemoryCrashDump",
"(",
"@",
"NonNull",
"Model",
"net",
",",
"@",
"NonNull",
"Throwable",
"e",
")",
"{",
"if",
"(",
"!",
"crashDumpsEnabled",
")",
"{",
"return",
";",
"}",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"tid",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getId",
"(",
")",
";",
"//Also add thread ID to avoid name clashes (parallel wrapper, etc)",
"String",
"threadName",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
";",
"crashDumpRootDirectory",
".",
"mkdirs",
"(",
")",
";",
"File",
"f",
"=",
"new",
"File",
"(",
"crashDumpRootDirectory",
",",
"\"dl4j-memory-crash-dump-\"",
"+",
"now",
"+",
"\"_\"",
"+",
"tid",
"+",
"\".txt\"",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"SimpleDateFormat",
"sdf",
"=",
"new",
"SimpleDateFormat",
"(",
"\"yyyy-MM-dd HH:mm:ss.SSS\"",
")",
";",
"sb",
".",
"append",
"(",
"\"Deeplearning4j OOM Exception Encountered for \"",
")",
".",
"append",
"(",
"net",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
".",
"append",
"(",
"\"\\n\"",
")",
".",
"append",
"(",
"f",
"(",
"\"Timestamp: \"",
",",
"sdf",
".",
"format",
"(",
"now",
")",
")",
")",
".",
"append",
"(",
"f",
"(",
"\"Thread ID\"",
",",
"tid",
")",
")",
".",
"append",
"(",
"f",
"(",
"\"Thread Name\"",
",",
"threadName",
")",
")",
".",
"append",
"(",
"\"\\n\\n\"",
")",
";",
"sb",
".",
"append",
"(",
"\"Stack Trace:\\n\"",
")",
".",
"append",
"(",
"ExceptionUtils",
".",
"getStackTrace",
"(",
"e",
")",
")",
";",
"try",
"{",
"sb",
".",
"append",
"(",
"\"\\n\\n\"",
")",
";",
"sb",
".",
"append",
"(",
"generateMemoryStatus",
"(",
"net",
",",
"-",
"1",
",",
"(",
"InputType",
"[",
"]",
")",
"null",
")",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"sb",
".",
"append",
"(",
"\"<Error generating network memory status information section>\"",
")",
".",
"append",
"(",
"ExceptionUtils",
".",
"getStackTrace",
"(",
"t",
")",
")",
";",
"}",
"String",
"toWrite",
"=",
"sb",
".",
"toString",
"(",
")",
";",
"try",
"{",
"FileUtils",
".",
"writeStringToFile",
"(",
"f",
",",
"toWrite",
")",
";",
"}",
"catch",
"(",
"IOException",
"e2",
")",
"{",
"log",
".",
"error",
"(",
"\"Error writing memory crash dump information to disk: {}\"",
",",
"f",
".",
"getAbsolutePath",
"(",
")",
",",
"e2",
")",
";",
"}",
"log",
".",
"error",
"(",
"\">>> Out of Memory Exception Detected. Memory crash dump written to: {}\"",
",",
"f",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"log",
".",
"warn",
"(",
"\"Memory crash dump reporting can be disabled with CrashUtil.crashDumpsEnabled(false) or using system \"",
"+",
"\"property -D\"",
"+",
"DL4JSystemProperties",
".",
"CRASH_DUMP_ENABLED_PROPERTY",
"+",
"\"=false\"",
")",
";",
"log",
".",
"warn",
"(",
"\"Memory crash dump reporting output location can be set with CrashUtil.crashDumpOutputDirectory(File) or using system \"",
"+",
"\"property -D\"",
"+",
"DL4JSystemProperties",
".",
"CRASH_DUMP_OUTPUT_DIRECTORY_PROPERTY",
"+",
"\"=<path>\"",
")",
";",
"}"
] | Generate and write the crash dump to the crash dump root directory (by default, the working directory).
Naming convention for crash dump files: "dl4j-memory-crash-dump-<timestamp>_<thread-id>.txt"
@param net Net to generate the crash dump for. May not be null
@param e Throwable/exception. Stack trace will be included in the network output | [
"Generate",
"and",
"write",
"the",
"crash",
"dump",
"to",
"the",
"crash",
"dump",
"root",
"directory",
"(",
"by",
"default",
"the",
"working",
"directory",
")",
".",
"Naming",
"convention",
"for",
"crash",
"dump",
"files",
":",
"dl4j",
"-",
"memory",
"-",
"crash",
"-",
"dump",
"-",
"<timestamp",
">",
"_<thread",
"-",
"id",
">",
".",
"txt"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/CrashReportingUtil.java#L136-L178 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java | AppServicePlansInner.getHybridConnectionAsync | public Observable<HybridConnectionInner> getHybridConnectionAsync(String resourceGroupName, String name, String namespaceName, String relayName) {
"""
Retrieve a Hybrid Connection in use in an App Service plan.
Retrieve a Hybrid Connection in use in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param namespaceName Name of the Service Bus namespace.
@param relayName Name of the Service Bus relay.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the HybridConnectionInner object
"""
return getHybridConnectionWithServiceResponseAsync(resourceGroupName, name, namespaceName, relayName).map(new Func1<ServiceResponse<HybridConnectionInner>, HybridConnectionInner>() {
@Override
public HybridConnectionInner call(ServiceResponse<HybridConnectionInner> response) {
return response.body();
}
});
} | java | public Observable<HybridConnectionInner> getHybridConnectionAsync(String resourceGroupName, String name, String namespaceName, String relayName) {
return getHybridConnectionWithServiceResponseAsync(resourceGroupName, name, namespaceName, relayName).map(new Func1<ServiceResponse<HybridConnectionInner>, HybridConnectionInner>() {
@Override
public HybridConnectionInner call(ServiceResponse<HybridConnectionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"HybridConnectionInner",
">",
"getHybridConnectionAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"String",
"namespaceName",
",",
"String",
"relayName",
")",
"{",
"return",
"getHybridConnectionWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"namespaceName",
",",
"relayName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"HybridConnectionInner",
">",
",",
"HybridConnectionInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"HybridConnectionInner",
"call",
"(",
"ServiceResponse",
"<",
"HybridConnectionInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Retrieve a Hybrid Connection in use in an App Service plan.
Retrieve a Hybrid Connection in use in an App Service plan.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service plan.
@param namespaceName Name of the Service Bus namespace.
@param relayName Name of the Service Bus relay.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the HybridConnectionInner object | [
"Retrieve",
"a",
"Hybrid",
"Connection",
"in",
"use",
"in",
"an",
"App",
"Service",
"plan",
".",
"Retrieve",
"a",
"Hybrid",
"Connection",
"in",
"use",
"in",
"an",
"App",
"Service",
"plan",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L1166-L1173 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/impl/CacheProxyUtil.java | CacheProxyUtil.validateConfiguredKeyType | public static <K> void validateConfiguredKeyType(Class<K> keyType, K key) throws ClassCastException {
"""
Validates the key with key type.
@param keyType key class.
@param key key to be validated.
@param <K> the type of key.
@throws ClassCastException if the provided key do not match with keyType.
"""
if (Object.class != keyType) {
// means that type checks is required
if (!keyType.isAssignableFrom(key.getClass())) {
throw new ClassCastException("Key '" + key + "' is not assignable to " + keyType);
}
}
} | java | public static <K> void validateConfiguredKeyType(Class<K> keyType, K key) throws ClassCastException {
if (Object.class != keyType) {
// means that type checks is required
if (!keyType.isAssignableFrom(key.getClass())) {
throw new ClassCastException("Key '" + key + "' is not assignable to " + keyType);
}
}
} | [
"public",
"static",
"<",
"K",
">",
"void",
"validateConfiguredKeyType",
"(",
"Class",
"<",
"K",
">",
"keyType",
",",
"K",
"key",
")",
"throws",
"ClassCastException",
"{",
"if",
"(",
"Object",
".",
"class",
"!=",
"keyType",
")",
"{",
"// means that type checks is required",
"if",
"(",
"!",
"keyType",
".",
"isAssignableFrom",
"(",
"key",
".",
"getClass",
"(",
")",
")",
")",
"{",
"throw",
"new",
"ClassCastException",
"(",
"\"Key '\"",
"+",
"key",
"+",
"\"' is not assignable to \"",
"+",
"keyType",
")",
";",
"}",
"}",
"}"
] | Validates the key with key type.
@param keyType key class.
@param key key to be validated.
@param <K> the type of key.
@throws ClassCastException if the provided key do not match with keyType. | [
"Validates",
"the",
"key",
"with",
"key",
"type",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/impl/CacheProxyUtil.java#L214-L221 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java | ArchiveAnalyzer.extractAndAnalyze | private void extractAndAnalyze(Dependency dependency, Engine engine, int scanDepth) throws AnalysisException {
"""
Extracts the contents of the archive dependency and scans for additional
dependencies.
@param dependency the dependency being analyzed
@param engine the engine doing the analysis
@param scanDepth the current scan depth; extracctAndAnalyze is recursive
and will, be default, only go 3 levels deep
@throws AnalysisException thrown if there is a problem analyzing the
dependencies
"""
final File f = new File(dependency.getActualFilePath());
final File tmpDir = getNextTempDirectory();
extractFiles(f, tmpDir, engine);
//make a copy
final List<Dependency> dependencySet = findMoreDependencies(engine, tmpDir);
if (dependencySet != null && !dependencySet.isEmpty()) {
for (Dependency d : dependencySet) {
if (d.getFilePath().startsWith(tmpDir.getAbsolutePath())) {
//fix the dependency's display name and path
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
d.getFileName());
d.setFilePath(displayPath);
d.setFileName(displayName);
d.addAllProjectReferences(dependency.getProjectReferences());
//TODO - can we get more evidence from the parent? EAR contains module name, etc.
//analyze the dependency (i.e. extract files) if it is a supported type.
if (this.accept(d.getActualFile()) && scanDepth < maxScanDepth) {
extractAndAnalyze(d, engine, scanDepth + 1);
}
} else {
dependencySet.stream().filter((sub) -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach((sub) -> {
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
sub.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
sub.getFileName());
sub.setFilePath(displayPath);
sub.setFileName(displayName);
});
}
}
} | java | private void extractAndAnalyze(Dependency dependency, Engine engine, int scanDepth) throws AnalysisException {
final File f = new File(dependency.getActualFilePath());
final File tmpDir = getNextTempDirectory();
extractFiles(f, tmpDir, engine);
//make a copy
final List<Dependency> dependencySet = findMoreDependencies(engine, tmpDir);
if (dependencySet != null && !dependencySet.isEmpty()) {
for (Dependency d : dependencySet) {
if (d.getFilePath().startsWith(tmpDir.getAbsolutePath())) {
//fix the dependency's display name and path
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
d.getFileName());
d.setFilePath(displayPath);
d.setFileName(displayName);
d.addAllProjectReferences(dependency.getProjectReferences());
//TODO - can we get more evidence from the parent? EAR contains module name, etc.
//analyze the dependency (i.e. extract files) if it is a supported type.
if (this.accept(d.getActualFile()) && scanDepth < maxScanDepth) {
extractAndAnalyze(d, engine, scanDepth + 1);
}
} else {
dependencySet.stream().filter((sub) -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach((sub) -> {
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
sub.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
sub.getFileName());
sub.setFilePath(displayPath);
sub.setFileName(displayName);
});
}
}
} | [
"private",
"void",
"extractAndAnalyze",
"(",
"Dependency",
"dependency",
",",
"Engine",
"engine",
",",
"int",
"scanDepth",
")",
"throws",
"AnalysisException",
"{",
"final",
"File",
"f",
"=",
"new",
"File",
"(",
"dependency",
".",
"getActualFilePath",
"(",
")",
")",
";",
"final",
"File",
"tmpDir",
"=",
"getNextTempDirectory",
"(",
")",
";",
"extractFiles",
"(",
"f",
",",
"tmpDir",
",",
"engine",
")",
";",
"//make a copy",
"final",
"List",
"<",
"Dependency",
">",
"dependencySet",
"=",
"findMoreDependencies",
"(",
"engine",
",",
"tmpDir",
")",
";",
"if",
"(",
"dependencySet",
"!=",
"null",
"&&",
"!",
"dependencySet",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"Dependency",
"d",
":",
"dependencySet",
")",
"{",
"if",
"(",
"d",
".",
"getFilePath",
"(",
")",
".",
"startsWith",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
")",
")",
"{",
"//fix the dependency's display name and path",
"final",
"String",
"displayPath",
"=",
"String",
".",
"format",
"(",
"\"%s%s\"",
",",
"dependency",
".",
"getFilePath",
"(",
")",
",",
"d",
".",
"getActualFilePath",
"(",
")",
".",
"substring",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
".",
"length",
"(",
")",
")",
")",
";",
"final",
"String",
"displayName",
"=",
"String",
".",
"format",
"(",
"\"%s: %s\"",
",",
"dependency",
".",
"getFileName",
"(",
")",
",",
"d",
".",
"getFileName",
"(",
")",
")",
";",
"d",
".",
"setFilePath",
"(",
"displayPath",
")",
";",
"d",
".",
"setFileName",
"(",
"displayName",
")",
";",
"d",
".",
"addAllProjectReferences",
"(",
"dependency",
".",
"getProjectReferences",
"(",
")",
")",
";",
"//TODO - can we get more evidence from the parent? EAR contains module name, etc.",
"//analyze the dependency (i.e. extract files) if it is a supported type.",
"if",
"(",
"this",
".",
"accept",
"(",
"d",
".",
"getActualFile",
"(",
")",
")",
"&&",
"scanDepth",
"<",
"maxScanDepth",
")",
"{",
"extractAndAnalyze",
"(",
"d",
",",
"engine",
",",
"scanDepth",
"+",
"1",
")",
";",
"}",
"}",
"else",
"{",
"dependencySet",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"(",
"sub",
")",
"-",
">",
"sub",
".",
"getFilePath",
"(",
")",
".",
"startsWith",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
")",
")",
".",
"forEach",
"(",
"(",
"sub",
")",
"-",
">",
"{",
"final",
"String",
"displayPath",
"=",
"String",
".",
"format",
"(",
"\"%s%s\"",
",",
"dependency",
".",
"getFilePath",
"(",
")",
",",
"sub",
".",
"getActualFilePath",
"(",
")",
".",
"substring",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
".",
"length",
"(",
")",
")",
")",
"",
";",
"final",
"String",
"displayName",
"=",
"String",
".",
"format",
"(",
"\"%s: %s\"",
",",
"dependency",
".",
"getFileName",
"(",
")",
",",
"sub",
".",
"getFileName",
"(",
")",
")",
";",
"sub",
".",
"setFilePath",
"(",
"displayPath",
")",
";",
"sub",
".",
"setFileName",
"(",
"displayName",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
] | Extracts the contents of the archive dependency and scans for additional
dependencies.
@param dependency the dependency being analyzed
@param engine the engine doing the analysis
@param scanDepth the current scan depth; extracctAndAnalyze is recursive
and will, be default, only go 3 levels deep
@throws AnalysisException thrown if there is a problem analyzing the
dependencies | [
"Extracts",
"the",
"contents",
"of",
"the",
"archive",
"dependency",
"and",
"scans",
"for",
"additional",
"dependencies",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java#L248-L288 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/application/greedyensemble/ComputeKNNOutlierScores.java | ComputeKNNOutlierScores.writeResult | void writeResult(PrintStream out, DBIDs ids, OutlierResult result, ScalingFunction scaling, String label) {
"""
Write a single output line.
@param out Output stream
@param ids DBIDs
@param result Outlier result
@param scaling Scaling function
@param label Identification label
"""
if(scaling instanceof OutlierScaling) {
((OutlierScaling) scaling).prepare(result);
}
out.append(label);
DoubleRelation scores = result.getScores();
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
double value = scores.doubleValue(iter);
value = scaling != null ? scaling.getScaled(value) : value;
out.append(' ').append(Double.toString(value));
}
out.append(FormatUtil.NEWLINE);
} | java | void writeResult(PrintStream out, DBIDs ids, OutlierResult result, ScalingFunction scaling, String label) {
if(scaling instanceof OutlierScaling) {
((OutlierScaling) scaling).prepare(result);
}
out.append(label);
DoubleRelation scores = result.getScores();
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
double value = scores.doubleValue(iter);
value = scaling != null ? scaling.getScaled(value) : value;
out.append(' ').append(Double.toString(value));
}
out.append(FormatUtil.NEWLINE);
} | [
"void",
"writeResult",
"(",
"PrintStream",
"out",
",",
"DBIDs",
"ids",
",",
"OutlierResult",
"result",
",",
"ScalingFunction",
"scaling",
",",
"String",
"label",
")",
"{",
"if",
"(",
"scaling",
"instanceof",
"OutlierScaling",
")",
"{",
"(",
"(",
"OutlierScaling",
")",
"scaling",
")",
".",
"prepare",
"(",
"result",
")",
";",
"}",
"out",
".",
"append",
"(",
"label",
")",
";",
"DoubleRelation",
"scores",
"=",
"result",
".",
"getScores",
"(",
")",
";",
"for",
"(",
"DBIDIter",
"iter",
"=",
"ids",
".",
"iter",
"(",
")",
";",
"iter",
".",
"valid",
"(",
")",
";",
"iter",
".",
"advance",
"(",
")",
")",
"{",
"double",
"value",
"=",
"scores",
".",
"doubleValue",
"(",
"iter",
")",
";",
"value",
"=",
"scaling",
"!=",
"null",
"?",
"scaling",
".",
"getScaled",
"(",
"value",
")",
":",
"value",
";",
"out",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"Double",
".",
"toString",
"(",
"value",
")",
")",
";",
"}",
"out",
".",
"append",
"(",
"FormatUtil",
".",
"NEWLINE",
")",
";",
"}"
] | Write a single output line.
@param out Output stream
@param ids DBIDs
@param result Outlier result
@param scaling Scaling function
@param label Identification label | [
"Write",
"a",
"single",
"output",
"line",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/application/greedyensemble/ComputeKNNOutlierScores.java#L336-L348 |
unbescape/unbescape | src/main/java/org/unbescape/properties/PropertiesEscape.java | PropertiesEscape.unescapeProperties | public static void unescapeProperties(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
"""
<p>
Perform a Java Properties (key or value) <strong>unescape</strong> operation on a <tt>char[]</tt> input.
</p>
<p>
No additional configuration arguments are required. Unescape operations
will always perform <em>complete</em> Java Properties unescape of SECs and u-based escapes.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the unescape operation should start.
@param len the number of characters in <tt>text</tt> that should be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
"""
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
final int textLen = (text == null? 0 : text.length);
if (offset < 0 || offset > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
if (len < 0 || (offset + len) > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
PropertiesUnescapeUtil.unescape(text, offset, len, writer);
} | java | public static void unescapeProperties(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
final int textLen = (text == null? 0 : text.length);
if (offset < 0 || offset > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
if (len < 0 || (offset + len) > textLen) {
throw new IllegalArgumentException(
"Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen);
}
PropertiesUnescapeUtil.unescape(text, offset, len, writer);
} | [
"public",
"static",
"void",
"unescapeProperties",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' cannot be null\"",
")",
";",
"}",
"final",
"int",
"textLen",
"=",
"(",
"text",
"==",
"null",
"?",
"0",
":",
"text",
".",
"length",
")",
";",
"if",
"(",
"offset",
"<",
"0",
"||",
"offset",
">",
"textLen",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid (offset, len). offset=\"",
"+",
"offset",
"+",
"\", len=\"",
"+",
"len",
"+",
"\", text.length=\"",
"+",
"textLen",
")",
";",
"}",
"if",
"(",
"len",
"<",
"0",
"||",
"(",
"offset",
"+",
"len",
")",
">",
"textLen",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid (offset, len). offset=\"",
"+",
"offset",
"+",
"\", len=\"",
"+",
"len",
"+",
"\", text.length=\"",
"+",
"textLen",
")",
";",
"}",
"PropertiesUnescapeUtil",
".",
"unescape",
"(",
"text",
",",
"offset",
",",
"len",
",",
"writer",
")",
";",
"}"
] | <p>
Perform a Java Properties (key or value) <strong>unescape</strong> operation on a <tt>char[]</tt> input.
</p>
<p>
No additional configuration arguments are required. Unescape operations
will always perform <em>complete</em> Java Properties unescape of SECs and u-based escapes.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be unescaped.
@param offset the position in <tt>text</tt> at which the unescape operation should start.
@param len the number of characters in <tt>text</tt> that should be unescaped.
@param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"a",
"Java",
"Properties",
"(",
"key",
"or",
"value",
")",
"<strong",
">",
"unescape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"No",
"additional",
"configuration",
"arguments",
"are",
"required",
".",
"Unescape",
"operations",
"will",
"always",
"perform",
"<em",
">",
"complete<",
"/",
"em",
">",
"Java",
"Properties",
"unescape",
"of",
"SECs",
"and",
"u",
"-",
"based",
"escapes",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"is",
"<strong",
">",
"thread",
"-",
"safe<",
"/",
"strong",
">",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/properties/PropertiesEscape.java#L1476-L1497 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/comp/TransTypes.java | TransTypes.addBridges | void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
"""
Add all necessary bridges to some class appending them to list buffer.
@param pos The source code position to be used for the bridges.
@param origin The class in which the bridges go.
@param bridges The list buffer to which the bridges are added.
"""
Type st = types.supertype(origin.type);
while (st.hasTag(CLASS)) {
// if (isSpecialization(st))
addBridges(pos, st.tsym, origin, bridges);
st = types.supertype(st);
}
for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
// if (isSpecialization(l.head))
addBridges(pos, l.head.tsym, origin, bridges);
} | java | void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
Type st = types.supertype(origin.type);
while (st.hasTag(CLASS)) {
// if (isSpecialization(st))
addBridges(pos, st.tsym, origin, bridges);
st = types.supertype(st);
}
for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
// if (isSpecialization(l.head))
addBridges(pos, l.head.tsym, origin, bridges);
} | [
"void",
"addBridges",
"(",
"DiagnosticPosition",
"pos",
",",
"ClassSymbol",
"origin",
",",
"ListBuffer",
"<",
"JCTree",
">",
"bridges",
")",
"{",
"Type",
"st",
"=",
"types",
".",
"supertype",
"(",
"origin",
".",
"type",
")",
";",
"while",
"(",
"st",
".",
"hasTag",
"(",
"CLASS",
")",
")",
"{",
"// if (isSpecialization(st))",
"addBridges",
"(",
"pos",
",",
"st",
".",
"tsym",
",",
"origin",
",",
"bridges",
")",
";",
"st",
"=",
"types",
".",
"supertype",
"(",
"st",
")",
";",
"}",
"for",
"(",
"List",
"<",
"Type",
">",
"l",
"=",
"types",
".",
"interfaces",
"(",
"origin",
".",
"type",
")",
";",
"l",
".",
"nonEmpty",
"(",
")",
";",
"l",
"=",
"l",
".",
"tail",
")",
"// if (isSpecialization(l.head))",
"addBridges",
"(",
"pos",
",",
"l",
".",
"head",
".",
"tsym",
",",
"origin",
",",
"bridges",
")",
";",
"}"
] | Add all necessary bridges to some class appending them to list buffer.
@param pos The source code position to be used for the bridges.
@param origin The class in which the bridges go.
@param bridges The list buffer to which the bridges are added. | [
"Add",
"all",
"necessary",
"bridges",
"to",
"some",
"class",
"appending",
"them",
"to",
"list",
"buffer",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/comp/TransTypes.java#L464-L474 |
lessthanoptimal/ejml | examples/src/org/ejml/example/PrincipalComponentAnalysis.java | PrincipalComponentAnalysis.response | public double response( double[] sample ) {
"""
Computes the dot product of each basis vector against the sample. Can be used as a measure
for membership in the training sample set. High values correspond to a better fit.
@param sample Sample of original data.
@return Higher value indicates it is more likely to be a member of input dataset.
"""
if( sample.length != A.numCols )
throw new IllegalArgumentException("Expected input vector to be in sample space");
DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);
DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);
CommonOps_DDRM.mult(V_t,s,dots);
return NormOps_DDRM.normF(dots);
} | java | public double response( double[] sample ) {
if( sample.length != A.numCols )
throw new IllegalArgumentException("Expected input vector to be in sample space");
DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);
DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);
CommonOps_DDRM.mult(V_t,s,dots);
return NormOps_DDRM.normF(dots);
} | [
"public",
"double",
"response",
"(",
"double",
"[",
"]",
"sample",
")",
"{",
"if",
"(",
"sample",
".",
"length",
"!=",
"A",
".",
"numCols",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expected input vector to be in sample space\"",
")",
";",
"DMatrixRMaj",
"dots",
"=",
"new",
"DMatrixRMaj",
"(",
"numComponents",
",",
"1",
")",
";",
"DMatrixRMaj",
"s",
"=",
"DMatrixRMaj",
".",
"wrap",
"(",
"A",
".",
"numCols",
",",
"1",
",",
"sample",
")",
";",
"CommonOps_DDRM",
".",
"mult",
"(",
"V_t",
",",
"s",
",",
"dots",
")",
";",
"return",
"NormOps_DDRM",
".",
"normF",
"(",
"dots",
")",
";",
"}"
] | Computes the dot product of each basis vector against the sample. Can be used as a measure
for membership in the training sample set. High values correspond to a better fit.
@param sample Sample of original data.
@return Higher value indicates it is more likely to be a member of input dataset. | [
"Computes",
"the",
"dot",
"product",
"of",
"each",
"basis",
"vector",
"against",
"the",
"sample",
".",
"Can",
"be",
"used",
"as",
"a",
"measure",
"for",
"membership",
"in",
"the",
"training",
"sample",
"set",
".",
"High",
"values",
"correspond",
"to",
"a",
"better",
"fit",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/examples/src/org/ejml/example/PrincipalComponentAnalysis.java#L247-L257 |
MenoData/Time4J | base/src/main/java/net/time4j/history/ChronoHistory.java | ChronoHistory.with | public ChronoHistory with(AncientJulianLeapYears ancientJulianLeapYears) {
"""
/*[deutsch]
<p>Erzeugt eine Kopie dieser Instanz mit den angegebenen historischen julianischen Schaltjahren. </p>
<p>Diese Methode hat keine Auswirkung, wenn angewandt auf {@code ChronoHistory.PROLEPTIC_GREGORIAN}
oder {@code ChronoHistory.PROLEPTIC_JULIAN} oder {@code ChronoHistory.PROLEPTIC_BYZANTINE}. </p>
@param ancientJulianLeapYears sequence of historic julian leap years
@return new history which starts at first of January in year BC 45
@since 3.11/4.8
"""
if (ancientJulianLeapYears == null) {
throw new NullPointerException("Missing ancient julian leap years.");
} else if (!this.hasGregorianCutOverDate()) {
return this;
}
return new ChronoHistory(this.variant, this.events, ancientJulianLeapYears, this.nys, this.eraPreference);
} | java | public ChronoHistory with(AncientJulianLeapYears ancientJulianLeapYears) {
if (ancientJulianLeapYears == null) {
throw new NullPointerException("Missing ancient julian leap years.");
} else if (!this.hasGregorianCutOverDate()) {
return this;
}
return new ChronoHistory(this.variant, this.events, ancientJulianLeapYears, this.nys, this.eraPreference);
} | [
"public",
"ChronoHistory",
"with",
"(",
"AncientJulianLeapYears",
"ancientJulianLeapYears",
")",
"{",
"if",
"(",
"ancientJulianLeapYears",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Missing ancient julian leap years.\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"hasGregorianCutOverDate",
"(",
")",
")",
"{",
"return",
"this",
";",
"}",
"return",
"new",
"ChronoHistory",
"(",
"this",
".",
"variant",
",",
"this",
".",
"events",
",",
"ancientJulianLeapYears",
",",
"this",
".",
"nys",
",",
"this",
".",
"eraPreference",
")",
";",
"}"
] | /*[deutsch]
<p>Erzeugt eine Kopie dieser Instanz mit den angegebenen historischen julianischen Schaltjahren. </p>
<p>Diese Methode hat keine Auswirkung, wenn angewandt auf {@code ChronoHistory.PROLEPTIC_GREGORIAN}
oder {@code ChronoHistory.PROLEPTIC_JULIAN} oder {@code ChronoHistory.PROLEPTIC_BYZANTINE}. </p>
@param ancientJulianLeapYears sequence of historic julian leap years
@return new history which starts at first of January in year BC 45
@since 3.11/4.8 | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Erzeugt",
"eine",
"Kopie",
"dieser",
"Instanz",
"mit",
"den",
"angegebenen",
"historischen",
"julianischen",
"Schaltjahren",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/history/ChronoHistory.java#L1299-L1309 |
foundation-runtime/service-directory | 1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryLookupService.java | DirectoryLookupService.addNotificationHandler | public void addNotificationHandler(String serviceName, NotificationHandler handler) {
"""
Add a NotificationHandler to the Service.
This method checks the duplicated NotificationHandler for the serviceName, if the NotificationHandler
already exists for the serviceName, do nothing.
@param serviceName
the service name.
@param handler
the NotificationHandler for the service.
"""
ServiceInstanceUtils.validateServiceName(serviceName);
if (handler == null) {
throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR,
ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(),
"NotificationHandler");
}
synchronized(notificationHandlers){
if(! notificationHandlers.containsKey(serviceName)){
notificationHandlers.put(serviceName, new ArrayList<NotificationHandler>());
}
notificationHandlers.get(serviceName).add(handler);
}
} | java | public void addNotificationHandler(String serviceName, NotificationHandler handler){
ServiceInstanceUtils.validateServiceName(serviceName);
if (handler == null) {
throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR,
ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(),
"NotificationHandler");
}
synchronized(notificationHandlers){
if(! notificationHandlers.containsKey(serviceName)){
notificationHandlers.put(serviceName, new ArrayList<NotificationHandler>());
}
notificationHandlers.get(serviceName).add(handler);
}
} | [
"public",
"void",
"addNotificationHandler",
"(",
"String",
"serviceName",
",",
"NotificationHandler",
"handler",
")",
"{",
"ServiceInstanceUtils",
".",
"validateServiceName",
"(",
"serviceName",
")",
";",
"if",
"(",
"handler",
"==",
"null",
")",
"{",
"throw",
"new",
"ServiceException",
"(",
"ErrorCode",
".",
"SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR",
",",
"ErrorCode",
".",
"SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR",
".",
"getMessageTemplate",
"(",
")",
",",
"\"NotificationHandler\"",
")",
";",
"}",
"synchronized",
"(",
"notificationHandlers",
")",
"{",
"if",
"(",
"!",
"notificationHandlers",
".",
"containsKey",
"(",
"serviceName",
")",
")",
"{",
"notificationHandlers",
".",
"put",
"(",
"serviceName",
",",
"new",
"ArrayList",
"<",
"NotificationHandler",
">",
"(",
")",
")",
";",
"}",
"notificationHandlers",
".",
"get",
"(",
"serviceName",
")",
".",
"add",
"(",
"handler",
")",
";",
"}",
"}"
] | Add a NotificationHandler to the Service.
This method checks the duplicated NotificationHandler for the serviceName, if the NotificationHandler
already exists for the serviceName, do nothing.
@param serviceName
the service name.
@param handler
the NotificationHandler for the service. | [
"Add",
"a",
"NotificationHandler",
"to",
"the",
"Service",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryLookupService.java#L206-L221 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.transformEntry | public static boolean transformEntry(File zip, ZipEntryTransformerEntry entry, File destZip) {
"""
Copies an existing ZIP file and transforms a given entry in it.
@param zip
an existing ZIP file (only read).
@param entry
transformer for a ZIP entry.
@param destZip
new ZIP file created.
@return <code>true</code> if the entry was replaced.
"""
return transformEntries(zip, new ZipEntryTransformerEntry[] { entry }, destZip);
} | java | public static boolean transformEntry(File zip, ZipEntryTransformerEntry entry, File destZip) {
return transformEntries(zip, new ZipEntryTransformerEntry[] { entry }, destZip);
} | [
"public",
"static",
"boolean",
"transformEntry",
"(",
"File",
"zip",
",",
"ZipEntryTransformerEntry",
"entry",
",",
"File",
"destZip",
")",
"{",
"return",
"transformEntries",
"(",
"zip",
",",
"new",
"ZipEntryTransformerEntry",
"[",
"]",
"{",
"entry",
"}",
",",
"destZip",
")",
";",
"}"
] | Copies an existing ZIP file and transforms a given entry in it.
@param zip
an existing ZIP file (only read).
@param entry
transformer for a ZIP entry.
@param destZip
new ZIP file created.
@return <code>true</code> if the entry was replaced. | [
"Copies",
"an",
"existing",
"ZIP",
"file",
"and",
"transforms",
"a",
"given",
"entry",
"in",
"it",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2813-L2815 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/VCardManager.java | VCardManager.isSupported | @Deprecated
public static boolean isSupported(Jid jid, XMPPConnection connection) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
"""
Returns true if the given entity understands the vCard-XML format and allows the exchange of such.
@param jid
@param connection
@return true if the given entity understands the vCard-XML format and exchange.
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException
@deprecated use {@link #isSupported(Jid)} instead.
"""
return VCardManager.getInstanceFor(connection).isSupported(jid);
} | java | @Deprecated
public static boolean isSupported(Jid jid, XMPPConnection connection) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return VCardManager.getInstanceFor(connection).isSupported(jid);
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"isSupported",
"(",
"Jid",
"jid",
",",
"XMPPConnection",
"connection",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"return",
"VCardManager",
".",
"getInstanceFor",
"(",
"connection",
")",
".",
"isSupported",
"(",
"jid",
")",
";",
"}"
] | Returns true if the given entity understands the vCard-XML format and allows the exchange of such.
@param jid
@param connection
@return true if the given entity understands the vCard-XML format and exchange.
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException
@deprecated use {@link #isSupported(Jid)} instead. | [
"Returns",
"true",
"if",
"the",
"given",
"entity",
"understands",
"the",
"vCard",
"-",
"XML",
"format",
"and",
"allows",
"the",
"exchange",
"of",
"such",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/vcardtemp/VCardManager.java#L81-L84 |
NordicSemiconductor/Android-DFU-Library | dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java | SecureDfuImpl.writeCreateRequest | private void writeCreateRequest(final int type, final int size)
throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException,
UnknownResponseException {
"""
Writes Create Object request providing the type and size of the object.
@param type {@link #OBJECT_COMMAND} or {@link #OBJECT_DATA}.
@param size size of the object or current part of the object.
@throws DeviceDisconnectedException
@throws DfuException
@throws UploadAbortedException
@throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}
@throws UnknownResponseException
"""
if (!mConnected)
throw new DeviceDisconnectedException("Unable to create object: device disconnected");
final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
setObjectSize(data, size);
writeOpCode(mControlPointCharacteristic, data);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CREATE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Creating Command object failed", status);
} | java | private void writeCreateRequest(final int type, final int size)
throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException,
UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to create object: device disconnected");
final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
setObjectSize(data, size);
writeOpCode(mControlPointCharacteristic, data);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CREATE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Creating Command object failed", status);
} | [
"private",
"void",
"writeCreateRequest",
"(",
"final",
"int",
"type",
",",
"final",
"int",
"size",
")",
"throws",
"DeviceDisconnectedException",
",",
"DfuException",
",",
"UploadAbortedException",
",",
"RemoteDfuException",
",",
"UnknownResponseException",
"{",
"if",
"(",
"!",
"mConnected",
")",
"throw",
"new",
"DeviceDisconnectedException",
"(",
"\"Unable to create object: device disconnected\"",
")",
";",
"final",
"byte",
"[",
"]",
"data",
"=",
"(",
"type",
"==",
"OBJECT_COMMAND",
")",
"?",
"OP_CODE_CREATE_COMMAND",
":",
"OP_CODE_CREATE_DATA",
";",
"setObjectSize",
"(",
"data",
",",
"size",
")",
";",
"writeOpCode",
"(",
"mControlPointCharacteristic",
",",
"data",
")",
";",
"final",
"byte",
"[",
"]",
"response",
"=",
"readNotificationResponse",
"(",
")",
";",
"final",
"int",
"status",
"=",
"getStatusCode",
"(",
"response",
",",
"OP_CODE_CREATE_KEY",
")",
";",
"if",
"(",
"status",
"==",
"SecureDfuError",
".",
"EXTENDED_ERROR",
")",
"throw",
"new",
"RemoteDfuExtendedErrorException",
"(",
"\"Creating Command object failed\"",
",",
"response",
"[",
"3",
"]",
")",
";",
"if",
"(",
"status",
"!=",
"DFU_STATUS_SUCCESS",
")",
"throw",
"new",
"RemoteDfuException",
"(",
"\"Creating Command object failed\"",
",",
"status",
")",
";",
"}"
] | Writes Create Object request providing the type and size of the object.
@param type {@link #OBJECT_COMMAND} or {@link #OBJECT_DATA}.
@param size size of the object or current part of the object.
@throws DeviceDisconnectedException
@throws DfuException
@throws UploadAbortedException
@throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}
@throws UnknownResponseException | [
"Writes",
"Create",
"Object",
"request",
"providing",
"the",
"type",
"and",
"size",
"of",
"the",
"object",
"."
] | train | https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L807-L823 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/FileUtils.java | FileUtils.changeLocalFileGroup | public static void changeLocalFileGroup(String path, String group) throws IOException {
"""
Changes the local file's group.
@param path that will change owner
@param group the new group
"""
UserPrincipalLookupService lookupService =
FileSystems.getDefault().getUserPrincipalLookupService();
PosixFileAttributeView view =
Files.getFileAttributeView(Paths.get(path), PosixFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS);
GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(group);
view.setGroup(groupPrincipal);
} | java | public static void changeLocalFileGroup(String path, String group) throws IOException {
UserPrincipalLookupService lookupService =
FileSystems.getDefault().getUserPrincipalLookupService();
PosixFileAttributeView view =
Files.getFileAttributeView(Paths.get(path), PosixFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS);
GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(group);
view.setGroup(groupPrincipal);
} | [
"public",
"static",
"void",
"changeLocalFileGroup",
"(",
"String",
"path",
",",
"String",
"group",
")",
"throws",
"IOException",
"{",
"UserPrincipalLookupService",
"lookupService",
"=",
"FileSystems",
".",
"getDefault",
"(",
")",
".",
"getUserPrincipalLookupService",
"(",
")",
";",
"PosixFileAttributeView",
"view",
"=",
"Files",
".",
"getFileAttributeView",
"(",
"Paths",
".",
"get",
"(",
"path",
")",
",",
"PosixFileAttributeView",
".",
"class",
",",
"LinkOption",
".",
"NOFOLLOW_LINKS",
")",
";",
"GroupPrincipal",
"groupPrincipal",
"=",
"lookupService",
".",
"lookupPrincipalByGroupName",
"(",
"group",
")",
";",
"view",
".",
"setGroup",
"(",
"groupPrincipal",
")",
";",
"}"
] | Changes the local file's group.
@param path that will change owner
@param group the new group | [
"Changes",
"the",
"local",
"file",
"s",
"group",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/FileUtils.java#L57-L65 |
mikereedell/sunrisesunsetlib-java | src/main/java/com/luckycatlabs/sunrisesunset/calculator/SolarEventCalculator.java | SolarEventCalculator.computeSunriseTime | public String computeSunriseTime(Zenith solarZenith, Calendar date) {
"""
Computes the sunrise time for the given zenith at the given date.
@param solarZenith
<code>Zenith</code> enum corresponding to the type of sunrise to compute.
@param date
<code>Calendar</code> object representing the date to compute the sunrise for.
@return the sunrise time, in HH:MM format (24-hour clock), 00:00 if the sun does not rise on the given
date.
"""
return getLocalTimeAsString(computeSolarEventTime(solarZenith, date, true));
} | java | public String computeSunriseTime(Zenith solarZenith, Calendar date) {
return getLocalTimeAsString(computeSolarEventTime(solarZenith, date, true));
} | [
"public",
"String",
"computeSunriseTime",
"(",
"Zenith",
"solarZenith",
",",
"Calendar",
"date",
")",
"{",
"return",
"getLocalTimeAsString",
"(",
"computeSolarEventTime",
"(",
"solarZenith",
",",
"date",
",",
"true",
")",
")",
";",
"}"
] | Computes the sunrise time for the given zenith at the given date.
@param solarZenith
<code>Zenith</code> enum corresponding to the type of sunrise to compute.
@param date
<code>Calendar</code> object representing the date to compute the sunrise for.
@return the sunrise time, in HH:MM format (24-hour clock), 00:00 if the sun does not rise on the given
date. | [
"Computes",
"the",
"sunrise",
"time",
"for",
"the",
"given",
"zenith",
"at",
"the",
"given",
"date",
"."
] | train | https://github.com/mikereedell/sunrisesunsetlib-java/blob/6e6de23f1d11429eef58de2541582cbde9b85b92/src/main/java/com/luckycatlabs/sunrisesunset/calculator/SolarEventCalculator.java#L72-L74 |
square/phrase | src/main/java/com/squareup/phrase/Phrase.java | Phrase.from | public static Phrase from(Fragment f, @StringRes int patternResourceId) {
"""
Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors.
"""
return from(f.getResources(), patternResourceId);
} | java | public static Phrase from(Fragment f, @StringRes int patternResourceId) {
return from(f.getResources(), patternResourceId);
} | [
"public",
"static",
"Phrase",
"from",
"(",
"Fragment",
"f",
",",
"@",
"StringRes",
"int",
"patternResourceId",
")",
"{",
"return",
"from",
"(",
"f",
".",
"getResources",
"(",
")",
",",
"patternResourceId",
")",
";",
"}"
] | Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors. | [
"Entry",
"point",
"into",
"this",
"API",
"."
] | train | https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/Phrase.java#L78-L80 |
google/gson | gson/src/main/java/com/google/gson/Gson.java | Gson.toJson | public String toJson(Object src, Type typeOfSrc) {
"""
This method serializes the specified object, including those of generic types, into its
equivalent Json representation. This method must be used if the specified object is a generic
type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out
the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
@param src the object for which JSON representation is to be created
@param typeOfSrc The specific genericized type of src. You can obtain
this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
to get the type for {@code Collection<Foo>}, you should use:
<pre>
Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
</pre>
@return Json representation of {@code src}
"""
StringWriter writer = new StringWriter();
toJson(src, typeOfSrc, writer);
return writer.toString();
} | java | public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter();
toJson(src, typeOfSrc, writer);
return writer.toString();
} | [
"public",
"String",
"toJson",
"(",
"Object",
"src",
",",
"Type",
"typeOfSrc",
")",
"{",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"toJson",
"(",
"src",
",",
"typeOfSrc",
",",
"writer",
")",
";",
"return",
"writer",
".",
"toString",
"(",
")",
";",
"}"
] | This method serializes the specified object, including those of generic types, into its
equivalent Json representation. This method must be used if the specified object is a generic
type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out
the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
@param src the object for which JSON representation is to be created
@param typeOfSrc The specific genericized type of src. You can obtain
this type by using the {@link com.google.gson.reflect.TypeToken} class. For example,
to get the type for {@code Collection<Foo>}, you should use:
<pre>
Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
</pre>
@return Json representation of {@code src} | [
"This",
"method",
"serializes",
"the",
"specified",
"object",
"including",
"those",
"of",
"generic",
"types",
"into",
"its",
"equivalent",
"Json",
"representation",
".",
"This",
"method",
"must",
"be",
"used",
"if",
"the",
"specified",
"object",
"is",
"a",
"generic",
"type",
".",
"For",
"non",
"-",
"generic",
"objects",
"use",
"{",
"@link",
"#toJson",
"(",
"Object",
")",
"}",
"instead",
".",
"If",
"you",
"want",
"to",
"write",
"out",
"the",
"object",
"to",
"a",
"{",
"@link",
"Appendable",
"}",
"use",
"{",
"@link",
"#toJson",
"(",
"Object",
"Type",
"Appendable",
")",
"}",
"instead",
"."
] | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/Gson.java#L636-L640 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java | TransformerIdentityImpl.setParameter | public void setParameter(String name, Object value) {
"""
Add a parameter for the transformation.
<p>Pass a qualified name as a two-part string, the namespace URI
enclosed in curly braces ({}), followed by the local name. If the
name has a null URL, the String only contain the local name. An
application can safely check for a non-null URI by testing to see if the first
character of the name is a '{' character.</p>
<p>For example, if a URI and local name were obtained from an element
defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
no prefix is used.</p>
@param name The name of the parameter, which may begin with a namespace URI
in curly braces ({}).
@param value The value object. This can be any valid Java object. It is
up to the processor to provide the proper object coersion or to simply
pass the object on for use in an extension.
"""
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
} | java | public void setParameter(String name, Object value)
{
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
} | [
"public",
"void",
"setParameter",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"XSLMessages",
".",
"createMessage",
"(",
"XSLTErrorResources",
".",
"ER_INVALID_SET_PARAM_VALUE",
",",
"new",
"Object",
"[",
"]",
"{",
"name",
"}",
")",
")",
";",
"}",
"if",
"(",
"null",
"==",
"m_params",
")",
"{",
"m_params",
"=",
"new",
"Hashtable",
"(",
")",
";",
"}",
"m_params",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"}"
] | Add a parameter for the transformation.
<p>Pass a qualified name as a two-part string, the namespace URI
enclosed in curly braces ({}), followed by the local name. If the
name has a null URL, the String only contain the local name. An
application can safely check for a non-null URI by testing to see if the first
character of the name is a '{' character.</p>
<p>For example, if a URI and local name were obtained from an element
defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
no prefix is used.</p>
@param name The name of the parameter, which may begin with a namespace URI
in curly braces ({}).
@param value The value object. This can be any valid Java object. It is
up to the processor to provide the proper object coersion or to simply
pass the object on for use in an extension. | [
"Add",
"a",
"parameter",
"for",
"the",
"transformation",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java#L546-L558 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/spider/SpiderThread.java | SpiderThread.addMessageToSitesTree | private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) {
"""
Adds the given message to the sites tree.
@param historyReference the history reference of the message, must not be {@code null}
@param message the actual message, must not be {@code null}
"""
if (View.isInitialised() && !EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
addMessageToSitesTree(historyReference, message);
}
});
return;
}
StructuralNode node = SessionStructure.addPath(
Model.getSingleton().getSession(), historyReference, message, true);
if (node != null) {
try {
addUriToAddedNodesModel(SessionStructure.getNodeName(message),
message.getRequestHeader().getMethod(), "");
} catch (URIException e) {
log.error("Error while adding node to added nodes model: " + e.getMessage(), e);
}
}
} | java | private void addMessageToSitesTree(final HistoryReference historyReference, final HttpMessage message) {
if (View.isInitialised() && !EventQueue.isDispatchThread()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
addMessageToSitesTree(historyReference, message);
}
});
return;
}
StructuralNode node = SessionStructure.addPath(
Model.getSingleton().getSession(), historyReference, message, true);
if (node != null) {
try {
addUriToAddedNodesModel(SessionStructure.getNodeName(message),
message.getRequestHeader().getMethod(), "");
} catch (URIException e) {
log.error("Error while adding node to added nodes model: " + e.getMessage(), e);
}
}
} | [
"private",
"void",
"addMessageToSitesTree",
"(",
"final",
"HistoryReference",
"historyReference",
",",
"final",
"HttpMessage",
"message",
")",
"{",
"if",
"(",
"View",
".",
"isInitialised",
"(",
")",
"&&",
"!",
"EventQueue",
".",
"isDispatchThread",
"(",
")",
")",
"{",
"EventQueue",
".",
"invokeLater",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"addMessageToSitesTree",
"(",
"historyReference",
",",
"message",
")",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"StructuralNode",
"node",
"=",
"SessionStructure",
".",
"addPath",
"(",
"Model",
".",
"getSingleton",
"(",
")",
".",
"getSession",
"(",
")",
",",
"historyReference",
",",
"message",
",",
"true",
")",
";",
"if",
"(",
"node",
"!=",
"null",
")",
"{",
"try",
"{",
"addUriToAddedNodesModel",
"(",
"SessionStructure",
".",
"getNodeName",
"(",
"message",
")",
",",
"message",
".",
"getRequestHeader",
"(",
")",
".",
"getMethod",
"(",
")",
",",
"\"\"",
")",
";",
"}",
"catch",
"(",
"URIException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Error while adding node to added nodes model: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Adds the given message to the sites tree.
@param historyReference the history reference of the message, must not be {@code null}
@param message the actual message, must not be {@code null} | [
"Adds",
"the",
"given",
"message",
"to",
"the",
"sites",
"tree",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/spider/SpiderThread.java#L504-L526 |
trellis-ldp/trellis | core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java | TrellisHttpResource.getResource | @GET
@Timed
public void getResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers) {
"""
Perform a GET operation on an LDP Resource.
@implNote The Memento implemenation pattern exactly follows
<a href="https://tools.ietf.org/html/rfc7089#section-4.2.1">section 4.2.1 of RFC 7089</a>.
@param response the async response
@param uriInfo the URI info
@param headers the HTTP headers
@param request the request
"""
fetchResource(new TrellisRequest(request, uriInfo, headers))
.thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume);
} | java | @GET
@Timed
public void getResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers) {
fetchResource(new TrellisRequest(request, uriInfo, headers))
.thenApply(ResponseBuilder::build).exceptionally(this::handleException).thenApply(response::resume);
} | [
"@",
"GET",
"@",
"Timed",
"public",
"void",
"getResource",
"(",
"@",
"Suspended",
"final",
"AsyncResponse",
"response",
",",
"@",
"Context",
"final",
"Request",
"request",
",",
"@",
"Context",
"final",
"UriInfo",
"uriInfo",
",",
"@",
"Context",
"final",
"HttpHeaders",
"headers",
")",
"{",
"fetchResource",
"(",
"new",
"TrellisRequest",
"(",
"request",
",",
"uriInfo",
",",
"headers",
")",
")",
".",
"thenApply",
"(",
"ResponseBuilder",
"::",
"build",
")",
".",
"exceptionally",
"(",
"this",
"::",
"handleException",
")",
".",
"thenApply",
"(",
"response",
"::",
"resume",
")",
";",
"}"
] | Perform a GET operation on an LDP Resource.
@implNote The Memento implemenation pattern exactly follows
<a href="https://tools.ietf.org/html/rfc7089#section-4.2.1">section 4.2.1 of RFC 7089</a>.
@param response the async response
@param uriInfo the URI info
@param headers the HTTP headers
@param request the request | [
"Perform",
"a",
"GET",
"operation",
"on",
"an",
"LDP",
"Resource",
"."
] | train | https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/TrellisHttpResource.java#L203-L209 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/core/Parser.java | Parser.parseUpdateKeyword | public static boolean parseUpdateKeyword(final char[] query, int offset) {
"""
Parse string to check presence of UPDATE keyword regardless of case.
@param query char[] of the query statement
@param offset position of query to start checking
@return boolean indicates presence of word
"""
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'u'
&& (query[offset + 1] | 32) == 'p'
&& (query[offset + 2] | 32) == 'd'
&& (query[offset + 3] | 32) == 'a'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | java | public static boolean parseUpdateKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'u'
&& (query[offset + 1] | 32) == 'p'
&& (query[offset + 2] | 32) == 'd'
&& (query[offset + 3] | 32) == 'a'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | [
"public",
"static",
"boolean",
"parseUpdateKeyword",
"(",
"final",
"char",
"[",
"]",
"query",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"query",
".",
"length",
"<",
"(",
"offset",
"+",
"6",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"query",
"[",
"offset",
"]",
"|",
"32",
")",
"==",
"'",
"'",
"&&",
"(",
"query",
"[",
"offset",
"+",
"1",
"]",
"|",
"32",
")",
"==",
"'",
"'",
"&&",
"(",
"query",
"[",
"offset",
"+",
"2",
"]",
"|",
"32",
")",
"==",
"'",
"'",
"&&",
"(",
"query",
"[",
"offset",
"+",
"3",
"]",
"|",
"32",
")",
"==",
"'",
"'",
"&&",
"(",
"query",
"[",
"offset",
"+",
"4",
"]",
"|",
"32",
")",
"==",
"'",
"'",
"&&",
"(",
"query",
"[",
"offset",
"+",
"5",
"]",
"|",
"32",
")",
"==",
"'",
"'",
";",
"}"
] | Parse string to check presence of UPDATE keyword regardless of case.
@param query char[] of the query statement
@param offset position of query to start checking
@return boolean indicates presence of word | [
"Parse",
"string",
"to",
"check",
"presence",
"of",
"UPDATE",
"keyword",
"regardless",
"of",
"case",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L663-L674 |
nextreports/nextreports-engine | src/ro/nextreports/engine/util/DateUtil.java | DateUtil.sameHour | public static boolean sameHour(Date dateOne, Date dateTwo) {
"""
Test to see if two dates are in the same hour of day
@param dateOne first date
@param dateTwo second date
@return true if the two dates are in the same hour of day
"""
if ((dateOne == null) || (dateTwo == null)) {
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTime(dateOne);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_YEAR);
int hour = cal.get(Calendar.HOUR_OF_DAY);
cal.setTime(dateTwo);
int year2 = cal.get(Calendar.YEAR);
int month2 = cal.get(Calendar.MONTH);
int day2 = cal.get(Calendar.DAY_OF_YEAR);
int hour2 = cal.get(Calendar.HOUR_OF_DAY);
return ( (year == year2) && (month == month2) && (day == day2) &&
(hour == hour2));
} | java | public static boolean sameHour(Date dateOne, Date dateTwo) {
if ((dateOne == null) || (dateTwo == null)) {
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTime(dateOne);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_YEAR);
int hour = cal.get(Calendar.HOUR_OF_DAY);
cal.setTime(dateTwo);
int year2 = cal.get(Calendar.YEAR);
int month2 = cal.get(Calendar.MONTH);
int day2 = cal.get(Calendar.DAY_OF_YEAR);
int hour2 = cal.get(Calendar.HOUR_OF_DAY);
return ( (year == year2) && (month == month2) && (day == day2) &&
(hour == hour2));
} | [
"public",
"static",
"boolean",
"sameHour",
"(",
"Date",
"dateOne",
",",
"Date",
"dateTwo",
")",
"{",
"if",
"(",
"(",
"dateOne",
"==",
"null",
")",
"||",
"(",
"dateTwo",
"==",
"null",
")",
")",
"{",
"return",
"false",
";",
"}",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"dateOne",
")",
";",
"int",
"year",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
";",
"int",
"month",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
";",
"int",
"day",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_YEAR",
")",
";",
"int",
"hour",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
")",
";",
"cal",
".",
"setTime",
"(",
"dateTwo",
")",
";",
"int",
"year2",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
";",
"int",
"month2",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
";",
"int",
"day2",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_YEAR",
")",
";",
"int",
"hour2",
"=",
"cal",
".",
"get",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
")",
";",
"return",
"(",
"(",
"year",
"==",
"year2",
")",
"&&",
"(",
"month",
"==",
"month2",
")",
"&&",
"(",
"day",
"==",
"day2",
")",
"&&",
"(",
"hour",
"==",
"hour2",
")",
")",
";",
"}"
] | Test to see if two dates are in the same hour of day
@param dateOne first date
@param dateTwo second date
@return true if the two dates are in the same hour of day | [
"Test",
"to",
"see",
"if",
"two",
"dates",
"are",
"in",
"the",
"same",
"hour",
"of",
"day"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/DateUtil.java#L301-L321 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerValue.java | DerValue.getPositiveBigInteger | public BigInteger getPositiveBigInteger() throws IOException {
"""
Returns an ASN.1 INTEGER value as a positive BigInteger.
This is just to deal with implementations that incorrectly encode
some values as negative.
@return the integer held in this DER value as a BigInteger.
"""
if (tag != tag_Integer)
throw new IOException("DerValue.getBigInteger, not an int " + tag);
return buffer.getBigInteger(data.available(), true);
} | java | public BigInteger getPositiveBigInteger() throws IOException {
if (tag != tag_Integer)
throw new IOException("DerValue.getBigInteger, not an int " + tag);
return buffer.getBigInteger(data.available(), true);
} | [
"public",
"BigInteger",
"getPositiveBigInteger",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"tag",
"!=",
"tag_Integer",
")",
"throw",
"new",
"IOException",
"(",
"\"DerValue.getBigInteger, not an int \"",
"+",
"tag",
")",
";",
"return",
"buffer",
".",
"getBigInteger",
"(",
"data",
".",
"available",
"(",
")",
",",
"true",
")",
";",
"}"
] | Returns an ASN.1 INTEGER value as a positive BigInteger.
This is just to deal with implementations that incorrectly encode
some values as negative.
@return the integer held in this DER value as a BigInteger. | [
"Returns",
"an",
"ASN",
".",
"1",
"INTEGER",
"value",
"as",
"a",
"positive",
"BigInteger",
".",
"This",
"is",
"just",
"to",
"deal",
"with",
"implementations",
"that",
"incorrectly",
"encode",
"some",
"values",
"as",
"negative",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerValue.java#L535-L539 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java | UnicodeSet.applyPropertyAlias | public UnicodeSet applyPropertyAlias(String propertyAlias, String valueAlias) {
"""
Modifies this set to contain those code points which have the
given value for the given property. Prior contents of this
set are lost.
@param propertyAlias a property alias, either short or long.
The name is matched loosely. See PropertyAliases.txt for names
and a description of loose matching. If the value string is
empty, then this string is interpreted as either a
General_Category value alias, a Script value alias, a binary
property alias, or a special ID. Special IDs are matched
loosely and correspond to the following sets:
"ANY" = [\\u0000-\\u0010FFFF],
"ASCII" = [\\u0000-\\u007F].
@param valueAlias a value alias, either short or long. The
name is matched loosely. See PropertyValueAliases.txt for
names and a description of loose matching. In addition to
aliases listed, numeric values and canonical combining classes
may be expressed numerically, e.g., ("nv", "0.5") or ("ccc",
"220"). The value string may also be empty.
@return a reference to this set
"""
return applyPropertyAlias(propertyAlias, valueAlias, null);
} | java | public UnicodeSet applyPropertyAlias(String propertyAlias, String valueAlias) {
return applyPropertyAlias(propertyAlias, valueAlias, null);
} | [
"public",
"UnicodeSet",
"applyPropertyAlias",
"(",
"String",
"propertyAlias",
",",
"String",
"valueAlias",
")",
"{",
"return",
"applyPropertyAlias",
"(",
"propertyAlias",
",",
"valueAlias",
",",
"null",
")",
";",
"}"
] | Modifies this set to contain those code points which have the
given value for the given property. Prior contents of this
set are lost.
@param propertyAlias a property alias, either short or long.
The name is matched loosely. See PropertyAliases.txt for names
and a description of loose matching. If the value string is
empty, then this string is interpreted as either a
General_Category value alias, a Script value alias, a binary
property alias, or a special ID. Special IDs are matched
loosely and correspond to the following sets:
"ANY" = [\\u0000-\\u0010FFFF],
"ASCII" = [\\u0000-\\u007F].
@param valueAlias a value alias, either short or long. The
name is matched loosely. See PropertyValueAliases.txt for
names and a description of loose matching. In addition to
aliases listed, numeric values and canonical combining classes
may be expressed numerically, e.g., ("nv", "0.5") or ("ccc",
"220"). The value string may also be empty.
@return a reference to this set | [
"Modifies",
"this",
"set",
"to",
"contain",
"those",
"code",
"points",
"which",
"have",
"the",
"given",
"value",
"for",
"the",
"given",
"property",
".",
"Prior",
"contents",
"of",
"this",
"set",
"are",
"lost",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/UnicodeSet.java#L3349-L3351 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/HashUtils.java | HashUtils.hashHex | public static String hashHex(byte[] data, HashAlgorithm alg) throws NoSuchAlgorithmException {
"""
Hashes data with the specified hashing algorithm. Returns a hexadecimal result.
@since 1.1
@param data the data to hash
@param alg the hashing algorithm to use
@return the hexadecimal hash of the data
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers
"""
return hashHex(data, alg.toString());
} | java | public static String hashHex(byte[] data, HashAlgorithm alg) throws NoSuchAlgorithmException {
return hashHex(data, alg.toString());
} | [
"public",
"static",
"String",
"hashHex",
"(",
"byte",
"[",
"]",
"data",
",",
"HashAlgorithm",
"alg",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"return",
"hashHex",
"(",
"data",
",",
"alg",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Hashes data with the specified hashing algorithm. Returns a hexadecimal result.
@since 1.1
@param data the data to hash
@param alg the hashing algorithm to use
@return the hexadecimal hash of the data
@throws NoSuchAlgorithmException the algorithm is not supported by existing providers | [
"Hashes",
"data",
"with",
"the",
"specified",
"hashing",
"algorithm",
".",
"Returns",
"a",
"hexadecimal",
"result",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/HashUtils.java#L76-L78 |
evernote/android-job | library/src/main/java/com/evernote/android/job/JobConfig.java | JobConfig.setApiEnabled | public static void setApiEnabled(@NonNull JobApi api, boolean enabled) {
"""
<b>WARNING:</b> Please use this method carefully. It's only meant to be used for testing purposes
and could break how the library works.
<br>
<br>
Programmatic switch to enable or disable the given API. This only has an impact for new scheduled jobs.
@param api The API which should be enabled or disabled.
@param enabled Whether the API should be enabled or disabled.
"""
ENABLED_APIS.put(api, enabled);
CAT.w("setApiEnabled - %s, %b", api, enabled);
} | java | public static void setApiEnabled(@NonNull JobApi api, boolean enabled) {
ENABLED_APIS.put(api, enabled);
CAT.w("setApiEnabled - %s, %b", api, enabled);
} | [
"public",
"static",
"void",
"setApiEnabled",
"(",
"@",
"NonNull",
"JobApi",
"api",
",",
"boolean",
"enabled",
")",
"{",
"ENABLED_APIS",
".",
"put",
"(",
"api",
",",
"enabled",
")",
";",
"CAT",
".",
"w",
"(",
"\"setApiEnabled - %s, %b\"",
",",
"api",
",",
"enabled",
")",
";",
"}"
] | <b>WARNING:</b> Please use this method carefully. It's only meant to be used for testing purposes
and could break how the library works.
<br>
<br>
Programmatic switch to enable or disable the given API. This only has an impact for new scheduled jobs.
@param api The API which should be enabled or disabled.
@param enabled Whether the API should be enabled or disabled. | [
"<b",
">",
"WARNING",
":",
"<",
"/",
"b",
">",
"Please",
"use",
"this",
"method",
"carefully",
".",
"It",
"s",
"only",
"meant",
"to",
"be",
"used",
"for",
"testing",
"purposes",
"and",
"could",
"break",
"how",
"the",
"library",
"works",
".",
"<br",
">",
"<br",
">",
"Programmatic",
"switch",
"to",
"enable",
"or",
"disable",
"the",
"given",
"API",
".",
"This",
"only",
"has",
"an",
"impact",
"for",
"new",
"scheduled",
"jobs",
"."
] | train | https://github.com/evernote/android-job/blob/5ae3d776ad9d80b5b7f60ae3e382d44d0d193faf/library/src/main/java/com/evernote/android/job/JobConfig.java#L110-L113 |
alkacon/opencms-core | src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java | CmsDefaultAppButtonProvider.createAppFolderButton | public static Component createAppFolderButton(CmsObject cms, final CmsAppCategoryNode node, final Locale locale) {
"""
Creates a properly styled button for the given app.<p>
@param cms the cms context
@param node the node to display a buttom for
@param locale the locale
@return the button component
(I_CmsFolderAppCategory)childNode.getCategory(),
childNode.getAppConfigurations())
"""
Button button = createAppFolderIconButton((I_CmsFolderAppCategory)node.getCategory(), locale);
button.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_WIDTH = 855;
private static final int DEFAULT_MAX_APP_PER_ROW = 5;
private static final int MARGIN = 10;
public void buttonClick(ClickEvent event) {
CmsAppHierarchyPanel panel = new CmsAppHierarchyPanel(new CmsDefaultAppButtonProvider());
// panel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
panel.setCaption("Test caption");
panel.fill(node, locale);
Panel realPanel = new Panel();
realPanel.setContent(panel);
realPanel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
int browtherWidth = A_CmsUI.get().getPage().getBrowserWindowWidth();
if (node.getAppConfigurations().size() <= DEFAULT_MAX_APP_PER_ROW) {
panel.setComponentAlignment(panel.getComponent(0), com.vaadin.ui.Alignment.MIDDLE_CENTER);
}
if (browtherWidth < DEFAULT_WIDTH) {
realPanel.setWidth((browtherWidth - (2 * MARGIN)) + "px");
} else {
realPanel.setWidth(DEFAULT_WIDTH + "px");
}
final Window window = CmsBasicDialog.prepareWindow(DialogWidth.content);
window.setResizable(false);
window.setContent(realPanel);
window.setClosable(true);
window.addStyleName("o-close-on-background");
window.setModal(true);
window.setDraggable(false);
CmsAppWorkplaceUi.get().addWindow(window);
}
});
return button;
} | java | public static Component createAppFolderButton(CmsObject cms, final CmsAppCategoryNode node, final Locale locale) {
Button button = createAppFolderIconButton((I_CmsFolderAppCategory)node.getCategory(), locale);
button.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_WIDTH = 855;
private static final int DEFAULT_MAX_APP_PER_ROW = 5;
private static final int MARGIN = 10;
public void buttonClick(ClickEvent event) {
CmsAppHierarchyPanel panel = new CmsAppHierarchyPanel(new CmsDefaultAppButtonProvider());
// panel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
panel.setCaption("Test caption");
panel.fill(node, locale);
Panel realPanel = new Panel();
realPanel.setContent(panel);
realPanel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));
int browtherWidth = A_CmsUI.get().getPage().getBrowserWindowWidth();
if (node.getAppConfigurations().size() <= DEFAULT_MAX_APP_PER_ROW) {
panel.setComponentAlignment(panel.getComponent(0), com.vaadin.ui.Alignment.MIDDLE_CENTER);
}
if (browtherWidth < DEFAULT_WIDTH) {
realPanel.setWidth((browtherWidth - (2 * MARGIN)) + "px");
} else {
realPanel.setWidth(DEFAULT_WIDTH + "px");
}
final Window window = CmsBasicDialog.prepareWindow(DialogWidth.content);
window.setResizable(false);
window.setContent(realPanel);
window.setClosable(true);
window.addStyleName("o-close-on-background");
window.setModal(true);
window.setDraggable(false);
CmsAppWorkplaceUi.get().addWindow(window);
}
});
return button;
} | [
"public",
"static",
"Component",
"createAppFolderButton",
"(",
"CmsObject",
"cms",
",",
"final",
"CmsAppCategoryNode",
"node",
",",
"final",
"Locale",
"locale",
")",
"{",
"Button",
"button",
"=",
"createAppFolderIconButton",
"(",
"(",
"I_CmsFolderAppCategory",
")",
"node",
".",
"getCategory",
"(",
")",
",",
"locale",
")",
";",
"button",
".",
"addClickListener",
"(",
"new",
"ClickListener",
"(",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"private",
"static",
"final",
"int",
"DEFAULT_WIDTH",
"=",
"855",
";",
"private",
"static",
"final",
"int",
"DEFAULT_MAX_APP_PER_ROW",
"=",
"5",
";",
"private",
"static",
"final",
"int",
"MARGIN",
"=",
"10",
";",
"public",
"void",
"buttonClick",
"(",
"ClickEvent",
"event",
")",
"{",
"CmsAppHierarchyPanel",
"panel",
"=",
"new",
"CmsAppHierarchyPanel",
"(",
"new",
"CmsDefaultAppButtonProvider",
"(",
")",
")",
";",
"// panel.setCaption(((I_CmsFolderAppCategory)node.getCategory()).getName(locale));",
"panel",
".",
"setCaption",
"(",
"\"Test caption\"",
")",
";",
"panel",
".",
"fill",
"(",
"node",
",",
"locale",
")",
";",
"Panel",
"realPanel",
"=",
"new",
"Panel",
"(",
")",
";",
"realPanel",
".",
"setContent",
"(",
"panel",
")",
";",
"realPanel",
".",
"setCaption",
"(",
"(",
"(",
"I_CmsFolderAppCategory",
")",
"node",
".",
"getCategory",
"(",
")",
")",
".",
"getName",
"(",
"locale",
")",
")",
";",
"int",
"browtherWidth",
"=",
"A_CmsUI",
".",
"get",
"(",
")",
".",
"getPage",
"(",
")",
".",
"getBrowserWindowWidth",
"(",
")",
";",
"if",
"(",
"node",
".",
"getAppConfigurations",
"(",
")",
".",
"size",
"(",
")",
"<=",
"DEFAULT_MAX_APP_PER_ROW",
")",
"{",
"panel",
".",
"setComponentAlignment",
"(",
"panel",
".",
"getComponent",
"(",
"0",
")",
",",
"com",
".",
"vaadin",
".",
"ui",
".",
"Alignment",
".",
"MIDDLE_CENTER",
")",
";",
"}",
"if",
"(",
"browtherWidth",
"<",
"DEFAULT_WIDTH",
")",
"{",
"realPanel",
".",
"setWidth",
"(",
"(",
"browtherWidth",
"-",
"(",
"2",
"*",
"MARGIN",
")",
")",
"+",
"\"px\"",
")",
";",
"}",
"else",
"{",
"realPanel",
".",
"setWidth",
"(",
"DEFAULT_WIDTH",
"+",
"\"px\"",
")",
";",
"}",
"final",
"Window",
"window",
"=",
"CmsBasicDialog",
".",
"prepareWindow",
"(",
"DialogWidth",
".",
"content",
")",
";",
"window",
".",
"setResizable",
"(",
"false",
")",
";",
"window",
".",
"setContent",
"(",
"realPanel",
")",
";",
"window",
".",
"setClosable",
"(",
"true",
")",
";",
"window",
".",
"addStyleName",
"(",
"\"o-close-on-background\"",
")",
";",
"window",
".",
"setModal",
"(",
"true",
")",
";",
"window",
".",
"setDraggable",
"(",
"false",
")",
";",
"CmsAppWorkplaceUi",
".",
"get",
"(",
")",
".",
"addWindow",
"(",
"window",
")",
";",
"}",
"}",
")",
";",
"return",
"button",
";",
"}"
] | Creates a properly styled button for the given app.<p>
@param cms the cms context
@param node the node to display a buttom for
@param locale the locale
@return the button component
(I_CmsFolderAppCategory)childNode.getCategory(),
childNode.getAppConfigurations()) | [
"Creates",
"a",
"properly",
"styled",
"button",
"for",
"the",
"given",
"app",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/CmsDefaultAppButtonProvider.java#L107-L150 |
elki-project/elki | elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/AbstractObjDynamicHistogram.java | AbstractObjDynamicHistogram.aggregateSpecial | protected void aggregateSpecial(T value, int bin) {
"""
Aggregate for a special value.
@param value Parameter value
@param bin Special bin index.
"""
final T exist = getSpecial(bin);
// Note: do not inline above accessor, as getSpecial will initialize the
// special variable used below!
special[bin] = aggregate(exist, value);
} | java | protected void aggregateSpecial(T value, int bin) {
final T exist = getSpecial(bin);
// Note: do not inline above accessor, as getSpecial will initialize the
// special variable used below!
special[bin] = aggregate(exist, value);
} | [
"protected",
"void",
"aggregateSpecial",
"(",
"T",
"value",
",",
"int",
"bin",
")",
"{",
"final",
"T",
"exist",
"=",
"getSpecial",
"(",
"bin",
")",
";",
"// Note: do not inline above accessor, as getSpecial will initialize the",
"// special variable used below!",
"special",
"[",
"bin",
"]",
"=",
"aggregate",
"(",
"exist",
",",
"value",
")",
";",
"}"
] | Aggregate for a special value.
@param value Parameter value
@param bin Special bin index. | [
"Aggregate",
"for",
"a",
"special",
"value",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/AbstractObjDynamicHistogram.java#L161-L166 |
matomo-org/piwik-java-tracker | src/main/java/org/piwik/java/tracking/PiwikRequest.java | PiwikRequest.setNonEmptyStringParameter | private void setNonEmptyStringParameter(String key, String value) {
"""
Set a stored parameter and verify it is a non-empty string.
@param key the parameter's key
@param value the parameter's value. Cannot be the empty. Removes the parameter if null
string
"""
if (value == null){
parameters.remove(key);
}
else if (value.length() == 0){
throw new IllegalArgumentException("Value cannot be empty.");
}
else{
parameters.put(key, value);
}
} | java | private void setNonEmptyStringParameter(String key, String value){
if (value == null){
parameters.remove(key);
}
else if (value.length() == 0){
throw new IllegalArgumentException("Value cannot be empty.");
}
else{
parameters.put(key, value);
}
} | [
"private",
"void",
"setNonEmptyStringParameter",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"parameters",
".",
"remove",
"(",
"key",
")",
";",
"}",
"else",
"if",
"(",
"value",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Value cannot be empty.\"",
")",
";",
"}",
"else",
"{",
"parameters",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Set a stored parameter and verify it is a non-empty string.
@param key the parameter's key
@param value the parameter's value. Cannot be the empty. Removes the parameter if null
string | [
"Set",
"a",
"stored",
"parameter",
"and",
"verify",
"it",
"is",
"a",
"non",
"-",
"empty",
"string",
"."
] | train | https://github.com/matomo-org/piwik-java-tracker/blob/23df71d27a89e89dc7a539b2eda88c90a206458b/src/main/java/org/piwik/java/tracking/PiwikRequest.java#L1781-L1791 |
cdk/cdk | app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java | Depiction.writeTo | public final void writeTo(String fmt, OutputStream out) throws IOException {
"""
Write the depiction to the provided output stream.
@param fmt format
@param out output stream
@throws IOException depiction could not be written, low level IO problem
@see #listFormats()
"""
if (fmt.equalsIgnoreCase(SVG_FMT)) {
out.write(toSvgStr().getBytes(Charsets.UTF_8));
} else if (fmt.equalsIgnoreCase(PS_FMT)) {
out.write(toEpsStr().getBytes(Charsets.UTF_8));
} else if (fmt.equalsIgnoreCase(PDF_FMT)) {
out.write(toPdfStr().getBytes(Charsets.UTF_8));
} else {
ImageIO.write(toImg(), fmt, out);
}
} | java | public final void writeTo(String fmt, OutputStream out) throws IOException {
if (fmt.equalsIgnoreCase(SVG_FMT)) {
out.write(toSvgStr().getBytes(Charsets.UTF_8));
} else if (fmt.equalsIgnoreCase(PS_FMT)) {
out.write(toEpsStr().getBytes(Charsets.UTF_8));
} else if (fmt.equalsIgnoreCase(PDF_FMT)) {
out.write(toPdfStr().getBytes(Charsets.UTF_8));
} else {
ImageIO.write(toImg(), fmt, out);
}
} | [
"public",
"final",
"void",
"writeTo",
"(",
"String",
"fmt",
",",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"fmt",
".",
"equalsIgnoreCase",
"(",
"SVG_FMT",
")",
")",
"{",
"out",
".",
"write",
"(",
"toSvgStr",
"(",
")",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"}",
"else",
"if",
"(",
"fmt",
".",
"equalsIgnoreCase",
"(",
"PS_FMT",
")",
")",
"{",
"out",
".",
"write",
"(",
"toEpsStr",
"(",
")",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"}",
"else",
"if",
"(",
"fmt",
".",
"equalsIgnoreCase",
"(",
"PDF_FMT",
")",
")",
"{",
"out",
".",
"write",
"(",
"toPdfStr",
"(",
")",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_8",
")",
")",
";",
"}",
"else",
"{",
"ImageIO",
".",
"write",
"(",
"toImg",
"(",
")",
",",
"fmt",
",",
"out",
")",
";",
"}",
"}"
] | Write the depiction to the provided output stream.
@param fmt format
@param out output stream
@throws IOException depiction could not be written, low level IO problem
@see #listFormats() | [
"Write",
"the",
"depiction",
"to",
"the",
"provided",
"output",
"stream",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/app/depict/src/main/java/org/openscience/cdk/depict/Depiction.java#L246-L256 |
onepf/OpenIAB | library/src/main/java/org/onepf/oms/appstore/googleUtils/IabHelper.java | IabHelper.startSetup | public void startSetup(@Nullable final OnIabSetupFinishedListener listener) {
"""
Starts the setup process. This will start up the setup process asynchronously.
You will be notified through the listener when the setup process is complete.
This method is safe to call from a UI thread.
@param listener The listener to notify when the setup process is complete.
"""
// If already set up, can't do it again.
if (mSetupDone) throw new IllegalStateException("IAB helper is already set up.");
// Connection to IAB service
Logger.d("Starting in-app billing setup.");
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Logger.d("Billing service disconnected.");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Logger.d("Billing service connected.");
mService = getServiceFromBinder(service);
componentName = name;
String packageName = mContext.getPackageName();
final Handler handler = new Handler();
flagStartAsync("startSetup");
startSetupIabAsync(packageName, new OnIabSetupFinishedListener() {
@Override public void onIabSetupFinished(final IabResult result) {
handler.post(new Runnable() {
@Override public void run() {
flagEndAsync();
listener.onIabSetupFinished(result);
}
});
}
});
}
};
Intent serviceIntent = getServiceIntent();
final List<ResolveInfo> infoList = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (infoList != null && !infoList.isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
} else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
Logger.d("Billing service unavailable on device.");
}
}
} | java | public void startSetup(@Nullable final OnIabSetupFinishedListener listener) {
// If already set up, can't do it again.
if (mSetupDone) throw new IllegalStateException("IAB helper is already set up.");
// Connection to IAB service
Logger.d("Starting in-app billing setup.");
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Logger.d("Billing service disconnected.");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Logger.d("Billing service connected.");
mService = getServiceFromBinder(service);
componentName = name;
String packageName = mContext.getPackageName();
final Handler handler = new Handler();
flagStartAsync("startSetup");
startSetupIabAsync(packageName, new OnIabSetupFinishedListener() {
@Override public void onIabSetupFinished(final IabResult result) {
handler.post(new Runnable() {
@Override public void run() {
flagEndAsync();
listener.onIabSetupFinished(result);
}
});
}
});
}
};
Intent serviceIntent = getServiceIntent();
final List<ResolveInfo> infoList = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (infoList != null && !infoList.isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
} else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
Logger.d("Billing service unavailable on device.");
}
}
} | [
"public",
"void",
"startSetup",
"(",
"@",
"Nullable",
"final",
"OnIabSetupFinishedListener",
"listener",
")",
"{",
"// If already set up, can't do it again.",
"if",
"(",
"mSetupDone",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"IAB helper is already set up.\"",
")",
";",
"// Connection to IAB service",
"Logger",
".",
"d",
"(",
"\"Starting in-app billing setup.\"",
")",
";",
"mServiceConn",
"=",
"new",
"ServiceConnection",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onServiceDisconnected",
"(",
"ComponentName",
"name",
")",
"{",
"Logger",
".",
"d",
"(",
"\"Billing service disconnected.\"",
")",
";",
"mService",
"=",
"null",
";",
"}",
"@",
"Override",
"public",
"void",
"onServiceConnected",
"(",
"ComponentName",
"name",
",",
"IBinder",
"service",
")",
"{",
"Logger",
".",
"d",
"(",
"\"Billing service connected.\"",
")",
";",
"mService",
"=",
"getServiceFromBinder",
"(",
"service",
")",
";",
"componentName",
"=",
"name",
";",
"String",
"packageName",
"=",
"mContext",
".",
"getPackageName",
"(",
")",
";",
"final",
"Handler",
"handler",
"=",
"new",
"Handler",
"(",
")",
";",
"flagStartAsync",
"(",
"\"startSetup\"",
")",
";",
"startSetupIabAsync",
"(",
"packageName",
",",
"new",
"OnIabSetupFinishedListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onIabSetupFinished",
"(",
"final",
"IabResult",
"result",
")",
"{",
"handler",
".",
"post",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"flagEndAsync",
"(",
")",
";",
"listener",
".",
"onIabSetupFinished",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"Intent",
"serviceIntent",
"=",
"getServiceIntent",
"(",
")",
";",
"final",
"List",
"<",
"ResolveInfo",
">",
"infoList",
"=",
"mContext",
".",
"getPackageManager",
"(",
")",
".",
"queryIntentServices",
"(",
"serviceIntent",
",",
"0",
")",
";",
"if",
"(",
"infoList",
"!=",
"null",
"&&",
"!",
"infoList",
".",
"isEmpty",
"(",
")",
")",
"{",
"// service available to handle that Intent",
"mContext",
".",
"bindService",
"(",
"serviceIntent",
",",
"mServiceConn",
",",
"Context",
".",
"BIND_AUTO_CREATE",
")",
";",
"}",
"else",
"{",
"// no service available to handle that Intent",
"if",
"(",
"listener",
"!=",
"null",
")",
"{",
"listener",
".",
"onIabSetupFinished",
"(",
"new",
"IabResult",
"(",
"BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE",
",",
"\"Billing service unavailable on device.\"",
")",
")",
";",
"Logger",
".",
"d",
"(",
"\"Billing service unavailable on device.\"",
")",
";",
"}",
"}",
"}"
] | Starts the setup process. This will start up the setup process asynchronously.
You will be notified through the listener when the setup process is complete.
This method is safe to call from a UI thread.
@param listener The listener to notify when the setup process is complete. | [
"Starts",
"the",
"setup",
"process",
".",
"This",
"will",
"start",
"up",
"the",
"setup",
"process",
"asynchronously",
".",
"You",
"will",
"be",
"notified",
"through",
"the",
"listener",
"when",
"the",
"setup",
"process",
"is",
"complete",
".",
"This",
"method",
"is",
"safe",
"to",
"call",
"from",
"a",
"UI",
"thread",
"."
] | train | https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/appstore/googleUtils/IabHelper.java#L213-L261 |
UrielCh/ovh-java-sdk | ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java | ApiOvhPackxdsl.packName_promotionCode_capabilities_GET | public OvhCapabilities packName_promotionCode_capabilities_GET(String packName) throws IOException {
"""
Get informations about the promotion code generation
REST: GET /pack/xdsl/{packName}/promotionCode/capabilities
@param packName [required] The internal name of your pack
"""
String qPath = "/pack/xdsl/{packName}/promotionCode/capabilities";
StringBuilder sb = path(qPath, packName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhCapabilities.class);
} | java | public OvhCapabilities packName_promotionCode_capabilities_GET(String packName) throws IOException {
String qPath = "/pack/xdsl/{packName}/promotionCode/capabilities";
StringBuilder sb = path(qPath, packName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhCapabilities.class);
} | [
"public",
"OvhCapabilities",
"packName_promotionCode_capabilities_GET",
"(",
"String",
"packName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/pack/xdsl/{packName}/promotionCode/capabilities\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"packName",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhCapabilities",
".",
"class",
")",
";",
"}"
] | Get informations about the promotion code generation
REST: GET /pack/xdsl/{packName}/promotionCode/capabilities
@param packName [required] The internal name of your pack | [
"Get",
"informations",
"about",
"the",
"promotion",
"code",
"generation"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java#L788-L793 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-integrations/valkyrie-rcp-jidedocking/src/main/java/org/valkyriercp/application/docking/LayoutManager.java | LayoutManager.loadPageLayoutData | public static boolean loadPageLayoutData(DockingManager manager, String pageId, Perspective perspective) {
"""
Loads a the previously saved layout for the current page. If no
previously persisted layout exists for the given page the built
in default layout is used.
@param manager The docking manager to use
@param pageId The page to get the layout for
@return a boolean saying if the layout requested was previously saved
"""
manager.beginLoadLayoutData();
try{
if(isValidLayout(manager, pageId, perspective)){
String pageLayout = MessageFormat.format(PAGE_LAYOUT, pageId, perspective.getId());
manager.loadLayoutDataFrom(pageLayout);
return true;
}
else{
manager.loadLayoutData();
return false;
}
}
catch(Exception e){
manager.loadLayoutData();
return false;
}
} | java | public static boolean loadPageLayoutData(DockingManager manager, String pageId, Perspective perspective){
manager.beginLoadLayoutData();
try{
if(isValidLayout(manager, pageId, perspective)){
String pageLayout = MessageFormat.format(PAGE_LAYOUT, pageId, perspective.getId());
manager.loadLayoutDataFrom(pageLayout);
return true;
}
else{
manager.loadLayoutData();
return false;
}
}
catch(Exception e){
manager.loadLayoutData();
return false;
}
} | [
"public",
"static",
"boolean",
"loadPageLayoutData",
"(",
"DockingManager",
"manager",
",",
"String",
"pageId",
",",
"Perspective",
"perspective",
")",
"{",
"manager",
".",
"beginLoadLayoutData",
"(",
")",
";",
"try",
"{",
"if",
"(",
"isValidLayout",
"(",
"manager",
",",
"pageId",
",",
"perspective",
")",
")",
"{",
"String",
"pageLayout",
"=",
"MessageFormat",
".",
"format",
"(",
"PAGE_LAYOUT",
",",
"pageId",
",",
"perspective",
".",
"getId",
"(",
")",
")",
";",
"manager",
".",
"loadLayoutDataFrom",
"(",
"pageLayout",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"manager",
".",
"loadLayoutData",
"(",
")",
";",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"manager",
".",
"loadLayoutData",
"(",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Loads a the previously saved layout for the current page. If no
previously persisted layout exists for the given page the built
in default layout is used.
@param manager The docking manager to use
@param pageId The page to get the layout for
@return a boolean saying if the layout requested was previously saved | [
"Loads",
"a",
"the",
"previously",
"saved",
"layout",
"for",
"the",
"current",
"page",
".",
"If",
"no",
"previously",
"persisted",
"layout",
"exists",
"for",
"the",
"given",
"page",
"the",
"built",
"in",
"default",
"layout",
"is",
"used",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-integrations/valkyrie-rcp-jidedocking/src/main/java/org/valkyriercp/application/docking/LayoutManager.java#L51-L68 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java | RelativeDateTimeFormatter.formatNumeric | public String formatNumeric(double offset, RelativeDateTimeUnit unit) {
"""
Format a combination of RelativeDateTimeUnit and numeric offset
using a numeric style, e.g. "1 week ago", "in 1 week",
"5 weeks ago", "in 5 weeks".
@param offset The signed offset for the specified unit. This
will be formatted according to this object's
NumberFormat object.
@param unit The unit to use when formatting the relative
date, e.g. RelativeDateTimeUnit.WEEK,
RelativeDateTimeUnit.FRIDAY.
@return The formatted string (may be empty in case of error)
@hide draft / provisional / internal are hidden on Android
"""
// TODO:
// The full implementation of this depends on CLDR data that is not yet available,
// see: http://unicode.org/cldr/trac/ticket/9165 Add more relative field data.
// In the meantime do a quick bring-up by calling the old format method. When the
// new CLDR data is available, update the data storage accordingly, rewrite this
// to use it directly, and rewrite the old format method to call this new one;
// that is covered by http://bugs.icu-project.org/trac/ticket/12171.
RelativeUnit relunit = RelativeUnit.SECONDS;
switch (unit) {
case YEAR: relunit = RelativeUnit.YEARS; break;
case QUARTER: relunit = RelativeUnit.QUARTERS; break;
case MONTH: relunit = RelativeUnit.MONTHS; break;
case WEEK: relunit = RelativeUnit.WEEKS; break;
case DAY: relunit = RelativeUnit.DAYS; break;
case HOUR: relunit = RelativeUnit.HOURS; break;
case MINUTE: relunit = RelativeUnit.MINUTES; break;
case SECOND: break; // set above
default: // SUNDAY..SATURDAY
throw new UnsupportedOperationException("formatNumeric does not currently support RelativeUnit.SUNDAY..SATURDAY");
}
Direction direction = Direction.NEXT;
if (offset < 0) {
direction = Direction.LAST;
offset = -offset;
}
String result = format(offset, direction, relunit);
return (result != null)? result: "";
} | java | public String formatNumeric(double offset, RelativeDateTimeUnit unit) {
// TODO:
// The full implementation of this depends on CLDR data that is not yet available,
// see: http://unicode.org/cldr/trac/ticket/9165 Add more relative field data.
// In the meantime do a quick bring-up by calling the old format method. When the
// new CLDR data is available, update the data storage accordingly, rewrite this
// to use it directly, and rewrite the old format method to call this new one;
// that is covered by http://bugs.icu-project.org/trac/ticket/12171.
RelativeUnit relunit = RelativeUnit.SECONDS;
switch (unit) {
case YEAR: relunit = RelativeUnit.YEARS; break;
case QUARTER: relunit = RelativeUnit.QUARTERS; break;
case MONTH: relunit = RelativeUnit.MONTHS; break;
case WEEK: relunit = RelativeUnit.WEEKS; break;
case DAY: relunit = RelativeUnit.DAYS; break;
case HOUR: relunit = RelativeUnit.HOURS; break;
case MINUTE: relunit = RelativeUnit.MINUTES; break;
case SECOND: break; // set above
default: // SUNDAY..SATURDAY
throw new UnsupportedOperationException("formatNumeric does not currently support RelativeUnit.SUNDAY..SATURDAY");
}
Direction direction = Direction.NEXT;
if (offset < 0) {
direction = Direction.LAST;
offset = -offset;
}
String result = format(offset, direction, relunit);
return (result != null)? result: "";
} | [
"public",
"String",
"formatNumeric",
"(",
"double",
"offset",
",",
"RelativeDateTimeUnit",
"unit",
")",
"{",
"// TODO:",
"// The full implementation of this depends on CLDR data that is not yet available,",
"// see: http://unicode.org/cldr/trac/ticket/9165 Add more relative field data.",
"// In the meantime do a quick bring-up by calling the old format method. When the",
"// new CLDR data is available, update the data storage accordingly, rewrite this",
"// to use it directly, and rewrite the old format method to call this new one;",
"// that is covered by http://bugs.icu-project.org/trac/ticket/12171.",
"RelativeUnit",
"relunit",
"=",
"RelativeUnit",
".",
"SECONDS",
";",
"switch",
"(",
"unit",
")",
"{",
"case",
"YEAR",
":",
"relunit",
"=",
"RelativeUnit",
".",
"YEARS",
";",
"break",
";",
"case",
"QUARTER",
":",
"relunit",
"=",
"RelativeUnit",
".",
"QUARTERS",
";",
"break",
";",
"case",
"MONTH",
":",
"relunit",
"=",
"RelativeUnit",
".",
"MONTHS",
";",
"break",
";",
"case",
"WEEK",
":",
"relunit",
"=",
"RelativeUnit",
".",
"WEEKS",
";",
"break",
";",
"case",
"DAY",
":",
"relunit",
"=",
"RelativeUnit",
".",
"DAYS",
";",
"break",
";",
"case",
"HOUR",
":",
"relunit",
"=",
"RelativeUnit",
".",
"HOURS",
";",
"break",
";",
"case",
"MINUTE",
":",
"relunit",
"=",
"RelativeUnit",
".",
"MINUTES",
";",
"break",
";",
"case",
"SECOND",
":",
"break",
";",
"// set above",
"default",
":",
"// SUNDAY..SATURDAY",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"formatNumeric does not currently support RelativeUnit.SUNDAY..SATURDAY\"",
")",
";",
"}",
"Direction",
"direction",
"=",
"Direction",
".",
"NEXT",
";",
"if",
"(",
"offset",
"<",
"0",
")",
"{",
"direction",
"=",
"Direction",
".",
"LAST",
";",
"offset",
"=",
"-",
"offset",
";",
"}",
"String",
"result",
"=",
"format",
"(",
"offset",
",",
"direction",
",",
"relunit",
")",
";",
"return",
"(",
"result",
"!=",
"null",
")",
"?",
"result",
":",
"\"\"",
";",
"}"
] | Format a combination of RelativeDateTimeUnit and numeric offset
using a numeric style, e.g. "1 week ago", "in 1 week",
"5 weeks ago", "in 5 weeks".
@param offset The signed offset for the specified unit. This
will be formatted according to this object's
NumberFormat object.
@param unit The unit to use when formatting the relative
date, e.g. RelativeDateTimeUnit.WEEK,
RelativeDateTimeUnit.FRIDAY.
@return The formatted string (may be empty in case of error)
@hide draft / provisional / internal are hidden on Android | [
"Format",
"a",
"combination",
"of",
"RelativeDateTimeUnit",
"and",
"numeric",
"offset",
"using",
"a",
"numeric",
"style",
"e",
".",
"g",
".",
"1",
"week",
"ago",
"in",
"1",
"week",
"5",
"weeks",
"ago",
"in",
"5",
"weeks",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java#L493-L521 |
ixa-ehu/ixa-pipe-ml | src/main/java/eus/ixa/ixa/pipe/ml/parse/AbstractContextGenerator.java | AbstractContextGenerator.punctbo | protected String punctbo(final Parse punct, final int i) {
"""
Creates punctuation feature for the specified punctuation at the specfied
index based on the punctuation's tag.
@param punct
The punctuation which is in context.
@param i
The index of the punctuation relative to the parse.
@return Punctuation feature for the specified parse and the specified
punctuation at the specfied index.
"""
final StringBuilder feat = new StringBuilder(5);
feat.append(i).append("=");
feat.append(punct.getType());
return feat.toString();
} | java | protected String punctbo(final Parse punct, final int i) {
final StringBuilder feat = new StringBuilder(5);
feat.append(i).append("=");
feat.append(punct.getType());
return feat.toString();
} | [
"protected",
"String",
"punctbo",
"(",
"final",
"Parse",
"punct",
",",
"final",
"int",
"i",
")",
"{",
"final",
"StringBuilder",
"feat",
"=",
"new",
"StringBuilder",
"(",
"5",
")",
";",
"feat",
".",
"append",
"(",
"i",
")",
".",
"append",
"(",
"\"=\"",
")",
";",
"feat",
".",
"append",
"(",
"punct",
".",
"getType",
"(",
")",
")",
";",
"return",
"feat",
".",
"toString",
"(",
")",
";",
"}"
] | Creates punctuation feature for the specified punctuation at the specfied
index based on the punctuation's tag.
@param punct
The punctuation which is in context.
@param i
The index of the punctuation relative to the parse.
@return Punctuation feature for the specified parse and the specified
punctuation at the specfied index. | [
"Creates",
"punctuation",
"feature",
"for",
"the",
"specified",
"punctuation",
"at",
"the",
"specfied",
"index",
"based",
"on",
"the",
"punctuation",
"s",
"tag",
"."
] | train | https://github.com/ixa-ehu/ixa-pipe-ml/blob/c817fa1e40e96ed15fc79d22c3a7c25f1a40d172/src/main/java/eus/ixa/ixa/pipe/ml/parse/AbstractContextGenerator.java#L66-L71 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java | PermissionsImpl.updateAsync | public Observable<OperationStatus> updateAsync(UUID appId, UpdatePermissionsOptionalParameter updateOptionalParameter) {
"""
Replaces the current users access list with the one sent in the body. If an empty list is sent, all access to other users will be removed.
@param appId The application ID.
@param updateOptionalParameter 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 OperationStatus object
"""
return updateWithServiceResponseAsync(appId, updateOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> updateAsync(UUID appId, UpdatePermissionsOptionalParameter updateOptionalParameter) {
return updateWithServiceResponseAsync(appId, updateOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"updateAsync",
"(",
"UUID",
"appId",
",",
"UpdatePermissionsOptionalParameter",
"updateOptionalParameter",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"appId",
",",
"updateOptionalParameter",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"OperationStatus",
">",
",",
"OperationStatus",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"OperationStatus",
"call",
"(",
"ServiceResponse",
"<",
"OperationStatus",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Replaces the current users access list with the one sent in the body. If an empty list is sent, all access to other users will be removed.
@param appId The application ID.
@param updateOptionalParameter 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 OperationStatus object | [
"Replaces",
"the",
"current",
"users",
"access",
"list",
"with",
"the",
"one",
"sent",
"in",
"the",
"body",
".",
"If",
"an",
"empty",
"list",
"is",
"sent",
"all",
"access",
"to",
"other",
"users",
"will",
"be",
"removed",
"."
] | 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/PermissionsImpl.java#L506-L513 |
OpenLiberty/open-liberty | dev/com.ibm.ws.persistence/src/com/ibm/wsspi/persistence/internal/SchemaManager.java | SchemaManager.overrideDatabaseTerminationToken | private void overrideDatabaseTerminationToken(Map<Object, Object> props) {
"""
Helper method that will override the termination token if the database detected is in our
platformTerminationToken list.
"""
String overrideTermToken = null;
String platformClassName = _dbMgr.getDatabasePlatformClassName(_pui);
if (platformClassName != null) {
overrideTermToken = platformTerminationToken.get(platformClassName);
}
if (overrideTermToken != null) {
String existing = (String) props.get(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES);
if (existing != null) {
existing = existing + ",";
} else {
existing = "";
}
existing = (existing + "StoredProcedureTerminationToken=" + overrideTermToken);
props.put(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, existing);
}
} | java | private void overrideDatabaseTerminationToken(Map<Object, Object> props) {
String overrideTermToken = null;
String platformClassName = _dbMgr.getDatabasePlatformClassName(_pui);
if (platformClassName != null) {
overrideTermToken = platformTerminationToken.get(platformClassName);
}
if (overrideTermToken != null) {
String existing = (String) props.get(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES);
if (existing != null) {
existing = existing + ",";
} else {
existing = "";
}
existing = (existing + "StoredProcedureTerminationToken=" + overrideTermToken);
props.put(PersistenceUnitProperties.TARGET_DATABASE_PROPERTIES, existing);
}
} | [
"private",
"void",
"overrideDatabaseTerminationToken",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"props",
")",
"{",
"String",
"overrideTermToken",
"=",
"null",
";",
"String",
"platformClassName",
"=",
"_dbMgr",
".",
"getDatabasePlatformClassName",
"(",
"_pui",
")",
";",
"if",
"(",
"platformClassName",
"!=",
"null",
")",
"{",
"overrideTermToken",
"=",
"platformTerminationToken",
".",
"get",
"(",
"platformClassName",
")",
";",
"}",
"if",
"(",
"overrideTermToken",
"!=",
"null",
")",
"{",
"String",
"existing",
"=",
"(",
"String",
")",
"props",
".",
"get",
"(",
"PersistenceUnitProperties",
".",
"TARGET_DATABASE_PROPERTIES",
")",
";",
"if",
"(",
"existing",
"!=",
"null",
")",
"{",
"existing",
"=",
"existing",
"+",
"\",\"",
";",
"}",
"else",
"{",
"existing",
"=",
"\"\"",
";",
"}",
"existing",
"=",
"(",
"existing",
"+",
"\"StoredProcedureTerminationToken=\"",
"+",
"overrideTermToken",
")",
";",
"props",
".",
"put",
"(",
"PersistenceUnitProperties",
".",
"TARGET_DATABASE_PROPERTIES",
",",
"existing",
")",
";",
"}",
"}"
] | Helper method that will override the termination token if the database detected is in our
platformTerminationToken list. | [
"Helper",
"method",
"that",
"will",
"override",
"the",
"termination",
"token",
"if",
"the",
"database",
"detected",
"is",
"in",
"our",
"platformTerminationToken",
"list",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.persistence/src/com/ibm/wsspi/persistence/internal/SchemaManager.java#L163-L182 |
dropbox/dropbox-sdk-java | src/main/java/com/dropbox/core/v1/DbxClientV1.java | DbxClientV1.getMetadataWithChildrenC | public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, final Collector<DbxEntry, ? extends C> collector)
throws DbxException {
"""
Same as {@link #getMetadataWithChildrenC(String, boolean, Collector)} with {@code includeMediaInfo} set
to {@code false}.
"""
return getMetadataWithChildrenC(path, false, collector);
} | java | public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, final Collector<DbxEntry, ? extends C> collector)
throws DbxException
{
return getMetadataWithChildrenC(path, false, collector);
} | [
"public",
"<",
"C",
">",
"DbxEntry",
".",
"/*@Nullable*/",
"WithChildrenC",
"<",
"C",
">",
"getMetadataWithChildrenC",
"(",
"String",
"path",
",",
"final",
"Collector",
"<",
"DbxEntry",
",",
"?",
"extends",
"C",
">",
"collector",
")",
"throws",
"DbxException",
"{",
"return",
"getMetadataWithChildrenC",
"(",
"path",
",",
"false",
",",
"collector",
")",
";",
"}"
] | Same as {@link #getMetadataWithChildrenC(String, boolean, Collector)} with {@code includeMediaInfo} set
to {@code false}. | [
"Same",
"as",
"{"
] | train | https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L214-L218 |
jmeetsma/Iglu-Http | src/main/java/org/ijsberg/iglu/util/http/ServletSupport.java | ServletSupport.forward | public static void forward(String url, ServletRequest req, ServletResponse res) throws ServletException, IOException {
"""
Dispatches http-request to url
@param url
@throws ServletException to abort request handling
"""
RequestDispatcher dispatch = req.getRequestDispatcher(url);
System.out.println(new LogEntry("about to forward to " + url));
dispatch.forward(req, res);
} | java | public static void forward(String url, ServletRequest req, ServletResponse res) throws ServletException, IOException
{
RequestDispatcher dispatch = req.getRequestDispatcher(url);
System.out.println(new LogEntry("about to forward to " + url));
dispatch.forward(req, res);
} | [
"public",
"static",
"void",
"forward",
"(",
"String",
"url",
",",
"ServletRequest",
"req",
",",
"ServletResponse",
"res",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"RequestDispatcher",
"dispatch",
"=",
"req",
".",
"getRequestDispatcher",
"(",
"url",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"new",
"LogEntry",
"(",
"\"about to forward to \"",
"+",
"url",
")",
")",
";",
"dispatch",
".",
"forward",
"(",
"req",
",",
"res",
")",
";",
"}"
] | Dispatches http-request to url
@param url
@throws ServletException to abort request handling | [
"Dispatches",
"http",
"-",
"request",
"to",
"url"
] | train | https://github.com/jmeetsma/Iglu-Http/blob/5b5ed3b417285dc79b7aa013bf2340bb5ba1ffbe/src/main/java/org/ijsberg/iglu/util/http/ServletSupport.java#L472-L477 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java | SequenceMixin.sequenceEquality | public static <C extends Compound> boolean sequenceEquality(Sequence<C> source, Sequence<C> target) {
"""
A case-sensitive manner of comparing two sequence objects together.
We will throw out any compounds which fail to match on their sequence
length & compound sets used. The code will also bail out the moment
we find something is wrong with a Sequence. Cost to run is linear to
the length of the Sequence.
@param <C> The type of compound
@param source Source sequence to assess
@param target Target sequence to assess
@return Boolean indicating if the sequences matched
"""
return baseSequenceEquality(source, target, false);
} | java | public static <C extends Compound> boolean sequenceEquality(Sequence<C> source, Sequence<C> target) {
return baseSequenceEquality(source, target, false);
} | [
"public",
"static",
"<",
"C",
"extends",
"Compound",
">",
"boolean",
"sequenceEquality",
"(",
"Sequence",
"<",
"C",
">",
"source",
",",
"Sequence",
"<",
"C",
">",
"target",
")",
"{",
"return",
"baseSequenceEquality",
"(",
"source",
",",
"target",
",",
"false",
")",
";",
"}"
] | A case-sensitive manner of comparing two sequence objects together.
We will throw out any compounds which fail to match on their sequence
length & compound sets used. The code will also bail out the moment
we find something is wrong with a Sequence. Cost to run is linear to
the length of the Sequence.
@param <C> The type of compound
@param source Source sequence to assess
@param target Target sequence to assess
@return Boolean indicating if the sequences matched | [
"A",
"case",
"-",
"sensitive",
"manner",
"of",
"comparing",
"two",
"sequence",
"objects",
"together",
".",
"We",
"will",
"throw",
"out",
"any",
"compounds",
"which",
"fail",
"to",
"match",
"on",
"their",
"sequence",
"length",
"&",
"compound",
"sets",
"used",
".",
"The",
"code",
"will",
"also",
"bail",
"out",
"the",
"moment",
"we",
"find",
"something",
"is",
"wrong",
"with",
"a",
"Sequence",
".",
"Cost",
"to",
"run",
"is",
"linear",
"to",
"the",
"length",
"of",
"the",
"Sequence",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java#L371-L373 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.transformEntry | public static boolean transformEntry(final File zip, final ZipEntryTransformerEntry entry) {
"""
Changes an existing ZIP file: transforms a given entry in it.
@param zip
an existing ZIP file (only read).
@param entry
transformer for a ZIP entry.
@return <code>true</code> if the entry was replaced.
"""
return operateInPlace(zip, new InPlaceAction() {
public boolean act(File tmpFile) {
return transformEntry(zip, entry, tmpFile);
}
});
} | java | public static boolean transformEntry(final File zip, final ZipEntryTransformerEntry entry) {
return operateInPlace(zip, new InPlaceAction() {
public boolean act(File tmpFile) {
return transformEntry(zip, entry, tmpFile);
}
});
} | [
"public",
"static",
"boolean",
"transformEntry",
"(",
"final",
"File",
"zip",
",",
"final",
"ZipEntryTransformerEntry",
"entry",
")",
"{",
"return",
"operateInPlace",
"(",
"zip",
",",
"new",
"InPlaceAction",
"(",
")",
"{",
"public",
"boolean",
"act",
"(",
"File",
"tmpFile",
")",
"{",
"return",
"transformEntry",
"(",
"zip",
",",
"entry",
",",
"tmpFile",
")",
";",
"}",
"}",
")",
";",
"}"
] | Changes an existing ZIP file: transforms a given entry in it.
@param zip
an existing ZIP file (only read).
@param entry
transformer for a ZIP entry.
@return <code>true</code> if the entry was replaced. | [
"Changes",
"an",
"existing",
"ZIP",
"file",
":",
"transforms",
"a",
"given",
"entry",
"in",
"it",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2826-L2832 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/transport/netty/AuthHandler.java | AuthHandler.handleAuthResponse | private void handleAuthResponse(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
"""
Runs the SASL challenge protocol and dispatches the next step if required.
"""
if (saslClient.isComplete()) {
checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
return;
}
ByteBuf challengeBuf = SaslAuthResponse.challenge(msg);
byte[] challenge = new byte[challengeBuf.readableBytes()];
challengeBuf.readBytes(challenge);
byte[] evaluatedBytes = saslClient.evaluateChallenge(challenge);
if (evaluatedBytes != null) {
ByteBuf content;
// This is needed against older server versions where the protocol does not
// align on cram and plain, the else block is used for all the newer cram-sha*
// mechanisms.
//
// Note that most likely this is only executed in the CRAM-MD5 case only, but
// just to play it safe keep it for both mechanisms.
if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
String[] evaluated = new String(evaluatedBytes).split(" ");
content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
} else {
content = Unpooled.wrappedBuffer(evaluatedBytes);
}
ByteBuf request = ctx.alloc().buffer();
SaslStepRequest.init(request);
SaslStepRequest.mechanism(selectedMechanism, request);
SaslStepRequest.challengeResponse(content, request);
ChannelFuture future = ctx.writeAndFlush(request);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
originalPromise().setFailure(future.cause());
}
}
});
} else {
throw new AuthenticationException("SASL Challenge evaluation returned null.");
}
} | java | private void handleAuthResponse(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception {
if (saslClient.isComplete()) {
checkIsAuthed(ctx, MessageUtil.getResponseStatus(msg));
return;
}
ByteBuf challengeBuf = SaslAuthResponse.challenge(msg);
byte[] challenge = new byte[challengeBuf.readableBytes()];
challengeBuf.readBytes(challenge);
byte[] evaluatedBytes = saslClient.evaluateChallenge(challenge);
if (evaluatedBytes != null) {
ByteBuf content;
// This is needed against older server versions where the protocol does not
// align on cram and plain, the else block is used for all the newer cram-sha*
// mechanisms.
//
// Note that most likely this is only executed in the CRAM-MD5 case only, but
// just to play it safe keep it for both mechanisms.
if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
String[] evaluated = new String(evaluatedBytes).split(" ");
content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
} else {
content = Unpooled.wrappedBuffer(evaluatedBytes);
}
ByteBuf request = ctx.alloc().buffer();
SaslStepRequest.init(request);
SaslStepRequest.mechanism(selectedMechanism, request);
SaslStepRequest.challengeResponse(content, request);
ChannelFuture future = ctx.writeAndFlush(request);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
originalPromise().setFailure(future.cause());
}
}
});
} else {
throw new AuthenticationException("SASL Challenge evaluation returned null.");
}
} | [
"private",
"void",
"handleAuthResponse",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"ByteBuf",
"msg",
")",
"throws",
"Exception",
"{",
"if",
"(",
"saslClient",
".",
"isComplete",
"(",
")",
")",
"{",
"checkIsAuthed",
"(",
"ctx",
",",
"MessageUtil",
".",
"getResponseStatus",
"(",
"msg",
")",
")",
";",
"return",
";",
"}",
"ByteBuf",
"challengeBuf",
"=",
"SaslAuthResponse",
".",
"challenge",
"(",
"msg",
")",
";",
"byte",
"[",
"]",
"challenge",
"=",
"new",
"byte",
"[",
"challengeBuf",
".",
"readableBytes",
"(",
")",
"]",
";",
"challengeBuf",
".",
"readBytes",
"(",
"challenge",
")",
";",
"byte",
"[",
"]",
"evaluatedBytes",
"=",
"saslClient",
".",
"evaluateChallenge",
"(",
"challenge",
")",
";",
"if",
"(",
"evaluatedBytes",
"!=",
"null",
")",
"{",
"ByteBuf",
"content",
";",
"// This is needed against older server versions where the protocol does not",
"// align on cram and plain, the else block is used for all the newer cram-sha*",
"// mechanisms.",
"//",
"// Note that most likely this is only executed in the CRAM-MD5 case only, but",
"// just to play it safe keep it for both mechanisms.",
"if",
"(",
"selectedMechanism",
".",
"equals",
"(",
"\"CRAM-MD5\"",
")",
"||",
"selectedMechanism",
".",
"equals",
"(",
"\"PLAIN\"",
")",
")",
"{",
"String",
"[",
"]",
"evaluated",
"=",
"new",
"String",
"(",
"evaluatedBytes",
")",
".",
"split",
"(",
"\" \"",
")",
";",
"content",
"=",
"Unpooled",
".",
"copiedBuffer",
"(",
"username",
"+",
"\"\\0\"",
"+",
"evaluated",
"[",
"1",
"]",
",",
"CharsetUtil",
".",
"UTF_8",
")",
";",
"}",
"else",
"{",
"content",
"=",
"Unpooled",
".",
"wrappedBuffer",
"(",
"evaluatedBytes",
")",
";",
"}",
"ByteBuf",
"request",
"=",
"ctx",
".",
"alloc",
"(",
")",
".",
"buffer",
"(",
")",
";",
"SaslStepRequest",
".",
"init",
"(",
"request",
")",
";",
"SaslStepRequest",
".",
"mechanism",
"(",
"selectedMechanism",
",",
"request",
")",
";",
"SaslStepRequest",
".",
"challengeResponse",
"(",
"content",
",",
"request",
")",
";",
"ChannelFuture",
"future",
"=",
"ctx",
".",
"writeAndFlush",
"(",
"request",
")",
";",
"future",
".",
"addListener",
"(",
"new",
"GenericFutureListener",
"<",
"Future",
"<",
"Void",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"operationComplete",
"(",
"Future",
"<",
"Void",
">",
"future",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"future",
".",
"isSuccess",
"(",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Error during SASL Auth negotiation phase.\"",
",",
"future",
")",
";",
"originalPromise",
"(",
")",
".",
"setFailure",
"(",
"future",
".",
"cause",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"AuthenticationException",
"(",
"\"SASL Challenge evaluation returned null.\"",
")",
";",
"}",
"}"
] | Runs the SASL challenge protocol and dispatches the next step if required. | [
"Runs",
"the",
"SASL",
"challenge",
"protocol",
"and",
"dispatches",
"the",
"next",
"step",
"if",
"required",
"."
] | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/transport/netty/AuthHandler.java#L123-L169 |
alkacon/opencms-core | src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java | CmsContainerpageController.addToRecentList | public void addToRecentList(final String clientId, final Runnable nextAction) {
"""
Adds an element specified by it's id to the recent list.<p>
@param clientId the element id
@param nextAction the action to execute after the element has been added
"""
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
getContainerpageService().addToRecentList(getData().getRpcContext(), clientId, this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Void result) {
if (nextAction != null) {
nextAction.run();
}
}
};
action.execute();
} | java | public void addToRecentList(final String clientId, final Runnable nextAction) {
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
getContainerpageService().addToRecentList(getData().getRpcContext(), clientId, this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Void result) {
if (nextAction != null) {
nextAction.run();
}
}
};
action.execute();
} | [
"public",
"void",
"addToRecentList",
"(",
"final",
"String",
"clientId",
",",
"final",
"Runnable",
"nextAction",
")",
"{",
"CmsRpcAction",
"<",
"Void",
">",
"action",
"=",
"new",
"CmsRpcAction",
"<",
"Void",
">",
"(",
")",
"{",
"/**\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()\n */",
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"getContainerpageService",
"(",
")",
".",
"addToRecentList",
"(",
"getData",
"(",
")",
".",
"getRpcContext",
"(",
")",
",",
"clientId",
",",
"this",
")",
";",
"}",
"/**\n * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)\n */",
"@",
"Override",
"protected",
"void",
"onResponse",
"(",
"Void",
"result",
")",
"{",
"if",
"(",
"nextAction",
"!=",
"null",
")",
"{",
"nextAction",
".",
"run",
"(",
")",
";",
"}",
"}",
"}",
";",
"action",
".",
"execute",
"(",
")",
";",
"}"
] | Adds an element specified by it's id to the recent list.<p>
@param clientId the element id
@param nextAction the action to execute after the element has been added | [
"Adds",
"an",
"element",
"specified",
"by",
"it",
"s",
"id",
"to",
"the",
"recent",
"list",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L875-L900 |
Netflix/netflix-commons | netflix-infix/src/main/java/com/netflix/infix/lang/infix/antlr/EqualityComparisonBaseTreeNode.java | EqualityComparisonBaseTreeNode.getEqualFilter | protected Predicate<Object> getEqualFilter() {
"""
but I can't get ANTLR to generated nested tree with added node.
"""
String xpath = getXPath(getChild(0));
Tree valueNode = getChild(1);
switch(valueNode.getType()){
case NUMBER:
Number value = (Number)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new NumericValuePredicate(value, "="));
case STRING:
String sValue = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new StringValuePredicate(sValue));
case TRUE:
return new PathValueEventFilter(xpath, BooleanValuePredicate.TRUE);
case FALSE:
return new PathValueEventFilter(xpath, BooleanValuePredicate.FALSE);
case NULL:
return new PathValueEventFilter(xpath, NullValuePredicate.INSTANCE);
case XPATH_FUN_NAME:
String aPath = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new XPathValuePredicate(aPath, xpath));
case TIME_MILLIS_FUN_NAME:
TimeMillisValueTreeNode timeNode = (TimeMillisValueTreeNode)valueNode;
return new PathValueEventFilter(xpath,
new TimeMillisValuePredicate(
timeNode.getValueFormat(),
timeNode.getValue(),
"="));
case TIME_STRING_FUN_NAME:
TimeStringValueTreeNode timeStringNode = (TimeStringValueTreeNode)valueNode;
return new PathValueEventFilter(xpath,
new TimeStringValuePredicate(
timeStringNode.getValueTimeFormat(),
timeStringNode.getInputTimeFormat(),
timeStringNode.getValue(),
"="));
default:
throw new UnexpectedTokenException(valueNode, "Number", "String", "TRUE", "FALSE");
}
} | java | protected Predicate<Object> getEqualFilter() {
String xpath = getXPath(getChild(0));
Tree valueNode = getChild(1);
switch(valueNode.getType()){
case NUMBER:
Number value = (Number)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new NumericValuePredicate(value, "="));
case STRING:
String sValue = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new StringValuePredicate(sValue));
case TRUE:
return new PathValueEventFilter(xpath, BooleanValuePredicate.TRUE);
case FALSE:
return new PathValueEventFilter(xpath, BooleanValuePredicate.FALSE);
case NULL:
return new PathValueEventFilter(xpath, NullValuePredicate.INSTANCE);
case XPATH_FUN_NAME:
String aPath = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueEventFilter(xpath, new XPathValuePredicate(aPath, xpath));
case TIME_MILLIS_FUN_NAME:
TimeMillisValueTreeNode timeNode = (TimeMillisValueTreeNode)valueNode;
return new PathValueEventFilter(xpath,
new TimeMillisValuePredicate(
timeNode.getValueFormat(),
timeNode.getValue(),
"="));
case TIME_STRING_FUN_NAME:
TimeStringValueTreeNode timeStringNode = (TimeStringValueTreeNode)valueNode;
return new PathValueEventFilter(xpath,
new TimeStringValuePredicate(
timeStringNode.getValueTimeFormat(),
timeStringNode.getInputTimeFormat(),
timeStringNode.getValue(),
"="));
default:
throw new UnexpectedTokenException(valueNode, "Number", "String", "TRUE", "FALSE");
}
} | [
"protected",
"Predicate",
"<",
"Object",
">",
"getEqualFilter",
"(",
")",
"{",
"String",
"xpath",
"=",
"getXPath",
"(",
"getChild",
"(",
"0",
")",
")",
";",
"Tree",
"valueNode",
"=",
"getChild",
"(",
"1",
")",
";",
"switch",
"(",
"valueNode",
".",
"getType",
"(",
")",
")",
"{",
"case",
"NUMBER",
":",
"Number",
"value",
"=",
"(",
"Number",
")",
"(",
"(",
"ValueTreeNode",
")",
"valueNode",
")",
".",
"getValue",
"(",
")",
";",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"new",
"NumericValuePredicate",
"(",
"value",
",",
"\"=\"",
")",
")",
";",
"case",
"STRING",
":",
"String",
"sValue",
"=",
"(",
"String",
")",
"(",
"(",
"ValueTreeNode",
")",
"valueNode",
")",
".",
"getValue",
"(",
")",
";",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"new",
"StringValuePredicate",
"(",
"sValue",
")",
")",
";",
"case",
"TRUE",
":",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"BooleanValuePredicate",
".",
"TRUE",
")",
";",
"case",
"FALSE",
":",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"BooleanValuePredicate",
".",
"FALSE",
")",
";",
"case",
"NULL",
":",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"NullValuePredicate",
".",
"INSTANCE",
")",
";",
"case",
"XPATH_FUN_NAME",
":",
"String",
"aPath",
"=",
"(",
"String",
")",
"(",
"(",
"ValueTreeNode",
")",
"valueNode",
")",
".",
"getValue",
"(",
")",
";",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"new",
"XPathValuePredicate",
"(",
"aPath",
",",
"xpath",
")",
")",
";",
"case",
"TIME_MILLIS_FUN_NAME",
":",
"TimeMillisValueTreeNode",
"timeNode",
"=",
"(",
"TimeMillisValueTreeNode",
")",
"valueNode",
";",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"new",
"TimeMillisValuePredicate",
"(",
"timeNode",
".",
"getValueFormat",
"(",
")",
",",
"timeNode",
".",
"getValue",
"(",
")",
",",
"\"=\"",
")",
")",
";",
"case",
"TIME_STRING_FUN_NAME",
":",
"TimeStringValueTreeNode",
"timeStringNode",
"=",
"(",
"TimeStringValueTreeNode",
")",
"valueNode",
";",
"return",
"new",
"PathValueEventFilter",
"(",
"xpath",
",",
"new",
"TimeStringValuePredicate",
"(",
"timeStringNode",
".",
"getValueTimeFormat",
"(",
")",
",",
"timeStringNode",
".",
"getInputTimeFormat",
"(",
")",
",",
"timeStringNode",
".",
"getValue",
"(",
")",
",",
"\"=\"",
")",
")",
";",
"default",
":",
"throw",
"new",
"UnexpectedTokenException",
"(",
"valueNode",
",",
"\"Number\"",
",",
"\"String\"",
",",
"\"TRUE\"",
",",
"\"FALSE\"",
")",
";",
"}",
"}"
] | but I can't get ANTLR to generated nested tree with added node. | [
"but",
"I",
"can",
"t",
"get",
"ANTLR",
"to",
"generated",
"nested",
"tree",
"with",
"added",
"node",
"."
] | train | https://github.com/Netflix/netflix-commons/blob/7a158af76906d4a9b753e9344ce3e7abeb91dc01/netflix-infix/src/main/java/com/netflix/infix/lang/infix/antlr/EqualityComparisonBaseTreeNode.java#L24-L63 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java | FileDownloadUtils.deleteDirectory | public static void deleteDirectory(Path dir) throws IOException {
"""
Recursively delete a folder & contents
@param dir directory to delete
"""
if(dir == null || !Files.exists(dir))
return;
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) {
throw e;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} | java | public static void deleteDirectory(Path dir) throws IOException {
if(dir == null || !Files.exists(dir))
return;
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e != null) {
throw e;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} | [
"public",
"static",
"void",
"deleteDirectory",
"(",
"Path",
"dir",
")",
"throws",
"IOException",
"{",
"if",
"(",
"dir",
"==",
"null",
"||",
"!",
"Files",
".",
"exists",
"(",
"dir",
")",
")",
"return",
";",
"Files",
".",
"walkFileTree",
"(",
"dir",
",",
"new",
"SimpleFileVisitor",
"<",
"Path",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"FileVisitResult",
"visitFile",
"(",
"Path",
"file",
",",
"BasicFileAttributes",
"attrs",
")",
"throws",
"IOException",
"{",
"Files",
".",
"delete",
"(",
"file",
")",
";",
"return",
"FileVisitResult",
".",
"CONTINUE",
";",
"}",
"@",
"Override",
"public",
"FileVisitResult",
"postVisitDirectory",
"(",
"Path",
"dir",
",",
"IOException",
"e",
")",
"throws",
"IOException",
"{",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"throw",
"e",
";",
"}",
"Files",
".",
"delete",
"(",
"dir",
")",
";",
"return",
"FileVisitResult",
".",
"CONTINUE",
";",
"}",
"}",
")",
";",
"}"
] | Recursively delete a folder & contents
@param dir directory to delete | [
"Recursively",
"delete",
"a",
"folder",
"&",
"contents"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java#L255-L274 |
phax/ph-web | ph-web/src/main/java/com/helger/web/fileupload/parse/ParameterParser.java | ParameterParser.parse | @Nonnull
@ReturnsMutableCopy
public ICommonsMap <String, String> parse (@Nullable final String sStr, @Nullable final char [] aSeparators) {
"""
Extracts a map of name/value pairs from the given string. Names are
expected to be unique. Multiple separators may be specified and the
earliest found in the input string is used.
@param sStr
the string that contains a sequence of name/value pairs
@param aSeparators
the name/value pairs separators
@return a map of name/value pairs
"""
if (ArrayHelper.isEmpty (aSeparators))
return new CommonsHashMap <> ();
char cSep = aSeparators[0];
if (sStr != null)
{
// Find the first separator to use
int nFirstIndex = sStr.length ();
for (final char cSep2 : aSeparators)
{
final int nCurIndex = sStr.indexOf (cSep2);
if (nCurIndex != -1 && nCurIndex < nFirstIndex)
{
nFirstIndex = nCurIndex;
cSep = cSep2;
}
}
}
return parse (sStr, cSep);
} | java | @Nonnull
@ReturnsMutableCopy
public ICommonsMap <String, String> parse (@Nullable final String sStr, @Nullable final char [] aSeparators)
{
if (ArrayHelper.isEmpty (aSeparators))
return new CommonsHashMap <> ();
char cSep = aSeparators[0];
if (sStr != null)
{
// Find the first separator to use
int nFirstIndex = sStr.length ();
for (final char cSep2 : aSeparators)
{
final int nCurIndex = sStr.indexOf (cSep2);
if (nCurIndex != -1 && nCurIndex < nFirstIndex)
{
nFirstIndex = nCurIndex;
cSep = cSep2;
}
}
}
return parse (sStr, cSep);
} | [
"@",
"Nonnull",
"@",
"ReturnsMutableCopy",
"public",
"ICommonsMap",
"<",
"String",
",",
"String",
">",
"parse",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"@",
"Nullable",
"final",
"char",
"[",
"]",
"aSeparators",
")",
"{",
"if",
"(",
"ArrayHelper",
".",
"isEmpty",
"(",
"aSeparators",
")",
")",
"return",
"new",
"CommonsHashMap",
"<>",
"(",
")",
";",
"char",
"cSep",
"=",
"aSeparators",
"[",
"0",
"]",
";",
"if",
"(",
"sStr",
"!=",
"null",
")",
"{",
"// Find the first separator to use",
"int",
"nFirstIndex",
"=",
"sStr",
".",
"length",
"(",
")",
";",
"for",
"(",
"final",
"char",
"cSep2",
":",
"aSeparators",
")",
"{",
"final",
"int",
"nCurIndex",
"=",
"sStr",
".",
"indexOf",
"(",
"cSep2",
")",
";",
"if",
"(",
"nCurIndex",
"!=",
"-",
"1",
"&&",
"nCurIndex",
"<",
"nFirstIndex",
")",
"{",
"nFirstIndex",
"=",
"nCurIndex",
";",
"cSep",
"=",
"cSep2",
";",
"}",
"}",
"}",
"return",
"parse",
"(",
"sStr",
",",
"cSep",
")",
";",
"}"
] | Extracts a map of name/value pairs from the given string. Names are
expected to be unique. Multiple separators may be specified and the
earliest found in the input string is used.
@param sStr
the string that contains a sequence of name/value pairs
@param aSeparators
the name/value pairs separators
@return a map of name/value pairs | [
"Extracts",
"a",
"map",
"of",
"name",
"/",
"value",
"pairs",
"from",
"the",
"given",
"string",
".",
"Names",
"are",
"expected",
"to",
"be",
"unique",
".",
"Multiple",
"separators",
"may",
"be",
"specified",
"and",
"the",
"earliest",
"found",
"in",
"the",
"input",
"string",
"is",
"used",
"."
] | train | https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/fileupload/parse/ParameterParser.java#L231-L254 |
xcesco/kripton | kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java | XMLSerializer.addPrintable | private static void addPrintable(StringBuffer retval, char ch) {
"""
Adds the printable.
@param retval the retval
@param ch the ch
"""
switch (ch) {
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
final String ss = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + ss.substring(ss.length() - 4, ss.length()));
} else {
retval.append(ch);
}
}
} | java | private static void addPrintable(StringBuffer retval, char ch) {
switch (ch) {
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
final String ss = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + ss.substring(ss.length() - 4, ss.length()));
} else {
retval.append(ch);
}
}
} | [
"private",
"static",
"void",
"addPrintable",
"(",
"StringBuffer",
"retval",
",",
"char",
"ch",
")",
"{",
"switch",
"(",
"ch",
")",
"{",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\b\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\t\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\n\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\f\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\r\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\\\\"\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\\\'\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"retval",
".",
"append",
"(",
"\"\\\\\\\\\"",
")",
";",
"break",
";",
"default",
":",
"if",
"(",
"ch",
"<",
"0x20",
"||",
"ch",
">",
"0x7e",
")",
"{",
"final",
"String",
"ss",
"=",
"\"0000\"",
"+",
"Integer",
".",
"toString",
"(",
"ch",
",",
"16",
")",
";",
"retval",
".",
"append",
"(",
"\"\\\\u\"",
"+",
"ss",
".",
"substring",
"(",
"ss",
".",
"length",
"(",
")",
"-",
"4",
",",
"ss",
".",
"length",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"retval",
".",
"append",
"(",
"ch",
")",
";",
"}",
"}",
"}"
] | Adds the printable.
@param retval the retval
@param ch the ch | [
"Adds",
"the",
"printable",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java#L1457-L1491 |
zxing/zxing | core/src/main/java/com/google/zxing/aztec/detector/Detector.java | Detector.extractParameters | private void extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException {
"""
Extracts the number of data layers and data blocks from the layer around the bull's eye.
@param bullsEyeCorners the array of bull's eye corners
@throws NotFoundException in case of too many errors or invalid parameters
"""
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3])) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides = {
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
} | java | private void extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException {
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3])) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides = {
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
} | [
"private",
"void",
"extractParameters",
"(",
"ResultPoint",
"[",
"]",
"bullsEyeCorners",
")",
"throws",
"NotFoundException",
"{",
"if",
"(",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"0",
"]",
")",
"||",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"1",
"]",
")",
"||",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"2",
"]",
")",
"||",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"3",
"]",
")",
")",
"{",
"throw",
"NotFoundException",
".",
"getNotFoundInstance",
"(",
")",
";",
"}",
"int",
"length",
"=",
"2",
"*",
"nbCenterLayers",
";",
"// Get the bits around the bull's eye",
"int",
"[",
"]",
"sides",
"=",
"{",
"sampleLine",
"(",
"bullsEyeCorners",
"[",
"0",
"]",
",",
"bullsEyeCorners",
"[",
"1",
"]",
",",
"length",
")",
",",
"// Right side",
"sampleLine",
"(",
"bullsEyeCorners",
"[",
"1",
"]",
",",
"bullsEyeCorners",
"[",
"2",
"]",
",",
"length",
")",
",",
"// Bottom",
"sampleLine",
"(",
"bullsEyeCorners",
"[",
"2",
"]",
",",
"bullsEyeCorners",
"[",
"3",
"]",
",",
"length",
")",
",",
"// Left side",
"sampleLine",
"(",
"bullsEyeCorners",
"[",
"3",
"]",
",",
"bullsEyeCorners",
"[",
"0",
"]",
",",
"length",
")",
"// Top",
"}",
";",
"// bullsEyeCorners[shift] is the corner of the bulls'eye that has three",
"// orientation marks.",
"// sides[shift] is the row/column that goes from the corner with three",
"// orientation marks to the corner with two.",
"shift",
"=",
"getRotation",
"(",
"sides",
",",
"length",
")",
";",
"// Flatten the parameter bits into a single 28- or 40-bit long",
"long",
"parameterData",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"int",
"side",
"=",
"sides",
"[",
"(",
"shift",
"+",
"i",
")",
"%",
"4",
"]",
";",
"if",
"(",
"compact",
")",
"{",
"// Each side of the form ..XXXXXXX. where Xs are parameter data",
"parameterData",
"<<=",
"7",
";",
"parameterData",
"+=",
"(",
"side",
">>",
"1",
")",
"&",
"0x7F",
";",
"}",
"else",
"{",
"// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data",
"parameterData",
"<<=",
"10",
";",
"parameterData",
"+=",
"(",
"(",
"side",
">>",
"2",
")",
"&",
"(",
"0x1f",
"<<",
"5",
")",
")",
"+",
"(",
"(",
"side",
">>",
"1",
")",
"&",
"0x1F",
")",
";",
"}",
"}",
"// Corrects parameter data using RS. Returns just the data portion",
"// without the error correction.",
"int",
"correctedData",
"=",
"getCorrectedParameterData",
"(",
"parameterData",
",",
"compact",
")",
";",
"if",
"(",
"compact",
")",
"{",
"// 8 bits: 2 bits layers and 6 bits data blocks",
"nbLayers",
"=",
"(",
"correctedData",
">>",
"6",
")",
"+",
"1",
";",
"nbDataBlocks",
"=",
"(",
"correctedData",
"&",
"0x3F",
")",
"+",
"1",
";",
"}",
"else",
"{",
"// 16 bits: 5 bits layers and 11 bits data blocks",
"nbLayers",
"=",
"(",
"correctedData",
">>",
"11",
")",
"+",
"1",
";",
"nbDataBlocks",
"=",
"(",
"correctedData",
"&",
"0x7FF",
")",
"+",
"1",
";",
"}",
"}"
] | Extracts the number of data layers and data blocks from the layer around the bull's eye.
@param bullsEyeCorners the array of bull's eye corners
@throws NotFoundException in case of too many errors or invalid parameters | [
"Extracts",
"the",
"number",
"of",
"data",
"layers",
"and",
"data",
"blocks",
"from",
"the",
"layer",
"around",
"the",
"bull",
"s",
"eye",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/aztec/detector/Detector.java#L106-L154 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java | NodeSSHConnectionInfo.resolveLongFwk | private long resolveLongFwk(final String key, final String frameworkProp, final long defval) {
"""
Look for a node/project/framework config property of the given key, and if not found
fallback to a framework property, return parsed long or the default
@param key key for node attribute/project/framework property
@param frameworkProp fallback framework property
@param defval default value
@return parsed value or default
"""
long timeout = defval;
String opt = resolve(key);
if (opt == null && frameworkProp != null && framework.getPropertyLookup().hasProperty(frameworkProp)) {
opt = framework.getProperty(frameworkProp);
}
if (opt != null) {
try {
timeout = Long.parseLong(opt);
} catch (NumberFormatException ignored) {
}
}
return timeout;
} | java | private long resolveLongFwk(final String key, final String frameworkProp, final long defval) {
long timeout = defval;
String opt = resolve(key);
if (opt == null && frameworkProp != null && framework.getPropertyLookup().hasProperty(frameworkProp)) {
opt = framework.getProperty(frameworkProp);
}
if (opt != null) {
try {
timeout = Long.parseLong(opt);
} catch (NumberFormatException ignored) {
}
}
return timeout;
} | [
"private",
"long",
"resolveLongFwk",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"frameworkProp",
",",
"final",
"long",
"defval",
")",
"{",
"long",
"timeout",
"=",
"defval",
";",
"String",
"opt",
"=",
"resolve",
"(",
"key",
")",
";",
"if",
"(",
"opt",
"==",
"null",
"&&",
"frameworkProp",
"!=",
"null",
"&&",
"framework",
".",
"getPropertyLookup",
"(",
")",
".",
"hasProperty",
"(",
"frameworkProp",
")",
")",
"{",
"opt",
"=",
"framework",
".",
"getProperty",
"(",
"frameworkProp",
")",
";",
"}",
"if",
"(",
"opt",
"!=",
"null",
")",
"{",
"try",
"{",
"timeout",
"=",
"Long",
".",
"parseLong",
"(",
"opt",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"ignored",
")",
"{",
"}",
"}",
"return",
"timeout",
";",
"}"
] | Look for a node/project/framework config property of the given key, and if not found
fallback to a framework property, return parsed long or the default
@param key key for node attribute/project/framework property
@param frameworkProp fallback framework property
@param defval default value
@return parsed value or default | [
"Look",
"for",
"a",
"node",
"/",
"project",
"/",
"framework",
"config",
"property",
"of",
"the",
"given",
"key",
"and",
"if",
"not",
"found",
"fallback",
"to",
"a",
"framework",
"property",
"return",
"parsed",
"long",
"or",
"the",
"default"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/impl/jsch/NodeSSHConnectionInfo.java#L252-L265 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java | HttpHeaders.addIntHeader | @Deprecated
public static void addIntHeader(HttpMessage message, CharSequence name, int value) {
"""
@deprecated Use {@link #addInt(CharSequence, int)} instead.
Adds a new integer header with the specified name and value.
"""
message.headers().addInt(name, value);
} | java | @Deprecated
public static void addIntHeader(HttpMessage message, CharSequence name, int value) {
message.headers().addInt(name, value);
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"addIntHeader",
"(",
"HttpMessage",
"message",
",",
"CharSequence",
"name",
",",
"int",
"value",
")",
"{",
"message",
".",
"headers",
"(",
")",
".",
"addInt",
"(",
"name",
",",
"value",
")",
";",
"}"
] | @deprecated Use {@link #addInt(CharSequence, int)} instead.
Adds a new integer header with the specified name and value. | [
"@deprecated",
"Use",
"{",
"@link",
"#addInt",
"(",
"CharSequence",
"int",
")",
"}",
"instead",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L816-L819 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.setCMYKColorStrokeF | public void setCMYKColorStrokeF(float cyan, float magenta, float yellow, float black) {
"""
Changes the current color for stroking paths (device dependent colors!).
<P>
Sets the color space to <B>DeviceCMYK</B> (or the <B>DefaultCMYK</B> color space),
and sets the color to use for stroking paths.</P>
<P>
Following the PDF manual, each operand must be a number between 0 (miniumum intensity) and
1 (maximum intensity).
@param cyan the intensity of cyan. A value between 0 and 1
@param magenta the intensity of magenta. A value between 0 and 1
@param yellow the intensity of yellow. A value between 0 and 1
@param black the intensity of black. A value between 0 and 1
"""
HelperCMYK(cyan, magenta, yellow, black);
content.append(" K").append_i(separator);
} | java | public void setCMYKColorStrokeF(float cyan, float magenta, float yellow, float black) {
HelperCMYK(cyan, magenta, yellow, black);
content.append(" K").append_i(separator);
} | [
"public",
"void",
"setCMYKColorStrokeF",
"(",
"float",
"cyan",
",",
"float",
"magenta",
",",
"float",
"yellow",
",",
"float",
"black",
")",
"{",
"HelperCMYK",
"(",
"cyan",
",",
"magenta",
",",
"yellow",
",",
"black",
")",
";",
"content",
".",
"append",
"(",
"\" K\"",
")",
".",
"append_i",
"(",
"separator",
")",
";",
"}"
] | Changes the current color for stroking paths (device dependent colors!).
<P>
Sets the color space to <B>DeviceCMYK</B> (or the <B>DefaultCMYK</B> color space),
and sets the color to use for stroking paths.</P>
<P>
Following the PDF manual, each operand must be a number between 0 (miniumum intensity) and
1 (maximum intensity).
@param cyan the intensity of cyan. A value between 0 and 1
@param magenta the intensity of magenta. A value between 0 and 1
@param yellow the intensity of yellow. A value between 0 and 1
@param black the intensity of black. A value between 0 and 1 | [
"Changes",
"the",
"current",
"color",
"for",
"stroking",
"paths",
"(",
"device",
"dependent",
"colors!",
")",
".",
"<P",
">",
"Sets",
"the",
"color",
"space",
"to",
"<B",
">",
"DeviceCMYK<",
"/",
"B",
">",
"(",
"or",
"the",
"<B",
">",
"DefaultCMYK<",
"/",
"B",
">",
"color",
"space",
")",
"and",
"sets",
"the",
"color",
"to",
"use",
"for",
"stroking",
"paths",
".",
"<",
"/",
"P",
">",
"<P",
">",
"Following",
"the",
"PDF",
"manual",
"each",
"operand",
"must",
"be",
"a",
"number",
"between",
"0",
"(",
"miniumum",
"intensity",
")",
"and",
"1",
"(",
"maximum",
"intensity",
")",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L681-L684 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassRootPaneUI.java | SeaGlassRootPaneUI.setTitlePane | private void setTitlePane(JRootPane root, JComponent titlePane) {
"""
Sets the window title pane -- the JComponent used to provide a plaf a way
to override the native operating system's window title pane with one
whose look and feel are controlled by the plaf. The plaf creates and sets
this value; the default is null, implying a native operating system
window title pane.
@param root content the <code>JComponent</code> to use for the
window title pane.
@param titlePane the SeaGlassTitlePane.
"""
JLayeredPane layeredPane = root.getLayeredPane();
JComponent oldTitlePane = getTitlePane();
if (oldTitlePane != null) {
oldTitlePane.setVisible(false);
layeredPane.remove(oldTitlePane);
}
if (titlePane != null) {
layeredPane.add(titlePane, JLayeredPane.FRAME_CONTENT_LAYER);
titlePane.setVisible(true);
}
this.titlePane = titlePane;
} | java | private void setTitlePane(JRootPane root, JComponent titlePane) {
JLayeredPane layeredPane = root.getLayeredPane();
JComponent oldTitlePane = getTitlePane();
if (oldTitlePane != null) {
oldTitlePane.setVisible(false);
layeredPane.remove(oldTitlePane);
}
if (titlePane != null) {
layeredPane.add(titlePane, JLayeredPane.FRAME_CONTENT_LAYER);
titlePane.setVisible(true);
}
this.titlePane = titlePane;
} | [
"private",
"void",
"setTitlePane",
"(",
"JRootPane",
"root",
",",
"JComponent",
"titlePane",
")",
"{",
"JLayeredPane",
"layeredPane",
"=",
"root",
".",
"getLayeredPane",
"(",
")",
";",
"JComponent",
"oldTitlePane",
"=",
"getTitlePane",
"(",
")",
";",
"if",
"(",
"oldTitlePane",
"!=",
"null",
")",
"{",
"oldTitlePane",
".",
"setVisible",
"(",
"false",
")",
";",
"layeredPane",
".",
"remove",
"(",
"oldTitlePane",
")",
";",
"}",
"if",
"(",
"titlePane",
"!=",
"null",
")",
"{",
"layeredPane",
".",
"add",
"(",
"titlePane",
",",
"JLayeredPane",
".",
"FRAME_CONTENT_LAYER",
")",
";",
"titlePane",
".",
"setVisible",
"(",
"true",
")",
";",
"}",
"this",
".",
"titlePane",
"=",
"titlePane",
";",
"}"
] | Sets the window title pane -- the JComponent used to provide a plaf a way
to override the native operating system's window title pane with one
whose look and feel are controlled by the plaf. The plaf creates and sets
this value; the default is null, implying a native operating system
window title pane.
@param root content the <code>JComponent</code> to use for the
window title pane.
@param titlePane the SeaGlassTitlePane. | [
"Sets",
"the",
"window",
"title",
"pane",
"--",
"the",
"JComponent",
"used",
"to",
"provide",
"a",
"plaf",
"a",
"way",
"to",
"override",
"the",
"native",
"operating",
"system",
"s",
"window",
"title",
"pane",
"with",
"one",
"whose",
"look",
"and",
"feel",
"are",
"controlled",
"by",
"the",
"plaf",
".",
"The",
"plaf",
"creates",
"and",
"sets",
"this",
"value",
";",
"the",
"default",
"is",
"null",
"implying",
"a",
"native",
"operating",
"system",
"window",
"title",
"pane",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassRootPaneUI.java#L572-L587 |
lightbend/config | config/src/main/java/com/typesafe/config/ConfigFactory.java | ConfigFactory.parseResources | public static Config parseResources(ClassLoader loader, String resource) {
"""
Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but always uses
default parse options.
@param loader
will be used to load resources
@param resource
resource to look up in the loader
@return the parsed configuration
"""
return parseResources(loader, resource, ConfigParseOptions.defaults());
} | java | public static Config parseResources(ClassLoader loader, String resource) {
return parseResources(loader, resource, ConfigParseOptions.defaults());
} | [
"public",
"static",
"Config",
"parseResources",
"(",
"ClassLoader",
"loader",
",",
"String",
"resource",
")",
"{",
"return",
"parseResources",
"(",
"loader",
",",
"resource",
",",
"ConfigParseOptions",
".",
"defaults",
"(",
")",
")",
";",
"}"
] | Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but always uses
default parse options.
@param loader
will be used to load resources
@param resource
resource to look up in the loader
@return the parsed configuration | [
"Like",
"{",
"@link",
"#parseResources",
"(",
"ClassLoader",
"String",
"ConfigParseOptions",
")",
"}",
"but",
"always",
"uses",
"default",
"parse",
"options",
"."
] | train | https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/ConfigFactory.java#L948-L950 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java | StyleUtils.setFeatureStyle | public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyle featureStyle, float density, IconCache iconCache) {
"""
Set the feature style (icon or style) into the marker options
@param markerOptions marker options
@param featureStyle feature style
@param density display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return true if icon or style was set into the marker options
"""
boolean featureStyleSet = false;
if (featureStyle != null) {
featureStyleSet = setIcon(markerOptions, featureStyle.getIcon(), density, iconCache);
if (!featureStyleSet) {
featureStyleSet = setStyle(markerOptions, featureStyle.getStyle());
}
}
return featureStyleSet;
} | java | public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyle featureStyle, float density, IconCache iconCache) {
boolean featureStyleSet = false;
if (featureStyle != null) {
featureStyleSet = setIcon(markerOptions, featureStyle.getIcon(), density, iconCache);
if (!featureStyleSet) {
featureStyleSet = setStyle(markerOptions, featureStyle.getStyle());
}
}
return featureStyleSet;
} | [
"public",
"static",
"boolean",
"setFeatureStyle",
"(",
"MarkerOptions",
"markerOptions",
",",
"FeatureStyle",
"featureStyle",
",",
"float",
"density",
",",
"IconCache",
"iconCache",
")",
"{",
"boolean",
"featureStyleSet",
"=",
"false",
";",
"if",
"(",
"featureStyle",
"!=",
"null",
")",
"{",
"featureStyleSet",
"=",
"setIcon",
"(",
"markerOptions",
",",
"featureStyle",
".",
"getIcon",
"(",
")",
",",
"density",
",",
"iconCache",
")",
";",
"if",
"(",
"!",
"featureStyleSet",
")",
"{",
"featureStyleSet",
"=",
"setStyle",
"(",
"markerOptions",
",",
"featureStyle",
".",
"getStyle",
"(",
")",
")",
";",
"}",
"}",
"return",
"featureStyleSet",
";",
"}"
] | Set the feature style (icon or style) into the marker options
@param markerOptions marker options
@param featureStyle feature style
@param density display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return true if icon or style was set into the marker options | [
"Set",
"the",
"feature",
"style",
"(",
"icon",
"or",
"style",
")",
"into",
"the",
"marker",
"options"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L197-L214 |
openengsb/openengsb | components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/PersistInterfaceService.java | PersistInterfaceService.performRevertLogic | private void performRevertLogic(String revision, UUID expectedContextHeadRevision, boolean expectedHeadCheck) {
"""
Performs the actual revert logic including the context locking and the context head revision check if desired.
"""
String contextId = "";
try {
EDBCommit commit = edbService.getCommitByRevision(revision);
contextId = commit.getContextId();
lockContext(contextId);
if (expectedHeadCheck) {
checkForContextHeadRevision(contextId, expectedContextHeadRevision);
}
EDBCommit newCommit = edbService.createEDBCommit(new ArrayList<EDBObject>(),
new ArrayList<EDBObject>(), new ArrayList<EDBObject>());
for (EDBObject reverted : commit.getObjects()) {
// need to be done in order to avoid problems with conflict detection
reverted.remove(EDBConstants.MODEL_VERSION);
newCommit.update(reverted);
}
for (String delete : commit.getDeletions()) {
newCommit.delete(delete);
}
newCommit.setComment(String.format("revert [%s] %s", commit.getRevisionNumber().toString(),
commit.getComment() != null ? commit.getComment() : ""));
edbService.commit(newCommit);
} catch (EDBException e) {
throw new EKBException("Unable to revert to the given revision " + revision, e);
} finally {
releaseContext(contextId);
}
} | java | private void performRevertLogic(String revision, UUID expectedContextHeadRevision, boolean expectedHeadCheck) {
String contextId = "";
try {
EDBCommit commit = edbService.getCommitByRevision(revision);
contextId = commit.getContextId();
lockContext(contextId);
if (expectedHeadCheck) {
checkForContextHeadRevision(contextId, expectedContextHeadRevision);
}
EDBCommit newCommit = edbService.createEDBCommit(new ArrayList<EDBObject>(),
new ArrayList<EDBObject>(), new ArrayList<EDBObject>());
for (EDBObject reverted : commit.getObjects()) {
// need to be done in order to avoid problems with conflict detection
reverted.remove(EDBConstants.MODEL_VERSION);
newCommit.update(reverted);
}
for (String delete : commit.getDeletions()) {
newCommit.delete(delete);
}
newCommit.setComment(String.format("revert [%s] %s", commit.getRevisionNumber().toString(),
commit.getComment() != null ? commit.getComment() : ""));
edbService.commit(newCommit);
} catch (EDBException e) {
throw new EKBException("Unable to revert to the given revision " + revision, e);
} finally {
releaseContext(contextId);
}
} | [
"private",
"void",
"performRevertLogic",
"(",
"String",
"revision",
",",
"UUID",
"expectedContextHeadRevision",
",",
"boolean",
"expectedHeadCheck",
")",
"{",
"String",
"contextId",
"=",
"\"\"",
";",
"try",
"{",
"EDBCommit",
"commit",
"=",
"edbService",
".",
"getCommitByRevision",
"(",
"revision",
")",
";",
"contextId",
"=",
"commit",
".",
"getContextId",
"(",
")",
";",
"lockContext",
"(",
"contextId",
")",
";",
"if",
"(",
"expectedHeadCheck",
")",
"{",
"checkForContextHeadRevision",
"(",
"contextId",
",",
"expectedContextHeadRevision",
")",
";",
"}",
"EDBCommit",
"newCommit",
"=",
"edbService",
".",
"createEDBCommit",
"(",
"new",
"ArrayList",
"<",
"EDBObject",
">",
"(",
")",
",",
"new",
"ArrayList",
"<",
"EDBObject",
">",
"(",
")",
",",
"new",
"ArrayList",
"<",
"EDBObject",
">",
"(",
")",
")",
";",
"for",
"(",
"EDBObject",
"reverted",
":",
"commit",
".",
"getObjects",
"(",
")",
")",
"{",
"// need to be done in order to avoid problems with conflict detection",
"reverted",
".",
"remove",
"(",
"EDBConstants",
".",
"MODEL_VERSION",
")",
";",
"newCommit",
".",
"update",
"(",
"reverted",
")",
";",
"}",
"for",
"(",
"String",
"delete",
":",
"commit",
".",
"getDeletions",
"(",
")",
")",
"{",
"newCommit",
".",
"delete",
"(",
"delete",
")",
";",
"}",
"newCommit",
".",
"setComment",
"(",
"String",
".",
"format",
"(",
"\"revert [%s] %s\"",
",",
"commit",
".",
"getRevisionNumber",
"(",
")",
".",
"toString",
"(",
")",
",",
"commit",
".",
"getComment",
"(",
")",
"!=",
"null",
"?",
"commit",
".",
"getComment",
"(",
")",
":",
"\"\"",
")",
")",
";",
"edbService",
".",
"commit",
"(",
"newCommit",
")",
";",
"}",
"catch",
"(",
"EDBException",
"e",
")",
"{",
"throw",
"new",
"EKBException",
"(",
"\"Unable to revert to the given revision \"",
"+",
"revision",
",",
"e",
")",
";",
"}",
"finally",
"{",
"releaseContext",
"(",
"contextId",
")",
";",
"}",
"}"
] | Performs the actual revert logic including the context locking and the context head revision check if desired. | [
"Performs",
"the",
"actual",
"revert",
"logic",
"including",
"the",
"context",
"locking",
"and",
"the",
"context",
"head",
"revision",
"check",
"if",
"desired",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/PersistInterfaceService.java#L168-L195 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jaspic/src/com/ibm/ws/security/jaspi/JaspiServiceImpl.java | JaspiServiceImpl.isAnyProviderRegistered | @Override
public boolean isAnyProviderRegistered(WebRequest webRequest) {
"""
/*
This is for performance - so we will not call jaspi processing for a request
if there are no providers registered.
@see com.ibm.ws.webcontainer.security.JaspiService#isAnyProviderRegistered()
"""
// default to true for case where a custom factory is used (i.e. not our ProviderRegistry)
// we will assume that some provider is registered so we will call jaspi to
// process the request.
boolean result = true;
AuthConfigFactory providerFactory = getAuthConfigFactory();
BridgeBuilderService bridgeBuilderService = bridgeBuilderServiceRef.getService();
if (bridgeBuilderService != null) {
JaspiRequest jaspiRequest = new JaspiRequest(webRequest, null); //TODO: Some paths have a WebAppConfig that should be taken into accounnt when getting the appContext
String appContext = jaspiRequest.getAppContext();
bridgeBuilderService.buildBridgeIfNeeded(appContext, providerFactory);
}
if (providerFactory != null && providerFactory instanceof ProviderRegistry) {
// if the user defined feature provider came or went, process that 1st
if (providerConfigModified) {
((ProviderRegistry) providerFactory).setProvider(jaspiProviderServiceRef.getService());
}
providerConfigModified = false;
result = ((ProviderRegistry) providerFactory).isAnyProviderRegistered();
}
return result;
} | java | @Override
public boolean isAnyProviderRegistered(WebRequest webRequest) {
// default to true for case where a custom factory is used (i.e. not our ProviderRegistry)
// we will assume that some provider is registered so we will call jaspi to
// process the request.
boolean result = true;
AuthConfigFactory providerFactory = getAuthConfigFactory();
BridgeBuilderService bridgeBuilderService = bridgeBuilderServiceRef.getService();
if (bridgeBuilderService != null) {
JaspiRequest jaspiRequest = new JaspiRequest(webRequest, null); //TODO: Some paths have a WebAppConfig that should be taken into accounnt when getting the appContext
String appContext = jaspiRequest.getAppContext();
bridgeBuilderService.buildBridgeIfNeeded(appContext, providerFactory);
}
if (providerFactory != null && providerFactory instanceof ProviderRegistry) {
// if the user defined feature provider came or went, process that 1st
if (providerConfigModified) {
((ProviderRegistry) providerFactory).setProvider(jaspiProviderServiceRef.getService());
}
providerConfigModified = false;
result = ((ProviderRegistry) providerFactory).isAnyProviderRegistered();
}
return result;
} | [
"@",
"Override",
"public",
"boolean",
"isAnyProviderRegistered",
"(",
"WebRequest",
"webRequest",
")",
"{",
"// default to true for case where a custom factory is used (i.e. not our ProviderRegistry)",
"// we will assume that some provider is registered so we will call jaspi to",
"// process the request.",
"boolean",
"result",
"=",
"true",
";",
"AuthConfigFactory",
"providerFactory",
"=",
"getAuthConfigFactory",
"(",
")",
";",
"BridgeBuilderService",
"bridgeBuilderService",
"=",
"bridgeBuilderServiceRef",
".",
"getService",
"(",
")",
";",
"if",
"(",
"bridgeBuilderService",
"!=",
"null",
")",
"{",
"JaspiRequest",
"jaspiRequest",
"=",
"new",
"JaspiRequest",
"(",
"webRequest",
",",
"null",
")",
";",
"//TODO: Some paths have a WebAppConfig that should be taken into accounnt when getting the appContext",
"String",
"appContext",
"=",
"jaspiRequest",
".",
"getAppContext",
"(",
")",
";",
"bridgeBuilderService",
".",
"buildBridgeIfNeeded",
"(",
"appContext",
",",
"providerFactory",
")",
";",
"}",
"if",
"(",
"providerFactory",
"!=",
"null",
"&&",
"providerFactory",
"instanceof",
"ProviderRegistry",
")",
"{",
"// if the user defined feature provider came or went, process that 1st",
"if",
"(",
"providerConfigModified",
")",
"{",
"(",
"(",
"ProviderRegistry",
")",
"providerFactory",
")",
".",
"setProvider",
"(",
"jaspiProviderServiceRef",
".",
"getService",
"(",
")",
")",
";",
"}",
"providerConfigModified",
"=",
"false",
";",
"result",
"=",
"(",
"(",
"ProviderRegistry",
")",
"providerFactory",
")",
".",
"isAnyProviderRegistered",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
] | /*
This is for performance - so we will not call jaspi processing for a request
if there are no providers registered.
@see com.ibm.ws.webcontainer.security.JaspiService#isAnyProviderRegistered() | [
"/",
"*",
"This",
"is",
"for",
"performance",
"-",
"so",
"we",
"will",
"not",
"call",
"jaspi",
"processing",
"for",
"a",
"request",
"if",
"there",
"are",
"no",
"providers",
"registered",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jaspic/src/com/ibm/ws/security/jaspi/JaspiServiceImpl.java#L1080-L1103 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findIndexOf | public static int findIndexOf(Object self, int startIndex, Closure condition) {
"""
Iterates over the elements of an aggregate of items, starting from a
specified startIndex, and returns the index of the first item that matches the
condition specified in the closure.
@param self the iteration object over which to iterate
@param startIndex start matching from this index
@param condition the matching condition
@return an integer that is the index of the first matched object or -1 if no match was found
@since 1.5.0
"""
return findIndexOf(InvokerHelper.asIterator(self), condition);
} | java | public static int findIndexOf(Object self, int startIndex, Closure condition) {
return findIndexOf(InvokerHelper.asIterator(self), condition);
} | [
"public",
"static",
"int",
"findIndexOf",
"(",
"Object",
"self",
",",
"int",
"startIndex",
",",
"Closure",
"condition",
")",
"{",
"return",
"findIndexOf",
"(",
"InvokerHelper",
".",
"asIterator",
"(",
"self",
")",
",",
"condition",
")",
";",
"}"
] | Iterates over the elements of an aggregate of items, starting from a
specified startIndex, and returns the index of the first item that matches the
condition specified in the closure.
@param self the iteration object over which to iterate
@param startIndex start matching from this index
@param condition the matching condition
@return an integer that is the index of the first matched object or -1 if no match was found
@since 1.5.0 | [
"Iterates",
"over",
"the",
"elements",
"of",
"an",
"aggregate",
"of",
"items",
"starting",
"from",
"a",
"specified",
"startIndex",
"and",
"returns",
"the",
"index",
"of",
"the",
"first",
"item",
"that",
"matches",
"the",
"condition",
"specified",
"in",
"the",
"closure",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L16709-L16711 |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/endpoint/JmsSyncConsumer.java | JmsSyncConsumer.saveReplyDestination | public void saveReplyDestination(JmsMessage jmsMessage, TestContext context) {
"""
Store the reply destination either straight forward or with a given
message correlation key.
@param jmsMessage
@param context
"""
if (jmsMessage.getReplyTo() != null) {
String correlationKeyName = endpointConfiguration.getCorrelator().getCorrelationKeyName(getName());
String correlationKey = endpointConfiguration.getCorrelator().getCorrelationKey(jmsMessage);
correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);
correlationManager.store(correlationKey, jmsMessage.getReplyTo());
} else {
log.warn("Unable to retrieve reply to destination for message \n" +
jmsMessage + "\n - no reply to destination found in message headers!");
}
} | java | public void saveReplyDestination(JmsMessage jmsMessage, TestContext context) {
if (jmsMessage.getReplyTo() != null) {
String correlationKeyName = endpointConfiguration.getCorrelator().getCorrelationKeyName(getName());
String correlationKey = endpointConfiguration.getCorrelator().getCorrelationKey(jmsMessage);
correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);
correlationManager.store(correlationKey, jmsMessage.getReplyTo());
} else {
log.warn("Unable to retrieve reply to destination for message \n" +
jmsMessage + "\n - no reply to destination found in message headers!");
}
} | [
"public",
"void",
"saveReplyDestination",
"(",
"JmsMessage",
"jmsMessage",
",",
"TestContext",
"context",
")",
"{",
"if",
"(",
"jmsMessage",
".",
"getReplyTo",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"correlationKeyName",
"=",
"endpointConfiguration",
".",
"getCorrelator",
"(",
")",
".",
"getCorrelationKeyName",
"(",
"getName",
"(",
")",
")",
";",
"String",
"correlationKey",
"=",
"endpointConfiguration",
".",
"getCorrelator",
"(",
")",
".",
"getCorrelationKey",
"(",
"jmsMessage",
")",
";",
"correlationManager",
".",
"saveCorrelationKey",
"(",
"correlationKeyName",
",",
"correlationKey",
",",
"context",
")",
";",
"correlationManager",
".",
"store",
"(",
"correlationKey",
",",
"jmsMessage",
".",
"getReplyTo",
"(",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"warn",
"(",
"\"Unable to retrieve reply to destination for message \\n\"",
"+",
"jmsMessage",
"+",
"\"\\n - no reply to destination found in message headers!\"",
")",
";",
"}",
"}"
] | Store the reply destination either straight forward or with a given
message correlation key.
@param jmsMessage
@param context | [
"Store",
"the",
"reply",
"destination",
"either",
"straight",
"forward",
"or",
"with",
"a",
"given",
"message",
"correlation",
"key",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/endpoint/JmsSyncConsumer.java#L105-L115 |
abel533/Mapper | core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java | SqlHelper.updateTable | public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) {
"""
update tableName - 动态表名
@param entityClass
@param defaultTableName 默认表名
@param entityName 别名
@return
"""
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ");
sql.append(getDynamicTableName(entityClass, defaultTableName, entityName));
sql.append(" ");
return sql.toString();
} | java | public static String updateTable(Class<?> entityClass, String defaultTableName, String entityName) {
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ");
sql.append(getDynamicTableName(entityClass, defaultTableName, entityName));
sql.append(" ");
return sql.toString();
} | [
"public",
"static",
"String",
"updateTable",
"(",
"Class",
"<",
"?",
">",
"entityClass",
",",
"String",
"defaultTableName",
",",
"String",
"entityName",
")",
"{",
"StringBuilder",
"sql",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sql",
".",
"append",
"(",
"\"UPDATE \"",
")",
";",
"sql",
".",
"append",
"(",
"getDynamicTableName",
"(",
"entityClass",
",",
"defaultTableName",
",",
"entityName",
")",
")",
";",
"sql",
".",
"append",
"(",
"\" \"",
")",
";",
"return",
"sql",
".",
"toString",
"(",
")",
";",
"}"
] | update tableName - 动态表名
@param entityClass
@param defaultTableName 默认表名
@param entityName 别名
@return | [
"update",
"tableName",
"-",
"动态表名"
] | train | https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java#L339-L345 |
stephanenicolas/toothpick | toothpick-compiler/src/main/java/toothpick/compiler/common/ToothpickProcessor.java | ToothpickProcessor.hasWarningSuppressed | protected boolean hasWarningSuppressed(Element element, String warningSuppressString) {
"""
Checks if {@code element} has a @SuppressWarning("{@code warningSuppressString}")
annotation.
@param element the element to check if the warning is suppressed.
@param warningSuppressString the value of the SuppressWarning annotation.
@return true is the injectable warning is suppressed, false otherwise.
"""
SuppressWarnings suppressWarnings = element.getAnnotation(SuppressWarnings.class);
if (suppressWarnings != null) {
for (String value : suppressWarnings.value()) {
if (value.equalsIgnoreCase(warningSuppressString)) {
return true;
}
}
}
return false;
} | java | protected boolean hasWarningSuppressed(Element element, String warningSuppressString) {
SuppressWarnings suppressWarnings = element.getAnnotation(SuppressWarnings.class);
if (suppressWarnings != null) {
for (String value : suppressWarnings.value()) {
if (value.equalsIgnoreCase(warningSuppressString)) {
return true;
}
}
}
return false;
} | [
"protected",
"boolean",
"hasWarningSuppressed",
"(",
"Element",
"element",
",",
"String",
"warningSuppressString",
")",
"{",
"SuppressWarnings",
"suppressWarnings",
"=",
"element",
".",
"getAnnotation",
"(",
"SuppressWarnings",
".",
"class",
")",
";",
"if",
"(",
"suppressWarnings",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"value",
":",
"suppressWarnings",
".",
"value",
"(",
")",
")",
"{",
"if",
"(",
"value",
".",
"equalsIgnoreCase",
"(",
"warningSuppressString",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks if {@code element} has a @SuppressWarning("{@code warningSuppressString}")
annotation.
@param element the element to check if the warning is suppressed.
@param warningSuppressString the value of the SuppressWarning annotation.
@return true is the injectable warning is suppressed, false otherwise. | [
"Checks",
"if",
"{",
"@code",
"element",
"}",
"has",
"a",
"@SuppressWarning",
"(",
"{",
"@code",
"warningSuppressString",
"}",
")",
"annotation",
"."
] | train | https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-compiler/src/main/java/toothpick/compiler/common/ToothpickProcessor.java#L444-L454 |
spring-projects/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java | MapConfigurationPropertySource.putAll | public void putAll(Map<?, ?> map) {
"""
Add all entries from the specified map.
@param map the source map
"""
Assert.notNull(map, "Map must not be null");
assertNotReadOnlySystemAttributesMap(map);
map.forEach(this::put);
} | java | public void putAll(Map<?, ?> map) {
Assert.notNull(map, "Map must not be null");
assertNotReadOnlySystemAttributesMap(map);
map.forEach(this::put);
} | [
"public",
"void",
"putAll",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"map",
")",
"{",
"Assert",
".",
"notNull",
"(",
"map",
",",
"\"Map must not be null\"",
")",
";",
"assertNotReadOnlySystemAttributesMap",
"(",
"map",
")",
";",
"map",
".",
"forEach",
"(",
"this",
"::",
"put",
")",
";",
"}"
] | Add all entries from the specified map.
@param map the source map | [
"Add",
"all",
"entries",
"from",
"the",
"specified",
"map",
"."
] | train | https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java#L66-L70 |
pravega/pravega | client/src/main/java/io/pravega/client/batch/impl/BatchClientFactoryImpl.java | BatchClientFactoryImpl.getStreamInfo | @Override
@Deprecated
public CompletableFuture<io.pravega.client.batch.StreamInfo> getStreamInfo(final Stream stream) {
"""
Used to fetch the StreamInfo of a given stream. This should be removed in time.
@deprecated Use {@link io.pravega.client.admin.StreamManager#getStreamInfo(String, String)} to fetch StreamInfo.
"""
Preconditions.checkNotNull(stream, "stream");
StreamManagerImpl streamManager = new StreamManagerImpl(this.controller, this.connectionFactory);
return streamManager.getStreamInfo(stream)
.thenApply(info -> new io.pravega.client.batch.StreamInfo(
info.getScope(), info.getStreamName(), info.getTailStreamCut(), info.getHeadStreamCut()));
} | java | @Override
@Deprecated
public CompletableFuture<io.pravega.client.batch.StreamInfo> getStreamInfo(final Stream stream) {
Preconditions.checkNotNull(stream, "stream");
StreamManagerImpl streamManager = new StreamManagerImpl(this.controller, this.connectionFactory);
return streamManager.getStreamInfo(stream)
.thenApply(info -> new io.pravega.client.batch.StreamInfo(
info.getScope(), info.getStreamName(), info.getTailStreamCut(), info.getHeadStreamCut()));
} | [
"@",
"Override",
"@",
"Deprecated",
"public",
"CompletableFuture",
"<",
"io",
".",
"pravega",
".",
"client",
".",
"batch",
".",
"StreamInfo",
">",
"getStreamInfo",
"(",
"final",
"Stream",
"stream",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"stream",
",",
"\"stream\"",
")",
";",
"StreamManagerImpl",
"streamManager",
"=",
"new",
"StreamManagerImpl",
"(",
"this",
".",
"controller",
",",
"this",
".",
"connectionFactory",
")",
";",
"return",
"streamManager",
".",
"getStreamInfo",
"(",
"stream",
")",
".",
"thenApply",
"(",
"info",
"->",
"new",
"io",
".",
"pravega",
".",
"client",
".",
"batch",
".",
"StreamInfo",
"(",
"info",
".",
"getScope",
"(",
")",
",",
"info",
".",
"getStreamName",
"(",
")",
",",
"info",
".",
"getTailStreamCut",
"(",
")",
",",
"info",
".",
"getHeadStreamCut",
"(",
")",
")",
")",
";",
"}"
] | Used to fetch the StreamInfo of a given stream. This should be removed in time.
@deprecated Use {@link io.pravega.client.admin.StreamManager#getStreamInfo(String, String)} to fetch StreamInfo. | [
"Used",
"to",
"fetch",
"the",
"StreamInfo",
"of",
"a",
"given",
"stream",
".",
"This",
"should",
"be",
"removed",
"in",
"time",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/batch/impl/BatchClientFactoryImpl.java#L75-L84 |
headius/invokebinder | src/main/java/com/headius/invokebinder/Binder.java | Binder.invokeStatic | public MethodHandle invokeStatic(MethodHandles.Lookup lookup, Class<?> target, String name) throws NoSuchMethodException, IllegalAccessException {
"""
Apply the chain of transforms and bind them to a static method specified
using the end signature plus the given class and name. The method will
be retrieved using the given Lookup and must match the end signature
exactly.
If the final handle's type does not exactly match the initial type for
this Binder, an additional cast will be attempted.
@param lookup the MethodHandles.Lookup to use to unreflect the method
@param target the class in which to find the method
@param name the name of the method to invoke
@return the full handle chain, bound to the given method
@throws java.lang.NoSuchMethodException if the method does not exist
@throws java.lang.IllegalAccessException if the method is not accessible
"""
return invoke(lookup.findStatic(target, name, type()));
} | java | public MethodHandle invokeStatic(MethodHandles.Lookup lookup, Class<?> target, String name) throws NoSuchMethodException, IllegalAccessException {
return invoke(lookup.findStatic(target, name, type()));
} | [
"public",
"MethodHandle",
"invokeStatic",
"(",
"MethodHandles",
".",
"Lookup",
"lookup",
",",
"Class",
"<",
"?",
">",
"target",
",",
"String",
"name",
")",
"throws",
"NoSuchMethodException",
",",
"IllegalAccessException",
"{",
"return",
"invoke",
"(",
"lookup",
".",
"findStatic",
"(",
"target",
",",
"name",
",",
"type",
"(",
")",
")",
")",
";",
"}"
] | Apply the chain of transforms and bind them to a static method specified
using the end signature plus the given class and name. The method will
be retrieved using the given Lookup and must match the end signature
exactly.
If the final handle's type does not exactly match the initial type for
this Binder, an additional cast will be attempted.
@param lookup the MethodHandles.Lookup to use to unreflect the method
@param target the class in which to find the method
@param name the name of the method to invoke
@return the full handle chain, bound to the given method
@throws java.lang.NoSuchMethodException if the method does not exist
@throws java.lang.IllegalAccessException if the method is not accessible | [
"Apply",
"the",
"chain",
"of",
"transforms",
"and",
"bind",
"them",
"to",
"a",
"static",
"method",
"specified",
"using",
"the",
"end",
"signature",
"plus",
"the",
"given",
"class",
"and",
"name",
".",
"The",
"method",
"will",
"be",
"retrieved",
"using",
"the",
"given",
"Lookup",
"and",
"must",
"match",
"the",
"end",
"signature",
"exactly",
"."
] | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Binder.java#L1210-L1212 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/ImagesInner.java | ImagesInner.beginUpdate | public ImageInner beginUpdate(String resourceGroupName, String imageName, ImageUpdate parameters) {
"""
Update an image.
@param resourceGroupName The name of the resource group.
@param imageName The name of the image.
@param parameters Parameters supplied to the Update Image 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 ImageInner object if successful.
"""
return beginUpdateWithServiceResponseAsync(resourceGroupName, imageName, parameters).toBlocking().single().body();
} | java | public ImageInner beginUpdate(String resourceGroupName, String imageName, ImageUpdate parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, imageName, parameters).toBlocking().single().body();
} | [
"public",
"ImageInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"imageName",
",",
"ImageUpdate",
"parameters",
")",
"{",
"return",
"beginUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"imageName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Update an image.
@param resourceGroupName The name of the resource group.
@param imageName The name of the image.
@param parameters Parameters supplied to the Update Image 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 ImageInner object if successful. | [
"Update",
"an",
"image",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/ImagesInner.java#L375-L377 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java | LocalNetworkGatewaysInner.beginDelete | public void beginDelete(String resourceGroupName, String localNetworkGatewayName) {
"""
Deletes the specified local network gateway.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@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
"""
beginDeleteWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String localNetworkGatewayName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, localNetworkGatewayName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"localNetworkGatewayName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"localNetworkGatewayName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Deletes the specified local network gateway.
@param resourceGroupName The name of the resource group.
@param localNetworkGatewayName The name of the local network gateway.
@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",
"local",
"network",
"gateway",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LocalNetworkGatewaysInner.java#L434-L436 |
wisdom-framework/wisdom | core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/JavaScriptCompilerMojo.java | JavaScriptCompilerMojo.createSourceMapFile | private void createSourceMapFile(File output,SourceMap sourceMap) throws WatchingException {
"""
Create a source map file corresponding to the given compiled js file.
@param output The compiled js file
@param sourceMap The {@link SourceMap} retrieved from the compiler
@throws WatchingException If an IOException occurred while creating the source map file.
"""
if (googleClosureMap) {
PrintWriter mapWriter = null;
File mapFile = new File(output.getPath() + ".map");
FileUtils.deleteQuietly(mapFile);
try {
mapWriter = new PrintWriter(mapFile, Charset.defaultCharset().name());
sourceMap.appendTo(mapWriter, output.getName());
FileUtils.write(output, "\n//# sourceMappingURL=" + mapFile.getName(), true);
} catch (IOException e) {
throw new WatchingException("Cannot create source map file for JavaScript file '" +
output.getAbsolutePath() + "'", e);
} finally {
IOUtils.closeQuietly(mapWriter);
}
}
} | java | private void createSourceMapFile(File output,SourceMap sourceMap) throws WatchingException{
if (googleClosureMap) {
PrintWriter mapWriter = null;
File mapFile = new File(output.getPath() + ".map");
FileUtils.deleteQuietly(mapFile);
try {
mapWriter = new PrintWriter(mapFile, Charset.defaultCharset().name());
sourceMap.appendTo(mapWriter, output.getName());
FileUtils.write(output, "\n//# sourceMappingURL=" + mapFile.getName(), true);
} catch (IOException e) {
throw new WatchingException("Cannot create source map file for JavaScript file '" +
output.getAbsolutePath() + "'", e);
} finally {
IOUtils.closeQuietly(mapWriter);
}
}
} | [
"private",
"void",
"createSourceMapFile",
"(",
"File",
"output",
",",
"SourceMap",
"sourceMap",
")",
"throws",
"WatchingException",
"{",
"if",
"(",
"googleClosureMap",
")",
"{",
"PrintWriter",
"mapWriter",
"=",
"null",
";",
"File",
"mapFile",
"=",
"new",
"File",
"(",
"output",
".",
"getPath",
"(",
")",
"+",
"\".map\"",
")",
";",
"FileUtils",
".",
"deleteQuietly",
"(",
"mapFile",
")",
";",
"try",
"{",
"mapWriter",
"=",
"new",
"PrintWriter",
"(",
"mapFile",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
".",
"name",
"(",
")",
")",
";",
"sourceMap",
".",
"appendTo",
"(",
"mapWriter",
",",
"output",
".",
"getName",
"(",
")",
")",
";",
"FileUtils",
".",
"write",
"(",
"output",
",",
"\"\\n//# sourceMappingURL=\"",
"+",
"mapFile",
".",
"getName",
"(",
")",
",",
"true",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"WatchingException",
"(",
"\"Cannot create source map file for JavaScript file '\"",
"+",
"output",
".",
"getAbsolutePath",
"(",
")",
"+",
"\"'\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"mapWriter",
")",
";",
"}",
"}",
"}"
] | Create a source map file corresponding to the given compiled js file.
@param output The compiled js file
@param sourceMap The {@link SourceMap} retrieved from the compiler
@throws WatchingException If an IOException occurred while creating the source map file. | [
"Create",
"a",
"source",
"map",
"file",
"corresponding",
"to",
"the",
"given",
"compiled",
"js",
"file",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/mojos/JavaScriptCompilerMojo.java#L466-L483 |
FitLayout/segmentation | src/main/java/org/fit/segm/grouping/op/GroupAnalyzerByStyles.java | GroupAnalyzerByStyles.limitReached | private boolean limitReached(Rectangular gp, Rectangular limit, short required) {
"""
Checks if the grid bounds have reached a specified limit in the specified direction.
@param gp the bounds to check
@param limit the limit to be reached
@param required the required direction (use the REQ_* constants)
@return true if the limit has been reached or exceeded
"""
switch (required)
{
case REQ_HORIZONTAL:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2();
case REQ_VERTICAL:
return gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
case REQ_BOTH:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2()
&& gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
}
return false;
} | java | private boolean limitReached(Rectangular gp, Rectangular limit, short required)
{
switch (required)
{
case REQ_HORIZONTAL:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2();
case REQ_VERTICAL:
return gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
case REQ_BOTH:
return gp.getX1() <= limit.getX1() && gp.getX2() >= limit.getX2()
&& gp.getY1() <= limit.getY1() && gp.getY2() >= limit.getY2();
}
return false;
} | [
"private",
"boolean",
"limitReached",
"(",
"Rectangular",
"gp",
",",
"Rectangular",
"limit",
",",
"short",
"required",
")",
"{",
"switch",
"(",
"required",
")",
"{",
"case",
"REQ_HORIZONTAL",
":",
"return",
"gp",
".",
"getX1",
"(",
")",
"<=",
"limit",
".",
"getX1",
"(",
")",
"&&",
"gp",
".",
"getX2",
"(",
")",
">=",
"limit",
".",
"getX2",
"(",
")",
";",
"case",
"REQ_VERTICAL",
":",
"return",
"gp",
".",
"getY1",
"(",
")",
"<=",
"limit",
".",
"getY1",
"(",
")",
"&&",
"gp",
".",
"getY2",
"(",
")",
">=",
"limit",
".",
"getY2",
"(",
")",
";",
"case",
"REQ_BOTH",
":",
"return",
"gp",
".",
"getX1",
"(",
")",
"<=",
"limit",
".",
"getX1",
"(",
")",
"&&",
"gp",
".",
"getX2",
"(",
")",
">=",
"limit",
".",
"getX2",
"(",
")",
"&&",
"gp",
".",
"getY1",
"(",
")",
"<=",
"limit",
".",
"getY1",
"(",
")",
"&&",
"gp",
".",
"getY2",
"(",
")",
">=",
"limit",
".",
"getY2",
"(",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Checks if the grid bounds have reached a specified limit in the specified direction.
@param gp the bounds to check
@param limit the limit to be reached
@param required the required direction (use the REQ_* constants)
@return true if the limit has been reached or exceeded | [
"Checks",
"if",
"the",
"grid",
"bounds",
"have",
"reached",
"a",
"specified",
"limit",
"in",
"the",
"specified",
"direction",
"."
] | train | https://github.com/FitLayout/segmentation/blob/12998087d576640c2f2a6360cf6088af95eea5f4/src/main/java/org/fit/segm/grouping/op/GroupAnalyzerByStyles.java#L221-L235 |
AzureAD/azure-activedirectory-library-for-java | src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/BasicFilter.java | BasicFilter.validateState | private StateData validateState(HttpSession session, String state) throws Exception {
"""
make sure that state is stored in the session,
delete it from session - should be used only once
@param session
@param state
@throws Exception
"""
if (StringUtils.isNotEmpty(state)) {
StateData stateDataInSession = removeStateFromSession(session, state);
if (stateDataInSession != null) {
return stateDataInSession;
}
}
throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
} | java | private StateData validateState(HttpSession session, String state) throws Exception {
if (StringUtils.isNotEmpty(state)) {
StateData stateDataInSession = removeStateFromSession(session, state);
if (stateDataInSession != null) {
return stateDataInSession;
}
}
throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
} | [
"private",
"StateData",
"validateState",
"(",
"HttpSession",
"session",
",",
"String",
"state",
")",
"throws",
"Exception",
"{",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"state",
")",
")",
"{",
"StateData",
"stateDataInSession",
"=",
"removeStateFromSession",
"(",
"session",
",",
"state",
")",
";",
"if",
"(",
"stateDataInSession",
"!=",
"null",
")",
"{",
"return",
"stateDataInSession",
";",
"}",
"}",
"throw",
"new",
"Exception",
"(",
"FAILED_TO_VALIDATE_MESSAGE",
"+",
"\"could not validate state\"",
")",
";",
"}"
] | make sure that state is stored in the session,
delete it from session - should be used only once
@param session
@param state
@throws Exception | [
"make",
"sure",
"that",
"state",
"is",
"stored",
"in",
"the",
"session",
"delete",
"it",
"from",
"session",
"-",
"should",
"be",
"used",
"only",
"once"
] | train | https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/BasicFilter.java#L182-L190 |
alexa/alexa-skills-kit-sdk-for-java | ask-sdk-servlet-support/src/com/amazon/ask/servlet/SkillServlet.java | SkillServlet.doPost | @Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws IOException {
"""
Handles a POST request. Based on the request parameters, invokes the right method on the
{@code Skill}.
@param request the object that contains the request the client has made of the servlet
@param response object that contains the response the servlet sends to the client
@throws IOException if an input or output error is detected when the servlet handles the request
"""
byte[] serializedRequestEnvelope = IOUtils.toByteArray(request.getInputStream());
try {
final RequestEnvelope deserializedRequestEnvelope = serializer.deserialize(IOUtils.toString(
serializedRequestEnvelope, ServletConstants.CHARACTER_ENCODING), RequestEnvelope.class);
// Verify the authenticity of the request by executing configured verifiers.
for (SkillServletVerifier verifier : verifiers) {
verifier.verify(request, serializedRequestEnvelope, deserializedRequestEnvelope);
}
ResponseEnvelope skillResponse = skill.invoke(deserializedRequestEnvelope);
// Generate JSON and send back the response
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
if (skillResponse != null) {
byte[] serializedResponse = serializer.serialize(skillResponse).getBytes(StandardCharsets.UTF_8);
try (final OutputStream out = response.getOutputStream()) {
response.setContentLength(serializedResponse.length);
out.write(serializedResponse);
}
}
} catch (SecurityException ex) {
int statusCode = HttpServletResponse.SC_BAD_REQUEST;
log.error("Incoming request failed verification {}", statusCode, ex);
response.sendError(statusCode, ex.getMessage());
} catch (AskSdkException ex) {
int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
response.sendError(statusCode, ex.getMessage());
}
} | java | @Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws IOException {
byte[] serializedRequestEnvelope = IOUtils.toByteArray(request.getInputStream());
try {
final RequestEnvelope deserializedRequestEnvelope = serializer.deserialize(IOUtils.toString(
serializedRequestEnvelope, ServletConstants.CHARACTER_ENCODING), RequestEnvelope.class);
// Verify the authenticity of the request by executing configured verifiers.
for (SkillServletVerifier verifier : verifiers) {
verifier.verify(request, serializedRequestEnvelope, deserializedRequestEnvelope);
}
ResponseEnvelope skillResponse = skill.invoke(deserializedRequestEnvelope);
// Generate JSON and send back the response
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
if (skillResponse != null) {
byte[] serializedResponse = serializer.serialize(skillResponse).getBytes(StandardCharsets.UTF_8);
try (final OutputStream out = response.getOutputStream()) {
response.setContentLength(serializedResponse.length);
out.write(serializedResponse);
}
}
} catch (SecurityException ex) {
int statusCode = HttpServletResponse.SC_BAD_REQUEST;
log.error("Incoming request failed verification {}", statusCode, ex);
response.sendError(statusCode, ex.getMessage());
} catch (AskSdkException ex) {
int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
response.sendError(statusCode, ex.getMessage());
}
} | [
"@",
"Override",
"protected",
"void",
"doPost",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"serializedRequestEnvelope",
"=",
"IOUtils",
".",
"toByteArray",
"(",
"request",
".",
"getInputStream",
"(",
")",
")",
";",
"try",
"{",
"final",
"RequestEnvelope",
"deserializedRequestEnvelope",
"=",
"serializer",
".",
"deserialize",
"(",
"IOUtils",
".",
"toString",
"(",
"serializedRequestEnvelope",
",",
"ServletConstants",
".",
"CHARACTER_ENCODING",
")",
",",
"RequestEnvelope",
".",
"class",
")",
";",
"// Verify the authenticity of the request by executing configured verifiers.",
"for",
"(",
"SkillServletVerifier",
"verifier",
":",
"verifiers",
")",
"{",
"verifier",
".",
"verify",
"(",
"request",
",",
"serializedRequestEnvelope",
",",
"deserializedRequestEnvelope",
")",
";",
"}",
"ResponseEnvelope",
"skillResponse",
"=",
"skill",
".",
"invoke",
"(",
"deserializedRequestEnvelope",
")",
";",
"// Generate JSON and send back the response",
"response",
".",
"setContentType",
"(",
"\"application/json\"",
")",
";",
"response",
".",
"setStatus",
"(",
"HttpServletResponse",
".",
"SC_OK",
")",
";",
"if",
"(",
"skillResponse",
"!=",
"null",
")",
"{",
"byte",
"[",
"]",
"serializedResponse",
"=",
"serializer",
".",
"serialize",
"(",
"skillResponse",
")",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"try",
"(",
"final",
"OutputStream",
"out",
"=",
"response",
".",
"getOutputStream",
"(",
")",
")",
"{",
"response",
".",
"setContentLength",
"(",
"serializedResponse",
".",
"length",
")",
";",
"out",
".",
"write",
"(",
"serializedResponse",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"SecurityException",
"ex",
")",
"{",
"int",
"statusCode",
"=",
"HttpServletResponse",
".",
"SC_BAD_REQUEST",
";",
"log",
".",
"error",
"(",
"\"Incoming request failed verification {}\"",
",",
"statusCode",
",",
"ex",
")",
";",
"response",
".",
"sendError",
"(",
"statusCode",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"AskSdkException",
"ex",
")",
"{",
"int",
"statusCode",
"=",
"HttpServletResponse",
".",
"SC_INTERNAL_SERVER_ERROR",
";",
"log",
".",
"error",
"(",
"\"Exception occurred in doPost, returning status code {}\"",
",",
"statusCode",
",",
"ex",
")",
";",
"response",
".",
"sendError",
"(",
"statusCode",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Handles a POST request. Based on the request parameters, invokes the right method on the
{@code Skill}.
@param request the object that contains the request the client has made of the servlet
@param response object that contains the response the servlet sends to the client
@throws IOException if an input or output error is detected when the servlet handles the request | [
"Handles",
"a",
"POST",
"request",
".",
"Based",
"on",
"the",
"request",
"parameters",
"invokes",
"the",
"right",
"method",
"on",
"the",
"{",
"@code",
"Skill",
"}",
"."
] | train | https://github.com/alexa/alexa-skills-kit-sdk-for-java/blob/c49194da0693898c70f3f2c4a372f5a12da04e3e/ask-sdk-servlet-support/src/com/amazon/ask/servlet/SkillServlet.java#L92-L125 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java | Utility.compareUnsigned | public static final int compareUnsigned(int source, int target) {
"""
Compares 2 unsigned integers
@param source 32 bit unsigned integer
@param target 32 bit unsigned integer
@return 0 if equals, 1 if source is greater than target and -1
otherwise
"""
source += MAGIC_UNSIGNED;
target += MAGIC_UNSIGNED;
if (source < target) {
return -1;
}
else if (source > target) {
return 1;
}
return 0;
} | java | public static final int compareUnsigned(int source, int target)
{
source += MAGIC_UNSIGNED;
target += MAGIC_UNSIGNED;
if (source < target) {
return -1;
}
else if (source > target) {
return 1;
}
return 0;
} | [
"public",
"static",
"final",
"int",
"compareUnsigned",
"(",
"int",
"source",
",",
"int",
"target",
")",
"{",
"source",
"+=",
"MAGIC_UNSIGNED",
";",
"target",
"+=",
"MAGIC_UNSIGNED",
";",
"if",
"(",
"source",
"<",
"target",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"source",
">",
"target",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}"
] | Compares 2 unsigned integers
@param source 32 bit unsigned integer
@param target 32 bit unsigned integer
@return 0 if equals, 1 if source is greater than target and -1
otherwise | [
"Compares",
"2",
"unsigned",
"integers"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java#L1687-L1698 |
RestComm/sipunit | src/main/java/org/cafesip/sipunit/ReferNotifySender.java | ReferNotifySender.processRefer | public void processRefer(long timeout, int statusCode, String reasonPhrase) {
"""
This method starts a thread that waits for up to 'timeout' milliseconds to receive a REFER and
if received, it sends a response with 'statusCode' and 'reasonPhrase' (if not null). This
method waits 500 ms before returning to allow the thread to get started and begin waiting for
an incoming REFER. This method adds 500ms to the given timeout to account for this delay.
@param timeout - number of milliseconds to wait for the request
@param statusCode - use in the response to the request
@param reasonPhrase - if not null, use in the response
"""
processRefer(timeout, statusCode, reasonPhrase, -1, null);
} | java | public void processRefer(long timeout, int statusCode, String reasonPhrase) {
processRefer(timeout, statusCode, reasonPhrase, -1, null);
} | [
"public",
"void",
"processRefer",
"(",
"long",
"timeout",
",",
"int",
"statusCode",
",",
"String",
"reasonPhrase",
")",
"{",
"processRefer",
"(",
"timeout",
",",
"statusCode",
",",
"reasonPhrase",
",",
"-",
"1",
",",
"null",
")",
";",
"}"
] | This method starts a thread that waits for up to 'timeout' milliseconds to receive a REFER and
if received, it sends a response with 'statusCode' and 'reasonPhrase' (if not null). This
method waits 500 ms before returning to allow the thread to get started and begin waiting for
an incoming REFER. This method adds 500ms to the given timeout to account for this delay.
@param timeout - number of milliseconds to wait for the request
@param statusCode - use in the response to the request
@param reasonPhrase - if not null, use in the response | [
"This",
"method",
"starts",
"a",
"thread",
"that",
"waits",
"for",
"up",
"to",
"timeout",
"milliseconds",
"to",
"receive",
"a",
"REFER",
"and",
"if",
"received",
"it",
"sends",
"a",
"response",
"with",
"statusCode",
"and",
"reasonPhrase",
"(",
"if",
"not",
"null",
")",
".",
"This",
"method",
"waits",
"500",
"ms",
"before",
"returning",
"to",
"allow",
"the",
"thread",
"to",
"get",
"started",
"and",
"begin",
"waiting",
"for",
"an",
"incoming",
"REFER",
".",
"This",
"method",
"adds",
"500ms",
"to",
"the",
"given",
"timeout",
"to",
"account",
"for",
"this",
"delay",
"."
] | train | https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/ReferNotifySender.java#L84-L86 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java | SVGPath.ellipticalArc | public SVGPath ellipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) {
"""
Elliptical arc curve to the given coordinates.
@param rx x radius
@param ry y radius
@param ar x-axis-rotation
@param la large arc flag, if angle >= 180 deg
@param sp sweep flag, if arc will be drawn in positive-angle direction
@param xy new coordinates
"""
return append(PATH_ARC).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
} | java | public SVGPath ellipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) {
return append(PATH_ARC).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]);
} | [
"public",
"SVGPath",
"ellipticalArc",
"(",
"double",
"rx",
",",
"double",
"ry",
",",
"double",
"ar",
",",
"double",
"la",
",",
"double",
"sp",
",",
"double",
"[",
"]",
"xy",
")",
"{",
"return",
"append",
"(",
"PATH_ARC",
")",
".",
"append",
"(",
"rx",
")",
".",
"append",
"(",
"ry",
")",
".",
"append",
"(",
"ar",
")",
".",
"append",
"(",
"la",
")",
".",
"append",
"(",
"sp",
")",
".",
"append",
"(",
"xy",
"[",
"0",
"]",
")",
".",
"append",
"(",
"xy",
"[",
"1",
"]",
")",
";",
"}"
] | Elliptical arc curve to the given coordinates.
@param rx x radius
@param ry y radius
@param ar x-axis-rotation
@param la large arc flag, if angle >= 180 deg
@param sp sweep flag, if arc will be drawn in positive-angle direction
@param xy new coordinates | [
"Elliptical",
"arc",
"curve",
"to",
"the",
"given",
"coordinates",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L563-L565 |
Subsets and Splits