repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
apereo/cas | core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java | WebUtils.putLogoutRequests | public static void putLogoutRequests(final RequestContext context, final List<SingleLogoutRequest> requests) {
"""
Put logout requests into flow scope.
@param context the context
@param requests the requests
"""
context.getFlowScope().put(PARAMETER_LOGOUT_REQUESTS, requests);
} | java | public static void putLogoutRequests(final RequestContext context, final List<SingleLogoutRequest> requests) {
context.getFlowScope().put(PARAMETER_LOGOUT_REQUESTS, requests);
} | [
"public",
"static",
"void",
"putLogoutRequests",
"(",
"final",
"RequestContext",
"context",
",",
"final",
"List",
"<",
"SingleLogoutRequest",
">",
"requests",
")",
"{",
"context",
".",
"getFlowScope",
"(",
")",
".",
"put",
"(",
"PARAMETER_LOGOUT_REQUESTS",
",",
... | Put logout requests into flow scope.
@param context the context
@param requests the requests | [
"Put",
"logout",
"requests",
"into",
"flow",
"scope",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/web/support/WebUtils.java#L269-L271 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/plugin/AbstractPlugin.java | AbstractPlugin.getLang | public String getLang(final Locale locale, final String key) {
"""
Gets language label with the specified locale and key.
@param locale the specified locale
@param key the specified key
@return language label
"""
return langs.get(locale.toString()).getProperty(key);
} | java | public String getLang(final Locale locale, final String key) {
return langs.get(locale.toString()).getProperty(key);
} | [
"public",
"String",
"getLang",
"(",
"final",
"Locale",
"locale",
",",
"final",
"String",
"key",
")",
"{",
"return",
"langs",
".",
"get",
"(",
"locale",
".",
"toString",
"(",
")",
")",
".",
"getProperty",
"(",
"key",
")",
";",
"}"
] | Gets language label with the specified locale and key.
@param locale the specified locale
@param key the specified key
@return language label | [
"Gets",
"language",
"label",
"with",
"the",
"specified",
"locale",
"and",
"key",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/plugin/AbstractPlugin.java#L217-L219 |
alkacon/opencms-core | src/org/opencms/util/CmsRequestUtil.java | CmsRequestUtil.readMultipartFileItems | public static List<FileItem> readMultipartFileItems(HttpServletRequest request) {
"""
Parses a request of the form <code>multipart/form-data</code>.
The result list will contain items of type <code>{@link FileItem}</code>.
If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
@param request the HTTP servlet request to parse
@return the list of <code>{@link FileItem}</code> extracted from the multipart request,
or <code>null</code> if the request was not of type <code>multipart/form-data</code>
"""
return readMultipartFileItems(request, OpenCms.getSystemInfo().getPackagesRfsPath());
} | java | public static List<FileItem> readMultipartFileItems(HttpServletRequest request) {
return readMultipartFileItems(request, OpenCms.getSystemInfo().getPackagesRfsPath());
} | [
"public",
"static",
"List",
"<",
"FileItem",
">",
"readMultipartFileItems",
"(",
"HttpServletRequest",
"request",
")",
"{",
"return",
"readMultipartFileItems",
"(",
"request",
",",
"OpenCms",
".",
"getSystemInfo",
"(",
")",
".",
"getPackagesRfsPath",
"(",
")",
")"... | Parses a request of the form <code>multipart/form-data</code>.
The result list will contain items of type <code>{@link FileItem}</code>.
If the request is not of type <code>multipart/form-data</code>, then <code>null</code> is returned.<p>
@param request the HTTP servlet request to parse
@return the list of <code>{@link FileItem}</code> extracted from the multipart request,
or <code>null</code> if the request was not of type <code>multipart/form-data</code> | [
"Parses",
"a",
"request",
"of",
"the",
"form",
"<code",
">",
"multipart",
"/",
"form",
"-",
"data<",
"/",
"code",
">",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsRequestUtil.java#L746-L749 |
rometools/rome | rome/src/main/java/com/rometools/rome/io/impl/Atom10Parser.java | Atom10Parser.findAtomLink | private String findAtomLink(final Element parent, final String rel) {
"""
Return URL string of Atom link element under parent element. Link with no rel attribute is
considered to be rel="alternate"
@param parent Consider only children of this parent element
@param rel Consider only links with this relationship
"""
String ret = null;
final List<Element> linksList = parent.getChildren("link", ATOM_10_NS);
if (linksList != null) {
for (final Element element : linksList) {
final Element link = element;
final Attribute relAtt = getAttribute(link, "rel");
final Attribute hrefAtt = getAttribute(link, "href");
if (relAtt == null && "alternate".equals(rel) || relAtt != null && relAtt.getValue().equals(rel)) {
ret = hrefAtt.getValue();
break;
}
}
}
return ret;
} | java | private String findAtomLink(final Element parent, final String rel) {
String ret = null;
final List<Element> linksList = parent.getChildren("link", ATOM_10_NS);
if (linksList != null) {
for (final Element element : linksList) {
final Element link = element;
final Attribute relAtt = getAttribute(link, "rel");
final Attribute hrefAtt = getAttribute(link, "href");
if (relAtt == null && "alternate".equals(rel) || relAtt != null && relAtt.getValue().equals(rel)) {
ret = hrefAtt.getValue();
break;
}
}
}
return ret;
} | [
"private",
"String",
"findAtomLink",
"(",
"final",
"Element",
"parent",
",",
"final",
"String",
"rel",
")",
"{",
"String",
"ret",
"=",
"null",
";",
"final",
"List",
"<",
"Element",
">",
"linksList",
"=",
"parent",
".",
"getChildren",
"(",
"\"link\"",
",",
... | Return URL string of Atom link element under parent element. Link with no rel attribute is
considered to be rel="alternate"
@param parent Consider only children of this parent element
@param rel Consider only links with this relationship | [
"Return",
"URL",
"string",
"of",
"Atom",
"link",
"element",
"under",
"parent",
"element",
".",
"Link",
"with",
"no",
"rel",
"attribute",
"is",
"considered",
"to",
"be",
"rel",
"=",
"alternate"
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/Atom10Parser.java#L622-L637 |
sirthias/parboiled | parboiled-core/src/main/java/org/parboiled/errors/ErrorUtils.java | ErrorUtils.printErrorMessage | public static String printErrorMessage(String format, String errorMessage, int startIndex, int endIndex,
InputBuffer inputBuffer) {
"""
Prints an error message showing a location in the given InputBuffer.
@param format the format string, must include three placeholders for a string
(the error message) and two integers (the error line / column respectively)
@param errorMessage the error message
@param startIndex the start location of the error as an index into the inputBuffer
@param endIndex the end location of the error as an index into the inputBuffer
@param inputBuffer the underlying InputBuffer
@return the error message including the relevant line from the underlying input plus location indicators
"""
checkArgNotNull(inputBuffer, "inputBuffer");
checkArgument(startIndex <= endIndex);
Position pos = inputBuffer.getPosition(startIndex);
StringBuilder sb = new StringBuilder(String.format(format, errorMessage, pos.line, pos.column));
sb.append('\n');
String line = inputBuffer.extractLine(pos.line);
sb.append(line);
sb.append('\n');
int charCount = Math.max(Math.min(endIndex - startIndex, StringUtils.length(line) - pos.column + 2), 1);
for (int i = 0; i < pos.column - 1; i++) sb.append(' ');
for (int i = 0; i < charCount; i++) sb.append('^');
sb.append("\n");
return sb.toString();
} | java | public static String printErrorMessage(String format, String errorMessage, int startIndex, int endIndex,
InputBuffer inputBuffer) {
checkArgNotNull(inputBuffer, "inputBuffer");
checkArgument(startIndex <= endIndex);
Position pos = inputBuffer.getPosition(startIndex);
StringBuilder sb = new StringBuilder(String.format(format, errorMessage, pos.line, pos.column));
sb.append('\n');
String line = inputBuffer.extractLine(pos.line);
sb.append(line);
sb.append('\n');
int charCount = Math.max(Math.min(endIndex - startIndex, StringUtils.length(line) - pos.column + 2), 1);
for (int i = 0; i < pos.column - 1; i++) sb.append(' ');
for (int i = 0; i < charCount; i++) sb.append('^');
sb.append("\n");
return sb.toString();
} | [
"public",
"static",
"String",
"printErrorMessage",
"(",
"String",
"format",
",",
"String",
"errorMessage",
",",
"int",
"startIndex",
",",
"int",
"endIndex",
",",
"InputBuffer",
"inputBuffer",
")",
"{",
"checkArgNotNull",
"(",
"inputBuffer",
",",
"\"inputBuffer\"",
... | Prints an error message showing a location in the given InputBuffer.
@param format the format string, must include three placeholders for a string
(the error message) and two integers (the error line / column respectively)
@param errorMessage the error message
@param startIndex the start location of the error as an index into the inputBuffer
@param endIndex the end location of the error as an index into the inputBuffer
@param inputBuffer the underlying InputBuffer
@return the error message including the relevant line from the underlying input plus location indicators | [
"Prints",
"an",
"error",
"message",
"showing",
"a",
"location",
"in",
"the",
"given",
"InputBuffer",
"."
] | train | https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/errors/ErrorUtils.java#L149-L167 |
gdx-libs/gdx-kiwi | src/com/github/czyzby/kiwi/util/common/Comparables.java | Comparables.nullSafeCompare | public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
"""
Safely compares two values that might be null. Null value is considered lower than non-null, even if the
non-null value is minimal in its range.
@return comparison result of first and second value.
"""
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT;
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} | java | public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT;
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} | [
"public",
"static",
"<",
"Value",
"extends",
"Comparable",
"<",
"Value",
">",
">",
"int",
"nullSafeCompare",
"(",
"final",
"Value",
"first",
",",
"final",
"Value",
"second",
")",
"{",
"if",
"(",
"first",
"==",
"null",
")",
"{",
"return",
"second",
"==",
... | Safely compares two values that might be null. Null value is considered lower than non-null, even if the
non-null value is minimal in its range.
@return comparison result of first and second value. | [
"Safely",
"compares",
"two",
"values",
"that",
"might",
"be",
"null",
".",
"Null",
"value",
"is",
"considered",
"lower",
"than",
"non",
"-",
"null",
"even",
"if",
"the",
"non",
"-",
"null",
"value",
"is",
"minimal",
"in",
"its",
"range",
"."
] | train | https://github.com/gdx-libs/gdx-kiwi/blob/0172ee7534162f33b939bcdc4de089bc9579dd62/src/com/github/czyzby/kiwi/util/common/Comparables.java#L72-L77 |
minio/minio-java | api/src/main/java/io/minio/MinioClient.java | MinioClient.executeHead | private HttpResponse executeHead(String bucketName, String objectName, Map<String,String> headerMap)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
"""
Executes HEAD method for given request parameters.
@param bucketName Bucket name.
@param objectName Object name in the bucket.
@param headerMap Map of header parameters of the request.
"""
HttpResponse response = execute(Method.HEAD, getRegion(bucketName), bucketName, objectName, headerMap,
null, null, 0);
response.body().close();
return response;
} | java | private HttpResponse executeHead(String bucketName, String objectName, Map<String,String> headerMap)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
HttpResponse response = execute(Method.HEAD, getRegion(bucketName), bucketName, objectName, headerMap,
null, null, 0);
response.body().close();
return response;
} | [
"private",
"HttpResponse",
"executeHead",
"(",
"String",
"bucketName",
",",
"String",
"objectName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headerMap",
")",
"throws",
"InvalidBucketNameException",
",",
"NoSuchAlgorithmException",
",",
"InsufficientDataException"... | Executes HEAD method for given request parameters.
@param bucketName Bucket name.
@param objectName Object name in the bucket.
@param headerMap Map of header parameters of the request. | [
"Executes",
"HEAD",
"method",
"for",
"given",
"request",
"parameters",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L1325-L1334 |
jasminb/jsonapi-converter | src/main/java/com/github/jasminb/jsonapi/ConverterConfiguration.java | ConverterConfiguration.getRelationshipField | public Field getRelationshipField(Class<?> clazz, String fieldName) {
"""
Returns relationship field.
@param clazz {@link Class} class holding relationship
@param fieldName {@link String} name of the field
@return {@link Field} field
"""
return relationshipFieldMap.get(clazz).get(fieldName);
} | java | public Field getRelationshipField(Class<?> clazz, String fieldName) {
return relationshipFieldMap.get(clazz).get(fieldName);
} | [
"public",
"Field",
"getRelationshipField",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fieldName",
")",
"{",
"return",
"relationshipFieldMap",
".",
"get",
"(",
"clazz",
")",
".",
"get",
"(",
"fieldName",
")",
";",
"}"
] | Returns relationship field.
@param clazz {@link Class} class holding relationship
@param fieldName {@link String} name of the field
@return {@link Field} field | [
"Returns",
"relationship",
"field",
"."
] | train | https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ConverterConfiguration.java#L235-L237 |
exoplatform/jcr | exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderPlugin.java | GroovyScript2RestLoaderPlugin.getRepository | public String getRepository() {
"""
Get working repository name. Returns the repository name from configuration
if it previously configured and returns the name of current repository in other case.
@return String
repository name
"""
if (repository == null)
{
try
{
return repositoryService.getCurrentRepository().getConfiguration().getName();
}
catch (RepositoryException e)
{
throw new RuntimeException("Can not get current repository and repository name was not configured", e);
}
}
else
{
return repository;
}
} | java | public String getRepository()
{
if (repository == null)
{
try
{
return repositoryService.getCurrentRepository().getConfiguration().getName();
}
catch (RepositoryException e)
{
throw new RuntimeException("Can not get current repository and repository name was not configured", e);
}
}
else
{
return repository;
}
} | [
"public",
"String",
"getRepository",
"(",
")",
"{",
"if",
"(",
"repository",
"==",
"null",
")",
"{",
"try",
"{",
"return",
"repositoryService",
".",
"getCurrentRepository",
"(",
")",
".",
"getConfiguration",
"(",
")",
".",
"getName",
"(",
")",
";",
"}",
... | Get working repository name. Returns the repository name from configuration
if it previously configured and returns the name of current repository in other case.
@return String
repository name | [
"Get",
"working",
"repository",
"name",
".",
"Returns",
"the",
"repository",
"name",
"from",
"configuration",
"if",
"it",
"previously",
"configured",
"and",
"returns",
"the",
"name",
"of",
"current",
"repository",
"in",
"other",
"case",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderPlugin.java#L92-L109 |
cybazeitalia/emaze-dysfunctional | src/main/java/net/emaze/dysfunctional/Spies.java | Spies.spy3rd | public static <T1, T2, T3> TriConsumer<T1, T2, T3> spy3rd(TriConsumer<T1, T2, T3> consumer, Box<T3> param3) {
"""
Proxies a ternary consumer spying for third parameter.
@param <T1> the consumer first parameter type
@param <T2> the consumer second parameter type
@param <T3> the consumer third parameter type
@param consumer the consumer that will be spied
@param param3 a box that will be containing the third spied parameter
@return the proxied consumer
"""
return spy(consumer, Box.<T1>empty(), Box.<T2>empty(), param3);
} | java | public static <T1, T2, T3> TriConsumer<T1, T2, T3> spy3rd(TriConsumer<T1, T2, T3> consumer, Box<T3> param3) {
return spy(consumer, Box.<T1>empty(), Box.<T2>empty(), param3);
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
">",
"TriConsumer",
"<",
"T1",
",",
"T2",
",",
"T3",
">",
"spy3rd",
"(",
"TriConsumer",
"<",
"T1",
",",
"T2",
",",
"T3",
">",
"consumer",
",",
"Box",
"<",
"T3",
">",
"param3",
")",
"{",
"retu... | Proxies a ternary consumer spying for third parameter.
@param <T1> the consumer first parameter type
@param <T2> the consumer second parameter type
@param <T3> the consumer third parameter type
@param consumer the consumer that will be spied
@param param3 a box that will be containing the third spied parameter
@return the proxied consumer | [
"Proxies",
"a",
"ternary",
"consumer",
"spying",
"for",
"third",
"parameter",
"."
] | train | https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Spies.java#L349-L351 |
deephacks/confit | api-model/src/main/java/org/deephacks/confit/model/Bean.java | Bean.setProperty | public void setProperty(final String propertyName, final List<String> values) {
"""
Overwrite/replace the current values with the provided values.
@param propertyName name of the property as defined by the bean's schema.
@param values final String representations of the property that conforms to
its type as defined by the bean's schema.
"""
Preconditions.checkNotNull(propertyName);
if (values == null) {
properties.put(propertyName, null);
return;
}
properties.put(propertyName, values);
} | java | public void setProperty(final String propertyName, final List<String> values) {
Preconditions.checkNotNull(propertyName);
if (values == null) {
properties.put(propertyName, null);
return;
}
properties.put(propertyName, values);
} | [
"public",
"void",
"setProperty",
"(",
"final",
"String",
"propertyName",
",",
"final",
"List",
"<",
"String",
">",
"values",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"propertyName",
")",
";",
"if",
"(",
"values",
"==",
"null",
")",
"{",
"proper... | Overwrite/replace the current values with the provided values.
@param propertyName name of the property as defined by the bean's schema.
@param values final String representations of the property that conforms to
its type as defined by the bean's schema. | [
"Overwrite",
"/",
"replace",
"the",
"current",
"values",
"with",
"the",
"provided",
"values",
"."
] | train | https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-model/src/main/java/org/deephacks/confit/model/Bean.java#L201-L208 |
belaban/JGroups | src/org/jgroups/util/ForwardQueue.java | ForwardQueue.canDeliver | protected boolean canDeliver(Address sender, long seqno) {
"""
Checks if seqno has already been received from sender. This weeds out duplicates.
Note that this method is never called concurrently for the same sender.
"""
BoundedHashMap<Long,Long> seqno_set=delivery_table.get(sender);
if(seqno_set == null) {
seqno_set=new BoundedHashMap<>(delivery_table_max_size);
BoundedHashMap<Long,Long> existing=delivery_table.put(sender,seqno_set);
if(existing != null)
seqno_set=existing;
}
return seqno_set.add(seqno, seqno);
} | java | protected boolean canDeliver(Address sender, long seqno) {
BoundedHashMap<Long,Long> seqno_set=delivery_table.get(sender);
if(seqno_set == null) {
seqno_set=new BoundedHashMap<>(delivery_table_max_size);
BoundedHashMap<Long,Long> existing=delivery_table.put(sender,seqno_set);
if(existing != null)
seqno_set=existing;
}
return seqno_set.add(seqno, seqno);
} | [
"protected",
"boolean",
"canDeliver",
"(",
"Address",
"sender",
",",
"long",
"seqno",
")",
"{",
"BoundedHashMap",
"<",
"Long",
",",
"Long",
">",
"seqno_set",
"=",
"delivery_table",
".",
"get",
"(",
"sender",
")",
";",
"if",
"(",
"seqno_set",
"==",
"null",
... | Checks if seqno has already been received from sender. This weeds out duplicates.
Note that this method is never called concurrently for the same sender. | [
"Checks",
"if",
"seqno",
"has",
"already",
"been",
"received",
"from",
"sender",
".",
"This",
"weeds",
"out",
"duplicates",
".",
"Note",
"that",
"this",
"method",
"is",
"never",
"called",
"concurrently",
"for",
"the",
"same",
"sender",
"."
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/ForwardQueue.java#L236-L245 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/robust/Se3FromEssentialGenerator.java | Se3FromEssentialGenerator.generate | @Override
public boolean generate(List<AssociatedPair> dataSet, Se3_F64 model ) {
"""
Computes the camera motion from the set of observations. The motion is from the first
into the second camera frame.
@param dataSet Associated pairs in normalized camera coordinates.
@param model The best pose according to the positive depth constraint.
"""
if( !computeEssential.process(dataSet,E) )
return false;
// extract the possible motions
decomposeE.decompose(E);
selectBest.select(decomposeE.getSolutions(),dataSet,model);
return true;
} | java | @Override
public boolean generate(List<AssociatedPair> dataSet, Se3_F64 model ) {
if( !computeEssential.process(dataSet,E) )
return false;
// extract the possible motions
decomposeE.decompose(E);
selectBest.select(decomposeE.getSolutions(),dataSet,model);
return true;
} | [
"@",
"Override",
"public",
"boolean",
"generate",
"(",
"List",
"<",
"AssociatedPair",
">",
"dataSet",
",",
"Se3_F64",
"model",
")",
"{",
"if",
"(",
"!",
"computeEssential",
".",
"process",
"(",
"dataSet",
",",
"E",
")",
")",
"return",
"false",
";",
"// e... | Computes the camera motion from the set of observations. The motion is from the first
into the second camera frame.
@param dataSet Associated pairs in normalized camera coordinates.
@param model The best pose according to the positive depth constraint. | [
"Computes",
"the",
"camera",
"motion",
"from",
"the",
"set",
"of",
"observations",
".",
"The",
"motion",
"is",
"from",
"the",
"first",
"into",
"the",
"second",
"camera",
"frame",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/robust/Se3FromEssentialGenerator.java#L69-L79 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/vfs/VfsUtility.java | VfsUtility.configHttpFileSystemProxy | static public void configHttpFileSystemProxy(FileSystemOptions fsOptions,
String webProxyHost, Integer webProxyPort, String webProxyUserName, String webProxyPassword) {
"""
Configure FileSystemOptions for HttpFileSystem
@param fsOptions
@param webProxyHost
@param webProxyPort
@param webProxyUserName
@param webProxyPassword
"""
if (webProxyHost != null && webProxyPort != null){
HttpFileSystemConfigBuilder.getInstance().setProxyHost(fsOptions, webProxyHost);
HttpFileSystemConfigBuilder.getInstance().setProxyPort(fsOptions, webProxyPort);
if (webProxyUserName != null){
StaticUserAuthenticator auth = new StaticUserAuthenticator(webProxyUserName, webProxyPassword, null);
HttpFileSystemConfigBuilder.getInstance().setProxyAuthenticator(fsOptions, auth);
}
}
} | java | static public void configHttpFileSystemProxy(FileSystemOptions fsOptions,
String webProxyHost, Integer webProxyPort, String webProxyUserName, String webProxyPassword){
if (webProxyHost != null && webProxyPort != null){
HttpFileSystemConfigBuilder.getInstance().setProxyHost(fsOptions, webProxyHost);
HttpFileSystemConfigBuilder.getInstance().setProxyPort(fsOptions, webProxyPort);
if (webProxyUserName != null){
StaticUserAuthenticator auth = new StaticUserAuthenticator(webProxyUserName, webProxyPassword, null);
HttpFileSystemConfigBuilder.getInstance().setProxyAuthenticator(fsOptions, auth);
}
}
} | [
"static",
"public",
"void",
"configHttpFileSystemProxy",
"(",
"FileSystemOptions",
"fsOptions",
",",
"String",
"webProxyHost",
",",
"Integer",
"webProxyPort",
",",
"String",
"webProxyUserName",
",",
"String",
"webProxyPassword",
")",
"{",
"if",
"(",
"webProxyHost",
"!... | Configure FileSystemOptions for HttpFileSystem
@param fsOptions
@param webProxyHost
@param webProxyPort
@param webProxyUserName
@param webProxyPassword | [
"Configure",
"FileSystemOptions",
"for",
"HttpFileSystem"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/vfs/VfsUtility.java#L119-L130 |
rolfl/MicroBench | src/main/java/net/tuis/ubench/UBench.java | UBench.addTask | public UBench addTask(String name, Runnable task) {
"""
Include a named task that has no output value in to the benchmark.
@param name
The name of the task. Only one task with any one name is
allowed.
@param task
The task to perform
@return The same object, for chaining calls.
"""
return putTask(name, () -> {
long start = System.nanoTime();
task.run();
return System.nanoTime() - start;
});
} | java | public UBench addTask(String name, Runnable task) {
return putTask(name, () -> {
long start = System.nanoTime();
task.run();
return System.nanoTime() - start;
});
} | [
"public",
"UBench",
"addTask",
"(",
"String",
"name",
",",
"Runnable",
"task",
")",
"{",
"return",
"putTask",
"(",
"name",
",",
"(",
")",
"->",
"{",
"long",
"start",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"task",
".",
"run",
"(",
")",
";",
... | Include a named task that has no output value in to the benchmark.
@param name
The name of the task. Only one task with any one name is
allowed.
@param task
The task to perform
@return The same object, for chaining calls. | [
"Include",
"a",
"named",
"task",
"that",
"has",
"no",
"output",
"value",
"in",
"to",
"the",
"benchmark",
"."
] | train | https://github.com/rolfl/MicroBench/blob/f2bfa92dacd7ea0d6b8eae4d4fe2975139d317ce/src/main/java/net/tuis/ubench/UBench.java#L285-L291 |
facebookarchive/hadoop-20 | src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java | LocalStore.copyToHDFS | public static void copyToHDFS(String localFile, String hdfsFile) throws IOException {
"""
Copy a local file to HDFS
@param localFile the filename of the local file
@param hdfsFile the HDFS filename to copy to
"""
String hadoopConfPath;
if (Environment.getProperty("hadoop.conf.path") == null)
hadoopConfPath = "../../../conf";
else
hadoopConfPath = Environment.getProperty("hadoop.conf.path");
// Read the configuration for the Hadoop environment
Configuration hadoopConf = new Configuration();
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-default.xml"));
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-site.xml"));
// System.out.println(hadoopConf.get("hadoop.tmp.dir"));
// System.out.println(hadoopConf.get("fs.default.name"));
FileSystem fs = FileSystem.get(hadoopConf);
// HadoopDFS deals with Path
Path inFile = new Path("file://" + localFile);
Path outFile = new Path(hadoopConf.get("fs.default.name") + hdfsFile);
// Read from and write to new file
Environment.logInfo("Uploading to HDFS (file " + outFile + ") ...");
fs.copyFromLocalFile(false, inFile, outFile);
} | java | public static void copyToHDFS(String localFile, String hdfsFile) throws IOException {
String hadoopConfPath;
if (Environment.getProperty("hadoop.conf.path") == null)
hadoopConfPath = "../../../conf";
else
hadoopConfPath = Environment.getProperty("hadoop.conf.path");
// Read the configuration for the Hadoop environment
Configuration hadoopConf = new Configuration();
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-default.xml"));
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-site.xml"));
// System.out.println(hadoopConf.get("hadoop.tmp.dir"));
// System.out.println(hadoopConf.get("fs.default.name"));
FileSystem fs = FileSystem.get(hadoopConf);
// HadoopDFS deals with Path
Path inFile = new Path("file://" + localFile);
Path outFile = new Path(hadoopConf.get("fs.default.name") + hdfsFile);
// Read from and write to new file
Environment.logInfo("Uploading to HDFS (file " + outFile + ") ...");
fs.copyFromLocalFile(false, inFile, outFile);
} | [
"public",
"static",
"void",
"copyToHDFS",
"(",
"String",
"localFile",
",",
"String",
"hdfsFile",
")",
"throws",
"IOException",
"{",
"String",
"hadoopConfPath",
";",
"if",
"(",
"Environment",
".",
"getProperty",
"(",
"\"hadoop.conf.path\"",
")",
"==",
"null",
")"... | Copy a local file to HDFS
@param localFile the filename of the local file
@param hdfsFile the HDFS filename to copy to | [
"Copy",
"a",
"local",
"file",
"to",
"HDFS"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java#L229-L254 |
j256/ormlite-android | src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java | OrmLiteConfigUtil.writeConfigFile | public static void writeConfigFile(File configFile, Class<?>[] classes) throws SQLException, IOException {
"""
Write a configuration file with the configuration for classes.
"""
writeConfigFile(configFile, classes, false);
} | java | public static void writeConfigFile(File configFile, Class<?>[] classes) throws SQLException, IOException {
writeConfigFile(configFile, classes, false);
} | [
"public",
"static",
"void",
"writeConfigFile",
"(",
"File",
"configFile",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
")",
"throws",
"SQLException",
",",
"IOException",
"{",
"writeConfigFile",
"(",
"configFile",
",",
"classes",
",",
"false",
")",
";",
... | Write a configuration file with the configuration for classes. | [
"Write",
"a",
"configuration",
"file",
"with",
"the",
"configuration",
"for",
"classes",
"."
] | train | https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteConfigUtil.java#L186-L188 |
tdomzal/junit-docker-rule | src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java | DockerRuleBuilder.mountFrom | public DockerRuleMountToBuilder mountFrom(File hostFileOrDir) throws InvalidVolumeFrom {
"""
Host directory to be mounted into container.<br/>
Please note that in boot2docker environments (OSX or Windows)
only locations inside $HOME can work (/Users or /c/Users respectively).
@param hostFileOrDir Directory or file to be mounted.
"""
if ( ! hostFileOrDir.exists()) {
throw new InvalidVolumeFrom(String.format("mountFrom: %s does not exist", hostFileOrDir.getAbsolutePath()));
}
String hostDirUnixPath = DockerRuleMountBuilder.toUnixStylePath(hostFileOrDir.getAbsolutePath());
return new DockerRuleMountBuilder(this, hostDirUnixPath);
} | java | public DockerRuleMountToBuilder mountFrom(File hostFileOrDir) throws InvalidVolumeFrom {
if ( ! hostFileOrDir.exists()) {
throw new InvalidVolumeFrom(String.format("mountFrom: %s does not exist", hostFileOrDir.getAbsolutePath()));
}
String hostDirUnixPath = DockerRuleMountBuilder.toUnixStylePath(hostFileOrDir.getAbsolutePath());
return new DockerRuleMountBuilder(this, hostDirUnixPath);
} | [
"public",
"DockerRuleMountToBuilder",
"mountFrom",
"(",
"File",
"hostFileOrDir",
")",
"throws",
"InvalidVolumeFrom",
"{",
"if",
"(",
"!",
"hostFileOrDir",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"InvalidVolumeFrom",
"(",
"String",
".",
"format",
"(",
... | Host directory to be mounted into container.<br/>
Please note that in boot2docker environments (OSX or Windows)
only locations inside $HOME can work (/Users or /c/Users respectively).
@param hostFileOrDir Directory or file to be mounted. | [
"Host",
"directory",
"to",
"be",
"mounted",
"into",
"container",
".",
"<br",
"/",
">",
"Please",
"note",
"that",
"in",
"boot2docker",
"environments",
"(",
"OSX",
"or",
"Windows",
")",
"only",
"locations",
"inside",
"$HOME",
"can",
"work",
"(",
"/",
"Users"... | train | https://github.com/tdomzal/junit-docker-rule/blob/5a0ba2fd095d201530d3f9e614bc5e88d0afaeb2/src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java#L191-L197 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/WebContainer.java | WebContainer.sendAppUnavailableException | public static void sendAppUnavailableException(HttpServletRequest req, HttpServletResponse res) throws IOException {
"""
and throw a NPE because we couldn't get the application's configuration
"""
if ((req instanceof SRTServletRequest) && (res instanceof SRTServletResponse)) {
IRequest ireq = ((SRTServletRequest) req).getIRequest();
IResponse ires = ((SRTServletResponse) res).getIResponse();
sendUnavailableException(ireq, ires);
}
} | java | public static void sendAppUnavailableException(HttpServletRequest req, HttpServletResponse res) throws IOException {
if ((req instanceof SRTServletRequest) && (res instanceof SRTServletResponse)) {
IRequest ireq = ((SRTServletRequest) req).getIRequest();
IResponse ires = ((SRTServletResponse) res).getIResponse();
sendUnavailableException(ireq, ires);
}
} | [
"public",
"static",
"void",
"sendAppUnavailableException",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
")",
"throws",
"IOException",
"{",
"if",
"(",
"(",
"req",
"instanceof",
"SRTServletRequest",
")",
"&&",
"(",
"res",
"instanceof",
"SRTServ... | and throw a NPE because we couldn't get the application's configuration | [
"and",
"throw",
"a",
"NPE",
"because",
"we",
"couldn",
"t",
"get",
"the",
"application",
"s",
"configuration"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/WebContainer.java#L1570-L1577 |
citrusframework/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java | Functions.readFile | public static String readFile(String filePath, TestContext context) {
"""
Reads the file resource and returns the complete file content.
@param filePath
@return
"""
return new ReadFileResourceFunction().execute(Collections.singletonList(filePath), context);
} | java | public static String readFile(String filePath, TestContext context) {
return new ReadFileResourceFunction().execute(Collections.singletonList(filePath), context);
} | [
"public",
"static",
"String",
"readFile",
"(",
"String",
"filePath",
",",
"TestContext",
"context",
")",
"{",
"return",
"new",
"ReadFileResourceFunction",
"(",
")",
".",
"execute",
"(",
"Collections",
".",
"singletonList",
"(",
"filePath",
")",
",",
"context",
... | Reads the file resource and returns the complete file content.
@param filePath
@return | [
"Reads",
"the",
"file",
"resource",
"and",
"returns",
"the",
"complete",
"file",
"content",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java#L235-L237 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java | StructureIO.getBiologicalAssembly | public static Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws IOException, StructureException {
"""
Returns the first biological assembly that is available for the given PDB id.
<p>
The output Structure will be different depending on the multiModel parameter:
<li>
the symmetry-expanded chains are added as new models, one per transformId. All original models but
the first one are discarded.
</li>
<li>
as original with symmetry-expanded chains added with renamed chain ids and names (in the form
originalAsymId_transformId and originalAuthId_transformId)
</li>
<p>
For more documentation on quaternary structures see:
{@link http://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/biological-assemblies}
@param pdbId
@param multiModel if true the output Structure will be a multi-model one with one transformId per model,
if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId).
@return a Structure object or null if that assembly is not available
@throws StructureException
@throws IOException
"""
checkInitAtomCache();
pdbId = pdbId.toLowerCase();
Structure s = cache.getBiologicalAssembly(pdbId, multiModel);
return s;
} | java | public static Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws IOException, StructureException{
checkInitAtomCache();
pdbId = pdbId.toLowerCase();
Structure s = cache.getBiologicalAssembly(pdbId, multiModel);
return s;
} | [
"public",
"static",
"Structure",
"getBiologicalAssembly",
"(",
"String",
"pdbId",
",",
"boolean",
"multiModel",
")",
"throws",
"IOException",
",",
"StructureException",
"{",
"checkInitAtomCache",
"(",
")",
";",
"pdbId",
"=",
"pdbId",
".",
"toLowerCase",
"(",
")",
... | Returns the first biological assembly that is available for the given PDB id.
<p>
The output Structure will be different depending on the multiModel parameter:
<li>
the symmetry-expanded chains are added as new models, one per transformId. All original models but
the first one are discarded.
</li>
<li>
as original with symmetry-expanded chains added with renamed chain ids and names (in the form
originalAsymId_transformId and originalAuthId_transformId)
</li>
<p>
For more documentation on quaternary structures see:
{@link http://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/biological-assemblies}
@param pdbId
@param multiModel if true the output Structure will be a multi-model one with one transformId per model,
if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId).
@return a Structure object or null if that assembly is not available
@throws StructureException
@throws IOException | [
"Returns",
"the",
"first",
"biological",
"assembly",
"that",
"is",
"available",
"for",
"the",
"given",
"PDB",
"id",
".",
"<p",
">",
"The",
"output",
"Structure",
"will",
"be",
"different",
"depending",
"on",
"the",
"multiModel",
"parameter",
":",
"<li",
">",... | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java#L148-L157 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/Validate.java | Validate.validIndex | public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
"""
<p>Validates that the index is within the bounds of the argument collection; otherwise throwing an exception.</p>
<pre>Validate.validIndex(myCollection, 2);</pre>
<p>If the index is invalid, then the message of the exception is "The validated collection index is invalid: " followed by the index.</p>
@param <T>
the collection type
@param collection
the collection to check, validated not null by this method
@param index
the index to check
@return the validated collection (never {@code null} for method chaining)
@throws NullPointerValidationException
if the collection is {@code null}
@throws IndexOutOfBoundsException
if the index is invalid
@see #validIndex(Collection, int, String, Object...)
"""
return INSTANCE.validIndex(collection, index);
} | java | public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
return INSTANCE.validIndex(collection, index);
} | [
"public",
"static",
"<",
"T",
"extends",
"Collection",
"<",
"?",
">",
">",
"T",
"validIndex",
"(",
"final",
"T",
"collection",
",",
"final",
"int",
"index",
")",
"{",
"return",
"INSTANCE",
".",
"validIndex",
"(",
"collection",
",",
"index",
")",
";",
"... | <p>Validates that the index is within the bounds of the argument collection; otherwise throwing an exception.</p>
<pre>Validate.validIndex(myCollection, 2);</pre>
<p>If the index is invalid, then the message of the exception is "The validated collection index is invalid: " followed by the index.</p>
@param <T>
the collection type
@param collection
the collection to check, validated not null by this method
@param index
the index to check
@return the validated collection (never {@code null} for method chaining)
@throws NullPointerValidationException
if the collection is {@code null}
@throws IndexOutOfBoundsException
if the index is invalid
@see #validIndex(Collection, int, String, Object...) | [
"<p",
">",
"Validates",
"that",
"the",
"index",
"is",
"within",
"the",
"bounds",
"of",
"the",
"argument",
"collection",
";",
"otherwise",
"throwing",
"an",
"exception",
".",
"<",
"/",
"p",
">",
"<pre",
">",
"Validate",
".",
"validIndex",
"(",
"myCollection... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1256-L1258 |
UrielCh/ovh-java-sdk | ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java | ApiOvhIpLoadbalancing.serviceName_http_farm_farmId_GET | public OvhBackendHttp serviceName_http_farm_farmId_GET(String serviceName, Long farmId) throws IOException {
"""
Get this object properties
REST: GET /ipLoadbalancing/{serviceName}/http/farm/{farmId}
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm
"""
String qPath = "/ipLoadbalancing/{serviceName}/http/farm/{farmId}";
StringBuilder sb = path(qPath, serviceName, farmId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhBackendHttp.class);
} | java | public OvhBackendHttp serviceName_http_farm_farmId_GET(String serviceName, Long farmId) throws IOException {
String qPath = "/ipLoadbalancing/{serviceName}/http/farm/{farmId}";
StringBuilder sb = path(qPath, serviceName, farmId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhBackendHttp.class);
} | [
"public",
"OvhBackendHttp",
"serviceName_http_farm_farmId_GET",
"(",
"String",
"serviceName",
",",
"Long",
"farmId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/ipLoadbalancing/{serviceName}/http/farm/{farmId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
... | Get this object properties
REST: GET /ipLoadbalancing/{serviceName}/http/farm/{farmId}
@param serviceName [required] The internal name of your IP load balancing
@param farmId [required] Id of your farm | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L364-L369 |
IBM-Cloud/gp-java-client | src/main/java/com/ibm/g11n/pipeline/client/rb/CloudResourceBundleControl.java | CloudResourceBundleControl.getInstance | public static CloudResourceBundleControl getInstance(ServiceAccount serviceAccount, LookupMode mode) {
"""
Create an instance of <code>CloudResourceBundleControl</code> with the specified
service account.
@param serviceAccount The service account.
@param mode The resource bundle resolution mode, or null for default mode
({@link LookupMode#REMOTE_THEN_LOCAL}).
@return An instance of CloundResourceBundleControl.
@throws IllegalArgumentException when serviceAccount is null.
"""
return getInstance(serviceAccount, initCacheExpiration(), null, null, null, mode);
} | java | public static CloudResourceBundleControl getInstance(ServiceAccount serviceAccount, LookupMode mode) {
return getInstance(serviceAccount, initCacheExpiration(), null, null, null, mode);
} | [
"public",
"static",
"CloudResourceBundleControl",
"getInstance",
"(",
"ServiceAccount",
"serviceAccount",
",",
"LookupMode",
"mode",
")",
"{",
"return",
"getInstance",
"(",
"serviceAccount",
",",
"initCacheExpiration",
"(",
")",
",",
"null",
",",
"null",
",",
"null"... | Create an instance of <code>CloudResourceBundleControl</code> with the specified
service account.
@param serviceAccount The service account.
@param mode The resource bundle resolution mode, or null for default mode
({@link LookupMode#REMOTE_THEN_LOCAL}).
@return An instance of CloundResourceBundleControl.
@throws IllegalArgumentException when serviceAccount is null. | [
"Create",
"an",
"instance",
"of",
"<code",
">",
"CloudResourceBundleControl<",
"/",
"code",
">",
"with",
"the",
"specified",
"service",
"account",
"."
] | train | https://github.com/IBM-Cloud/gp-java-client/blob/b015a081d7a7313bc48c448087fbc07bce860427/src/main/java/com/ibm/g11n/pipeline/client/rb/CloudResourceBundleControl.java#L205-L207 |
Grasia/phatsim | phat-core/src/main/java/phat/util/SpatialFactory.java | SpatialFactory.createCube | public static Geometry createCube(Vector3f dimensions, ColorRGBA color) {
"""
Creates a cube given its dimensions and its color
@param dimensions
@param color
@return a cube Geometry
"""
checkInit();
Box b = new Box(dimensions.getX(), dimensions.getY(), dimensions.getZ()); // create cube shape at the origin
Geometry geom = new Geometry("Box", b); // create cube geometry from the shape
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md"); // create a simple material
mat.setColor("Color", color); // set color of material to blue
geom.setMaterial(mat); // set the cube's material
return geom;
} | java | public static Geometry createCube(Vector3f dimensions, ColorRGBA color) {
checkInit();
Box b = new Box(dimensions.getX(), dimensions.getY(), dimensions.getZ()); // create cube shape at the origin
Geometry geom = new Geometry("Box", b); // create cube geometry from the shape
Material mat = new Material(assetManager,
"Common/MatDefs/Misc/Unshaded.j3md"); // create a simple material
mat.setColor("Color", color); // set color of material to blue
geom.setMaterial(mat); // set the cube's material
return geom;
} | [
"public",
"static",
"Geometry",
"createCube",
"(",
"Vector3f",
"dimensions",
",",
"ColorRGBA",
"color",
")",
"{",
"checkInit",
"(",
")",
";",
"Box",
"b",
"=",
"new",
"Box",
"(",
"dimensions",
".",
"getX",
"(",
")",
",",
"dimensions",
".",
"getY",
"(",
... | Creates a cube given its dimensions and its color
@param dimensions
@param color
@return a cube Geometry | [
"Creates",
"a",
"cube",
"given",
"its",
"dimensions",
"and",
"its",
"color"
] | train | https://github.com/Grasia/phatsim/blob/2d4fc8189be9730b34c8e3e1a08fb4800e01c5df/phat-core/src/main/java/phat/util/SpatialFactory.java#L75-L85 |
Harium/keel | src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java | HistogramStatistics.Kurtosis | public static double Kurtosis(int[] values) {
"""
Calculate Kurtosis value.
@param values Values.
@return Returns kurtosis value of the specified histogram array.
"""
double mean = Mean(values);
double std = StdDev(values, mean);
return Kurtosis(values, mean, std);
} | java | public static double Kurtosis(int[] values){
double mean = Mean(values);
double std = StdDev(values, mean);
return Kurtosis(values, mean, std);
} | [
"public",
"static",
"double",
"Kurtosis",
"(",
"int",
"[",
"]",
"values",
")",
"{",
"double",
"mean",
"=",
"Mean",
"(",
"values",
")",
";",
"double",
"std",
"=",
"StdDev",
"(",
"values",
",",
"mean",
")",
";",
"return",
"Kurtosis",
"(",
"values",
","... | Calculate Kurtosis value.
@param values Values.
@return Returns kurtosis value of the specified histogram array. | [
"Calculate",
"Kurtosis",
"value",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java#L114-L118 |
Waikato/moa | moa/src/main/java/moa/gui/experimentertab/ImageChart.java | ImageChart.exportIMG | public void exportIMG(String path, String type) throws IOException {
"""
Export the image to formats JPG, PNG, SVG and EPS.
@param path
@param type
@throws IOException
"""
switch (type) {
case "JPG":
try {
ChartUtilities.saveChartAsJPEG(new File(path + File.separator + name + ".jpg"), chart, width, height);
} catch (IOException e) {
}
break;
case "PNG":
try {
ChartUtilities.saveChartAsPNG(new File(path + File.separator + name + ".png"), chart, width, height);
} catch (IOException e) {
}
break;
case "SVG":
String svg = generateSVG(width, height);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(path + File.separator + name + ".svg")));
writer.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
writer.write(svg + "\n");
writer.flush();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
break;
}
} | java | public void exportIMG(String path, String type) throws IOException {
switch (type) {
case "JPG":
try {
ChartUtilities.saveChartAsJPEG(new File(path + File.separator + name + ".jpg"), chart, width, height);
} catch (IOException e) {
}
break;
case "PNG":
try {
ChartUtilities.saveChartAsPNG(new File(path + File.separator + name + ".png"), chart, width, height);
} catch (IOException e) {
}
break;
case "SVG":
String svg = generateSVG(width, height);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(path + File.separator + name + ".svg")));
writer.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
writer.write(svg + "\n");
writer.flush();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
break;
}
} | [
"public",
"void",
"exportIMG",
"(",
"String",
"path",
",",
"String",
"type",
")",
"throws",
"IOException",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"\"JPG\"",
":",
"try",
"{",
"ChartUtilities",
".",
"saveChartAsJPEG",
"(",
"new",
"File",
"(",
"path",
... | Export the image to formats JPG, PNG, SVG and EPS.
@param path
@param type
@throws IOException | [
"Export",
"the",
"image",
"to",
"formats",
"JPG",
"PNG",
"SVG",
"and",
"EPS",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/experimentertab/ImageChart.java#L169-L207 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/operations/NestedMappingHandler.java | NestedMappingHandler.checkAccessors | private static MappedField checkAccessors(XML xml, Class<?> aClass, Field nestedField) {
"""
Checks get and set accessors of this field.
@param xml used to check xml configuration
@param aClass class where is the field with the nested mapping
@param nestedField field with nested mapping
@return mapped field
"""
MappedField field = checkGetAccessor(xml, aClass, nestedField);
verifySetterMethods(aClass,field);
return field;
} | java | private static MappedField checkAccessors(XML xml, Class<?> aClass, Field nestedField){
MappedField field = checkGetAccessor(xml, aClass, nestedField);
verifySetterMethods(aClass,field);
return field;
} | [
"private",
"static",
"MappedField",
"checkAccessors",
"(",
"XML",
"xml",
",",
"Class",
"<",
"?",
">",
"aClass",
",",
"Field",
"nestedField",
")",
"{",
"MappedField",
"field",
"=",
"checkGetAccessor",
"(",
"xml",
",",
"aClass",
",",
"nestedField",
")",
";",
... | Checks get and set accessors of this field.
@param xml used to check xml configuration
@param aClass class where is the field with the nested mapping
@param nestedField field with nested mapping
@return mapped field | [
"Checks",
"get",
"and",
"set",
"accessors",
"of",
"this",
"field",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/operations/NestedMappingHandler.java#L111-L116 |
vkostyukov/la4j | src/main/java/org/la4j/vector/DenseVector.java | DenseVector.fromMap | public static DenseVector fromMap(Map<Integer, ? extends Number> map, int length) {
"""
Creates new {@link DenseVector} from index-value map
@param map index-value map
@param length vector length
@return created vector
"""
return Vector.fromMap(map, length).to(Vectors.DENSE);
} | java | public static DenseVector fromMap(Map<Integer, ? extends Number> map, int length) {
return Vector.fromMap(map, length).to(Vectors.DENSE);
} | [
"public",
"static",
"DenseVector",
"fromMap",
"(",
"Map",
"<",
"Integer",
",",
"?",
"extends",
"Number",
">",
"map",
",",
"int",
"length",
")",
"{",
"return",
"Vector",
".",
"fromMap",
"(",
"map",
",",
"length",
")",
".",
"to",
"(",
"Vectors",
".",
"... | Creates new {@link DenseVector} from index-value map
@param map index-value map
@param length vector length
@return created vector | [
"Creates",
"new",
"{",
"@link",
"DenseVector",
"}",
"from",
"index",
"-",
"value",
"map"
] | train | https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/vector/DenseVector.java#L140-L142 |
andkulikov/Transitions-Everywhere | library(1.x)/src/main/java/com/transitionseverywhere/Transition.java | Transition.excludeTarget | @NonNull
public Transition excludeTarget(int targetId, boolean exclude) {
"""
Whether to add the given id to the list of target ids to exclude from this
transition. The <code>exclude</code> parameter specifies whether the target
should be added to or removed from the excluded list.
<p/>
<p>Excluding targets is a general mechanism for allowing transitions to run on
a view hierarchy while skipping target views that should not be part of
the transition. For example, you may want to avoid animating children
of a specific ListView or Spinner. Views can be excluded either by their
id, or by their instance reference, or by the Class of that view
(eg, {@link Spinner}).</p>
@param targetId The id of a target to ignore when running this transition.
@param exclude Whether to add the target to or remove the target from the
current list of excluded targets.
@return This transition object.
@see #excludeChildren(int, boolean)
@see #excludeTarget(View, boolean)
@see #excludeTarget(Class, boolean)
"""
if (targetId >= 0) {
mTargetIdExcludes = excludeObject(mTargetIdExcludes, targetId, exclude);
}
return this;
} | java | @NonNull
public Transition excludeTarget(int targetId, boolean exclude) {
if (targetId >= 0) {
mTargetIdExcludes = excludeObject(mTargetIdExcludes, targetId, exclude);
}
return this;
} | [
"@",
"NonNull",
"public",
"Transition",
"excludeTarget",
"(",
"int",
"targetId",
",",
"boolean",
"exclude",
")",
"{",
"if",
"(",
"targetId",
">=",
"0",
")",
"{",
"mTargetIdExcludes",
"=",
"excludeObject",
"(",
"mTargetIdExcludes",
",",
"targetId",
",",
"exclud... | Whether to add the given id to the list of target ids to exclude from this
transition. The <code>exclude</code> parameter specifies whether the target
should be added to or removed from the excluded list.
<p/>
<p>Excluding targets is a general mechanism for allowing transitions to run on
a view hierarchy while skipping target views that should not be part of
the transition. For example, you may want to avoid animating children
of a specific ListView or Spinner. Views can be excluded either by their
id, or by their instance reference, or by the Class of that view
(eg, {@link Spinner}).</p>
@param targetId The id of a target to ignore when running this transition.
@param exclude Whether to add the target to or remove the target from the
current list of excluded targets.
@return This transition object.
@see #excludeChildren(int, boolean)
@see #excludeTarget(View, boolean)
@see #excludeTarget(Class, boolean) | [
"Whether",
"to",
"add",
"the",
"given",
"id",
"to",
"the",
"list",
"of",
"target",
"ids",
"to",
"exclude",
"from",
"this",
"transition",
".",
"The",
"<code",
">",
"exclude<",
"/",
"code",
">",
"parameter",
"specifies",
"whether",
"the",
"target",
"should",... | train | https://github.com/andkulikov/Transitions-Everywhere/blob/828efe5f152a2f05e2bfeee6254b74ad2269d4f1/library(1.x)/src/main/java/com/transitionseverywhere/Transition.java#L1138-L1144 |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Mapping.java | Mapping.getIdValue | public <V> V getIdValue(T instance, Class<V> valueClass) {
"""
Return the value for the ID/Key column from the given instance
@param instance
the instance
@param valueClass
type of the value (must match the actual native type in the
instance's class)
@return value
"""
return getColumnValue(instance, idFieldName, valueClass);
} | java | public <V> V getIdValue(T instance, Class<V> valueClass) {
return getColumnValue(instance, idFieldName, valueClass);
} | [
"public",
"<",
"V",
">",
"V",
"getIdValue",
"(",
"T",
"instance",
",",
"Class",
"<",
"V",
">",
"valueClass",
")",
"{",
"return",
"getColumnValue",
"(",
"instance",
",",
"idFieldName",
",",
"valueClass",
")",
";",
"}"
] | Return the value for the ID/Key column from the given instance
@param instance
the instance
@param valueClass
type of the value (must match the actual native type in the
instance's class)
@return value | [
"Return",
"the",
"value",
"for",
"the",
"ID",
"/",
"Key",
"column",
"from",
"the",
"given",
"instance"
] | train | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Mapping.java#L163-L165 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java | RobustLoaderWriterResilienceStrategy.putIfAbsentFailure | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
"""
Write the value to the loader-writer if it doesn't already exist in it. Note that the load and write pair
is not atomic. This atomicity, if needed, should be handled by the something else.
@param key the key being put
@param value the value being put
@param e the triggered failure
@return the existing value or null if the new was set
"""
// FIXME: Should I care about useLoaderInAtomics?
try {
try {
V loaded = loaderWriter.load(key);
if (loaded != null) {
return loaded;
}
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
} finally {
cleanup(key, e);
}
return null;
} | java | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
// FIXME: Should I care about useLoaderInAtomics?
try {
try {
V loaded = loaderWriter.load(key);
if (loaded != null) {
return loaded;
}
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
} finally {
cleanup(key, e);
}
return null;
} | [
"@",
"Override",
"public",
"V",
"putIfAbsentFailure",
"(",
"K",
"key",
",",
"V",
"value",
",",
"StoreAccessException",
"e",
")",
"{",
"// FIXME: Should I care about useLoaderInAtomics?",
"try",
"{",
"try",
"{",
"V",
"loaded",
"=",
"loaderWriter",
".",
"load",
"(... | Write the value to the loader-writer if it doesn't already exist in it. Note that the load and write pair
is not atomic. This atomicity, if needed, should be handled by the something else.
@param key the key being put
@param value the value being put
@param e the triggered failure
@return the existing value or null if the new was set | [
"Write",
"the",
"value",
"to",
"the",
"loader",
"-",
"writer",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"in",
"it",
".",
"Note",
"that",
"the",
"load",
"and",
"write",
"pair",
"is",
"not",
"atomic",
".",
"This",
"atomicity",
"if",
"needed",
"shoul... | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L133-L154 |
VueGWT/vue-gwt | core/src/main/java/com/axellience/vuegwt/core/client/vnode/builder/VNodeBuilder.java | VNodeBuilder.el | public <T extends IsVueComponent> VNode el(VueJsConstructor<T> vueJsConstructor,
Object... children) {
"""
Create a VNode with the {@link IsVueComponent} of the given {@link VueJsConstructor}
@param vueJsConstructor {@link VueJsConstructor} for the Component we want
@param children Children
@param <T> The type of the {@link IsVueComponent}
@return a new VNode of this Component
"""
return el(vueJsConstructor, null, children);
} | java | public <T extends IsVueComponent> VNode el(VueJsConstructor<T> vueJsConstructor,
Object... children) {
return el(vueJsConstructor, null, children);
} | [
"public",
"<",
"T",
"extends",
"IsVueComponent",
">",
"VNode",
"el",
"(",
"VueJsConstructor",
"<",
"T",
">",
"vueJsConstructor",
",",
"Object",
"...",
"children",
")",
"{",
"return",
"el",
"(",
"vueJsConstructor",
",",
"null",
",",
"children",
")",
";",
"}... | Create a VNode with the {@link IsVueComponent} of the given {@link VueJsConstructor}
@param vueJsConstructor {@link VueJsConstructor} for the Component we want
@param children Children
@param <T> The type of the {@link IsVueComponent}
@return a new VNode of this Component | [
"Create",
"a",
"VNode",
"with",
"the",
"{",
"@link",
"IsVueComponent",
"}",
"of",
"the",
"given",
"{",
"@link",
"VueJsConstructor",
"}"
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/core/src/main/java/com/axellience/vuegwt/core/client/vnode/builder/VNodeBuilder.java#L87-L90 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/Comments.java | Comments.getNextNodeOrParent | private static Tree getNextNodeOrParent(Tree current, VisitorState state) {
"""
Find the node which (approximately) follows this one in the tree. This works by walking upwards
to find enclosing block (or class) and then looking for the node after the subtree we walked.
If our subtree is the last of the block then we return the node for the block instead, if we
can't find a suitable block we return the parent node.
"""
Tree predecessorNode = current;
TreePath enclosingPath = state.getPath();
while (enclosingPath != null
&& !(enclosingPath.getLeaf() instanceof BlockTree)
&& !(enclosingPath.getLeaf() instanceof ClassTree)) {
predecessorNode = enclosingPath.getLeaf();
enclosingPath = enclosingPath.getParentPath();
}
if (enclosingPath == null) {
return state.getPath().getParentPath().getLeaf();
}
Tree parent = enclosingPath.getLeaf();
if (parent instanceof BlockTree) {
return after(predecessorNode, ((BlockTree) parent).getStatements(), parent);
} else if (parent instanceof ClassTree) {
return after(predecessorNode, ((ClassTree) parent).getMembers(), parent);
}
return parent;
} | java | private static Tree getNextNodeOrParent(Tree current, VisitorState state) {
Tree predecessorNode = current;
TreePath enclosingPath = state.getPath();
while (enclosingPath != null
&& !(enclosingPath.getLeaf() instanceof BlockTree)
&& !(enclosingPath.getLeaf() instanceof ClassTree)) {
predecessorNode = enclosingPath.getLeaf();
enclosingPath = enclosingPath.getParentPath();
}
if (enclosingPath == null) {
return state.getPath().getParentPath().getLeaf();
}
Tree parent = enclosingPath.getLeaf();
if (parent instanceof BlockTree) {
return after(predecessorNode, ((BlockTree) parent).getStatements(), parent);
} else if (parent instanceof ClassTree) {
return after(predecessorNode, ((ClassTree) parent).getMembers(), parent);
}
return parent;
} | [
"private",
"static",
"Tree",
"getNextNodeOrParent",
"(",
"Tree",
"current",
",",
"VisitorState",
"state",
")",
"{",
"Tree",
"predecessorNode",
"=",
"current",
";",
"TreePath",
"enclosingPath",
"=",
"state",
".",
"getPath",
"(",
")",
";",
"while",
"(",
"enclosi... | Find the node which (approximately) follows this one in the tree. This works by walking upwards
to find enclosing block (or class) and then looking for the node after the subtree we walked.
If our subtree is the last of the block then we return the node for the block instead, if we
can't find a suitable block we return the parent node. | [
"Find",
"the",
"node",
"which",
"(",
"approximately",
")",
"follows",
"this",
"one",
"in",
"the",
"tree",
".",
"This",
"works",
"by",
"walking",
"upwards",
"to",
"find",
"enclosing",
"block",
"(",
"or",
"class",
")",
"and",
"then",
"looking",
"for",
"the... | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Comments.java#L268-L290 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/contentcensor/AipContentCensor.java | AipContentCensor.imageCensorComb | public JSONObject imageCensorComb(String imgPath, EImgType type,
List<String> scenes, HashMap<String, String> options) {
"""
组合审核接口
@param imgPath 本地图片路径或url
@param type imgPath类型:FILE或URL
@param scenes 需要审核的服务类型
@param options 可选参数
@return JSONObject
"""
if (type == EImgType.FILE) {
try {
byte[] imgData = Util.readFileByBytes(imgPath);
return imageCensorComb(imgData, scenes, options);
} catch (IOException e) {
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
// url
AipRequest request = new AipRequest();
request.addBody("imgUrl", imgPath);
return imageCensorCombHelper(request, scenes, options);
} | java | public JSONObject imageCensorComb(String imgPath, EImgType type,
List<String> scenes, HashMap<String, String> options) {
if (type == EImgType.FILE) {
try {
byte[] imgData = Util.readFileByBytes(imgPath);
return imageCensorComb(imgData, scenes, options);
} catch (IOException e) {
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
// url
AipRequest request = new AipRequest();
request.addBody("imgUrl", imgPath);
return imageCensorCombHelper(request, scenes, options);
} | [
"public",
"JSONObject",
"imageCensorComb",
"(",
"String",
"imgPath",
",",
"EImgType",
"type",
",",
"List",
"<",
"String",
">",
"scenes",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"options",
")",
"{",
"if",
"(",
"type",
"==",
"EImgType",
".",
"FI... | 组合审核接口
@param imgPath 本地图片路径或url
@param type imgPath类型:FILE或URL
@param scenes 需要审核的服务类型
@param options 可选参数
@return JSONObject | [
"组合审核接口"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/contentcensor/AipContentCensor.java#L157-L174 |
anotheria/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java | BaseAJAXMoskitoUIAction.writeTextToResponse | private static void writeTextToResponse(final HttpServletResponse res, final JSONResponse jsonResponse) throws IOException {
"""
Writes specified text to response and flushes the stream.
@param res
{@link HttpServletRequest}
@param jsonResponse
{@link JSONResponse}
@throws java.io.IOException
if an input or output exception occurred
"""
writeTextToResponse(res, jsonResponse.toString());
} | java | private static void writeTextToResponse(final HttpServletResponse res, final JSONResponse jsonResponse) throws IOException {
writeTextToResponse(res, jsonResponse.toString());
} | [
"private",
"static",
"void",
"writeTextToResponse",
"(",
"final",
"HttpServletResponse",
"res",
",",
"final",
"JSONResponse",
"jsonResponse",
")",
"throws",
"IOException",
"{",
"writeTextToResponse",
"(",
"res",
",",
"jsonResponse",
".",
"toString",
"(",
")",
")",
... | Writes specified text to response and flushes the stream.
@param res
{@link HttpServletRequest}
@param jsonResponse
{@link JSONResponse}
@throws java.io.IOException
if an input or output exception occurred | [
"Writes",
"specified",
"text",
"to",
"response",
"and",
"flushes",
"the",
"stream",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java#L98-L100 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/websphere/servlet/error/ServletErrorReport.java | ServletErrorReport.isApplicationError | private boolean isApplicationError(Throwable rootEx, String pkgRoot) {
"""
This method determines if the error is initiated by an application or not.
@param rootEx the exception being tested
@return true if a nice friendly app error should be returned, false otherwise.
"""
if (rootEx != null) {
StackTraceElement[] stackTrace = rootEx.getStackTrace();
if (stackTrace != null && stackTrace.length > 0) {
StackTraceElement rootThrower = stackTrace[0];
String className = rootThrower.getClassName();
if (className != null && !!!className.startsWith(pkgRoot)) {
return true;
}
}
}
return false;
} | java | private boolean isApplicationError(Throwable rootEx, String pkgRoot) {
if (rootEx != null) {
StackTraceElement[] stackTrace = rootEx.getStackTrace();
if (stackTrace != null && stackTrace.length > 0) {
StackTraceElement rootThrower = stackTrace[0];
String className = rootThrower.getClassName();
if (className != null && !!!className.startsWith(pkgRoot)) {
return true;
}
}
}
return false;
} | [
"private",
"boolean",
"isApplicationError",
"(",
"Throwable",
"rootEx",
",",
"String",
"pkgRoot",
")",
"{",
"if",
"(",
"rootEx",
"!=",
"null",
")",
"{",
"StackTraceElement",
"[",
"]",
"stackTrace",
"=",
"rootEx",
".",
"getStackTrace",
"(",
")",
";",
"if",
... | This method determines if the error is initiated by an application or not.
@param rootEx the exception being tested
@return true if a nice friendly app error should be returned, false otherwise. | [
"This",
"method",
"determines",
"if",
"the",
"error",
"is",
"initiated",
"by",
"an",
"application",
"or",
"not",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/websphere/servlet/error/ServletErrorReport.java#L320-L334 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/action/ActionableHelper.java | ActionableHelper.getArtifactoryProjectAction | public static List<ArtifactoryProjectAction> getArtifactoryProjectAction(
String artifactoryServerName, AbstractProject project, String buildName) {
"""
Return list with {@link ArtifactoryProjectAction} if not already exists in project actions.
@param artifactoryServerName The name of Artifactory server
@param project The hudson project
@return Empty list or list with one {@link ArtifactoryProjectAction}
"""
if (shouldReturnEmptyList(artifactoryServerName, project)) {
return Collections.emptyList();
}
return Lists.newArrayList(new ArtifactoryProjectAction(artifactoryServerName, buildName));
} | java | public static List<ArtifactoryProjectAction> getArtifactoryProjectAction(
String artifactoryServerName, AbstractProject project, String buildName) {
if (shouldReturnEmptyList(artifactoryServerName, project)) {
return Collections.emptyList();
}
return Lists.newArrayList(new ArtifactoryProjectAction(artifactoryServerName, buildName));
} | [
"public",
"static",
"List",
"<",
"ArtifactoryProjectAction",
">",
"getArtifactoryProjectAction",
"(",
"String",
"artifactoryServerName",
",",
"AbstractProject",
"project",
",",
"String",
"buildName",
")",
"{",
"if",
"(",
"shouldReturnEmptyList",
"(",
"artifactoryServerNam... | Return list with {@link ArtifactoryProjectAction} if not already exists in project actions.
@param artifactoryServerName The name of Artifactory server
@param project The hudson project
@return Empty list or list with one {@link ArtifactoryProjectAction} | [
"Return",
"list",
"with",
"{",
"@link",
"ArtifactoryProjectAction",
"}",
"if",
"not",
"already",
"exists",
"in",
"project",
"actions",
"."
] | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/action/ActionableHelper.java#L236-L243 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPTimephasedBaselineCostNormaliser.java | MPPTimephasedBaselineCostNormaliser.normalise | @Override public void normalise(ProjectCalendar calendar, LinkedList<TimephasedCost> list) {
"""
This method converts the internal representation of timephased
resource assignment data used by MS Project into a standardised
format to make it easy to work with.
@param calendar current calendar
@param list list of assignment data
"""
if (!list.isEmpty())
{
//dumpList(list);
splitDays(calendar, list);
//dumpList(list);
mergeSameDay(list);
//dumpList(list);
mergeSameCost(list);
//dumpList(list);
}
} | java | @Override public void normalise(ProjectCalendar calendar, LinkedList<TimephasedCost> list)
{
if (!list.isEmpty())
{
//dumpList(list);
splitDays(calendar, list);
//dumpList(list);
mergeSameDay(list);
//dumpList(list);
mergeSameCost(list);
//dumpList(list);
}
} | [
"@",
"Override",
"public",
"void",
"normalise",
"(",
"ProjectCalendar",
"calendar",
",",
"LinkedList",
"<",
"TimephasedCost",
">",
"list",
")",
"{",
"if",
"(",
"!",
"list",
".",
"isEmpty",
"(",
")",
")",
"{",
"//dumpList(list);",
"splitDays",
"(",
"calendar"... | This method converts the internal representation of timephased
resource assignment data used by MS Project into a standardised
format to make it easy to work with.
@param calendar current calendar
@param list list of assignment data | [
"This",
"method",
"converts",
"the",
"internal",
"representation",
"of",
"timephased",
"resource",
"assignment",
"data",
"used",
"by",
"MS",
"Project",
"into",
"a",
"standardised",
"format",
"to",
"make",
"it",
"easy",
"to",
"work",
"with",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPTimephasedBaselineCostNormaliser.java#L50-L62 |
cdk/cdk | misc/extra/src/main/java/org/openscience/cdk/io/VASPReader.java | VASPReader.nextVASPToken | public String nextVASPToken(boolean newLine) throws IOException {
"""
Find the next token of an VASP file.
ABINIT tokens are words separated by space(s). Characters
following a "#" are ignored till the end of the line.
@return a <code>String</code> value
@exception IOException if an error occurs
"""
String line;
if (newLine) { // We ignore the end of the line and go to the following line
if (inputBuffer.ready()) {
line = inputBuffer.readLine();
st = new StringTokenizer(line, " =\t");
}
}
while (!st.hasMoreTokens() && inputBuffer.ready()) {
line = inputBuffer.readLine();
st = new StringTokenizer(line, " =\t");
}
if (st.hasMoreTokens()) {
fieldVal = st.nextToken();
if (fieldVal.startsWith("#")) {
nextVASPToken(true);
}
} else {
fieldVal = null;
}
return this.fieldVal;
} | java | public String nextVASPToken(boolean newLine) throws IOException {
String line;
if (newLine) { // We ignore the end of the line and go to the following line
if (inputBuffer.ready()) {
line = inputBuffer.readLine();
st = new StringTokenizer(line, " =\t");
}
}
while (!st.hasMoreTokens() && inputBuffer.ready()) {
line = inputBuffer.readLine();
st = new StringTokenizer(line, " =\t");
}
if (st.hasMoreTokens()) {
fieldVal = st.nextToken();
if (fieldVal.startsWith("#")) {
nextVASPToken(true);
}
} else {
fieldVal = null;
}
return this.fieldVal;
} | [
"public",
"String",
"nextVASPToken",
"(",
"boolean",
"newLine",
")",
"throws",
"IOException",
"{",
"String",
"line",
";",
"if",
"(",
"newLine",
")",
"{",
"// We ignore the end of the line and go to the following line",
"if",
"(",
"inputBuffer",
".",
"ready",
"(",
")... | Find the next token of an VASP file.
ABINIT tokens are words separated by space(s). Characters
following a "#" are ignored till the end of the line.
@return a <code>String</code> value
@exception IOException if an error occurs | [
"Find",
"the",
"next",
"token",
"of",
"an",
"VASP",
"file",
".",
"ABINIT",
"tokens",
"are",
"words",
"separated",
"by",
"space",
"(",
"s",
")",
".",
"Characters",
"following",
"a",
"#",
"are",
"ignored",
"till",
"the",
"end",
"of",
"the",
"line",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/misc/extra/src/main/java/org/openscience/cdk/io/VASPReader.java#L280-L304 |
michaelliao/jsonstream | src/main/java/com/itranswarp/jsonstream/BeanObjectMapper.java | BeanObjectMapper.toSimpleValue | Object toSimpleValue(Class<?> genericType, Object element, TypeAdapters typeAdapters) {
"""
Convert a simple value object to specific type. e.g. Long to int, String to LocalDate.
@param genericType Object type: int.class, String.class, Float.class, etc.
@param element Value object.
@return Converted object.
"""
if (element == null) {
return null;
}
log.info("Convert from " + element.getClass().getName() + " to " + genericType.getName());
if (genericType.isEnum() && (element instanceof String)) {
@SuppressWarnings({ "unchecked", "rawtypes" })
Enum<?> enumValue = Enum.valueOf((Class<? extends Enum>) genericType, (String) element);
return enumValue;
}
Converter converter = SIMPLE_VALUE_CONVERTERS.get(genericType.getName());
if (converter != null) {
return converter.convert(element);
}
if ((element instanceof String) && (typeAdapters != null)) {
TypeAdapter<?> adapter = typeAdapters.getTypeAdapter(genericType);
if (adapter != null) {
return adapter.deserialize((String) element);
}
}
return element;
} | java | Object toSimpleValue(Class<?> genericType, Object element, TypeAdapters typeAdapters) {
if (element == null) {
return null;
}
log.info("Convert from " + element.getClass().getName() + " to " + genericType.getName());
if (genericType.isEnum() && (element instanceof String)) {
@SuppressWarnings({ "unchecked", "rawtypes" })
Enum<?> enumValue = Enum.valueOf((Class<? extends Enum>) genericType, (String) element);
return enumValue;
}
Converter converter = SIMPLE_VALUE_CONVERTERS.get(genericType.getName());
if (converter != null) {
return converter.convert(element);
}
if ((element instanceof String) && (typeAdapters != null)) {
TypeAdapter<?> adapter = typeAdapters.getTypeAdapter(genericType);
if (adapter != null) {
return adapter.deserialize((String) element);
}
}
return element;
} | [
"Object",
"toSimpleValue",
"(",
"Class",
"<",
"?",
">",
"genericType",
",",
"Object",
"element",
",",
"TypeAdapters",
"typeAdapters",
")",
"{",
"if",
"(",
"element",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"log",
".",
"info",
"(",
"\"Convert ... | Convert a simple value object to specific type. e.g. Long to int, String to LocalDate.
@param genericType Object type: int.class, String.class, Float.class, etc.
@param element Value object.
@return Converted object. | [
"Convert",
"a",
"simple",
"value",
"object",
"to",
"specific",
"type",
".",
"e",
".",
"g",
".",
"Long",
"to",
"int",
"String",
"to",
"LocalDate",
"."
] | train | https://github.com/michaelliao/jsonstream/blob/50adcff2e1293e655462eef5fc5f1b59277de514/src/main/java/com/itranswarp/jsonstream/BeanObjectMapper.java#L154-L175 |
Whiley/WhileyCompiler | src/main/java/wyil/interpreter/Interpreter.java | Interpreter.executeConst | private RValue executeConst(Expr.Constant expr, CallStack frame) {
"""
Execute a Constant expression at a given point in the function or
method body
@param expr
--- The expression to execute
@param frame
--- The current stack frame
@return
"""
Value v = expr.getValue();
switch (v.getOpcode()) {
case ITEM_null:
return RValue.Null;
case ITEM_bool: {
Value.Bool b = (Value.Bool) v;
if (b.get()) {
return RValue.True;
} else {
return RValue.False;
}
}
case ITEM_byte: {
Value.Byte b = (Value.Byte) v;
return semantics.Byte(b.get());
}
case ITEM_int: {
Value.Int i = (Value.Int) v;
return semantics.Int(i.get());
}
case ITEM_utf8: {
Value.UTF8 s = (Value.UTF8) v;
byte[] bytes = s.get();
RValue[] elements = new RValue[bytes.length];
for (int i = 0; i != elements.length; ++i) {
// FIXME: something tells me this is wrong for signed byte
// values?
elements[i] = semantics.Int(BigInteger.valueOf(bytes[i]));
}
return semantics.Array(elements);
}
default:
throw new RuntimeException("unknown value encountered (" + expr + ")");
}
} | java | private RValue executeConst(Expr.Constant expr, CallStack frame) {
Value v = expr.getValue();
switch (v.getOpcode()) {
case ITEM_null:
return RValue.Null;
case ITEM_bool: {
Value.Bool b = (Value.Bool) v;
if (b.get()) {
return RValue.True;
} else {
return RValue.False;
}
}
case ITEM_byte: {
Value.Byte b = (Value.Byte) v;
return semantics.Byte(b.get());
}
case ITEM_int: {
Value.Int i = (Value.Int) v;
return semantics.Int(i.get());
}
case ITEM_utf8: {
Value.UTF8 s = (Value.UTF8) v;
byte[] bytes = s.get();
RValue[] elements = new RValue[bytes.length];
for (int i = 0; i != elements.length; ++i) {
// FIXME: something tells me this is wrong for signed byte
// values?
elements[i] = semantics.Int(BigInteger.valueOf(bytes[i]));
}
return semantics.Array(elements);
}
default:
throw new RuntimeException("unknown value encountered (" + expr + ")");
}
} | [
"private",
"RValue",
"executeConst",
"(",
"Expr",
".",
"Constant",
"expr",
",",
"CallStack",
"frame",
")",
"{",
"Value",
"v",
"=",
"expr",
".",
"getValue",
"(",
")",
";",
"switch",
"(",
"v",
".",
"getOpcode",
"(",
")",
")",
"{",
"case",
"ITEM_null",
... | Execute a Constant expression at a given point in the function or
method body
@param expr
--- The expression to execute
@param frame
--- The current stack frame
@return | [
"Execute",
"a",
"Constant",
"expression",
"at",
"a",
"given",
"point",
"in",
"the",
"function",
"or",
"method",
"body"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/interpreter/Interpreter.java#L693-L728 |
logic-ng/LogicNG | src/main/java/org/logicng/solvers/sat/CleaneLingStyleSolver.java | CleaneLingStyleSolver.addWatch | protected void addWatch(final int lit, final int blit, final boolean binary, final CLClause clause) {
"""
Adds a new watcher for a given literal.
@param lit the literal
@param blit the blocking literal
@param binary indicates whether it is a binary clause or not
@param clause the watched clause
"""
watches(lit).push(new CLWatch(blit, binary, clause));
} | java | protected void addWatch(final int lit, final int blit, final boolean binary, final CLClause clause) {
watches(lit).push(new CLWatch(blit, binary, clause));
} | [
"protected",
"void",
"addWatch",
"(",
"final",
"int",
"lit",
",",
"final",
"int",
"blit",
",",
"final",
"boolean",
"binary",
",",
"final",
"CLClause",
"clause",
")",
"{",
"watches",
"(",
"lit",
")",
".",
"push",
"(",
"new",
"CLWatch",
"(",
"blit",
",",... | Adds a new watcher for a given literal.
@param lit the literal
@param blit the blocking literal
@param binary indicates whether it is a binary clause or not
@param clause the watched clause | [
"Adds",
"a",
"new",
"watcher",
"for",
"a",
"given",
"literal",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/sat/CleaneLingStyleSolver.java#L353-L355 |
cdk/cdk | base/dict/src/main/java/org/openscience/cdk/dict/DictionaryDatabase.java | DictionaryDatabase.hasEntry | public boolean hasEntry(String dictName, String entryID) {
"""
Returns true if the given dictionary contains the given
entry.
"""
if (hasDictionary(dictName)) {
Dictionary dictionary = (Dictionary) dictionaries.get(dictName);
return dictionary.hasEntry(entryID.toLowerCase());
} else {
return false;
}
} | java | public boolean hasEntry(String dictName, String entryID) {
if (hasDictionary(dictName)) {
Dictionary dictionary = (Dictionary) dictionaries.get(dictName);
return dictionary.hasEntry(entryID.toLowerCase());
} else {
return false;
}
} | [
"public",
"boolean",
"hasEntry",
"(",
"String",
"dictName",
",",
"String",
"entryID",
")",
"{",
"if",
"(",
"hasDictionary",
"(",
"dictName",
")",
")",
"{",
"Dictionary",
"dictionary",
"=",
"(",
"Dictionary",
")",
"dictionaries",
".",
"get",
"(",
"dictName",
... | Returns true if the given dictionary contains the given
entry. | [
"Returns",
"true",
"if",
"the",
"given",
"dictionary",
"contains",
"the",
"given",
"entry",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/dict/src/main/java/org/openscience/cdk/dict/DictionaryDatabase.java#L186-L193 |
FINRAOS/DataGenerator | dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/UserStub.java | UserStub.getStubWithRandomParams | public static UserStub getStubWithRandomParams(UserTypeVal userType) {
"""
Get random stub matching this user type
@param userType User type
@return Random stub
"""
// Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!
// Oh the joys of type erasure.
Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation();
return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()),
SocialNetworkUtilities.getRandomIsSecret());
} | java | public static UserStub getStubWithRandomParams(UserTypeVal userType) {
// Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!
// Oh the joys of type erasure.
Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation();
return new UserStub(userType, new Tuple2<>((Double) tuple._1(), (Double) tuple._2()),
SocialNetworkUtilities.getRandomIsSecret());
} | [
"public",
"static",
"UserStub",
"getStubWithRandomParams",
"(",
"UserTypeVal",
"userType",
")",
"{",
"// Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles!\r",
"// Oh the joys of type erasure.\r",
"Tuple2",
"<",
"Double",
",",
"Double",
"... | Get random stub matching this user type
@param userType User type
@return Random stub | [
"Get",
"random",
"stub",
"matching",
"this",
"user",
"type"
] | train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/UserStub.java#L116-L122 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.getDocLink | public Content getDocLink(LinkInfoImpl.Kind context, ClassDoc classDoc, MemberDoc doc,
Content label) {
"""
Return the link for the given member.
@param context the id of the context where the link will be added
@param classDoc the classDoc that we should link to. This is not
necessarily equal to doc.containingClass(). We may be
inheriting comments
@param doc the member being linked to
@param label the label for the link
@return the link for the given member
"""
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration))) {
return label;
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc) doc;
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(getAnchor(emd))));
} else if (doc instanceof MemberDoc) {
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(doc.name())));
} else {
return label;
}
} | java | public Content getDocLink(LinkInfoImpl.Kind context, ClassDoc classDoc, MemberDoc doc,
Content label) {
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration))) {
return label;
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc) doc;
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(getAnchor(emd))));
} else if (doc instanceof MemberDoc) {
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(doc.name())));
} else {
return label;
}
} | [
"public",
"Content",
"getDocLink",
"(",
"LinkInfoImpl",
".",
"Kind",
"context",
",",
"ClassDoc",
"classDoc",
",",
"MemberDoc",
"doc",
",",
"Content",
"label",
")",
"{",
"if",
"(",
"!",
"(",
"doc",
".",
"isIncluded",
"(",
")",
"||",
"Util",
".",
"isLinkab... | Return the link for the given member.
@param context the id of the context where the link will be added
@param classDoc the classDoc that we should link to. This is not
necessarily equal to doc.containingClass(). We may be
inheriting comments
@param doc the member being linked to
@param label the label for the link
@return the link for the given member | [
"Return",
"the",
"link",
"for",
"the",
"given",
"member",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L1317-L1332 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java | DependencyBundlingAnalyzer.isCore | protected boolean isCore(Dependency left, Dependency right) {
"""
This is likely a very broken attempt at determining if the 'left'
dependency is the 'core' library in comparison to the 'right' library.
@param left the dependency to test
@param right the dependency to test against
@return a boolean indicating whether or not the left dependency should be
considered the "core" version.
"""
final String leftName = left.getFileName().toLowerCase();
final String rightName = right.getFileName().toLowerCase();
final boolean returnVal;
//TODO - should we get rid of this merging? It removes a true BOM...
if (left.isVirtual() && !right.isVirtual()) {
returnVal = true;
} else if (!left.isVirtual() && right.isVirtual()) {
returnVal = false;
} else if ((!rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+"))
|| (rightName.contains("core") && !leftName.contains("core"))
|| (rightName.contains("kernel") && !leftName.contains("kernel"))
|| (rightName.contains("akka-stream") && !leftName.contains("akka-stream"))
|| (rightName.contains("netty-transport") && !leftName.contains("netty-transport"))) {
returnVal = false;
} else if ((rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && !leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+"))
|| (!rightName.contains("core") && leftName.contains("core"))
|| (!rightName.contains("kernel") && leftName.contains("kernel"))
|| (!rightName.contains("akka-stream") && leftName.contains("akka-stream"))
|| (!rightName.contains("netty-transport") && leftName.contains("netty-transport"))) {
returnVal = true;
} else {
/*
* considered splitting the names up and comparing the components,
* but decided that the file name length should be sufficient as the
* "core" component, if this follows a normal naming protocol should
* be shorter:
* axis2-saaj-1.4.1.jar
* axis2-1.4.1.jar <-----
* axis2-kernel-1.4.1.jar
*/
returnVal = leftName.length() <= rightName.length();
}
LOGGER.debug("IsCore={} ({}, {})", returnVal, left.getFileName(), right.getFileName());
return returnVal;
} | java | protected boolean isCore(Dependency left, Dependency right) {
final String leftName = left.getFileName().toLowerCase();
final String rightName = right.getFileName().toLowerCase();
final boolean returnVal;
//TODO - should we get rid of this merging? It removes a true BOM...
if (left.isVirtual() && !right.isVirtual()) {
returnVal = true;
} else if (!left.isVirtual() && right.isVirtual()) {
returnVal = false;
} else if ((!rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+"))
|| (rightName.contains("core") && !leftName.contains("core"))
|| (rightName.contains("kernel") && !leftName.contains("kernel"))
|| (rightName.contains("akka-stream") && !leftName.contains("akka-stream"))
|| (rightName.contains("netty-transport") && !leftName.contains("netty-transport"))) {
returnVal = false;
} else if ((rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && !leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+"))
|| (!rightName.contains("core") && leftName.contains("core"))
|| (!rightName.contains("kernel") && leftName.contains("kernel"))
|| (!rightName.contains("akka-stream") && leftName.contains("akka-stream"))
|| (!rightName.contains("netty-transport") && leftName.contains("netty-transport"))) {
returnVal = true;
} else {
/*
* considered splitting the names up and comparing the components,
* but decided that the file name length should be sufficient as the
* "core" component, if this follows a normal naming protocol should
* be shorter:
* axis2-saaj-1.4.1.jar
* axis2-1.4.1.jar <-----
* axis2-kernel-1.4.1.jar
*/
returnVal = leftName.length() <= rightName.length();
}
LOGGER.debug("IsCore={} ({}, {})", returnVal, left.getFileName(), right.getFileName());
return returnVal;
} | [
"protected",
"boolean",
"isCore",
"(",
"Dependency",
"left",
",",
"Dependency",
"right",
")",
"{",
"final",
"String",
"leftName",
"=",
"left",
".",
"getFileName",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"final",
"String",
"rightName",
"=",
"right",
".... | This is likely a very broken attempt at determining if the 'left'
dependency is the 'core' library in comparison to the 'right' library.
@param left the dependency to test
@param right the dependency to test against
@return a boolean indicating whether or not the left dependency should be
considered the "core" version. | [
"This",
"is",
"likely",
"a",
"very",
"broken",
"attempt",
"at",
"determining",
"if",
"the",
"left",
"dependency",
"is",
"the",
"core",
"library",
"in",
"comparison",
"to",
"the",
"right",
"library",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java#L342-L379 |
UrielCh/ovh-java-sdk | ovh-java-sdk-caascontainers/src/main/java/net/minidev/ovh/api/ApiOvhCaascontainers.java | ApiOvhCaascontainers.serviceName_registry_credentials_credentialsId_GET | public OvhRegistryCredentials serviceName_registry_credentials_credentialsId_GET(String serviceName, String credentialsId) throws IOException {
"""
Inspect the image registry credentials associated to the stack
REST: GET /caas/containers/{serviceName}/registry/credentials/{credentialsId}
@param credentialsId [required] credentials id
@param serviceName [required] service name
API beta
"""
String qPath = "/caas/containers/{serviceName}/registry/credentials/{credentialsId}";
StringBuilder sb = path(qPath, serviceName, credentialsId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRegistryCredentials.class);
} | java | public OvhRegistryCredentials serviceName_registry_credentials_credentialsId_GET(String serviceName, String credentialsId) throws IOException {
String qPath = "/caas/containers/{serviceName}/registry/credentials/{credentialsId}";
StringBuilder sb = path(qPath, serviceName, credentialsId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRegistryCredentials.class);
} | [
"public",
"OvhRegistryCredentials",
"serviceName_registry_credentials_credentialsId_GET",
"(",
"String",
"serviceName",
",",
"String",
"credentialsId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/caas/containers/{serviceName}/registry/credentials/{credentialsId}\""... | Inspect the image registry credentials associated to the stack
REST: GET /caas/containers/{serviceName}/registry/credentials/{credentialsId}
@param credentialsId [required] credentials id
@param serviceName [required] service name
API beta | [
"Inspect",
"the",
"image",
"registry",
"credentials",
"associated",
"to",
"the",
"stack"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-caascontainers/src/main/java/net/minidev/ovh/api/ApiOvhCaascontainers.java#L295-L300 |
hazelcast/hazelcast | hazelcast-client/src/main/java/com/hazelcast/client/config/ClientConfig.java | ClientConfig.setNearCacheConfigMap | public ClientConfig setNearCacheConfigMap(Map<String, NearCacheConfig> nearCacheConfigMap) {
"""
Sets all {@link NearCacheConfig}'s with the provided map
@param nearCacheConfigMap map of (name, {@link NearCacheConfig})
@return configured {@link com.hazelcast.client.config.ClientConfig} for chaining
"""
Preconditions.isNotNull(nearCacheConfigMap, "nearCacheConfigMap");
this.nearCacheConfigMap.clear();
this.nearCacheConfigMap.putAll(nearCacheConfigMap);
for (Entry<String, NearCacheConfig> entry : this.nearCacheConfigMap.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | java | public ClientConfig setNearCacheConfigMap(Map<String, NearCacheConfig> nearCacheConfigMap) {
Preconditions.isNotNull(nearCacheConfigMap, "nearCacheConfigMap");
this.nearCacheConfigMap.clear();
this.nearCacheConfigMap.putAll(nearCacheConfigMap);
for (Entry<String, NearCacheConfig> entry : this.nearCacheConfigMap.entrySet()) {
entry.getValue().setName(entry.getKey());
}
return this;
} | [
"public",
"ClientConfig",
"setNearCacheConfigMap",
"(",
"Map",
"<",
"String",
",",
"NearCacheConfig",
">",
"nearCacheConfigMap",
")",
"{",
"Preconditions",
".",
"isNotNull",
"(",
"nearCacheConfigMap",
",",
"\"nearCacheConfigMap\"",
")",
";",
"this",
".",
"nearCacheCon... | Sets all {@link NearCacheConfig}'s with the provided map
@param nearCacheConfigMap map of (name, {@link NearCacheConfig})
@return configured {@link com.hazelcast.client.config.ClientConfig} for chaining | [
"Sets",
"all",
"{",
"@link",
"NearCacheConfig",
"}",
"s",
"with",
"the",
"provided",
"map"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast-client/src/main/java/com/hazelcast/client/config/ClientConfig.java#L402-L410 |
clanie/clanie-core | src/main/java/dk/clanie/collections/Tuple.java | Tuple.elementsEquals | protected static boolean elementsEquals(Object e1, Object e2) {
"""
Helper-method to check if two elements are equal.
@param e1
@param e2
@return true if both e1 and e2 are null or if e1.equals(e2).
"""
return (e1 == null && e2 == null) || e1.equals(e2);
} | java | protected static boolean elementsEquals(Object e1, Object e2) {
return (e1 == null && e2 == null) || e1.equals(e2);
} | [
"protected",
"static",
"boolean",
"elementsEquals",
"(",
"Object",
"e1",
",",
"Object",
"e2",
")",
"{",
"return",
"(",
"e1",
"==",
"null",
"&&",
"e2",
"==",
"null",
")",
"||",
"e1",
".",
"equals",
"(",
"e2",
")",
";",
"}"
] | Helper-method to check if two elements are equal.
@param e1
@param e2
@return true if both e1 and e2 are null or if e1.equals(e2). | [
"Helper",
"-",
"method",
"to",
"check",
"if",
"two",
"elements",
"are",
"equal",
"."
] | train | https://github.com/clanie/clanie-core/blob/ac8a655b93127f0e281b741c4d53f429be2816ad/src/main/java/dk/clanie/collections/Tuple.java#L348-L350 |
JakeWharton/NineOldAndroids | library/src/com/nineoldandroids/view/ViewPropertyAnimatorPreHC.java | ViewPropertyAnimatorPreHC.animatePropertyBy | private void animatePropertyBy(int constantName, float byValue) {
"""
Utility function, called by the various xBy(), yBy(), etc. methods. This method is
just like animateProperty(), except the value is an offset from the property's
current value, instead of an absolute "to" value.
@param constantName The specifier for the property being animated
@param byValue The amount by which the property will change
"""
float fromValue = getValue(constantName);
animatePropertyBy(constantName, fromValue, byValue);
} | java | private void animatePropertyBy(int constantName, float byValue) {
float fromValue = getValue(constantName);
animatePropertyBy(constantName, fromValue, byValue);
} | [
"private",
"void",
"animatePropertyBy",
"(",
"int",
"constantName",
",",
"float",
"byValue",
")",
"{",
"float",
"fromValue",
"=",
"getValue",
"(",
"constantName",
")",
";",
"animatePropertyBy",
"(",
"constantName",
",",
"fromValue",
",",
"byValue",
")",
";",
"... | Utility function, called by the various xBy(), yBy(), etc. methods. This method is
just like animateProperty(), except the value is an offset from the property's
current value, instead of an absolute "to" value.
@param constantName The specifier for the property being animated
@param byValue The amount by which the property will change | [
"Utility",
"function",
"called",
"by",
"the",
"various",
"xBy",
"()",
"yBy",
"()",
"etc",
".",
"methods",
".",
"This",
"method",
"is",
"just",
"like",
"animateProperty",
"()",
"except",
"the",
"value",
"is",
"an",
"offset",
"from",
"the",
"property",
"s",
... | train | https://github.com/JakeWharton/NineOldAndroids/blob/d582f0ec8e79013e9fa96c07986160b52e662e63/library/src/com/nineoldandroids/view/ViewPropertyAnimatorPreHC.java#L487-L490 |
JOML-CI/JOML | src/org/joml/Matrix3d.java | Matrix3d.setColumn | public Matrix3d setColumn(int column, double x, double y, double z) throws IndexOutOfBoundsException {
"""
Set the column at the given <code>column</code> index, starting with <code>0</code>.
@param column
the column index in <code>[0..2]</code>
@param x
the first element in the column
@param y
the second element in the column
@param z
the third element in the column
@return this
@throws IndexOutOfBoundsException if <code>column</code> is not in <code>[0..2]</code>
"""
switch (column) {
case 0:
this.m00 = x;
this.m01 = y;
this.m02 = z;
break;
case 1:
this.m10 = x;
this.m11 = y;
this.m12 = z;
break;
case 2:
this.m20 = x;
this.m21 = y;
this.m22 = z;
break;
default:
throw new IndexOutOfBoundsException();
}
return this;
} | java | public Matrix3d setColumn(int column, double x, double y, double z) throws IndexOutOfBoundsException {
switch (column) {
case 0:
this.m00 = x;
this.m01 = y;
this.m02 = z;
break;
case 1:
this.m10 = x;
this.m11 = y;
this.m12 = z;
break;
case 2:
this.m20 = x;
this.m21 = y;
this.m22 = z;
break;
default:
throw new IndexOutOfBoundsException();
}
return this;
} | [
"public",
"Matrix3d",
"setColumn",
"(",
"int",
"column",
",",
"double",
"x",
",",
"double",
"y",
",",
"double",
"z",
")",
"throws",
"IndexOutOfBoundsException",
"{",
"switch",
"(",
"column",
")",
"{",
"case",
"0",
":",
"this",
".",
"m00",
"=",
"x",
";"... | Set the column at the given <code>column</code> index, starting with <code>0</code>.
@param column
the column index in <code>[0..2]</code>
@param x
the first element in the column
@param y
the second element in the column
@param z
the third element in the column
@return this
@throws IndexOutOfBoundsException if <code>column</code> is not in <code>[0..2]</code> | [
"Set",
"the",
"column",
"at",
"the",
"given",
"<code",
">",
"column<",
"/",
"code",
">",
"index",
"starting",
"with",
"<code",
">",
"0<",
"/",
"code",
">",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3d.java#L3607-L3628 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.ipxeScript_name_GET | public OvhIpxe ipxeScript_name_GET(String name) throws IOException {
"""
Get this object properties
REST: GET /me/ipxeScript/{name}
@param name [required] Name of this script
"""
String qPath = "/me/ipxeScript/{name}";
StringBuilder sb = path(qPath, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhIpxe.class);
} | java | public OvhIpxe ipxeScript_name_GET(String name) throws IOException {
String qPath = "/me/ipxeScript/{name}";
StringBuilder sb = path(qPath, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhIpxe.class);
} | [
"public",
"OvhIpxe",
"ipxeScript_name_GET",
"(",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/ipxeScript/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"name",
")",
";",
"String",
"resp",
"=",
"exe... | Get this object properties
REST: GET /me/ipxeScript/{name}
@param name [required] Name of this script | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L937-L942 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/UnboundMethodTemplateParameter.java | UnboundMethodTemplateParameter.isTemplateParent | private boolean isTemplateParent(String templateType, TemplateItem... items) {
"""
looks to see if this templateType is a parent of another template type
@param templateType
the type to look for
@param items
the items to search
@return whether this template type is something another template type extends
"""
for (TemplateItem item : items) {
if (templateType.equals(item.templateExtension)) {
return true;
}
}
return false;
} | java | private boolean isTemplateParent(String templateType, TemplateItem... items) {
for (TemplateItem item : items) {
if (templateType.equals(item.templateExtension)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"isTemplateParent",
"(",
"String",
"templateType",
",",
"TemplateItem",
"...",
"items",
")",
"{",
"for",
"(",
"TemplateItem",
"item",
":",
"items",
")",
"{",
"if",
"(",
"templateType",
".",
"equals",
"(",
"item",
".",
"templateExtension",... | looks to see if this templateType is a parent of another template type
@param templateType
the type to look for
@param items
the items to search
@return whether this template type is something another template type extends | [
"looks",
"to",
"see",
"if",
"this",
"templateType",
"is",
"a",
"parent",
"of",
"another",
"template",
"type"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/UnboundMethodTemplateParameter.java#L110-L118 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/trees/Treebank.java | Treebank.loadPath | public void loadPath(File path, String suffix, boolean recursively) {
"""
Load trees from given directory.
@param path file or directory to load from
@param suffix suffix of files to load
@param recursively descend into subdirectories as well
"""
loadPath(path, new ExtensionFileFilter(suffix, recursively));
} | java | public void loadPath(File path, String suffix, boolean recursively) {
loadPath(path, new ExtensionFileFilter(suffix, recursively));
} | [
"public",
"void",
"loadPath",
"(",
"File",
"path",
",",
"String",
"suffix",
",",
"boolean",
"recursively",
")",
"{",
"loadPath",
"(",
"path",
",",
"new",
"ExtensionFileFilter",
"(",
"suffix",
",",
"recursively",
")",
")",
";",
"}"
] | Load trees from given directory.
@param path file or directory to load from
@param suffix suffix of files to load
@param recursively descend into subdirectories as well | [
"Load",
"trees",
"from",
"given",
"directory",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/Treebank.java#L178-L180 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/LoggingSubsystemParser.java | LoggingSubsystemParser.parseFilter | static void parseFilter(final ModelNode operation, final XMLExtendedStreamReader reader) throws XMLStreamException {
"""
A helper to parse the deprecated {@code filter} for schema versions {@code 1.0} and {@code 1.1}. This parses the
XML and creates a {@code filter-spec} expression. The expression is set as the value for the {@code filter-spec}
attribute on the operation.
@param operation the operation to add the parsed filter to
@param reader the reader used to read the filter
@throws XMLStreamException if a parsing error occurs
"""
final StringBuilder filter = new StringBuilder();
parseFilterChildren(filter, false, reader);
operation.get(FILTER_SPEC.getName()).set(filter.toString());
} | java | static void parseFilter(final ModelNode operation, final XMLExtendedStreamReader reader) throws XMLStreamException {
final StringBuilder filter = new StringBuilder();
parseFilterChildren(filter, false, reader);
operation.get(FILTER_SPEC.getName()).set(filter.toString());
} | [
"static",
"void",
"parseFilter",
"(",
"final",
"ModelNode",
"operation",
",",
"final",
"XMLExtendedStreamReader",
"reader",
")",
"throws",
"XMLStreamException",
"{",
"final",
"StringBuilder",
"filter",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"parseFilterChildren",... | A helper to parse the deprecated {@code filter} for schema versions {@code 1.0} and {@code 1.1}. This parses the
XML and creates a {@code filter-spec} expression. The expression is set as the value for the {@code filter-spec}
attribute on the operation.
@param operation the operation to add the parsed filter to
@param reader the reader used to read the filter
@throws XMLStreamException if a parsing error occurs | [
"A",
"helper",
"to",
"parse",
"the",
"deprecated",
"{",
"@code",
"filter",
"}",
"for",
"schema",
"versions",
"{",
"@code",
"1",
".",
"0",
"}",
"and",
"{",
"@code",
"1",
".",
"1",
"}",
".",
"This",
"parses",
"the",
"XML",
"and",
"creates",
"a",
"{",... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/LoggingSubsystemParser.java#L182-L186 |
sebastiangraf/treetank | interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/algorithm/fmes/Matching.java | Matching.updateSubtreeMap | private void updateSubtreeMap(final ITreeData paramNode, final INodeReadTrx paramRtx) throws TTIOException {
"""
For each anchestor of n: n is in it's subtree.
@param paramNode
node in subtree
@param paramRtx
{@link IReadTransaction} reference
@throws TTIOException
"""
assert paramNode != null;
assert paramRtx != null;
mIsInSubtree.set(paramNode, paramNode, true);
if (paramNode.hasParent()) {
paramRtx.moveTo(paramNode.getDataKey());
while (((ITreeStructData)paramRtx.getNode()).hasParent()) {
paramRtx.moveTo(paramRtx.getNode().getParentKey());
mIsInSubtree.set(paramRtx.getNode(), paramNode, true);
}
}
} | java | private void updateSubtreeMap(final ITreeData paramNode, final INodeReadTrx paramRtx) throws TTIOException {
assert paramNode != null;
assert paramRtx != null;
mIsInSubtree.set(paramNode, paramNode, true);
if (paramNode.hasParent()) {
paramRtx.moveTo(paramNode.getDataKey());
while (((ITreeStructData)paramRtx.getNode()).hasParent()) {
paramRtx.moveTo(paramRtx.getNode().getParentKey());
mIsInSubtree.set(paramRtx.getNode(), paramNode, true);
}
}
} | [
"private",
"void",
"updateSubtreeMap",
"(",
"final",
"ITreeData",
"paramNode",
",",
"final",
"INodeReadTrx",
"paramRtx",
")",
"throws",
"TTIOException",
"{",
"assert",
"paramNode",
"!=",
"null",
";",
"assert",
"paramRtx",
"!=",
"null",
";",
"mIsInSubtree",
".",
... | For each anchestor of n: n is in it's subtree.
@param paramNode
node in subtree
@param paramRtx
{@link IReadTransaction} reference
@throws TTIOException | [
"For",
"each",
"anchestor",
"of",
"n",
":",
"n",
"is",
"in",
"it",
"s",
"subtree",
"."
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/algorithm/fmes/Matching.java#L122-L134 |
jenkinsci/jenkins | core/src/main/java/hudson/util/LineEndingConversion.java | LineEndingConversion.convertEOL | public static String convertEOL(String input, EOLType type) {
"""
Convert line endings of a string to the given type. Default to Unix type.
@param input
The string containing line endings to be converted.
@param type
Type of line endings to convert the string into.
@return
String updated with the new line endings or null if given null.
"""
if (null == input || 0 == input.length()) {
return input;
}
// Convert line endings to Unix LF,
// which also sets up the string for other conversions
input = input.replace("\r\n","\n");
input = input.replace("\r","\n");
switch (type) {
case CR:
case Mac:
// Convert line endings to CR
input = input.replace("\n", "\r");
break;
case CRLF:
case Windows:
// Convert line endings to Windows CR/LF
input = input.replace("\n", "\r\n");
break;
default:
case LF:
case Unix:
// Conversion already completed
return input;
case LFCR:
// Convert line endings to LF/CR
input = input.replace("\n", "\n\r");
break;
}
return input;
} | java | public static String convertEOL(String input, EOLType type) {
if (null == input || 0 == input.length()) {
return input;
}
// Convert line endings to Unix LF,
// which also sets up the string for other conversions
input = input.replace("\r\n","\n");
input = input.replace("\r","\n");
switch (type) {
case CR:
case Mac:
// Convert line endings to CR
input = input.replace("\n", "\r");
break;
case CRLF:
case Windows:
// Convert line endings to Windows CR/LF
input = input.replace("\n", "\r\n");
break;
default:
case LF:
case Unix:
// Conversion already completed
return input;
case LFCR:
// Convert line endings to LF/CR
input = input.replace("\n", "\n\r");
break;
}
return input;
} | [
"public",
"static",
"String",
"convertEOL",
"(",
"String",
"input",
",",
"EOLType",
"type",
")",
"{",
"if",
"(",
"null",
"==",
"input",
"||",
"0",
"==",
"input",
".",
"length",
"(",
")",
")",
"{",
"return",
"input",
";",
"}",
"// Convert line endings to ... | Convert line endings of a string to the given type. Default to Unix type.
@param input
The string containing line endings to be converted.
@param type
Type of line endings to convert the string into.
@return
String updated with the new line endings or null if given null. | [
"Convert",
"line",
"endings",
"of",
"a",
"string",
"to",
"the",
"given",
"type",
".",
"Default",
"to",
"Unix",
"type",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/LineEndingConversion.java#L34-L64 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/qjournal/server/JournalNodeHttpServer.java | JournalNodeHttpServer.sendResponse | static void sendResponse(String output, HttpServletResponse response)
throws IOException {
"""
Send string output when serving http request.
@param output data to be sent
@param response http response
@throws IOException
"""
PrintWriter out = null;
try {
out = response.getWriter();
out.write(output);
} finally {
if (out != null) {
out.close();
}
}
} | java | static void sendResponse(String output, HttpServletResponse response)
throws IOException {
PrintWriter out = null;
try {
out = response.getWriter();
out.write(output);
} finally {
if (out != null) {
out.close();
}
}
} | [
"static",
"void",
"sendResponse",
"(",
"String",
"output",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"PrintWriter",
"out",
"=",
"null",
";",
"try",
"{",
"out",
"=",
"response",
".",
"getWriter",
"(",
")",
";",
"out",
".",
"... | Send string output when serving http request.
@param output data to be sent
@param response http response
@throws IOException | [
"Send",
"string",
"output",
"when",
"serving",
"http",
"request",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/qjournal/server/JournalNodeHttpServer.java#L157-L168 |
fracpete/multisearch-weka-package | src/main/java/weka/core/setupgenerator/ListParameter.java | ListParameter.spaceDimension | public SpaceDimension spaceDimension() throws Exception {
"""
Returns the parameter as space dimensions.
@return the dimension
@throws Exception if instantiation of dimension fails
"""
String[] items;
items = getItems();
return new ListSpaceDimension(0, items.length - 1, items, getProperty());
} | java | public SpaceDimension spaceDimension() throws Exception {
String[] items;
items = getItems();
return new ListSpaceDimension(0, items.length - 1, items, getProperty());
} | [
"public",
"SpaceDimension",
"spaceDimension",
"(",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"items",
";",
"items",
"=",
"getItems",
"(",
")",
";",
"return",
"new",
"ListSpaceDimension",
"(",
"0",
",",
"items",
".",
"length",
"-",
"1",
",",
"i... | Returns the parameter as space dimensions.
@return the dimension
@throws Exception if instantiation of dimension fails | [
"Returns",
"the",
"parameter",
"as",
"space",
"dimensions",
"."
] | train | https://github.com/fracpete/multisearch-weka-package/blob/756fcf343e7cc9fd3844c99a0e1e828368f393d0/src/main/java/weka/core/setupgenerator/ListParameter.java#L219-L224 |
wildfly/wildfly-core | elytron/src/main/java/org/wildfly/extension/elytron/ModifiableRealmDecorator.java | ModifiableRealmDecorator.getRealmIdentity | static ModifiableRealmIdentity getRealmIdentity(OperationContext context, String principalName) throws OperationFailedException {
"""
Try to obtain a {@link ModifiableRealmIdentity} based on the identity and {@link ModifiableSecurityRealm} associated with given {@link OperationContext}.
@param context the current context
@return the current identity
@throws OperationFailedException if the identity does not exists or if any error occurs while obtaining it.
"""
ModifiableSecurityRealm modifiableRealm = getModifiableSecurityRealm(context);
ModifiableRealmIdentity realmIdentity = null;
try {
realmIdentity = modifiableRealm.getRealmIdentityForUpdate(new NamePrincipal(principalName));
if (!realmIdentity.exists()) {
throw new OperationFailedException(ROOT_LOGGER.identityNotFound(principalName));
}
return realmIdentity;
} catch (RealmUnavailableException e) {
throw ROOT_LOGGER.couldNotReadIdentity(principalName, e);
} finally {
if (realmIdentity != null) {
realmIdentity.dispose();
}
}
} | java | static ModifiableRealmIdentity getRealmIdentity(OperationContext context, String principalName) throws OperationFailedException {
ModifiableSecurityRealm modifiableRealm = getModifiableSecurityRealm(context);
ModifiableRealmIdentity realmIdentity = null;
try {
realmIdentity = modifiableRealm.getRealmIdentityForUpdate(new NamePrincipal(principalName));
if (!realmIdentity.exists()) {
throw new OperationFailedException(ROOT_LOGGER.identityNotFound(principalName));
}
return realmIdentity;
} catch (RealmUnavailableException e) {
throw ROOT_LOGGER.couldNotReadIdentity(principalName, e);
} finally {
if (realmIdentity != null) {
realmIdentity.dispose();
}
}
} | [
"static",
"ModifiableRealmIdentity",
"getRealmIdentity",
"(",
"OperationContext",
"context",
",",
"String",
"principalName",
")",
"throws",
"OperationFailedException",
"{",
"ModifiableSecurityRealm",
"modifiableRealm",
"=",
"getModifiableSecurityRealm",
"(",
"context",
")",
"... | Try to obtain a {@link ModifiableRealmIdentity} based on the identity and {@link ModifiableSecurityRealm} associated with given {@link OperationContext}.
@param context the current context
@return the current identity
@throws OperationFailedException if the identity does not exists or if any error occurs while obtaining it. | [
"Try",
"to",
"obtain",
"a",
"{",
"@link",
"ModifiableRealmIdentity",
"}",
"based",
"on",
"the",
"identity",
"and",
"{",
"@link",
"ModifiableSecurityRealm",
"}",
"associated",
"with",
"given",
"{",
"@link",
"OperationContext",
"}",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/elytron/src/main/java/org/wildfly/extension/elytron/ModifiableRealmDecorator.java#L628-L646 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/SibTr.java | SibTr.formatBytes | public static String formatBytes (byte[] data, int start, int count, int max) {
"""
Produce a formatted view of a limited portion of a byte array.
Duplicate output lines are suppressed to save space.
Formatting of the byte array starts at the specified position and continues
for count, max, or the end of the data, whichever occurs first.
<p>
@param data the byte array to be formatted
@param start position to start formatting the byte array
@param count of bytes from start position that should be formatted
@param max maximun number of bytes from start position that should be formatted,
regardless of the value of length.
@return the formatted byte array
"""
StringBuilder sb = new StringBuilder(256);
sb.append(ls);
formatBytesToSB(sb, data, start, count, true, max);
return sb.toString();
} | java | public static String formatBytes (byte[] data, int start, int count, int max) {
StringBuilder sb = new StringBuilder(256);
sb.append(ls);
formatBytesToSB(sb, data, start, count, true, max);
return sb.toString();
} | [
"public",
"static",
"String",
"formatBytes",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"start",
",",
"int",
"count",
",",
"int",
"max",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"256",
")",
";",
"sb",
".",
"append",
"(",
"ls... | Produce a formatted view of a limited portion of a byte array.
Duplicate output lines are suppressed to save space.
Formatting of the byte array starts at the specified position and continues
for count, max, or the end of the data, whichever occurs first.
<p>
@param data the byte array to be formatted
@param start position to start formatting the byte array
@param count of bytes from start position that should be formatted
@param max maximun number of bytes from start position that should be formatted,
regardless of the value of length.
@return the formatted byte array | [
"Produce",
"a",
"formatted",
"view",
"of",
"a",
"limited",
"portion",
"of",
"a",
"byte",
"array",
".",
"Duplicate",
"output",
"lines",
"are",
"suppressed",
"to",
"save",
"space",
".",
"Formatting",
"of",
"the",
"byte",
"array",
"starts",
"at",
"the",
"spec... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/SibTr.java#L1458-L1463 |
yavijava/yavijava | src/main/java/com/vmware/vim25/mo/IoFilterManager.java | IoFilterManager.resolveInstallationErrorsOnCluster_Task | public Task resolveInstallationErrorsOnCluster_Task(String filterId, ClusterComputeResource cluster) throws NotFound, RuntimeFault, RemoteException {
"""
Resolve the errors occured during an installation/uninstallation/upgrade operation of an IO Filter on a cluster.
Depending on the nature of the installation failure, vCenter will take the appropriate actions to resolve it. For
example, retry or resume installation.
@param filterId
- ID of the filter.
@param cluster
- The compute resource to install the IO Filter on. "compRes" must be a cluster.
@return - This method returns a Task object with which to monitor the operation. The task is set to success if
all the errors related to the filter are resolved on the cluster. If the task fails, first check error to
see the error. If the error indicates that issues persist on the cluster, use QueryIoFilterIssues to get
the detailed errors on the hosts in the cluster. The dynamic privilege check will ensure that the
appropriate privileges must be acquired for all the hosts in the cluster based on the remediation
actions. For example, Host.Config.Maintenance privilege and Host.Config.Patch privileges must be required
for upgrading a VIB.
@throws RuntimeFault
- Thrown if any type of runtime fault is thrown that is not covered by the other faults; for example,
a communication error.
@throws NotFound
@throws RemoteException
"""
return new Task(getServerConnection(), getVimService().resolveInstallationErrorsOnCluster_Task(getMOR(), filterId, cluster.getMOR()));
} | java | public Task resolveInstallationErrorsOnCluster_Task(String filterId, ClusterComputeResource cluster) throws NotFound, RuntimeFault, RemoteException {
return new Task(getServerConnection(), getVimService().resolveInstallationErrorsOnCluster_Task(getMOR(), filterId, cluster.getMOR()));
} | [
"public",
"Task",
"resolveInstallationErrorsOnCluster_Task",
"(",
"String",
"filterId",
",",
"ClusterComputeResource",
"cluster",
")",
"throws",
"NotFound",
",",
"RuntimeFault",
",",
"RemoteException",
"{",
"return",
"new",
"Task",
"(",
"getServerConnection",
"(",
")",
... | Resolve the errors occured during an installation/uninstallation/upgrade operation of an IO Filter on a cluster.
Depending on the nature of the installation failure, vCenter will take the appropriate actions to resolve it. For
example, retry or resume installation.
@param filterId
- ID of the filter.
@param cluster
- The compute resource to install the IO Filter on. "compRes" must be a cluster.
@return - This method returns a Task object with which to monitor the operation. The task is set to success if
all the errors related to the filter are resolved on the cluster. If the task fails, first check error to
see the error. If the error indicates that issues persist on the cluster, use QueryIoFilterIssues to get
the detailed errors on the hosts in the cluster. The dynamic privilege check will ensure that the
appropriate privileges must be acquired for all the hosts in the cluster based on the remediation
actions. For example, Host.Config.Maintenance privilege and Host.Config.Patch privileges must be required
for upgrading a VIB.
@throws RuntimeFault
- Thrown if any type of runtime fault is thrown that is not covered by the other faults; for example,
a communication error.
@throws NotFound
@throws RemoteException | [
"Resolve",
"the",
"errors",
"occured",
"during",
"an",
"installation",
"/",
"uninstallation",
"/",
"upgrade",
"operation",
"of",
"an",
"IO",
"Filter",
"on",
"a",
"cluster",
".",
"Depending",
"on",
"the",
"nature",
"of",
"the",
"installation",
"failure",
"vCent... | train | https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/IoFilterManager.java#L151-L153 |
wisdom-framework/wisdom | framework/i18n-service/src/main/java/org/wisdom/i18n/InternationalizationServiceSingleton.java | InternationalizationServiceSingleton.removedBundle | @Override
public void removedBundle(Bundle bundle, BundleEvent event, List<I18nExtension> list) {
"""
A bundle tracked by the {@code BundleTracker} has been removed.
<p/>
<p/>
This method is called after a bundle is no longer being tracked by the
{@code BundleTracker}.
@param bundle The {@code Bundle} that has been removed.
@param event The bundle event which caused this customizer method to be
called or {@code null} if there is no bundle event associated
with the call to this method.
@param list The tracked object for the specified bundle.
"""
String current = Long.toString(System.currentTimeMillis());
for (I18nExtension extension : list) {
synchronized (this) {
extensions.remove(extension);
etags.put(extension.locale(), current);
}
}
LOGGER.info("Bundle {} ({}) does not offer the {} resource bundle(s) anymore",
bundle.getSymbolicName(), bundle.getBundleId(), list.size());
} | java | @Override
public void removedBundle(Bundle bundle, BundleEvent event, List<I18nExtension> list) {
String current = Long.toString(System.currentTimeMillis());
for (I18nExtension extension : list) {
synchronized (this) {
extensions.remove(extension);
etags.put(extension.locale(), current);
}
}
LOGGER.info("Bundle {} ({}) does not offer the {} resource bundle(s) anymore",
bundle.getSymbolicName(), bundle.getBundleId(), list.size());
} | [
"@",
"Override",
"public",
"void",
"removedBundle",
"(",
"Bundle",
"bundle",
",",
"BundleEvent",
"event",
",",
"List",
"<",
"I18nExtension",
">",
"list",
")",
"{",
"String",
"current",
"=",
"Long",
".",
"toString",
"(",
"System",
".",
"currentTimeMillis",
"(... | A bundle tracked by the {@code BundleTracker} has been removed.
<p/>
<p/>
This method is called after a bundle is no longer being tracked by the
{@code BundleTracker}.
@param bundle The {@code Bundle} that has been removed.
@param event The bundle event which caused this customizer method to be
called or {@code null} if there is no bundle event associated
with the call to this method.
@param list The tracked object for the specified bundle. | [
"A",
"bundle",
"tracked",
"by",
"the",
"{",
"@code",
"BundleTracker",
"}",
"has",
"been",
"removed",
".",
"<p",
"/",
">",
"<p",
"/",
">",
"This",
"method",
"is",
"called",
"after",
"a",
"bundle",
"is",
"no",
"longer",
"being",
"tracked",
"by",
"the",
... | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/i18n-service/src/main/java/org/wisdom/i18n/InternationalizationServiceSingleton.java#L351-L362 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/TextComponentPainter.java | TextComponentPainter.paintBorder | private void paintBorder(Graphics2D g, JComponent c, int x, int y, int width, int height) {
"""
Paint the border.
@param g DOCUMENT ME!
@param c DOCUMENT ME!
@param x DOCUMENT ME!
@param y DOCUMENT ME!
@param width DOCUMENT ME!
@param height DOCUMENT ME!
"""
boolean useToolBarColors = isInToolBar(c);
Shape s;
if (focused) {
s = shapeGenerator.createRoundRectangle(x - 2, y - 2, width + 3, height + 3, CornerSize.OUTER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.OUTER_FOCUS, useToolBarColors));
g.draw(s);
s = shapeGenerator.createRoundRectangle(x - 1, y - 1, width + 1, height + 1, CornerSize.INNER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.INNER_FOCUS, useToolBarColors));
g.draw(s);
}
if (type != CommonControlState.DISABLED) {
s = shapeGenerator.createRoundRectangle(x + 1, x + 1, width - 2, height - 2, CornerSize.BORDER);
internalShadow.fill(g, s, false, true);
}
s = shapeGenerator.createRoundRectangle(x, y, width - 1, height - 1, CornerSize.BORDER);
g.setPaint(getTextBorderPaint(type, !focused && useToolBarColors));
g.draw(s);
} | java | private void paintBorder(Graphics2D g, JComponent c, int x, int y, int width, int height) {
boolean useToolBarColors = isInToolBar(c);
Shape s;
if (focused) {
s = shapeGenerator.createRoundRectangle(x - 2, y - 2, width + 3, height + 3, CornerSize.OUTER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.OUTER_FOCUS, useToolBarColors));
g.draw(s);
s = shapeGenerator.createRoundRectangle(x - 1, y - 1, width + 1, height + 1, CornerSize.INNER_FOCUS);
g.setPaint(getFocusPaint(s, FocusType.INNER_FOCUS, useToolBarColors));
g.draw(s);
}
if (type != CommonControlState.DISABLED) {
s = shapeGenerator.createRoundRectangle(x + 1, x + 1, width - 2, height - 2, CornerSize.BORDER);
internalShadow.fill(g, s, false, true);
}
s = shapeGenerator.createRoundRectangle(x, y, width - 1, height - 1, CornerSize.BORDER);
g.setPaint(getTextBorderPaint(type, !focused && useToolBarColors));
g.draw(s);
} | [
"private",
"void",
"paintBorder",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"boolean",
"useToolBarColors",
"=",
"isInToolBar",
"(",
"c",
")",
";",
"Shape",
"s"... | Paint the border.
@param g DOCUMENT ME!
@param c DOCUMENT ME!
@param x DOCUMENT ME!
@param y DOCUMENT ME!
@param width DOCUMENT ME!
@param height DOCUMENT ME! | [
"Paint",
"the",
"border",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TextComponentPainter.java#L232-L253 |
netty/netty | example/src/main/java/io/netty/example/http2/helloworld/client/HttpResponseHandler.java | HttpResponseHandler.awaitResponses | public void awaitResponses(long timeout, TimeUnit unit) {
"""
Wait (sequentially) for a time duration for each anticipated response
@param timeout Value of time to wait for each response
@param unit Units associated with {@code timeout}
@see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
"""
Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
ChannelFuture writeFuture = entry.getValue().getKey();
if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
}
if (!writeFuture.isSuccess()) {
throw new RuntimeException(writeFuture.cause());
}
ChannelPromise promise = entry.getValue().getValue();
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
System.out.println("---Stream id: " + entry.getKey() + " received---");
itr.remove();
}
} | java | public void awaitResponses(long timeout, TimeUnit unit) {
Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
ChannelFuture writeFuture = entry.getValue().getKey();
if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
}
if (!writeFuture.isSuccess()) {
throw new RuntimeException(writeFuture.cause());
}
ChannelPromise promise = entry.getValue().getValue();
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
System.out.println("---Stream id: " + entry.getKey() + " received---");
itr.remove();
}
} | [
"public",
"void",
"awaitResponses",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"Integer",
",",
"Entry",
"<",
"ChannelFuture",
",",
"ChannelPromise",
">",
">",
">",
"itr",
"=",
"streamidPromiseMap",
".",
"entrySe... | Wait (sequentially) for a time duration for each anticipated response
@param timeout Value of time to wait for each response
@param unit Units associated with {@code timeout}
@see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise) | [
"Wait",
"(",
"sequentially",
")",
"for",
"a",
"time",
"duration",
"for",
"each",
"anticipated",
"response"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http2/helloworld/client/HttpResponseHandler.java#L66-L87 |
respoke/respoke-sdk-android | respokeSDK/src/main/java/com/digium/respokesdk/RespokeCall.java | RespokeCall.iceCandidatesReceived | public void iceCandidatesReceived(JSONArray candidates) {
"""
Process ICE candidates suggested by the remote endpoint. This is used internally to the SDK and should not be called directly by your client application.
@param candidates Array of candidates to evaluate
"""
if (isActive()) {
for (int ii = 0; ii < candidates.length(); ii++) {
try {
JSONObject eachCandidate = (JSONObject) candidates.get(ii);
String mid = eachCandidate.getString("sdpMid");
int sdpLineIndex = eachCandidate.getInt("sdpMLineIndex");
String sdp = eachCandidate.getString("candidate");
IceCandidate rtcCandidate = new IceCandidate(mid, sdpLineIndex, sdp);
try {
// Start critical block
queuedRemoteCandidatesSemaphore.acquire();
if (null != queuedRemoteCandidates) {
queuedRemoteCandidates.add(rtcCandidate);
} else {
peerConnection.addIceCandidate(rtcCandidate);
}
// End critical block
queuedRemoteCandidatesSemaphore.release();
} catch (InterruptedException e) {
Log.d(TAG, "Error with remote candidates semaphore");
}
} catch (JSONException e) {
Log.d(TAG, "Error processing remote ice candidate data");
}
}
}
} | java | public void iceCandidatesReceived(JSONArray candidates) {
if (isActive()) {
for (int ii = 0; ii < candidates.length(); ii++) {
try {
JSONObject eachCandidate = (JSONObject) candidates.get(ii);
String mid = eachCandidate.getString("sdpMid");
int sdpLineIndex = eachCandidate.getInt("sdpMLineIndex");
String sdp = eachCandidate.getString("candidate");
IceCandidate rtcCandidate = new IceCandidate(mid, sdpLineIndex, sdp);
try {
// Start critical block
queuedRemoteCandidatesSemaphore.acquire();
if (null != queuedRemoteCandidates) {
queuedRemoteCandidates.add(rtcCandidate);
} else {
peerConnection.addIceCandidate(rtcCandidate);
}
// End critical block
queuedRemoteCandidatesSemaphore.release();
} catch (InterruptedException e) {
Log.d(TAG, "Error with remote candidates semaphore");
}
} catch (JSONException e) {
Log.d(TAG, "Error processing remote ice candidate data");
}
}
}
} | [
"public",
"void",
"iceCandidatesReceived",
"(",
"JSONArray",
"candidates",
")",
"{",
"if",
"(",
"isActive",
"(",
")",
")",
"{",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"candidates",
".",
"length",
"(",
")",
";",
"ii",
"++",
")",
"{",
"tr... | Process ICE candidates suggested by the remote endpoint. This is used internally to the SDK and should not be called directly by your client application.
@param candidates Array of candidates to evaluate | [
"Process",
"ICE",
"candidates",
"suggested",
"by",
"the",
"remote",
"endpoint",
".",
"This",
"is",
"used",
"internally",
"to",
"the",
"SDK",
"and",
"should",
"not",
"be",
"called",
"directly",
"by",
"your",
"client",
"application",
"."
] | train | https://github.com/respoke/respoke-sdk-android/blob/34a15f0558d29b1f1bc8481bbc5c505e855e05ef/respokeSDK/src/main/java/com/digium/respokesdk/RespokeCall.java#L605-L637 |
dihedron/dihedron-commons | src/main/java/org/dihedron/core/reflection/Types.java | Types.isOfSubClassOf | public static boolean isOfSubClassOf(Object object, Class<?> clazz) {
"""
Returns whether the given object is an instance of a subclass of the given
class, that is if it can be cast to the given class.
@param object
the object being tested.
@param clazz
the class to check.
@return
whether the object under inspection can be cast to the given class.
"""
if(object == null || clazz == null) {
return false;
}
try {
object.getClass().asSubclass(clazz);
return true;
} catch(ClassCastException e) {
return false;
}
} | java | public static boolean isOfSubClassOf(Object object, Class<?> clazz) {
if(object == null || clazz == null) {
return false;
}
try {
object.getClass().asSubclass(clazz);
return true;
} catch(ClassCastException e) {
return false;
}
} | [
"public",
"static",
"boolean",
"isOfSubClassOf",
"(",
"Object",
"object",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"if",
"(",
"object",
"==",
"null",
"||",
"clazz",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"object",
"."... | Returns whether the given object is an instance of a subclass of the given
class, that is if it can be cast to the given class.
@param object
the object being tested.
@param clazz
the class to check.
@return
whether the object under inspection can be cast to the given class. | [
"Returns",
"whether",
"the",
"given",
"object",
"is",
"an",
"instance",
"of",
"a",
"subclass",
"of",
"the",
"given",
"class",
"that",
"is",
"if",
"it",
"can",
"be",
"cast",
"to",
"the",
"given",
"class",
"."
] | train | https://github.com/dihedron/dihedron-commons/blob/a5194cdaa0d6417ef4aade6ea407a1cad6e8458e/src/main/java/org/dihedron/core/reflection/Types.java#L221-L231 |
adamfisk/littleshoot-util | src/main/java/org/littleshoot/util/Sha1.java | Sha1.engineUpdate | public void engineUpdate(byte[] input, int offset, int len) {
"""
Updates the digest using the specified array of bytes,
starting at the specified offset.
Input length can be any size. May require internal buffering,
if input blocks are not multiple of 64 bytes.
Overrides the protected abstract method of
java.security.MessageDigestSpi.
@param input the array of bytes to use for the update.
@param offset the offset to start from in the array of bytes.
@param len the number of bytes to use, starting at offset.
"""
if (offset >= 0 && len >= 0 && offset + len <= input.length) {
bytes += len;
/* Terminate the previous block. */
int padlen = 64 - padding;
if (padding > 0 && len >= padlen) {
System.arraycopy(input, offset, pad, padding, padlen);
computeBlock(pad, 0);
padding = 0;
offset += padlen;
len -= padlen;
}
/* Loop on large sets of complete blocks. */
while (len >= 512) {
computeBlock(input, offset);
computeBlock(input, offset + 64);
computeBlock(input, offset + 128);
computeBlock(input, offset + 192);
computeBlock(input, offset + 256);
computeBlock(input, offset + 320);
computeBlock(input, offset + 384);
computeBlock(input, offset + 448);
offset += 512;
len -= 512;
}
/* Loop on remaining complete blocks. */
while (len >= 64) {
computeBlock(input, offset);
offset += 64;
len -= 64;
}
/* remaining bytes kept for next block. */
if (len > 0) {
System.arraycopy(input, offset, pad, padding, len);
padding += len;
}
return;
}
throw new ArrayIndexOutOfBoundsException(offset);
} | java | public void engineUpdate(byte[] input, int offset, int len) {
if (offset >= 0 && len >= 0 && offset + len <= input.length) {
bytes += len;
/* Terminate the previous block. */
int padlen = 64 - padding;
if (padding > 0 && len >= padlen) {
System.arraycopy(input, offset, pad, padding, padlen);
computeBlock(pad, 0);
padding = 0;
offset += padlen;
len -= padlen;
}
/* Loop on large sets of complete blocks. */
while (len >= 512) {
computeBlock(input, offset);
computeBlock(input, offset + 64);
computeBlock(input, offset + 128);
computeBlock(input, offset + 192);
computeBlock(input, offset + 256);
computeBlock(input, offset + 320);
computeBlock(input, offset + 384);
computeBlock(input, offset + 448);
offset += 512;
len -= 512;
}
/* Loop on remaining complete blocks. */
while (len >= 64) {
computeBlock(input, offset);
offset += 64;
len -= 64;
}
/* remaining bytes kept for next block. */
if (len > 0) {
System.arraycopy(input, offset, pad, padding, len);
padding += len;
}
return;
}
throw new ArrayIndexOutOfBoundsException(offset);
} | [
"public",
"void",
"engineUpdate",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"offset",
",",
"int",
"len",
")",
"{",
"if",
"(",
"offset",
">=",
"0",
"&&",
"len",
">=",
"0",
"&&",
"offset",
"+",
"len",
"<=",
"input",
".",
"length",
")",
"{",
"byte... | Updates the digest using the specified array of bytes,
starting at the specified offset.
Input length can be any size. May require internal buffering,
if input blocks are not multiple of 64 bytes.
Overrides the protected abstract method of
java.security.MessageDigestSpi.
@param input the array of bytes to use for the update.
@param offset the offset to start from in the array of bytes.
@param len the number of bytes to use, starting at offset. | [
"Updates",
"the",
"digest",
"using",
"the",
"specified",
"array",
"of",
"bytes",
"starting",
"at",
"the",
"specified",
"offset",
"."
] | train | https://github.com/adamfisk/littleshoot-util/blob/3c0dc4955116b3382d6b0575d2f164b7508a4f73/src/main/java/org/littleshoot/util/Sha1.java#L167-L206 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java | LinearSearch.searchLast | public static int searchLast(int[] intArray, int value, int occurrence) {
"""
Search for the value in the int array and return the index of the specified occurrence from the
end of the array.
@param intArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1.
"""
if(occurrence <= 0 || occurrence > intArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = intArray.length-1; i >=0; i--) {
if(intArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | java | public static int searchLast(int[] intArray, int value, int occurrence) {
if(occurrence <= 0 || occurrence > intArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = intArray.length-1; i >=0; i--) {
if(intArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"searchLast",
"(",
"int",
"[",
"]",
"intArray",
",",
"int",
"value",
",",
"int",
"occurrence",
")",
"{",
"if",
"(",
"occurrence",
"<=",
"0",
"||",
"occurrence",
">",
"intArray",
".",
"length",
")",
"{",
"throw",
"new",
"Illeg... | Search for the value in the int array and return the index of the specified occurrence from the
end of the array.
@param intArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"int",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"specified",
"occurrence",
"from",
"the",
"end",
"of",
"the",
"array",
"."
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L1530-L1549 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java | CheckBoxMenuItemPainter.paintCheckIconEnabledAndMouseOver | private void paintCheckIconEnabledAndMouseOver(Graphics2D g, int width, int height) {
"""
Paint the check mark in mouse over state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height.
"""
g.setPaint(iconSelectedMouseOver);
g.drawRoundRect(0, 1, width-1, height-2, 4, 4);
} | java | private void paintCheckIconEnabledAndMouseOver(Graphics2D g, int width, int height) {
g.setPaint(iconSelectedMouseOver);
g.drawRoundRect(0, 1, width-1, height-2, 4, 4);
} | [
"private",
"void",
"paintCheckIconEnabledAndMouseOver",
"(",
"Graphics2D",
"g",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"g",
".",
"setPaint",
"(",
"iconSelectedMouseOver",
")",
";",
"g",
".",
"drawRoundRect",
"(",
"0",
",",
"1",
",",
"width",
... | Paint the check mark in mouse over state.
@param g the Graphics2D context to paint with.
@param width the width.
@param height the height. | [
"Paint",
"the",
"check",
"mark",
"in",
"mouse",
"over",
"state",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/CheckBoxMenuItemPainter.java#L187-L190 |
wuman/orientdb-android | core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordBytes.java | ORecordBytes.fromInputStream | public int fromInputStream(final InputStream in, final int iMaxSize) throws IOException {
"""
Reads the input stream in memory specifying the maximum bytes to read. This is more efficient than
{@link #fromInputStream(InputStream)} because allocation is made only once.
@param in
Input Stream, use buffered input stream wrapper to speed up reading
@param iMaxSize
Maximum size to read
@return Buffer count of bytes that are read from the stream. It's also the internal buffer size in bytes
@throws IOException if an I/O error occurs.
"""
final byte[] buffer = new byte[iMaxSize];
final int readBytesCount = in.read(buffer);
if (readBytesCount == -1) {
_source = EMPTY_SOURCE;
_size = 0;
} else if (readBytesCount == iMaxSize) {
_source = buffer;
_size = iMaxSize;
} else {
_source = Arrays.copyOf(buffer, readBytesCount);
_size = readBytesCount;
}
return _size;
} | java | public int fromInputStream(final InputStream in, final int iMaxSize) throws IOException {
final byte[] buffer = new byte[iMaxSize];
final int readBytesCount = in.read(buffer);
if (readBytesCount == -1) {
_source = EMPTY_SOURCE;
_size = 0;
} else if (readBytesCount == iMaxSize) {
_source = buffer;
_size = iMaxSize;
} else {
_source = Arrays.copyOf(buffer, readBytesCount);
_size = readBytesCount;
}
return _size;
} | [
"public",
"int",
"fromInputStream",
"(",
"final",
"InputStream",
"in",
",",
"final",
"int",
"iMaxSize",
")",
"throws",
"IOException",
"{",
"final",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"iMaxSize",
"]",
";",
"final",
"int",
"readBytesCount",
... | Reads the input stream in memory specifying the maximum bytes to read. This is more efficient than
{@link #fromInputStream(InputStream)} because allocation is made only once.
@param in
Input Stream, use buffered input stream wrapper to speed up reading
@param iMaxSize
Maximum size to read
@return Buffer count of bytes that are read from the stream. It's also the internal buffer size in bytes
@throws IOException if an I/O error occurs. | [
"Reads",
"the",
"input",
"stream",
"in",
"memory",
"specifying",
"the",
"maximum",
"bytes",
"to",
"read",
".",
"This",
"is",
"more",
"efficient",
"than",
"{",
"@link",
"#fromInputStream",
"(",
"InputStream",
")",
"}",
"because",
"allocation",
"is",
"made",
"... | train | https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/record/impl/ORecordBytes.java#L137-L151 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java | JSONHelpers.getJSONColor | public static int getJSONColor(final JSONObject json, String elementName, int defColor) {
"""
Attempts to get a color formatted as an integer with ARGB ordering. If the specified field
doesn't exist, returns {@code defColor}.
@param json {@link JSONObject} to get the color from
@param elementName Name of the color element
@param defColor Color to return if the element doesn't exist
@return An ARGB formatted integer
"""
try {
return getJSONColor(json, elementName);
} catch (JSONException e) {
return defColor;
}
} | java | public static int getJSONColor(final JSONObject json, String elementName, int defColor) {
try {
return getJSONColor(json, elementName);
} catch (JSONException e) {
return defColor;
}
} | [
"public",
"static",
"int",
"getJSONColor",
"(",
"final",
"JSONObject",
"json",
",",
"String",
"elementName",
",",
"int",
"defColor",
")",
"{",
"try",
"{",
"return",
"getJSONColor",
"(",
"json",
",",
"elementName",
")",
";",
"}",
"catch",
"(",
"JSONException"... | Attempts to get a color formatted as an integer with ARGB ordering. If the specified field
doesn't exist, returns {@code defColor}.
@param json {@link JSONObject} to get the color from
@param elementName Name of the color element
@param defColor Color to return if the element doesn't exist
@return An ARGB formatted integer | [
"Attempts",
"to",
"get",
"a",
"color",
"formatted",
"as",
"an",
"integer",
"with",
"ARGB",
"ordering",
".",
"If",
"the",
"specified",
"field",
"doesn",
"t",
"exist",
"returns",
"{",
"@code",
"defColor",
"}",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/widget/properties/JSONHelpers.java#L1648-L1654 |
mozilla/rhino | toolsrc/org/mozilla/javascript/tools/shell/Global.java | Global.readUrl | public static Object readUrl(Context cx, Scriptable thisObj, Object[] args,
Function funObj)
throws IOException {
"""
The readUrl opens connection to the given URL, read all its data
and converts them to a string
using the specified character coding or default character coding if
explicit coding argument is not given.
<p>
Usage:
<pre>
readUrl(url)
readUrl(url, charCoding)
</pre>
The first form converts file's context to string using the default
charCoding.
"""
if (args.length == 0) {
throw reportRuntimeError("msg.shell.readUrl.bad.args");
}
String url = ScriptRuntime.toString(args[0]);
String charCoding = null;
if (args.length >= 2) {
charCoding = ScriptRuntime.toString(args[1]);
}
return readUrl(url, charCoding, false);
} | java | public static Object readUrl(Context cx, Scriptable thisObj, Object[] args,
Function funObj)
throws IOException
{
if (args.length == 0) {
throw reportRuntimeError("msg.shell.readUrl.bad.args");
}
String url = ScriptRuntime.toString(args[0]);
String charCoding = null;
if (args.length >= 2) {
charCoding = ScriptRuntime.toString(args[1]);
}
return readUrl(url, charCoding, false);
} | [
"public",
"static",
"Object",
"readUrl",
"(",
"Context",
"cx",
",",
"Scriptable",
"thisObj",
",",
"Object",
"[",
"]",
"args",
",",
"Function",
"funObj",
")",
"throws",
"IOException",
"{",
"if",
"(",
"args",
".",
"length",
"==",
"0",
")",
"{",
"throw",
... | The readUrl opens connection to the given URL, read all its data
and converts them to a string
using the specified character coding or default character coding if
explicit coding argument is not given.
<p>
Usage:
<pre>
readUrl(url)
readUrl(url, charCoding)
</pre>
The first form converts file's context to string using the default
charCoding. | [
"The",
"readUrl",
"opens",
"connection",
"to",
"the",
"given",
"URL",
"read",
"all",
"its",
"data",
"and",
"converts",
"them",
"to",
"a",
"string",
"using",
"the",
"specified",
"character",
"coding",
"or",
"default",
"character",
"coding",
"if",
"explicit",
... | train | https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/shell/Global.java#L868-L882 |
ManfredTremmel/gwt-bean-validators | mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/RegularExpressionValidator.java | RegularExpressionValidator.isValid | @Override
public final boolean isValid(final String pvalue, final ConstraintValidatorContext pcontext) {
"""
{@inheritDoc} check if given string is a valid regular expression.
@see javax.validation.ConstraintValidator#isValid(java.lang.Object,
javax.validation.ConstraintValidatorContext)
"""
if (StringUtils.isEmpty(pvalue)) {
return true;
}
try {
// execute regular expression, result doesn't matter
"x".matches(pvalue);
return true;
} catch (final Exception pexception) {
// regular expression is invalid
return false;
}
} | java | @Override
public final boolean isValid(final String pvalue, final ConstraintValidatorContext pcontext) {
if (StringUtils.isEmpty(pvalue)) {
return true;
}
try {
// execute regular expression, result doesn't matter
"x".matches(pvalue);
return true;
} catch (final Exception pexception) {
// regular expression is invalid
return false;
}
} | [
"@",
"Override",
"public",
"final",
"boolean",
"isValid",
"(",
"final",
"String",
"pvalue",
",",
"final",
"ConstraintValidatorContext",
"pcontext",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"pvalue",
")",
")",
"{",
"return",
"true",
";",
"}",
... | {@inheritDoc} check if given string is a valid regular expression.
@see javax.validation.ConstraintValidator#isValid(java.lang.Object,
javax.validation.ConstraintValidatorContext) | [
"{",
"@inheritDoc",
"}",
"check",
"if",
"given",
"string",
"is",
"a",
"valid",
"regular",
"expression",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/RegularExpressionValidator.java#L49-L62 |
diffplug/durian | src/com/diffplug/common/base/FieldsAndGetters.java | FieldsAndGetters.dumpNonNull | public static void dumpNonNull(String name, Object obj, StringPrinter printer) {
"""
Dumps all non-null fields and getters of {@code obj} to {@code printer}.
@see #dumpIf
"""
dumpIf(name, obj, Predicates.alwaysTrue(), entry -> entry.getValue() != null, printer);
} | java | public static void dumpNonNull(String name, Object obj, StringPrinter printer) {
dumpIf(name, obj, Predicates.alwaysTrue(), entry -> entry.getValue() != null, printer);
} | [
"public",
"static",
"void",
"dumpNonNull",
"(",
"String",
"name",
",",
"Object",
"obj",
",",
"StringPrinter",
"printer",
")",
"{",
"dumpIf",
"(",
"name",
",",
"obj",
",",
"Predicates",
".",
"alwaysTrue",
"(",
")",
",",
"entry",
"->",
"entry",
".",
"getVa... | Dumps all non-null fields and getters of {@code obj} to {@code printer}.
@see #dumpIf | [
"Dumps",
"all",
"non",
"-",
"null",
"fields",
"and",
"getters",
"of",
"{"
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L193-L195 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_fax_serviceName_screenLists_reset_POST | public void billingAccount_fax_serviceName_screenLists_reset_POST(String billingAccount, String serviceName, Boolean blacklistedNumbers, Boolean blacklistedTSI, Boolean whitelistedNumbers, Boolean whitelistedTSI) throws IOException {
"""
Reset a specifical fax screenList
REST: POST /telephony/{billingAccount}/fax/{serviceName}/screenLists/reset
@param whitelistedTSI [required] List of white login (TSI or ID)
@param blacklistedTSI [required] List of black login (TSI or ID)
@param blacklistedNumbers [required] List of black numbers
@param whitelistedNumbers [required] List of white numbers
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
"""
String qPath = "/telephony/{billingAccount}/fax/{serviceName}/screenLists/reset";
StringBuilder sb = path(qPath, billingAccount, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "blacklistedNumbers", blacklistedNumbers);
addBody(o, "blacklistedTSI", blacklistedTSI);
addBody(o, "whitelistedNumbers", whitelistedNumbers);
addBody(o, "whitelistedTSI", whitelistedTSI);
exec(qPath, "POST", sb.toString(), o);
} | java | public void billingAccount_fax_serviceName_screenLists_reset_POST(String billingAccount, String serviceName, Boolean blacklistedNumbers, Boolean blacklistedTSI, Boolean whitelistedNumbers, Boolean whitelistedTSI) throws IOException {
String qPath = "/telephony/{billingAccount}/fax/{serviceName}/screenLists/reset";
StringBuilder sb = path(qPath, billingAccount, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "blacklistedNumbers", blacklistedNumbers);
addBody(o, "blacklistedTSI", blacklistedTSI);
addBody(o, "whitelistedNumbers", whitelistedNumbers);
addBody(o, "whitelistedTSI", whitelistedTSI);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"billingAccount_fax_serviceName_screenLists_reset_POST",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"Boolean",
"blacklistedNumbers",
",",
"Boolean",
"blacklistedTSI",
",",
"Boolean",
"whitelistedNumbers",
",",
"Boolean",
"whitelisted... | Reset a specifical fax screenList
REST: POST /telephony/{billingAccount}/fax/{serviceName}/screenLists/reset
@param whitelistedTSI [required] List of white login (TSI or ID)
@param blacklistedTSI [required] List of black login (TSI or ID)
@param blacklistedNumbers [required] List of black numbers
@param whitelistedNumbers [required] List of white numbers
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"Reset",
"a",
"specifical",
"fax",
"screenList"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L4499-L4508 |
belaban/JGroups | src/org/jgroups/util/Bits.java | Bits.writeLongSequence | public static void writeLongSequence(long hd, long hr, DataOutput out) throws IOException {
"""
Writes 2 sequence numbers (seqnos) in compressed format to an output stream.
The seqnos are non-negative and hr is guaranteed to be >= hd.
<p/>
Once variable-length encoding has been implemented, this method will probably get dropped as we can simply
write the 2 longs individually.
@param hd the highest delivered seqno. Guaranteed to be a positive number
@param hr the highest received seqno. Guaranteed to be a positive number. Greater than or equal to hd
@param out the output stream to write to
"""
if(hr < hd)
throw new IllegalArgumentException("hr (" + hr + ") has to be >= hd (" + hd + ")");
if(hd == 0 && hr == 0) {
out.write(0);
return;
}
long delta=hr - hd;
// encode highest_delivered followed by delta
byte bytes_for_hd=bytesRequiredFor(hd), bytes_for_delta=bytesRequiredFor(delta);
byte bytes_needed=encodeLength(bytes_for_hd, bytes_for_delta);
out.write(bytes_needed);
for(int i=0; i < bytes_for_hd; i++)
out.write(getByteAt(hd, i));
for(int i=0; i < bytes_for_delta; i++)
out.write(getByteAt(delta, i));
} | java | public static void writeLongSequence(long hd, long hr, DataOutput out) throws IOException {
if(hr < hd)
throw new IllegalArgumentException("hr (" + hr + ") has to be >= hd (" + hd + ")");
if(hd == 0 && hr == 0) {
out.write(0);
return;
}
long delta=hr - hd;
// encode highest_delivered followed by delta
byte bytes_for_hd=bytesRequiredFor(hd), bytes_for_delta=bytesRequiredFor(delta);
byte bytes_needed=encodeLength(bytes_for_hd, bytes_for_delta);
out.write(bytes_needed);
for(int i=0; i < bytes_for_hd; i++)
out.write(getByteAt(hd, i));
for(int i=0; i < bytes_for_delta; i++)
out.write(getByteAt(delta, i));
} | [
"public",
"static",
"void",
"writeLongSequence",
"(",
"long",
"hd",
",",
"long",
"hr",
",",
"DataOutput",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"hr",
"<",
"hd",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"hr (\"",
"+",
"hr",
"+"... | Writes 2 sequence numbers (seqnos) in compressed format to an output stream.
The seqnos are non-negative and hr is guaranteed to be >= hd.
<p/>
Once variable-length encoding has been implemented, this method will probably get dropped as we can simply
write the 2 longs individually.
@param hd the highest delivered seqno. Guaranteed to be a positive number
@param hr the highest received seqno. Guaranteed to be a positive number. Greater than or equal to hd
@param out the output stream to write to | [
"Writes",
"2",
"sequence",
"numbers",
"(",
"seqnos",
")",
"in",
"compressed",
"format",
"to",
"an",
"output",
"stream",
".",
"The",
"seqnos",
"are",
"non",
"-",
"negative",
"and",
"hr",
"is",
"guaranteed",
"to",
"be",
">",
";",
"=",
"hd",
".",
"<p",
... | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/Bits.java#L346-L367 |
RestComm/load-balancer | jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerUrlRewriter.java | BalancerUrlRewriter.getPathWithinApplication | public String getPathWithinApplication(HttpServletRequest request) {
"""
Return the path within the web application for the given request.
<p>Detects include request URL if called within a RequestDispatcher include.
"""
String requestUri = request.getRequestURI();
if (requestUri == null)
requestUri = "";
String decodedRequestUri = decodeRequestString(request, requestUri);
String contextPath = "";//getContextPath(request);
String path;
if (StringUtils.startsWithIgnoreCase(decodedRequestUri, contextPath) && !conf.isUseContext()) {
// Normal case: URI contains context path.
path = decodedRequestUri.substring(contextPath.length());
} else if (!StringUtils.startsWithIgnoreCase(decodedRequestUri, contextPath) && conf.isUseContext()) {
// add the context path on
path = contextPath + decodedRequestUri;
} else {
path = decodedRequestUri;
}
return StringUtils.isBlank(path) ? "/" : path;
} | java | public String getPathWithinApplication(HttpServletRequest request) {
String requestUri = request.getRequestURI();
if (requestUri == null)
requestUri = "";
String decodedRequestUri = decodeRequestString(request, requestUri);
String contextPath = "";//getContextPath(request);
String path;
if (StringUtils.startsWithIgnoreCase(decodedRequestUri, contextPath) && !conf.isUseContext()) {
// Normal case: URI contains context path.
path = decodedRequestUri.substring(contextPath.length());
} else if (!StringUtils.startsWithIgnoreCase(decodedRequestUri, contextPath) && conf.isUseContext()) {
// add the context path on
path = contextPath + decodedRequestUri;
} else {
path = decodedRequestUri;
}
return StringUtils.isBlank(path) ? "/" : path;
} | [
"public",
"String",
"getPathWithinApplication",
"(",
"HttpServletRequest",
"request",
")",
"{",
"String",
"requestUri",
"=",
"request",
".",
"getRequestURI",
"(",
")",
";",
"if",
"(",
"requestUri",
"==",
"null",
")",
"requestUri",
"=",
"\"\"",
";",
"String",
"... | Return the path within the web application for the given request.
<p>Detects include request URL if called within a RequestDispatcher include. | [
"Return",
"the",
"path",
"within",
"the",
"web",
"application",
"for",
"the",
"given",
"request",
".",
"<p",
">",
"Detects",
"include",
"request",
"URL",
"if",
"called",
"within",
"a",
"RequestDispatcher",
"include",
"."
] | train | https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerUrlRewriter.java#L83-L102 |
mcdiae/kludje | kludje-experimental/src/main/java/uk/kludje/experimental/stream/CollectionCombiners.java | CollectionCombiners.combineMutable | public static <E, C extends Collection<E>> C combineMutable(C target, C source) {
"""
A combiner for mutable {@link Collection} types.
Usage: {@code BinaryOperator<List<String>> combiner = CollectionCombiners::combineMutable; }
@param target the instance to call addAll on
@param source the argument for addAll
@param <E> the collection element type
@param <C> the collection type
@return the target
"""
target.addAll(source);
return target;
} | java | public static <E, C extends Collection<E>> C combineMutable(C target, C source) {
target.addAll(source);
return target;
} | [
"public",
"static",
"<",
"E",
",",
"C",
"extends",
"Collection",
"<",
"E",
">",
">",
"C",
"combineMutable",
"(",
"C",
"target",
",",
"C",
"source",
")",
"{",
"target",
".",
"addAll",
"(",
"source",
")",
";",
"return",
"target",
";",
"}"
] | A combiner for mutable {@link Collection} types.
Usage: {@code BinaryOperator<List<String>> combiner = CollectionCombiners::combineMutable; }
@param target the instance to call addAll on
@param source the argument for addAll
@param <E> the collection element type
@param <C> the collection type
@return the target | [
"A",
"combiner",
"for",
"mutable",
"{",
"@link",
"Collection",
"}",
"types",
".",
"Usage",
":",
"{",
"@code",
"BinaryOperator<List<String",
">>",
"combiner",
"=",
"CollectionCombiners",
"::",
"combineMutable",
";",
"}"
] | train | https://github.com/mcdiae/kludje/blob/9ed80cd183ebf162708d5922d784f79ac3841dfc/kludje-experimental/src/main/java/uk/kludje/experimental/stream/CollectionCombiners.java#L19-L22 |
PureSolTechnologies/graphs | graph/src/main/java/com/puresoltechnologies/graphs/graph/CycleAnalyzer.java | CycleAnalyzer.hasCycles | public static <V extends Vertex<V, E>, E extends Edge<V, E>> boolean hasCycles(
Graph<V, E> graph, V startVertex, boolean directed)
throws IllegalArgumentException {
"""
This method searches a given {@link Graph} for cycles. This method is
different to {@link #hasCycles(Graph, boolean)}, because here it is
started at a dedicated vertex and only vertices are checked for cycles
which are connected to this start vertex. If disconnected subgraphs
exist, these are not checked.
@param <V>
is the actual vertex implementation.
@param <E>
is the actual edge implementation.
@param graph
is the {@link Graph} to be searched for cycles.
@param startVertex
is the {@link Vertex} to start from. This vertex has to be
part of the given graph.
@param directed
is to be set to <code>true</code> is the graph is to be
handled as an directed graph (The {@link Pair} result in
{@link Edge#getVertices() is interpreted as startVertex and
targetVertex}.). <code>false</code> is to be set otherwise.
@return <code>true</code> is returned if a cycle was found.
<code>false</code> is returned otherwise.
@throws IllegalArgumentException
is thrown in case the startVertex is not part of the graph or
the graph of vertex are <code>null</code>.
"""
requireNonNull(graph, "The given start vertex is null");
requireNonNull(startVertex, "The given start vertex is null");
if (!graph.getVertices().contains(startVertex)) {
throw new IllegalArgumentException("The given start vertex '"
+ startVertex + "' is not part of the given graph '"
+ graph + "'.");
}
return hasCycle(startVertex, new Stack<>(), new Stack<>(),
new HashSet<V>(graph.getVertices()), directed);
} | java | public static <V extends Vertex<V, E>, E extends Edge<V, E>> boolean hasCycles(
Graph<V, E> graph, V startVertex, boolean directed)
throws IllegalArgumentException {
requireNonNull(graph, "The given start vertex is null");
requireNonNull(startVertex, "The given start vertex is null");
if (!graph.getVertices().contains(startVertex)) {
throw new IllegalArgumentException("The given start vertex '"
+ startVertex + "' is not part of the given graph '"
+ graph + "'.");
}
return hasCycle(startVertex, new Stack<>(), new Stack<>(),
new HashSet<V>(graph.getVertices()), directed);
} | [
"public",
"static",
"<",
"V",
"extends",
"Vertex",
"<",
"V",
",",
"E",
">",
",",
"E",
"extends",
"Edge",
"<",
"V",
",",
"E",
">",
">",
"boolean",
"hasCycles",
"(",
"Graph",
"<",
"V",
",",
"E",
">",
"graph",
",",
"V",
"startVertex",
",",
"boolean"... | This method searches a given {@link Graph} for cycles. This method is
different to {@link #hasCycles(Graph, boolean)}, because here it is
started at a dedicated vertex and only vertices are checked for cycles
which are connected to this start vertex. If disconnected subgraphs
exist, these are not checked.
@param <V>
is the actual vertex implementation.
@param <E>
is the actual edge implementation.
@param graph
is the {@link Graph} to be searched for cycles.
@param startVertex
is the {@link Vertex} to start from. This vertex has to be
part of the given graph.
@param directed
is to be set to <code>true</code> is the graph is to be
handled as an directed graph (The {@link Pair} result in
{@link Edge#getVertices() is interpreted as startVertex and
targetVertex}.). <code>false</code> is to be set otherwise.
@return <code>true</code> is returned if a cycle was found.
<code>false</code> is returned otherwise.
@throws IllegalArgumentException
is thrown in case the startVertex is not part of the graph or
the graph of vertex are <code>null</code>. | [
"This",
"method",
"searches",
"a",
"given",
"{",
"@link",
"Graph",
"}",
"for",
"cycles",
".",
"This",
"method",
"is",
"different",
"to",
"{",
"@link",
"#hasCycles",
"(",
"Graph",
"boolean",
")",
"}",
"because",
"here",
"it",
"is",
"started",
"at",
"a",
... | train | https://github.com/PureSolTechnologies/graphs/blob/35dbbd11ccaacbbc6321dcdcd4d31e9a1090d6f1/graph/src/main/java/com/puresoltechnologies/graphs/graph/CycleAnalyzer.java#L104-L116 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java | AccountsImpl.listPoolNodeCounts | public PagedList<PoolNodeCounts> listPoolNodeCounts() {
"""
Gets the number of nodes in each state, grouped by pool.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PagedList<PoolNodeCounts> object if successful.
"""
ServiceResponseWithHeaders<Page<PoolNodeCounts>, AccountListPoolNodeCountsHeaders> response = listPoolNodeCountsSinglePageAsync().toBlocking().single();
return new PagedList<PoolNodeCounts>(response.body()) {
@Override
public Page<PoolNodeCounts> nextPage(String nextPageLink) {
return listPoolNodeCountsNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | java | public PagedList<PoolNodeCounts> listPoolNodeCounts() {
ServiceResponseWithHeaders<Page<PoolNodeCounts>, AccountListPoolNodeCountsHeaders> response = listPoolNodeCountsSinglePageAsync().toBlocking().single();
return new PagedList<PoolNodeCounts>(response.body()) {
@Override
public Page<PoolNodeCounts> nextPage(String nextPageLink) {
return listPoolNodeCountsNextSinglePageAsync(nextPageLink, null).toBlocking().single().body();
}
};
} | [
"public",
"PagedList",
"<",
"PoolNodeCounts",
">",
"listPoolNodeCounts",
"(",
")",
"{",
"ServiceResponseWithHeaders",
"<",
"Page",
"<",
"PoolNodeCounts",
">",
",",
"AccountListPoolNodeCountsHeaders",
">",
"response",
"=",
"listPoolNodeCountsSinglePageAsync",
"(",
")",
"... | Gets the number of nodes in each state, grouped by pool.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws BatchErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PagedList<PoolNodeCounts> object if successful. | [
"Gets",
"the",
"number",
"of",
"nodes",
"in",
"each",
"state",
"grouped",
"by",
"pool",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java#L370-L378 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/postprocess/impl/JSMinPostProcessor.java | JSMinPostProcessor.byteArrayToString | private StringBuffer byteArrayToString(Charset charset, byte[] minified) throws IOException {
"""
Convert a byte array to a String buffer taking into account the charset
@param charset
the charset
@param minified
the byte array
@return the string buffer
@throws IOException
if an IO exception occurs
"""
// Write the data into a string
ReadableByteChannel chan = Channels.newChannel(new ByteArrayInputStream(minified));
Reader rd = Channels.newReader(chan, charset.newDecoder(), -1);
StringWriter writer = new StringWriter();
IOUtils.copy(rd, writer, true);
return writer.getBuffer();
} | java | private StringBuffer byteArrayToString(Charset charset, byte[] minified) throws IOException {
// Write the data into a string
ReadableByteChannel chan = Channels.newChannel(new ByteArrayInputStream(minified));
Reader rd = Channels.newReader(chan, charset.newDecoder(), -1);
StringWriter writer = new StringWriter();
IOUtils.copy(rd, writer, true);
return writer.getBuffer();
} | [
"private",
"StringBuffer",
"byteArrayToString",
"(",
"Charset",
"charset",
",",
"byte",
"[",
"]",
"minified",
")",
"throws",
"IOException",
"{",
"// Write the data into a string",
"ReadableByteChannel",
"chan",
"=",
"Channels",
".",
"newChannel",
"(",
"new",
"ByteArra... | Convert a byte array to a String buffer taking into account the charset
@param charset
the charset
@param minified
the byte array
@return the string buffer
@throws IOException
if an IO exception occurs | [
"Convert",
"a",
"byte",
"array",
"to",
"a",
"String",
"buffer",
"taking",
"into",
"account",
"the",
"charset"
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/postprocess/impl/JSMinPostProcessor.java#L123-L130 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/gyroscope/GyroscopeRenderer.java | GyroscopeRenderer.decode | @Override
public void decode(FacesContext context, UIComponent component) {
"""
This methods receives and processes input made by the user. More specifically, it ckecks whether the
user has interacted with the current b:gyroscope. The default implementation simply stores
the input value in the list of submitted values. If the validation checks are passed,
the values in the <code>submittedValues</code> list are store in the backend bean.
@param context the FacesContext.
@param component the current b:gyroscope.
"""
Gyroscope gyroscope = (Gyroscope) component;
if (gyroscope.isDisabled()) {
return;
}
decodeBehaviors(context, gyroscope);
String clientId = gyroscope.getClientId(context);
// String submittedAlpha = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".alpha");
// String submittedBeta = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".beta");
// String submittedGamma = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".gamma");
new AJAXRenderer().decode(context, component, clientId);
} | java | @Override
public void decode(FacesContext context, UIComponent component) {
Gyroscope gyroscope = (Gyroscope) component;
if (gyroscope.isDisabled()) {
return;
}
decodeBehaviors(context, gyroscope);
String clientId = gyroscope.getClientId(context);
// String submittedAlpha = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".alpha");
// String submittedBeta = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".beta");
// String submittedGamma = (String) context.getExternalContext().getRequestParameterMap().get(clientId+".gamma");
new AJAXRenderer().decode(context, component, clientId);
} | [
"@",
"Override",
"public",
"void",
"decode",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"{",
"Gyroscope",
"gyroscope",
"=",
"(",
"Gyroscope",
")",
"component",
";",
"if",
"(",
"gyroscope",
".",
"isDisabled",
"(",
")",
")",
"{",
"... | This methods receives and processes input made by the user. More specifically, it ckecks whether the
user has interacted with the current b:gyroscope. The default implementation simply stores
the input value in the list of submitted values. If the validation checks are passed,
the values in the <code>submittedValues</code> list are store in the backend bean.
@param context the FacesContext.
@param component the current b:gyroscope. | [
"This",
"methods",
"receives",
"and",
"processes",
"input",
"made",
"by",
"the",
"user",
".",
"More",
"specifically",
"it",
"ckecks",
"whether",
"the",
"user",
"has",
"interacted",
"with",
"the",
"current",
"b",
":",
"gyroscope",
".",
"The",
"default",
"impl... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/gyroscope/GyroscopeRenderer.java#L47-L63 |
nostra13/Android-Universal-Image-Loader | library/src/main/java/com/nostra13/universalimageloader/utils/MemoryCacheUtils.java | MemoryCacheUtils.removeFromCache | public static void removeFromCache(String imageUri, MemoryCache memoryCache) {
"""
Removes from memory cache all images for incoming URI.<br />
<b>Note:</b> Memory cache can contain multiple sizes of the same image if only you didn't set
{@link ImageLoaderConfiguration.Builder#denyCacheImageMultipleSizesInMemory()
denyCacheImageMultipleSizesInMemory()} option in {@linkplain ImageLoaderConfiguration configuration}
"""
List<String> keysToRemove = new ArrayList<String>();
for (String key : memoryCache.keys()) {
if (key.startsWith(imageUri)) {
keysToRemove.add(key);
}
}
for (String keyToRemove : keysToRemove) {
memoryCache.remove(keyToRemove);
}
} | java | public static void removeFromCache(String imageUri, MemoryCache memoryCache) {
List<String> keysToRemove = new ArrayList<String>();
for (String key : memoryCache.keys()) {
if (key.startsWith(imageUri)) {
keysToRemove.add(key);
}
}
for (String keyToRemove : keysToRemove) {
memoryCache.remove(keyToRemove);
}
} | [
"public",
"static",
"void",
"removeFromCache",
"(",
"String",
"imageUri",
",",
"MemoryCache",
"memoryCache",
")",
"{",
"List",
"<",
"String",
">",
"keysToRemove",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",... | Removes from memory cache all images for incoming URI.<br />
<b>Note:</b> Memory cache can contain multiple sizes of the same image if only you didn't set
{@link ImageLoaderConfiguration.Builder#denyCacheImageMultipleSizesInMemory()
denyCacheImageMultipleSizesInMemory()} option in {@linkplain ImageLoaderConfiguration configuration} | [
"Removes",
"from",
"memory",
"cache",
"all",
"images",
"for",
"incoming",
"URI",
".",
"<br",
"/",
">",
"<b",
">",
"Note",
":",
"<",
"/",
"b",
">",
"Memory",
"cache",
"can",
"contain",
"multiple",
"sizes",
"of",
"the",
"same",
"image",
"if",
"only",
"... | train | https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/utils/MemoryCacheUtils.java#L99-L109 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getSecretAsync | public Observable<SecretBundle> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) {
"""
Get a specified secret from a given key vault.
The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretName The name of the secret.
@param secretVersion The version of the secret.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SecretBundle object
"""
return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | java | public Observable<SecretBundle> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) {
return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SecretBundle",
">",
"getSecretAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"secretName",
",",
"String",
"secretVersion",
")",
"{",
"return",
"getSecretWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"secretName",
",",
"secre... | Get a specified secret from a given key vault.
The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretName The name of the secret.
@param secretVersion The version of the secret.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SecretBundle object | [
"Get",
"a",
"specified",
"secret",
"from",
"a",
"given",
"key",
"vault",
".",
"The",
"GET",
"operation",
"is",
"applicable",
"to",
"any",
"secret",
"stored",
"in",
"Azure",
"Key",
"Vault",
".",
"This",
"operation",
"requires",
"the",
"secrets",
"/",
"get",... | 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#L3857-L3864 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/distribution/TxDistributionInterceptor.java | TxDistributionInterceptor.handleTxWriteCommand | private Object handleTxWriteCommand(InvocationContext ctx, AbstractDataWriteCommand command,
Object key) throws Throwable {
"""
If we are within one transaction we won't do any replication as replication would only be performed at commit
time. If the operation didn't originate locally we won't do any replication either.
"""
try {
if (!ctx.isOriginLocal()) {
LocalizedCacheTopology cacheTopology = checkTopologyId(command);
// Ignore any remote command when we aren't the owner
if (!cacheTopology.isSegmentWriteOwner(command.getSegment())) {
return null;
}
}
CacheEntry entry = ctx.lookupEntry(command.getKey());
if (entry == null) {
if (isLocalModeForced(command) || command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP) || !needsPreviousValue(ctx, command)) {
// in transactional mode, we always need the entry wrapped
entryFactory.wrapExternalEntry(ctx, key, null, false, true);
} else {
// we need to retrieve the value locally regardless of load type; in transactional mode all operations
// execute on origin
// Also, operations that need value on backup [delta write] need to do the remote lookup even on
// non-origin
Object result = asyncInvokeNext(ctx, command, remoteGetSingleKey(ctx, command, command.getKey(), true));
return makeStage(result)
.andFinally(ctx, command, (rCtx, rCommand, rv, t) ->
updateMatcherForRetry((WriteCommand) rCommand));
}
}
// already wrapped, we can continue
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, t) -> updateMatcherForRetry((WriteCommand) rCommand));
} catch (Throwable t) {
updateMatcherForRetry(command);
throw t;
}
} | java | private Object handleTxWriteCommand(InvocationContext ctx, AbstractDataWriteCommand command,
Object key) throws Throwable {
try {
if (!ctx.isOriginLocal()) {
LocalizedCacheTopology cacheTopology = checkTopologyId(command);
// Ignore any remote command when we aren't the owner
if (!cacheTopology.isSegmentWriteOwner(command.getSegment())) {
return null;
}
}
CacheEntry entry = ctx.lookupEntry(command.getKey());
if (entry == null) {
if (isLocalModeForced(command) || command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP) || !needsPreviousValue(ctx, command)) {
// in transactional mode, we always need the entry wrapped
entryFactory.wrapExternalEntry(ctx, key, null, false, true);
} else {
// we need to retrieve the value locally regardless of load type; in transactional mode all operations
// execute on origin
// Also, operations that need value on backup [delta write] need to do the remote lookup even on
// non-origin
Object result = asyncInvokeNext(ctx, command, remoteGetSingleKey(ctx, command, command.getKey(), true));
return makeStage(result)
.andFinally(ctx, command, (rCtx, rCommand, rv, t) ->
updateMatcherForRetry((WriteCommand) rCommand));
}
}
// already wrapped, we can continue
return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, t) -> updateMatcherForRetry((WriteCommand) rCommand));
} catch (Throwable t) {
updateMatcherForRetry(command);
throw t;
}
} | [
"private",
"Object",
"handleTxWriteCommand",
"(",
"InvocationContext",
"ctx",
",",
"AbstractDataWriteCommand",
"command",
",",
"Object",
"key",
")",
"throws",
"Throwable",
"{",
"try",
"{",
"if",
"(",
"!",
"ctx",
".",
"isOriginLocal",
"(",
")",
")",
"{",
"Local... | If we are within one transaction we won't do any replication as replication would only be performed at commit
time. If the operation didn't originate locally we won't do any replication either. | [
"If",
"we",
"are",
"within",
"one",
"transaction",
"we",
"won",
"t",
"do",
"any",
"replication",
"as",
"replication",
"would",
"only",
"be",
"performed",
"at",
"commit",
"time",
".",
"If",
"the",
"operation",
"didn",
"t",
"originate",
"locally",
"we",
"won... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/distribution/TxDistributionInterceptor.java#L400-L432 |
VoltDB/voltdb | src/frontend/org/voltcore/agreement/AgreementSeeker.java | AgreementSeeker.seenByInterconnectedPeers | protected boolean seenByInterconnectedPeers( Set<Long> destinations, Set<Long> origins) {
"""
Walk the alive graph to see if there is a connected path between origins,
and destinations
@param destinations set of sites that we are looking a path to
@param origins set of sites that we are looking a path from
@return true origins have path to destinations
"""
Set<Long> seers = Multimaps.filterValues(m_alive, in(origins)).keySet();
int before = origins.size();
origins.addAll(seers);
if (origins.containsAll(destinations)) {
return true;
} else if (origins.size() == before) {
return false;
}
return seenByInterconnectedPeers(destinations, origins);
} | java | protected boolean seenByInterconnectedPeers( Set<Long> destinations, Set<Long> origins) {
Set<Long> seers = Multimaps.filterValues(m_alive, in(origins)).keySet();
int before = origins.size();
origins.addAll(seers);
if (origins.containsAll(destinations)) {
return true;
} else if (origins.size() == before) {
return false;
}
return seenByInterconnectedPeers(destinations, origins);
} | [
"protected",
"boolean",
"seenByInterconnectedPeers",
"(",
"Set",
"<",
"Long",
">",
"destinations",
",",
"Set",
"<",
"Long",
">",
"origins",
")",
"{",
"Set",
"<",
"Long",
">",
"seers",
"=",
"Multimaps",
".",
"filterValues",
"(",
"m_alive",
",",
"in",
"(",
... | Walk the alive graph to see if there is a connected path between origins,
and destinations
@param destinations set of sites that we are looking a path to
@param origins set of sites that we are looking a path from
@return true origins have path to destinations | [
"Walk",
"the",
"alive",
"graph",
"to",
"see",
"if",
"there",
"is",
"a",
"connected",
"path",
"between",
"origins",
"and",
"destinations"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/agreement/AgreementSeeker.java#L443-L454 |
haifengl/smile | math/src/main/java/smile/sort/QuickSelect.java | QuickSelect.q3 | public static <T extends Comparable<? super T>> T q3(T[] a) {
"""
Find the third quantile (p = 3/4) of an array of type double.
"""
int k = 3 * a.length / 4;
return select(a, k);
} | java | public static <T extends Comparable<? super T>> T q3(T[] a) {
int k = 3 * a.length / 4;
return select(a, k);
} | [
"public",
"static",
"<",
"T",
"extends",
"Comparable",
"<",
"?",
"super",
"T",
">",
">",
"T",
"q3",
"(",
"T",
"[",
"]",
"a",
")",
"{",
"int",
"k",
"=",
"3",
"*",
"a",
".",
"length",
"/",
"4",
";",
"return",
"select",
"(",
"a",
",",
"k",
")"... | Find the third quantile (p = 3/4) of an array of type double. | [
"Find",
"the",
"third",
"quantile",
"(",
"p",
"=",
"3",
"/",
"4",
")",
"of",
"an",
"array",
"of",
"type",
"double",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/sort/QuickSelect.java#L363-L366 |
lucee/Lucee | core/src/main/java/lucee/runtime/osgi/OSGiUtil.java | OSGiUtil.installBundle | public static Bundle installBundle(BundleContext context, InputStream bundleIS, boolean closeStream, boolean checkExistence) throws IOException, BundleException {
"""
only installs a bundle, if the bundle does not already exist, if the bundle exists the existing
bundle is unloaded first. the bundle is not stored physically on the system.
@param factory
@param context
@param bundle
@return
@throws IOException
@throws BundleException
"""
// store locally to test the bundle
String name = System.currentTimeMillis() + ".tmp";
Resource dir = SystemUtil.getTempDirectory();
Resource tmp = dir.getRealResource(name);
int count = 0;
while (tmp.exists())
tmp = dir.getRealResource((count++) + "_" + name);
IOUtil.copy(bundleIS, tmp, closeStream);
try {
return installBundle(context, tmp, checkExistence);
}
finally {
tmp.delete();
}
} | java | public static Bundle installBundle(BundleContext context, InputStream bundleIS, boolean closeStream, boolean checkExistence) throws IOException, BundleException {
// store locally to test the bundle
String name = System.currentTimeMillis() + ".tmp";
Resource dir = SystemUtil.getTempDirectory();
Resource tmp = dir.getRealResource(name);
int count = 0;
while (tmp.exists())
tmp = dir.getRealResource((count++) + "_" + name);
IOUtil.copy(bundleIS, tmp, closeStream);
try {
return installBundle(context, tmp, checkExistence);
}
finally {
tmp.delete();
}
} | [
"public",
"static",
"Bundle",
"installBundle",
"(",
"BundleContext",
"context",
",",
"InputStream",
"bundleIS",
",",
"boolean",
"closeStream",
",",
"boolean",
"checkExistence",
")",
"throws",
"IOException",
",",
"BundleException",
"{",
"// store locally to test the bundle... | only installs a bundle, if the bundle does not already exist, if the bundle exists the existing
bundle is unloaded first. the bundle is not stored physically on the system.
@param factory
@param context
@param bundle
@return
@throws IOException
@throws BundleException | [
"only",
"installs",
"a",
"bundle",
"if",
"the",
"bundle",
"does",
"not",
"already",
"exist",
"if",
"the",
"bundle",
"exists",
"the",
"existing",
"bundle",
"is",
"unloaded",
"first",
".",
"the",
"bundle",
"is",
"not",
"stored",
"physically",
"on",
"the",
"s... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/osgi/OSGiUtil.java#L156-L172 |
RestComm/media-core | rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java | SdpFactory.buildSdp | public static SessionDescription buildSdp(boolean offer, String localAddress, String externalAddress, MediaChannel... channels) {
"""
Builds a Session Description object to be sent to a remote peer.
@param offer if the SDP is for an answer or answer.
@param localAddress The local address of the media server.
@param externalAddress The public address of the media server.
@param channels The media channels to be included in the session description.
@return The Session Description object.
"""
// Session-level fields
SessionDescription sd = new SessionDescription();
sd.setVersion(new VersionField((short) 0));
String originAddress = (externalAddress == null || externalAddress.isEmpty()) ? localAddress : externalAddress;
sd.setOrigin(new OriginField("-", String.valueOf(System.currentTimeMillis()), "1", "IN", "IP4", originAddress));
sd.setSessionName(new SessionNameField("Mobicents Media Server"));
sd.setConnection(new ConnectionField("IN", "IP4", originAddress));
sd.setTiming(new TimingField(0, 0));
// Media Descriptions
boolean ice = false;
for (MediaChannel channel : channels) {
MediaDescriptionField md = buildMediaDescription(channel, offer);
md.setSession(sd);
sd.addMediaDescription(md);
if(md.containsIce()) {
// Fix session-level attribute
sd.getConnection().setAddress(md.getConnection().getAddress());
ice = true;
}
}
// Session-level ICE
if(ice) {
sd.setIceLite(new IceLiteAttribute());
}
return sd;
} | java | public static SessionDescription buildSdp(boolean offer, String localAddress, String externalAddress, MediaChannel... channels) {
// Session-level fields
SessionDescription sd = new SessionDescription();
sd.setVersion(new VersionField((short) 0));
String originAddress = (externalAddress == null || externalAddress.isEmpty()) ? localAddress : externalAddress;
sd.setOrigin(new OriginField("-", String.valueOf(System.currentTimeMillis()), "1", "IN", "IP4", originAddress));
sd.setSessionName(new SessionNameField("Mobicents Media Server"));
sd.setConnection(new ConnectionField("IN", "IP4", originAddress));
sd.setTiming(new TimingField(0, 0));
// Media Descriptions
boolean ice = false;
for (MediaChannel channel : channels) {
MediaDescriptionField md = buildMediaDescription(channel, offer);
md.setSession(sd);
sd.addMediaDescription(md);
if(md.containsIce()) {
// Fix session-level attribute
sd.getConnection().setAddress(md.getConnection().getAddress());
ice = true;
}
}
// Session-level ICE
if(ice) {
sd.setIceLite(new IceLiteAttribute());
}
return sd;
} | [
"public",
"static",
"SessionDescription",
"buildSdp",
"(",
"boolean",
"offer",
",",
"String",
"localAddress",
",",
"String",
"externalAddress",
",",
"MediaChannel",
"...",
"channels",
")",
"{",
"// Session-level fields",
"SessionDescription",
"sd",
"=",
"new",
"Sessio... | Builds a Session Description object to be sent to a remote peer.
@param offer if the SDP is for an answer or answer.
@param localAddress The local address of the media server.
@param externalAddress The public address of the media server.
@param channels The media channels to be included in the session description.
@return The Session Description object. | [
"Builds",
"a",
"Session",
"Description",
"object",
"to",
"be",
"sent",
"to",
"a",
"remote",
"peer",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/sdp/SdpFactory.java#L68-L97 |
czyzby/gdx-lml | kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/viewport/LetterboxingViewport.java | LetterboxingViewport.updateWorldSize | private void updateWorldSize(final int screenWidth, final int screenHeight) {
"""
Forces update of current world size according to window size. Will try to keep the set aspect ratio.
@param screenWidth current screen width.
@param screenHeight current screen height.
"""
final float width = screenWidth * scaleX;
final float height = screenHeight * scaleY;
final float fitHeight = width / aspectRatio;
if (fitHeight > height) {
setWorldSize(height * aspectRatio, height);
} else {
setWorldSize(width, fitHeight);
}
} | java | private void updateWorldSize(final int screenWidth, final int screenHeight) {
final float width = screenWidth * scaleX;
final float height = screenHeight * scaleY;
final float fitHeight = width / aspectRatio;
if (fitHeight > height) {
setWorldSize(height * aspectRatio, height);
} else {
setWorldSize(width, fitHeight);
}
} | [
"private",
"void",
"updateWorldSize",
"(",
"final",
"int",
"screenWidth",
",",
"final",
"int",
"screenHeight",
")",
"{",
"final",
"float",
"width",
"=",
"screenWidth",
"*",
"scaleX",
";",
"final",
"float",
"height",
"=",
"screenHeight",
"*",
"scaleY",
";",
"... | Forces update of current world size according to window size. Will try to keep the set aspect ratio.
@param screenWidth current screen width.
@param screenHeight current screen height. | [
"Forces",
"update",
"of",
"current",
"world",
"size",
"according",
"to",
"window",
"size",
".",
"Will",
"try",
"to",
"keep",
"the",
"set",
"aspect",
"ratio",
"."
] | train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/viewport/LetterboxingViewport.java#L89-L98 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/ImageAnchorCell.java | ImageAnchorCell.renderDataCellContents | protected void renderDataCellContents(AbstractRenderAppender appender, String jspFragmentOutput) {
"""
Render the contents of the HTML anchor and image. This method calls to an
{@link org.apache.beehive.netui.databinding.datagrid.api.rendering.CellDecorator} associated with this tag.
The result of renderingi is appended to the <code>appender</code>
@param appender the {@link AbstractRenderAppender} to which output should be rendered
@param jspFragmentOutput the result of having evaluated this tag's {@link javax.servlet.jsp.tagext.JspFragment}
"""
assert DECORATOR != null;
assert appender != null;
assert _imageAnchorCellModel != null;
String script = null;
/* render any JavaScript needed to support framework features */
if (_imageState.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
script = renderNameAndId(request, _imageState, null);
}
/* render any JavaScript needed to support framework features */
if (_anchorState.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
String anchorScript = renderNameAndId(request, _anchorState, null);
if(anchorScript != null)
script = (script != null ? script += anchorScript : anchorScript);
}
_imageAnchorCellModel.setJavascript(script);
DECORATOR.decorate(getJspContext(), appender, _imageAnchorCellModel);
} | java | protected void renderDataCellContents(AbstractRenderAppender appender, String jspFragmentOutput) {
assert DECORATOR != null;
assert appender != null;
assert _imageAnchorCellModel != null;
String script = null;
/* render any JavaScript needed to support framework features */
if (_imageState.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
script = renderNameAndId(request, _imageState, null);
}
/* render any JavaScript needed to support framework features */
if (_anchorState.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
String anchorScript = renderNameAndId(request, _anchorState, null);
if(anchorScript != null)
script = (script != null ? script += anchorScript : anchorScript);
}
_imageAnchorCellModel.setJavascript(script);
DECORATOR.decorate(getJspContext(), appender, _imageAnchorCellModel);
} | [
"protected",
"void",
"renderDataCellContents",
"(",
"AbstractRenderAppender",
"appender",
",",
"String",
"jspFragmentOutput",
")",
"{",
"assert",
"DECORATOR",
"!=",
"null",
";",
"assert",
"appender",
"!=",
"null",
";",
"assert",
"_imageAnchorCellModel",
"!=",
"null",
... | Render the contents of the HTML anchor and image. This method calls to an
{@link org.apache.beehive.netui.databinding.datagrid.api.rendering.CellDecorator} associated with this tag.
The result of renderingi is appended to the <code>appender</code>
@param appender the {@link AbstractRenderAppender} to which output should be rendered
@param jspFragmentOutput the result of having evaluated this tag's {@link javax.servlet.jsp.tagext.JspFragment} | [
"Render",
"the",
"contents",
"of",
"the",
"HTML",
"anchor",
"and",
"image",
".",
"This",
"method",
"calls",
"to",
"an",
"{"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/databinding/datagrid/ImageAnchorCell.java#L669-L692 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/tree/CmsTreeItem.java | CmsTreeItem.insertChild | public void insertChild(CmsTreeItem item, int position) {
"""
Inserts the given item at the given position.<p>
@param item the item to insert
@param position the position
@see org.opencms.gwt.client.ui.CmsList#insertItem(org.opencms.gwt.client.ui.I_CmsListItem, int)
"""
m_children.insert(item, position);
adopt(item);
} | java | public void insertChild(CmsTreeItem item, int position) {
m_children.insert(item, position);
adopt(item);
} | [
"public",
"void",
"insertChild",
"(",
"CmsTreeItem",
"item",
",",
"int",
"position",
")",
"{",
"m_children",
".",
"insert",
"(",
"item",
",",
"position",
")",
";",
"adopt",
"(",
"item",
")",
";",
"}"
] | Inserts the given item at the given position.<p>
@param item the item to insert
@param position the position
@see org.opencms.gwt.client.ui.CmsList#insertItem(org.opencms.gwt.client.ui.I_CmsListItem, int) | [
"Inserts",
"the",
"given",
"item",
"at",
"the",
"given",
"position",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/tree/CmsTreeItem.java#L442-L446 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.order_orderId_retraction_POST | public void order_orderId_retraction_POST(Long orderId, String comment, OvhRetractionReasonEnum reason) throws IOException {
"""
Request retraction of order
REST: POST /me/order/{orderId}/retraction
@param reason [required] The reason why you want to retract
@param comment [required] An optional comment of why you want to retract
@param orderId [required]
"""
String qPath = "/me/order/{orderId}/retraction";
StringBuilder sb = path(qPath, orderId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "comment", comment);
addBody(o, "reason", reason);
exec(qPath, "POST", sb.toString(), o);
} | java | public void order_orderId_retraction_POST(Long orderId, String comment, OvhRetractionReasonEnum reason) throws IOException {
String qPath = "/me/order/{orderId}/retraction";
StringBuilder sb = path(qPath, orderId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "comment", comment);
addBody(o, "reason", reason);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"order_orderId_retraction_POST",
"(",
"Long",
"orderId",
",",
"String",
"comment",
",",
"OvhRetractionReasonEnum",
"reason",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/order/{orderId}/retraction\"",
";",
"StringBuilder",
"sb",
"=... | Request retraction of order
REST: POST /me/order/{orderId}/retraction
@param reason [required] The reason why you want to retract
@param comment [required] An optional comment of why you want to retract
@param orderId [required] | [
"Request",
"retraction",
"of",
"order"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2096-L2103 |
alkacon/opencms-core | src/org/opencms/module/CmsModuleXmlHandler.java | CmsModuleXmlHandler.addDependency | public void addDependency(String name, String version) {
"""
Adds a module dependency to the current module.<p>
@param name the module name of the dependency
@param version the module version of the dependency
"""
CmsModuleVersion moduleVersion = new CmsModuleVersion(version);
CmsModuleDependency dependency = new CmsModuleDependency(name, moduleVersion);
m_dependencies.add(dependency);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_DEPENDENCY_2, name, version));
}
} | java | public void addDependency(String name, String version) {
CmsModuleVersion moduleVersion = new CmsModuleVersion(version);
CmsModuleDependency dependency = new CmsModuleDependency(name, moduleVersion);
m_dependencies.add(dependency);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_DEPENDENCY_2, name, version));
}
} | [
"public",
"void",
"addDependency",
"(",
"String",
"name",
",",
"String",
"version",
")",
"{",
"CmsModuleVersion",
"moduleVersion",
"=",
"new",
"CmsModuleVersion",
"(",
"version",
")",
";",
"CmsModuleDependency",
"dependency",
"=",
"new",
"CmsModuleDependency",
"(",
... | Adds a module dependency to the current module.<p>
@param name the module name of the dependency
@param version the module version of the dependency | [
"Adds",
"a",
"module",
"dependency",
"to",
"the",
"current",
"module",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleXmlHandler.java#L548-L558 |
amsa-code/risky | geo-analyzer/src/main/java/au/gov/amsa/util/navigation/Position.java | Position.getDistanceKmToPath | public final double getDistanceKmToPath(Position p1, Position p2) {
"""
calculates the distance of a point to the great circle path between p1
and p2.
Formula from: http://www.movable-type.co.uk/scripts/latlong.html
@param p1
@param p2
@return
"""
double d = radiusEarthKm
* asin(sin(getDistanceToKm(p1) / radiusEarthKm)
* sin(toRadians(getBearingDegrees(p1)
- p1.getBearingDegrees(p2))));
return abs(d);
} | java | public final double getDistanceKmToPath(Position p1, Position p2) {
double d = radiusEarthKm
* asin(sin(getDistanceToKm(p1) / radiusEarthKm)
* sin(toRadians(getBearingDegrees(p1)
- p1.getBearingDegrees(p2))));
return abs(d);
} | [
"public",
"final",
"double",
"getDistanceKmToPath",
"(",
"Position",
"p1",
",",
"Position",
"p2",
")",
"{",
"double",
"d",
"=",
"radiusEarthKm",
"*",
"asin",
"(",
"sin",
"(",
"getDistanceToKm",
"(",
"p1",
")",
"/",
"radiusEarthKm",
")",
"*",
"sin",
"(",
... | calculates the distance of a point to the great circle path between p1
and p2.
Formula from: http://www.movable-type.co.uk/scripts/latlong.html
@param p1
@param p2
@return | [
"calculates",
"the",
"distance",
"of",
"a",
"point",
"to",
"the",
"great",
"circle",
"path",
"between",
"p1",
"and",
"p2",
"."
] | train | https://github.com/amsa-code/risky/blob/13649942aeddfdb9210eec072c605bc5d7a6daf3/geo-analyzer/src/main/java/au/gov/amsa/util/navigation/Position.java#L341-L347 |
galan/commons | src/main/java/de/galan/commons/util/JmxUtil.java | JmxUtil.registerMBean | public static void registerMBean(String packageName, String type, String name, Object mbean) {
"""
Will register the given mbean using the given packageName, type and name. If no packageName has been given, the
package of the mbean will be used.
"""
try {
String pkg = defaultString(packageName, mbean.getClass().getPackage().getName());
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName on = new ObjectName(pkg + ":type=" + type + ",name=" + name);
if (server.isRegistered(on)) {
Say.debug("MBean with type {type} and name {name} for {package} has already been defined, ignoring", type, name, pkg);
}
else {
server.registerMBean(mbean, on);
}
}
catch (Exception ex) {
Say.warn("MBean could not be registered", ex);
}
} | java | public static void registerMBean(String packageName, String type, String name, Object mbean) {
try {
String pkg = defaultString(packageName, mbean.getClass().getPackage().getName());
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName on = new ObjectName(pkg + ":type=" + type + ",name=" + name);
if (server.isRegistered(on)) {
Say.debug("MBean with type {type} and name {name} for {package} has already been defined, ignoring", type, name, pkg);
}
else {
server.registerMBean(mbean, on);
}
}
catch (Exception ex) {
Say.warn("MBean could not be registered", ex);
}
} | [
"public",
"static",
"void",
"registerMBean",
"(",
"String",
"packageName",
",",
"String",
"type",
",",
"String",
"name",
",",
"Object",
"mbean",
")",
"{",
"try",
"{",
"String",
"pkg",
"=",
"defaultString",
"(",
"packageName",
",",
"mbean",
".",
"getClass",
... | Will register the given mbean using the given packageName, type and name. If no packageName has been given, the
package of the mbean will be used. | [
"Will",
"register",
"the",
"given",
"mbean",
"using",
"the",
"given",
"packageName",
"type",
"and",
"name",
".",
"If",
"no",
"packageName",
"has",
"been",
"given",
"the",
"package",
"of",
"the",
"mbean",
"will",
"be",
"used",
"."
] | train | https://github.com/galan/commons/blob/45d2f36c69958d3f847e5fed66603ea629471822/src/main/java/de/galan/commons/util/JmxUtil.java#L22-L37 |
aws/aws-sdk-java | aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/IdentityDkimAttributes.java | IdentityDkimAttributes.getDkimTokens | public java.util.List<String> getDkimTokens() {
"""
<p>
A set of character strings that represent the domain's identity. Using these tokens, you will need to create DNS
CNAME records that point to DKIM public keys hosted by Amazon SES. Amazon Web Services will eventually detect
that you have updated your DNS records; this detection process may take up to 72 hours. Upon successful
detection, Amazon SES will be able to DKIM-sign email originating from that domain. (This only applies to domain
identities, not email address identities.)
</p>
<p>
For more information about creating DNS records using DKIM tokens, go to the <a
href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html">Amazon SES Developer
Guide</a>.
</p>
@return A set of character strings that represent the domain's identity. Using these tokens, you will need to
create DNS CNAME records that point to DKIM public keys hosted by Amazon SES. Amazon Web Services will
eventually detect that you have updated your DNS records; this detection process may take up to 72 hours.
Upon successful detection, Amazon SES will be able to DKIM-sign email originating from that domain. (This
only applies to domain identities, not email address identities.)</p>
<p>
For more information about creating DNS records using DKIM tokens, go to the <a
href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html">Amazon SES
Developer Guide</a>.
"""
if (dkimTokens == null) {
dkimTokens = new com.amazonaws.internal.SdkInternalList<String>();
}
return dkimTokens;
} | java | public java.util.List<String> getDkimTokens() {
if (dkimTokens == null) {
dkimTokens = new com.amazonaws.internal.SdkInternalList<String>();
}
return dkimTokens;
} | [
"public",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
"getDkimTokens",
"(",
")",
"{",
"if",
"(",
"dkimTokens",
"==",
"null",
")",
"{",
"dkimTokens",
"=",
"new",
"com",
".",
"amazonaws",
".",
"internal",
".",
"SdkInternalList",
"<",
"String",
... | <p>
A set of character strings that represent the domain's identity. Using these tokens, you will need to create DNS
CNAME records that point to DKIM public keys hosted by Amazon SES. Amazon Web Services will eventually detect
that you have updated your DNS records; this detection process may take up to 72 hours. Upon successful
detection, Amazon SES will be able to DKIM-sign email originating from that domain. (This only applies to domain
identities, not email address identities.)
</p>
<p>
For more information about creating DNS records using DKIM tokens, go to the <a
href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html">Amazon SES Developer
Guide</a>.
</p>
@return A set of character strings that represent the domain's identity. Using these tokens, you will need to
create DNS CNAME records that point to DKIM public keys hosted by Amazon SES. Amazon Web Services will
eventually detect that you have updated your DNS records; this detection process may take up to 72 hours.
Upon successful detection, Amazon SES will be able to DKIM-sign email originating from that domain. (This
only applies to domain identities, not email address identities.)</p>
<p>
For more information about creating DNS records using DKIM tokens, go to the <a
href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html">Amazon SES
Developer Guide</a>. | [
"<p",
">",
"A",
"set",
"of",
"character",
"strings",
"that",
"represent",
"the",
"domain",
"s",
"identity",
".",
"Using",
"these",
"tokens",
"you",
"will",
"need",
"to",
"create",
"DNS",
"CNAME",
"records",
"that",
"point",
"to",
"DKIM",
"public",
"keys",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/IdentityDkimAttributes.java#L222-L227 |
recommenders/rival | rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java | StrategyRunner.instantiateStrategy | public static EvaluationStrategy<Long, Long> instantiateStrategy(final Properties properties, final DataModelIF<Long, Long> trainingModel, final DataModelIF<Long, Long> testModel)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
"""
Instantiates an strategy, according to the provided properties mapping.
@param properties the properties to be used.
@param trainingModel datamodel containing the training interactions to be
considered when generating the strategy.
@param testModel datamodel containing the interactions in the test split
to be considered when generating the strategy.
@return the strategy generated according to the provided properties
@throws ClassNotFoundException when {@link Class#forName(java.lang.String)}
fails
@throws IllegalAccessException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws InstantiationException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws InvocationTargetException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws NoSuchMethodException when {@link Class#getConstructor(java.lang.Class[])}
fails
"""
Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD));
String strategyClassName = properties.getProperty(STRATEGY);
Class<?> strategyClass = Class.forName(strategyClassName);
// get strategy
EvaluationStrategy<Long, Long> strategy = null;
if (strategyClassName.contains("RelPlusN")) {
Integer number = Integer.parseInt(properties.getProperty(RELPLUSN_N));
Long seed = Long.parseLong(properties.getProperty(RELPLUSN_SEED));
strategy = new RelPlusN(trainingModel, testModel, number, threshold, seed);
} else {
Object strategyObj = strategyClass.getConstructor(DataModelIF.class, DataModelIF.class, double.class).newInstance(trainingModel, testModel, threshold);
if (strategyObj instanceof EvaluationStrategy) {
@SuppressWarnings("unchecked")
EvaluationStrategy<Long, Long> strategyTemp = (EvaluationStrategy<Long, Long>) strategyObj;
strategy = strategyTemp;
}
}
return strategy;
} | java | public static EvaluationStrategy<Long, Long> instantiateStrategy(final Properties properties, final DataModelIF<Long, Long> trainingModel, final DataModelIF<Long, Long> testModel)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
Double threshold = Double.parseDouble(properties.getProperty(RELEVANCE_THRESHOLD));
String strategyClassName = properties.getProperty(STRATEGY);
Class<?> strategyClass = Class.forName(strategyClassName);
// get strategy
EvaluationStrategy<Long, Long> strategy = null;
if (strategyClassName.contains("RelPlusN")) {
Integer number = Integer.parseInt(properties.getProperty(RELPLUSN_N));
Long seed = Long.parseLong(properties.getProperty(RELPLUSN_SEED));
strategy = new RelPlusN(trainingModel, testModel, number, threshold, seed);
} else {
Object strategyObj = strategyClass.getConstructor(DataModelIF.class, DataModelIF.class, double.class).newInstance(trainingModel, testModel, threshold);
if (strategyObj instanceof EvaluationStrategy) {
@SuppressWarnings("unchecked")
EvaluationStrategy<Long, Long> strategyTemp = (EvaluationStrategy<Long, Long>) strategyObj;
strategy = strategyTemp;
}
}
return strategy;
} | [
"public",
"static",
"EvaluationStrategy",
"<",
"Long",
",",
"Long",
">",
"instantiateStrategy",
"(",
"final",
"Properties",
"properties",
",",
"final",
"DataModelIF",
"<",
"Long",
",",
"Long",
">",
"trainingModel",
",",
"final",
"DataModelIF",
"<",
"Long",
",",
... | Instantiates an strategy, according to the provided properties mapping.
@param properties the properties to be used.
@param trainingModel datamodel containing the training interactions to be
considered when generating the strategy.
@param testModel datamodel containing the interactions in the test split
to be considered when generating the strategy.
@return the strategy generated according to the provided properties
@throws ClassNotFoundException when {@link Class#forName(java.lang.String)}
fails
@throws IllegalAccessException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws InstantiationException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws InvocationTargetException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])}
fails
@throws NoSuchMethodException when {@link Class#getConstructor(java.lang.Class[])}
fails | [
"Instantiates",
"an",
"strategy",
"according",
"to",
"the",
"provided",
"properties",
"mapping",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java#L188-L208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.