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
|
---|---|---|---|---|---|---|---|---|---|---|
apache/flink
|
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/sharedbuffer/SharedBuffer.java
|
SharedBuffer.upsertEvent
|
void upsertEvent(EventId eventId, Lockable<V> event) {
"""
Inserts or updates an event in cache.
@param eventId id of the event
@param event event body
"""
this.eventsBufferCache.put(eventId, event);
}
|
java
|
void upsertEvent(EventId eventId, Lockable<V> event) {
this.eventsBufferCache.put(eventId, event);
}
|
[
"void",
"upsertEvent",
"(",
"EventId",
"eventId",
",",
"Lockable",
"<",
"V",
">",
"event",
")",
"{",
"this",
".",
"eventsBufferCache",
".",
"put",
"(",
"eventId",
",",
"event",
")",
";",
"}"
] |
Inserts or updates an event in cache.
@param eventId id of the event
@param event event body
|
[
"Inserts",
"or",
"updates",
"an",
"event",
"in",
"cache",
"."
] |
train
|
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/sharedbuffer/SharedBuffer.java#L162-L164
|
groupon/robo-remote
|
RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/robotium/Solo2.java
|
Solo2.getView
|
public View getView(int id, int timeout) {
"""
Extend the normal robotium getView to retry every 250ms over 10s to get the view requested
@param id Resource id of the view
@param timeout amount of time to retry getting the view
@return View that we want to find by id
"""
View v = null;
int RETRY_PERIOD = 250;
int retryNum = timeout / RETRY_PERIOD;
for (int i = 0; i < retryNum; i++) {
try {
v = super.getView(id);
} catch (Exception e) {}
if (v != null) {
break;
}
this.sleep(RETRY_PERIOD);
}
return v;
}
|
java
|
public View getView(int id, int timeout) {
View v = null;
int RETRY_PERIOD = 250;
int retryNum = timeout / RETRY_PERIOD;
for (int i = 0; i < retryNum; i++) {
try {
v = super.getView(id);
} catch (Exception e) {}
if (v != null) {
break;
}
this.sleep(RETRY_PERIOD);
}
return v;
}
|
[
"public",
"View",
"getView",
"(",
"int",
"id",
",",
"int",
"timeout",
")",
"{",
"View",
"v",
"=",
"null",
";",
"int",
"RETRY_PERIOD",
"=",
"250",
";",
"int",
"retryNum",
"=",
"timeout",
"/",
"RETRY_PERIOD",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"retryNum",
";",
"i",
"++",
")",
"{",
"try",
"{",
"v",
"=",
"super",
".",
"getView",
"(",
"id",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"if",
"(",
"v",
"!=",
"null",
")",
"{",
"break",
";",
"}",
"this",
".",
"sleep",
"(",
"RETRY_PERIOD",
")",
";",
"}",
"return",
"v",
";",
"}"
] |
Extend the normal robotium getView to retry every 250ms over 10s to get the view requested
@param id Resource id of the view
@param timeout amount of time to retry getting the view
@return View that we want to find by id
|
[
"Extend",
"the",
"normal",
"robotium",
"getView",
"to",
"retry",
"every",
"250ms",
"over",
"10s",
"to",
"get",
"the",
"view",
"requested"
] |
train
|
https://github.com/groupon/robo-remote/blob/12d242faad50bf90f98657ca9a0c0c3ae1993f07/RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/robotium/Solo2.java#L114-L130
|
MTDdk/jawn
|
jawn-core-new/src/main/java/net/javapla/jawn/core/internal/reflection/DynamicClassFactory.java
|
DynamicClassFactory.getCompiledClass
|
public final static Class<?> getCompiledClass(String fullClassName, boolean useCache) throws Err.Compilation, Err.UnloadableClass {
"""
Handles caching of classes if not useCache
@param fullClassName including package name
@param useCache flag to specify whether to cache the controller or not
@return
@throws CompilationException
@throws ClassLoadException
"""
try {
if (! useCache) {
DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(fullClassName.substring(0, fullClassName.lastIndexOf('.')));
Class<?> cl = dynamicClassLoader.loadClass(fullClassName);
dynamicClassLoader = null;
return cl;
} else {
return CACHED_CONTROLLERS.computeIfAbsent(fullClassName, WRAP_FORNAME);
}
} catch (Exception e) {
throw new Err.UnloadableClass(e);
}
}
|
java
|
public final static Class<?> getCompiledClass(String fullClassName, boolean useCache) throws Err.Compilation, Err.UnloadableClass {
try {
if (! useCache) {
DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(fullClassName.substring(0, fullClassName.lastIndexOf('.')));
Class<?> cl = dynamicClassLoader.loadClass(fullClassName);
dynamicClassLoader = null;
return cl;
} else {
return CACHED_CONTROLLERS.computeIfAbsent(fullClassName, WRAP_FORNAME);
}
} catch (Exception e) {
throw new Err.UnloadableClass(e);
}
}
|
[
"public",
"final",
"static",
"Class",
"<",
"?",
">",
"getCompiledClass",
"(",
"String",
"fullClassName",
",",
"boolean",
"useCache",
")",
"throws",
"Err",
".",
"Compilation",
",",
"Err",
".",
"UnloadableClass",
"{",
"try",
"{",
"if",
"(",
"!",
"useCache",
")",
"{",
"DynamicClassLoader",
"dynamicClassLoader",
"=",
"new",
"DynamicClassLoader",
"(",
"fullClassName",
".",
"substring",
"(",
"0",
",",
"fullClassName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
")",
";",
"Class",
"<",
"?",
">",
"cl",
"=",
"dynamicClassLoader",
".",
"loadClass",
"(",
"fullClassName",
")",
";",
"dynamicClassLoader",
"=",
"null",
";",
"return",
"cl",
";",
"}",
"else",
"{",
"return",
"CACHED_CONTROLLERS",
".",
"computeIfAbsent",
"(",
"fullClassName",
",",
"WRAP_FORNAME",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"Err",
".",
"UnloadableClass",
"(",
"e",
")",
";",
"}",
"}"
] |
Handles caching of classes if not useCache
@param fullClassName including package name
@param useCache flag to specify whether to cache the controller or not
@return
@throws CompilationException
@throws ClassLoadException
|
[
"Handles",
"caching",
"of",
"classes",
"if",
"not",
"useCache"
] |
train
|
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core-new/src/main/java/net/javapla/jawn/core/internal/reflection/DynamicClassFactory.java#L68-L81
|
looly/hutool
|
hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java
|
ArrayUtil.indexOfIgnoreCase
|
public static int indexOfIgnoreCase(CharSequence[] array, CharSequence value) {
"""
返回数组中指定元素所在位置,忽略大小写,未找到返回{@link #INDEX_NOT_FOUND}
@param array 数组
@param value 被检查的元素
@return 数组中指定元素所在位置,未找到返回{@link #INDEX_NOT_FOUND}
@since 3.1.2
"""
if (null != array) {
for (int i = 0; i < array.length; i++) {
if (StrUtil.equalsIgnoreCase(array[i], value)) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
|
java
|
public static int indexOfIgnoreCase(CharSequence[] array, CharSequence value) {
if (null != array) {
for (int i = 0; i < array.length; i++) {
if (StrUtil.equalsIgnoreCase(array[i], value)) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
|
[
"public",
"static",
"int",
"indexOfIgnoreCase",
"(",
"CharSequence",
"[",
"]",
"array",
",",
"CharSequence",
"value",
")",
"{",
"if",
"(",
"null",
"!=",
"array",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"StrUtil",
".",
"equalsIgnoreCase",
"(",
"array",
"[",
"i",
"]",
",",
"value",
")",
")",
"{",
"return",
"i",
";",
"}",
"}",
"}",
"return",
"INDEX_NOT_FOUND",
";",
"}"
] |
返回数组中指定元素所在位置,忽略大小写,未找到返回{@link #INDEX_NOT_FOUND}
@param array 数组
@param value 被检查的元素
@return 数组中指定元素所在位置,未找到返回{@link #INDEX_NOT_FOUND}
@since 3.1.2
|
[
"返回数组中指定元素所在位置,忽略大小写,未找到返回",
"{",
"@link",
"#INDEX_NOT_FOUND",
"}"
] |
train
|
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L916-L925
|
apache/spark
|
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockHandler.java
|
ExternalShuffleBlockHandler.reregisterExecutor
|
public void reregisterExecutor(AppExecId appExecId, ExecutorShuffleInfo executorInfo) {
"""
Register an (application, executor) with the given shuffle info.
The "re-" is meant to highlight the intended use of this method -- when this service is
restarted, this is used to restore the state of executors from before the restart. Normal
registration will happen via a message handled in receive()
@param appExecId
@param executorInfo
"""
blockManager.registerExecutor(appExecId.appId, appExecId.execId, executorInfo);
}
|
java
|
public void reregisterExecutor(AppExecId appExecId, ExecutorShuffleInfo executorInfo) {
blockManager.registerExecutor(appExecId.appId, appExecId.execId, executorInfo);
}
|
[
"public",
"void",
"reregisterExecutor",
"(",
"AppExecId",
"appExecId",
",",
"ExecutorShuffleInfo",
"executorInfo",
")",
"{",
"blockManager",
".",
"registerExecutor",
"(",
"appExecId",
".",
"appId",
",",
"appExecId",
".",
"execId",
",",
"executorInfo",
")",
";",
"}"
] |
Register an (application, executor) with the given shuffle info.
The "re-" is meant to highlight the intended use of this method -- when this service is
restarted, this is used to restore the state of executors from before the restart. Normal
registration will happen via a message handled in receive()
@param appExecId
@param executorInfo
|
[
"Register",
"an",
"(",
"application",
"executor",
")",
"with",
"the",
"given",
"shuffle",
"info",
"."
] |
train
|
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockHandler.java#L164-L166
|
paypal/SeLion
|
server/src/main/java/com/paypal/selion/node/servlets/LogServlet.java
|
LogServlet.appendMoreLogsLink
|
private String appendMoreLogsLink(final String fileName, String url) throws IOException {
"""
This method helps to display More log information of the node machine.
@param fileName
It is log file name available in node machine current directory Logs folder, it is used to identify
the current file to display in the web page.
@param url
It is node machine url (ex: http://10.232.88.10:5555)
@return String vlaue to add Form in html page
@throws IOException
"""
FileBackedStringBuffer buffer = new FileBackedStringBuffer();
int index = retrieveIndexValueFromFileName(fileName);
index++;
File logFileName = retrieveFileFromLogsFolder(Integer.toString(index));
if (logFileName == null) {
return "";
}
// TODO put this html code in a template
buffer.append("<form name ='myform' action=").append(url).append(" method= 'post'>");
buffer.append("<input type='hidden'").append(" name ='fileName'").append(" value ='")
.append(logFileName.getName()).append("'>");
buffer.append("<a href= 'javascript: submitform();' > More Logs </a>");
buffer.append("</form>");
return buffer.toString();
}
|
java
|
private String appendMoreLogsLink(final String fileName, String url) throws IOException {
FileBackedStringBuffer buffer = new FileBackedStringBuffer();
int index = retrieveIndexValueFromFileName(fileName);
index++;
File logFileName = retrieveFileFromLogsFolder(Integer.toString(index));
if (logFileName == null) {
return "";
}
// TODO put this html code in a template
buffer.append("<form name ='myform' action=").append(url).append(" method= 'post'>");
buffer.append("<input type='hidden'").append(" name ='fileName'").append(" value ='")
.append(logFileName.getName()).append("'>");
buffer.append("<a href= 'javascript: submitform();' > More Logs </a>");
buffer.append("</form>");
return buffer.toString();
}
|
[
"private",
"String",
"appendMoreLogsLink",
"(",
"final",
"String",
"fileName",
",",
"String",
"url",
")",
"throws",
"IOException",
"{",
"FileBackedStringBuffer",
"buffer",
"=",
"new",
"FileBackedStringBuffer",
"(",
")",
";",
"int",
"index",
"=",
"retrieveIndexValueFromFileName",
"(",
"fileName",
")",
";",
"index",
"++",
";",
"File",
"logFileName",
"=",
"retrieveFileFromLogsFolder",
"(",
"Integer",
".",
"toString",
"(",
"index",
")",
")",
";",
"if",
"(",
"logFileName",
"==",
"null",
")",
"{",
"return",
"\"\"",
";",
"}",
"// TODO put this html code in a template",
"buffer",
".",
"append",
"(",
"\"<form name ='myform' action=\"",
")",
".",
"append",
"(",
"url",
")",
".",
"append",
"(",
"\" method= 'post'>\"",
")",
";",
"buffer",
".",
"append",
"(",
"\"<input type='hidden'\"",
")",
".",
"append",
"(",
"\" name ='fileName'\"",
")",
".",
"append",
"(",
"\" value ='\"",
")",
".",
"append",
"(",
"logFileName",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\"'>\"",
")",
";",
"buffer",
".",
"append",
"(",
"\"<a href= 'javascript: submitform();' > More Logs </a>\"",
")",
";",
"buffer",
".",
"append",
"(",
"\"</form>\"",
")",
";",
"return",
"buffer",
".",
"toString",
"(",
")",
";",
"}"
] |
This method helps to display More log information of the node machine.
@param fileName
It is log file name available in node machine current directory Logs folder, it is used to identify
the current file to display in the web page.
@param url
It is node machine url (ex: http://10.232.88.10:5555)
@return String vlaue to add Form in html page
@throws IOException
|
[
"This",
"method",
"helps",
"to",
"display",
"More",
"log",
"information",
"of",
"the",
"node",
"machine",
"."
] |
train
|
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/server/src/main/java/com/paypal/selion/node/servlets/LogServlet.java#L69-L85
|
attribyte/wpdb
|
src/main/java/org/attribyte/wp/db/DB.java
|
DB.updatePostTimestamps
|
public boolean updatePostTimestamps(long postId, final long publishTimestamp, final long modifiedTimestamp, final TimeZone tz) throws SQLException {
"""
Updates only the timestamp fields for a post.
@param postId The post to update.
@param publishTimestamp The publish timestamp.
@param modifiedTimestamp The modified timestamp.
@param tz The local time zone.
@return Were the timestamps modified?
@throws SQLException on database error or missing post id.
"""
int offset = tz.getOffset(publishTimestamp);
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostTimestampsSQL);
stmt.setTimestamp(1, new Timestamp(publishTimestamp));
stmt.setTimestamp(2, new Timestamp(publishTimestamp - offset));
stmt.setTimestamp(3, new Timestamp(modifiedTimestamp));
stmt.setTimestamp(4, new Timestamp(modifiedTimestamp - offset));
stmt.setLong(5, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
}
|
java
|
public boolean updatePostTimestamps(long postId, final long publishTimestamp, final long modifiedTimestamp, final TimeZone tz) throws SQLException {
int offset = tz.getOffset(publishTimestamp);
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostTimestampsSQL);
stmt.setTimestamp(1, new Timestamp(publishTimestamp));
stmt.setTimestamp(2, new Timestamp(publishTimestamp - offset));
stmt.setTimestamp(3, new Timestamp(modifiedTimestamp));
stmt.setTimestamp(4, new Timestamp(modifiedTimestamp - offset));
stmt.setLong(5, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
}
|
[
"public",
"boolean",
"updatePostTimestamps",
"(",
"long",
"postId",
",",
"final",
"long",
"publishTimestamp",
",",
"final",
"long",
"modifiedTimestamp",
",",
"final",
"TimeZone",
"tz",
")",
"throws",
"SQLException",
"{",
"int",
"offset",
"=",
"tz",
".",
"getOffset",
"(",
"publishTimestamp",
")",
";",
"Connection",
"conn",
"=",
"null",
";",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"Timer",
".",
"Context",
"ctx",
"=",
"metrics",
".",
"updatePostTimer",
".",
"time",
"(",
")",
";",
"try",
"{",
"conn",
"=",
"connectionSupplier",
".",
"getConnection",
"(",
")",
";",
"stmt",
"=",
"conn",
".",
"prepareStatement",
"(",
"updatePostTimestampsSQL",
")",
";",
"stmt",
".",
"setTimestamp",
"(",
"1",
",",
"new",
"Timestamp",
"(",
"publishTimestamp",
")",
")",
";",
"stmt",
".",
"setTimestamp",
"(",
"2",
",",
"new",
"Timestamp",
"(",
"publishTimestamp",
"-",
"offset",
")",
")",
";",
"stmt",
".",
"setTimestamp",
"(",
"3",
",",
"new",
"Timestamp",
"(",
"modifiedTimestamp",
")",
")",
";",
"stmt",
".",
"setTimestamp",
"(",
"4",
",",
"new",
"Timestamp",
"(",
"modifiedTimestamp",
"-",
"offset",
")",
")",
";",
"stmt",
".",
"setLong",
"(",
"5",
",",
"postId",
")",
";",
"return",
"stmt",
".",
"executeUpdate",
"(",
")",
">",
"0",
";",
"}",
"finally",
"{",
"ctx",
".",
"stop",
"(",
")",
";",
"SQLUtil",
".",
"closeQuietly",
"(",
"conn",
",",
"stmt",
")",
";",
"}",
"}"
] |
Updates only the timestamp fields for a post.
@param postId The post to update.
@param publishTimestamp The publish timestamp.
@param modifiedTimestamp The modified timestamp.
@param tz The local time zone.
@return Were the timestamps modified?
@throws SQLException on database error or missing post id.
|
[
"Updates",
"only",
"the",
"timestamp",
"fields",
"for",
"a",
"post",
"."
] |
train
|
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L1496-L1514
|
Jasig/uPortal
|
uPortal-portlets/src/main/java/org/apereo/portal/portlets/sqlquery/SqlQueryPortletController.java
|
SqlQueryPortletController.evaluateSpelExpression
|
protected String evaluateSpelExpression(String value, PortletRequest request) {
"""
Substitute any SpEL expressions with values from the PortletRequest and other attributes
added to the SpEL context.
@param value SQL Query String with optional SpEL expressions in it
@param request Portlet request
@return SQL Query string with SpEL substitutions
"""
if (StringUtils.isNotBlank(value)) {
String result = portletSpELService.parseString(value, request);
return result;
}
throw new IllegalArgumentException("SQL Query expression required");
}
|
java
|
protected String evaluateSpelExpression(String value, PortletRequest request) {
if (StringUtils.isNotBlank(value)) {
String result = portletSpELService.parseString(value, request);
return result;
}
throw new IllegalArgumentException("SQL Query expression required");
}
|
[
"protected",
"String",
"evaluateSpelExpression",
"(",
"String",
"value",
",",
"PortletRequest",
"request",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"value",
")",
")",
"{",
"String",
"result",
"=",
"portletSpELService",
".",
"parseString",
"(",
"value",
",",
"request",
")",
";",
"return",
"result",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"SQL Query expression required\"",
")",
";",
"}"
] |
Substitute any SpEL expressions with values from the PortletRequest and other attributes
added to the SpEL context.
@param value SQL Query String with optional SpEL expressions in it
@param request Portlet request
@return SQL Query string with SpEL substitutions
|
[
"Substitute",
"any",
"SpEL",
"expressions",
"with",
"values",
"from",
"the",
"PortletRequest",
"and",
"other",
"attributes",
"added",
"to",
"the",
"SpEL",
"context",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/sqlquery/SqlQueryPortletController.java#L163-L169
|
OpenFeign/feign
|
core/src/main/java/feign/template/UriUtils.java
|
UriUtils.encodeReserved
|
public static String encodeReserved(String value, FragmentType type, Charset charset) {
"""
Encodes the value, preserving all reserved characters.. Values that are already pct-encoded are
ignored.
@param value inspect.
@param type identifying which uri fragment rules to apply.
@param charset to use.
@return a new String with the reserved characters preserved.
"""
/* value is encoded, we need to split it up and skip the parts that are already encoded */
Matcher matcher = PCT_ENCODED_PATTERN.matcher(value);
if (!matcher.find()) {
return encodeChunk(value, type, charset);
}
int length = value.length();
StringBuilder encoded = new StringBuilder(length + 8);
int index = 0;
do {
/* split out the value before the encoded value */
String before = value.substring(index, matcher.start());
/* encode it */
encoded.append(encodeChunk(before, type, charset));
/* append the encoded value */
encoded.append(matcher.group());
/* update the string search index */
index = matcher.end();
} while (matcher.find());
/* append the rest of the string */
String tail = value.substring(index, length);
encoded.append(encodeChunk(tail, type, charset));
return encoded.toString();
}
|
java
|
public static String encodeReserved(String value, FragmentType type, Charset charset) {
/* value is encoded, we need to split it up and skip the parts that are already encoded */
Matcher matcher = PCT_ENCODED_PATTERN.matcher(value);
if (!matcher.find()) {
return encodeChunk(value, type, charset);
}
int length = value.length();
StringBuilder encoded = new StringBuilder(length + 8);
int index = 0;
do {
/* split out the value before the encoded value */
String before = value.substring(index, matcher.start());
/* encode it */
encoded.append(encodeChunk(before, type, charset));
/* append the encoded value */
encoded.append(matcher.group());
/* update the string search index */
index = matcher.end();
} while (matcher.find());
/* append the rest of the string */
String tail = value.substring(index, length);
encoded.append(encodeChunk(tail, type, charset));
return encoded.toString();
}
|
[
"public",
"static",
"String",
"encodeReserved",
"(",
"String",
"value",
",",
"FragmentType",
"type",
",",
"Charset",
"charset",
")",
"{",
"/* value is encoded, we need to split it up and skip the parts that are already encoded */",
"Matcher",
"matcher",
"=",
"PCT_ENCODED_PATTERN",
".",
"matcher",
"(",
"value",
")",
";",
"if",
"(",
"!",
"matcher",
".",
"find",
"(",
")",
")",
"{",
"return",
"encodeChunk",
"(",
"value",
",",
"type",
",",
"charset",
")",
";",
"}",
"int",
"length",
"=",
"value",
".",
"length",
"(",
")",
";",
"StringBuilder",
"encoded",
"=",
"new",
"StringBuilder",
"(",
"length",
"+",
"8",
")",
";",
"int",
"index",
"=",
"0",
";",
"do",
"{",
"/* split out the value before the encoded value */",
"String",
"before",
"=",
"value",
".",
"substring",
"(",
"index",
",",
"matcher",
".",
"start",
"(",
")",
")",
";",
"/* encode it */",
"encoded",
".",
"append",
"(",
"encodeChunk",
"(",
"before",
",",
"type",
",",
"charset",
")",
")",
";",
"/* append the encoded value */",
"encoded",
".",
"append",
"(",
"matcher",
".",
"group",
"(",
")",
")",
";",
"/* update the string search index */",
"index",
"=",
"matcher",
".",
"end",
"(",
")",
";",
"}",
"while",
"(",
"matcher",
".",
"find",
"(",
")",
")",
";",
"/* append the rest of the string */",
"String",
"tail",
"=",
"value",
".",
"substring",
"(",
"index",
",",
"length",
")",
";",
"encoded",
".",
"append",
"(",
"encodeChunk",
"(",
"tail",
",",
"type",
",",
"charset",
")",
")",
";",
"return",
"encoded",
".",
"toString",
"(",
")",
";",
"}"
] |
Encodes the value, preserving all reserved characters.. Values that are already pct-encoded are
ignored.
@param value inspect.
@param type identifying which uri fragment rules to apply.
@param charset to use.
@return a new String with the reserved characters preserved.
|
[
"Encodes",
"the",
"value",
"preserving",
"all",
"reserved",
"characters",
"..",
"Values",
"that",
"are",
"already",
"pct",
"-",
"encoded",
"are",
"ignored",
"."
] |
train
|
https://github.com/OpenFeign/feign/blob/318fb0e955b8cfcf64f70d6aeea0ba5795f8a7eb/core/src/main/java/feign/template/UriUtils.java#L141-L170
|
ksclarke/freelib-utils
|
src/main/java/info/freelibrary/util/I18nObject.java
|
I18nObject.getI18n
|
protected String getI18n(final String aMessageKey, final String aDetail) {
"""
Gets the internationalized value for the supplied message key, using a string as additional information.
@param aMessageKey A message key
@param aDetail Additional details for the message
@return The internationalized message
"""
return StringUtils.normalizeWS(myBundle.get(aMessageKey, aDetail));
}
|
java
|
protected String getI18n(final String aMessageKey, final String aDetail) {
return StringUtils.normalizeWS(myBundle.get(aMessageKey, aDetail));
}
|
[
"protected",
"String",
"getI18n",
"(",
"final",
"String",
"aMessageKey",
",",
"final",
"String",
"aDetail",
")",
"{",
"return",
"StringUtils",
".",
"normalizeWS",
"(",
"myBundle",
".",
"get",
"(",
"aMessageKey",
",",
"aDetail",
")",
")",
";",
"}"
] |
Gets the internationalized value for the supplied message key, using a string as additional information.
@param aMessageKey A message key
@param aDetail Additional details for the message
@return The internationalized message
|
[
"Gets",
"the",
"internationalized",
"value",
"for",
"the",
"supplied",
"message",
"key",
"using",
"a",
"string",
"as",
"additional",
"information",
"."
] |
train
|
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/I18nObject.java#L79-L81
|
diirt/util
|
src/main/java/org/epics/util/text/CsvParser.java
|
CsvParser.isFirstLineData
|
private boolean isFirstLineData(State state, List<String> headerTokens) {
"""
Checks whether the header can be safely interpreted as data.
This is used for the auto header detection.
@param state the state of the parser
@param headerTokens the header
@return true if header should be handled as data
"""
// Check whether the type of the header match the type of the following data
boolean headerCompatible = true;
// Check whether if all types where strings
boolean allStrings = true;
for (int i = 0; i < state.nColumns; i++) {
if (state.columnNumberParsable.get(i)) {
allStrings = false;
if (!isTokenNumberParsable(state, headerTokens.get(i))) {
headerCompatible = false;
}
}
}
// If all columns are strings, it's impossible to tell whether we have
// a header or not: assume we have a header.
// If the column types matches (e.g. the header for a number column is also
// a number) then we'll assume the header is actually data.
return !allStrings && headerCompatible;
}
|
java
|
private boolean isFirstLineData(State state, List<String> headerTokens) {
// Check whether the type of the header match the type of the following data
boolean headerCompatible = true;
// Check whether if all types where strings
boolean allStrings = true;
for (int i = 0; i < state.nColumns; i++) {
if (state.columnNumberParsable.get(i)) {
allStrings = false;
if (!isTokenNumberParsable(state, headerTokens.get(i))) {
headerCompatible = false;
}
}
}
// If all columns are strings, it's impossible to tell whether we have
// a header or not: assume we have a header.
// If the column types matches (e.g. the header for a number column is also
// a number) then we'll assume the header is actually data.
return !allStrings && headerCompatible;
}
|
[
"private",
"boolean",
"isFirstLineData",
"(",
"State",
"state",
",",
"List",
"<",
"String",
">",
"headerTokens",
")",
"{",
"// Check whether the type of the header match the type of the following data\r",
"boolean",
"headerCompatible",
"=",
"true",
";",
"// Check whether if all types where strings\r",
"boolean",
"allStrings",
"=",
"true",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"state",
".",
"nColumns",
";",
"i",
"++",
")",
"{",
"if",
"(",
"state",
".",
"columnNumberParsable",
".",
"get",
"(",
"i",
")",
")",
"{",
"allStrings",
"=",
"false",
";",
"if",
"(",
"!",
"isTokenNumberParsable",
"(",
"state",
",",
"headerTokens",
".",
"get",
"(",
"i",
")",
")",
")",
"{",
"headerCompatible",
"=",
"false",
";",
"}",
"}",
"}",
"// If all columns are strings, it's impossible to tell whether we have\r",
"// a header or not: assume we have a header.\r",
"// If the column types matches (e.g. the header for a number column is also\r",
"// a number) then we'll assume the header is actually data.\r",
"return",
"!",
"allStrings",
"&&",
"headerCompatible",
";",
"}"
] |
Checks whether the header can be safely interpreted as data.
This is used for the auto header detection.
@param state the state of the parser
@param headerTokens the header
@return true if header should be handled as data
|
[
"Checks",
"whether",
"the",
"header",
"can",
"be",
"safely",
"interpreted",
"as",
"data",
".",
"This",
"is",
"used",
"for",
"the",
"auto",
"header",
"detection",
"."
] |
train
|
https://github.com/diirt/util/blob/24aca0a173a635aaf0b78d213a3fee8d4f91c077/src/main/java/org/epics/util/text/CsvParser.java#L450-L468
|
Jasig/uPortal
|
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java
|
RDBMUserLayoutStore.getLayoutID
|
private int getLayoutID(final int userId, final int profileId) {
"""
Returns the current layout ID for the user and profile. If the profile doesn't exist or the
layout_id field is null 0 is returned.
@param userId The userId for the profile
@param profileId The profileId for the profile
@return The layout_id field or 0 if it does not exist or is null
"""
return jdbcOperations.execute(
(ConnectionCallback<Integer>)
con -> {
String query =
"SELECT LAYOUT_ID "
+ "FROM UP_USER_PROFILE "
+ "WHERE USER_ID=? AND PROFILE_ID=?";
int layoutId = 0;
PreparedStatement pstmt = con.prepareStatement(query);
logger.debug(
"getLayoutID(userId={}, profileId={} ): {}",
userId,
profileId,
query);
pstmt.setInt(1, userId);
pstmt.setInt(2, profileId);
try {
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
}
} finally {
pstmt.close();
}
return layoutId;
});
}
|
java
|
private int getLayoutID(final int userId, final int profileId) {
return jdbcOperations.execute(
(ConnectionCallback<Integer>)
con -> {
String query =
"SELECT LAYOUT_ID "
+ "FROM UP_USER_PROFILE "
+ "WHERE USER_ID=? AND PROFILE_ID=?";
int layoutId = 0;
PreparedStatement pstmt = con.prepareStatement(query);
logger.debug(
"getLayoutID(userId={}, profileId={} ): {}",
userId,
profileId,
query);
pstmt.setInt(1, userId);
pstmt.setInt(2, profileId);
try {
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
}
} finally {
pstmt.close();
}
return layoutId;
});
}
|
[
"private",
"int",
"getLayoutID",
"(",
"final",
"int",
"userId",
",",
"final",
"int",
"profileId",
")",
"{",
"return",
"jdbcOperations",
".",
"execute",
"(",
"(",
"ConnectionCallback",
"<",
"Integer",
">",
")",
"con",
"->",
"{",
"String",
"query",
"=",
"\"SELECT LAYOUT_ID \"",
"+",
"\"FROM UP_USER_PROFILE \"",
"+",
"\"WHERE USER_ID=? AND PROFILE_ID=?\"",
";",
"int",
"layoutId",
"=",
"0",
";",
"PreparedStatement",
"pstmt",
"=",
"con",
".",
"prepareStatement",
"(",
"query",
")",
";",
"logger",
".",
"debug",
"(",
"\"getLayoutID(userId={}, profileId={} ): {}\"",
",",
"userId",
",",
"profileId",
",",
"query",
")",
";",
"pstmt",
".",
"setInt",
"(",
"1",
",",
"userId",
")",
";",
"pstmt",
".",
"setInt",
"(",
"2",
",",
"profileId",
")",
";",
"try",
"{",
"ResultSet",
"rs",
"=",
"pstmt",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"layoutId",
"=",
"rs",
".",
"getInt",
"(",
"1",
")",
";",
"if",
"(",
"rs",
".",
"wasNull",
"(",
")",
")",
"{",
"layoutId",
"=",
"0",
";",
"}",
"}",
"}",
"finally",
"{",
"pstmt",
".",
"close",
"(",
")",
";",
"}",
"return",
"layoutId",
";",
"}",
")",
";",
"}"
] |
Returns the current layout ID for the user and profile. If the profile doesn't exist or the
layout_id field is null 0 is returned.
@param userId The userId for the profile
@param profileId The profileId for the profile
@return The layout_id field or 0 if it does not exist or is null
|
[
"Returns",
"the",
"current",
"layout",
"ID",
"for",
"the",
"user",
"and",
"profile",
".",
"If",
"the",
"profile",
"doesn",
"t",
"exist",
"or",
"the",
"layout_id",
"field",
"is",
"null",
"0",
"is",
"returned",
"."
] |
train
|
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/simple/RDBMUserLayoutStore.java#L1491-L1525
|
Alluxio/alluxio
|
core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java
|
FileDataManager.prepareUfsFilePath
|
private String prepareUfsFilePath(FileInfo fileInfo, UnderFileSystem ufs)
throws AlluxioException, IOException {
"""
Prepares the destination file path of the given file id. Also creates the parent folder if it
does not exist.
@param fileInfo the file info
@param ufs the {@link UnderFileSystem} instance
@return the path for persistence
"""
AlluxioURI alluxioPath = new AlluxioURI(fileInfo.getPath());
FileSystem fs = mFileSystemFactory.get();
URIStatus status = fs.getStatus(alluxioPath);
String ufsPath = status.getUfsPath();
UnderFileSystemUtils.prepareFilePath(alluxioPath, ufsPath, fs, ufs);
return ufsPath;
}
|
java
|
private String prepareUfsFilePath(FileInfo fileInfo, UnderFileSystem ufs)
throws AlluxioException, IOException {
AlluxioURI alluxioPath = new AlluxioURI(fileInfo.getPath());
FileSystem fs = mFileSystemFactory.get();
URIStatus status = fs.getStatus(alluxioPath);
String ufsPath = status.getUfsPath();
UnderFileSystemUtils.prepareFilePath(alluxioPath, ufsPath, fs, ufs);
return ufsPath;
}
|
[
"private",
"String",
"prepareUfsFilePath",
"(",
"FileInfo",
"fileInfo",
",",
"UnderFileSystem",
"ufs",
")",
"throws",
"AlluxioException",
",",
"IOException",
"{",
"AlluxioURI",
"alluxioPath",
"=",
"new",
"AlluxioURI",
"(",
"fileInfo",
".",
"getPath",
"(",
")",
")",
";",
"FileSystem",
"fs",
"=",
"mFileSystemFactory",
".",
"get",
"(",
")",
";",
"URIStatus",
"status",
"=",
"fs",
".",
"getStatus",
"(",
"alluxioPath",
")",
";",
"String",
"ufsPath",
"=",
"status",
".",
"getUfsPath",
"(",
")",
";",
"UnderFileSystemUtils",
".",
"prepareFilePath",
"(",
"alluxioPath",
",",
"ufsPath",
",",
"fs",
",",
"ufs",
")",
";",
"return",
"ufsPath",
";",
"}"
] |
Prepares the destination file path of the given file id. Also creates the parent folder if it
does not exist.
@param fileInfo the file info
@param ufs the {@link UnderFileSystem} instance
@return the path for persistence
|
[
"Prepares",
"the",
"destination",
"file",
"path",
"of",
"the",
"given",
"file",
"id",
".",
"Also",
"creates",
"the",
"parent",
"folder",
"if",
"it",
"does",
"not",
"exist",
"."
] |
train
|
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/file/FileDataManager.java#L336-L344
|
wisdom-framework/wisdom
|
core/crypto/src/main/java/org/wisdom/crypto/CryptoServiceSingleton.java
|
CryptoServiceSingleton.encryptAES
|
@Override
public String encryptAES(String value, String privateKey) {
"""
Encrypt a String with the AES standard encryption (using the ECB mode). Private key must have a length of 16 bytes.
@param value The String to encrypt
@param privateKey The key used to encrypt
@return An hexadecimal encrypted string
"""
try {
byte[] raw = privateKey.getBytes(UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ECB_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ECB_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return hexToString(cipher.doFinal(value.getBytes(Charsets.UTF_8)));
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
throw new IllegalStateException(e);
}
}
|
java
|
@Override
public String encryptAES(String value, String privateKey) {
try {
byte[] raw = privateKey.getBytes(UTF_8);
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ECB_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ECB_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return hexToString(cipher.doFinal(value.getBytes(Charsets.UTF_8)));
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
throw new IllegalStateException(e);
}
}
|
[
"@",
"Override",
"public",
"String",
"encryptAES",
"(",
"String",
"value",
",",
"String",
"privateKey",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"raw",
"=",
"privateKey",
".",
"getBytes",
"(",
"UTF_8",
")",
";",
"SecretKeySpec",
"skeySpec",
"=",
"new",
"SecretKeySpec",
"(",
"raw",
",",
"AES_ECB_ALGORITHM",
")",
";",
"Cipher",
"cipher",
"=",
"Cipher",
".",
"getInstance",
"(",
"AES_ECB_ALGORITHM",
")",
";",
"cipher",
".",
"init",
"(",
"Cipher",
".",
"ENCRYPT_MODE",
",",
"skeySpec",
")",
";",
"return",
"hexToString",
"(",
"cipher",
".",
"doFinal",
"(",
"value",
".",
"getBytes",
"(",
"Charsets",
".",
"UTF_8",
")",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"|",
"NoSuchPaddingException",
"|",
"InvalidKeyException",
"|",
"BadPaddingException",
"|",
"IllegalBlockSizeException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] |
Encrypt a String with the AES standard encryption (using the ECB mode). Private key must have a length of 16 bytes.
@param value The String to encrypt
@param privateKey The key used to encrypt
@return An hexadecimal encrypted string
|
[
"Encrypt",
"a",
"String",
"with",
"the",
"AES",
"standard",
"encryption",
"(",
"using",
"the",
"ECB",
"mode",
")",
".",
"Private",
"key",
"must",
"have",
"a",
"length",
"of",
"16",
"bytes",
"."
] |
train
|
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/crypto/src/main/java/org/wisdom/crypto/CryptoServiceSingleton.java#L286-L298
|
ziccardi/jnrpe
|
jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysqlQuery.java
|
CheckMysqlQuery.gatherMetrics
|
public final Collection<Metric> gatherMetrics(final ICommandLine cl) throws MetricGatheringException {
"""
Execute and gather metrics.
@param cl
the command line
@throws MetricGatheringException
on any error gathering metrics
@return the metrics
"""
LOG.debug(getContext(), "check_mysql_query gather metrics");
List<Metric> metrics = new ArrayList<Metric>();
Mysql mysql = new Mysql(cl);
Connection conn = null;
try {
conn = mysql.getConnection();
} catch (ClassNotFoundException e) {
LOG.error(getContext(), "Mysql driver library not found into the classpath" + ": download and put it in the same directory " + "of this plugin");
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: Error accessing the " + "MySQL server - JDBC driver not installed",
Status.CRITICAL, e);
} catch (Exception e) {
LOG.error(getContext(), "Error accessing the MySQL server", e);
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: Error accessing " + "the MySQL server - " + e.getMessage(),
Status.CRITICAL, e);
}
String query = cl.getOptionValue("query");
Statement st = null;
ResultSet set = null;
try {
st = conn.createStatement();
st.execute(query);
set = st.getResultSet();
BigDecimal value = null;
if (set.first()) {
value = set.getBigDecimal(1);
}
metrics.add(new Metric("rows", "CHECK_MYSQL_QUERY - Returned value is " + (value != null ? value.longValue() : null), value, null, null));
} catch (SQLException e) {
String message = e.getMessage();
LOG.warn(getContext(), "Error executing plugin CheckMysqlQuery : " + message, e);
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: " + message, Status.CRITICAL, e);
} finally {
DBUtils.closeQuietly(set);
DBUtils.closeQuietly(st);
DBUtils.closeQuietly(conn);
}
return metrics;
}
|
java
|
public final Collection<Metric> gatherMetrics(final ICommandLine cl) throws MetricGatheringException {
LOG.debug(getContext(), "check_mysql_query gather metrics");
List<Metric> metrics = new ArrayList<Metric>();
Mysql mysql = new Mysql(cl);
Connection conn = null;
try {
conn = mysql.getConnection();
} catch (ClassNotFoundException e) {
LOG.error(getContext(), "Mysql driver library not found into the classpath" + ": download and put it in the same directory " + "of this plugin");
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: Error accessing the " + "MySQL server - JDBC driver not installed",
Status.CRITICAL, e);
} catch (Exception e) {
LOG.error(getContext(), "Error accessing the MySQL server", e);
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: Error accessing " + "the MySQL server - " + e.getMessage(),
Status.CRITICAL, e);
}
String query = cl.getOptionValue("query");
Statement st = null;
ResultSet set = null;
try {
st = conn.createStatement();
st.execute(query);
set = st.getResultSet();
BigDecimal value = null;
if (set.first()) {
value = set.getBigDecimal(1);
}
metrics.add(new Metric("rows", "CHECK_MYSQL_QUERY - Returned value is " + (value != null ? value.longValue() : null), value, null, null));
} catch (SQLException e) {
String message = e.getMessage();
LOG.warn(getContext(), "Error executing plugin CheckMysqlQuery : " + message, e);
throw new MetricGatheringException("CHECK_MYSQL_QUERY - CRITICAL: " + message, Status.CRITICAL, e);
} finally {
DBUtils.closeQuietly(set);
DBUtils.closeQuietly(st);
DBUtils.closeQuietly(conn);
}
return metrics;
}
|
[
"public",
"final",
"Collection",
"<",
"Metric",
">",
"gatherMetrics",
"(",
"final",
"ICommandLine",
"cl",
")",
"throws",
"MetricGatheringException",
"{",
"LOG",
".",
"debug",
"(",
"getContext",
"(",
")",
",",
"\"check_mysql_query gather metrics\"",
")",
";",
"List",
"<",
"Metric",
">",
"metrics",
"=",
"new",
"ArrayList",
"<",
"Metric",
">",
"(",
")",
";",
"Mysql",
"mysql",
"=",
"new",
"Mysql",
"(",
"cl",
")",
";",
"Connection",
"conn",
"=",
"null",
";",
"try",
"{",
"conn",
"=",
"mysql",
".",
"getConnection",
"(",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"getContext",
"(",
")",
",",
"\"Mysql driver library not found into the classpath\"",
"+",
"\": download and put it in the same directory \"",
"+",
"\"of this plugin\"",
")",
";",
"throw",
"new",
"MetricGatheringException",
"(",
"\"CHECK_MYSQL_QUERY - CRITICAL: Error accessing the \"",
"+",
"\"MySQL server - JDBC driver not installed\"",
",",
"Status",
".",
"CRITICAL",
",",
"e",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"getContext",
"(",
")",
",",
"\"Error accessing the MySQL server\"",
",",
"e",
")",
";",
"throw",
"new",
"MetricGatheringException",
"(",
"\"CHECK_MYSQL_QUERY - CRITICAL: Error accessing \"",
"+",
"\"the MySQL server - \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"Status",
".",
"CRITICAL",
",",
"e",
")",
";",
"}",
"String",
"query",
"=",
"cl",
".",
"getOptionValue",
"(",
"\"query\"",
")",
";",
"Statement",
"st",
"=",
"null",
";",
"ResultSet",
"set",
"=",
"null",
";",
"try",
"{",
"st",
"=",
"conn",
".",
"createStatement",
"(",
")",
";",
"st",
".",
"execute",
"(",
"query",
")",
";",
"set",
"=",
"st",
".",
"getResultSet",
"(",
")",
";",
"BigDecimal",
"value",
"=",
"null",
";",
"if",
"(",
"set",
".",
"first",
"(",
")",
")",
"{",
"value",
"=",
"set",
".",
"getBigDecimal",
"(",
"1",
")",
";",
"}",
"metrics",
".",
"add",
"(",
"new",
"Metric",
"(",
"\"rows\"",
",",
"\"CHECK_MYSQL_QUERY - Returned value is \"",
"+",
"(",
"value",
"!=",
"null",
"?",
"value",
".",
"longValue",
"(",
")",
":",
"null",
")",
",",
"value",
",",
"null",
",",
"null",
")",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"String",
"message",
"=",
"e",
".",
"getMessage",
"(",
")",
";",
"LOG",
".",
"warn",
"(",
"getContext",
"(",
")",
",",
"\"Error executing plugin CheckMysqlQuery : \"",
"+",
"message",
",",
"e",
")",
";",
"throw",
"new",
"MetricGatheringException",
"(",
"\"CHECK_MYSQL_QUERY - CRITICAL: \"",
"+",
"message",
",",
"Status",
".",
"CRITICAL",
",",
"e",
")",
";",
"}",
"finally",
"{",
"DBUtils",
".",
"closeQuietly",
"(",
"set",
")",
";",
"DBUtils",
".",
"closeQuietly",
"(",
"st",
")",
";",
"DBUtils",
".",
"closeQuietly",
"(",
"conn",
")",
";",
"}",
"return",
"metrics",
";",
"}"
] |
Execute and gather metrics.
@param cl
the command line
@throws MetricGatheringException
on any error gathering metrics
@return the metrics
|
[
"Execute",
"and",
"gather",
"metrics",
"."
] |
train
|
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysqlQuery.java#L63-L106
|
googleapis/google-cloud-java
|
google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java
|
LogEntry.of
|
public static LogEntry of(String logName, MonitoredResource resource, Payload<?> payload) {
"""
Creates a {@code LogEntry} object given the log name, the monitored resource and the entry
payload.
"""
return newBuilder(payload).setLogName(logName).setResource(resource).build();
}
|
java
|
public static LogEntry of(String logName, MonitoredResource resource, Payload<?> payload) {
return newBuilder(payload).setLogName(logName).setResource(resource).build();
}
|
[
"public",
"static",
"LogEntry",
"of",
"(",
"String",
"logName",
",",
"MonitoredResource",
"resource",
",",
"Payload",
"<",
"?",
">",
"payload",
")",
"{",
"return",
"newBuilder",
"(",
"payload",
")",
".",
"setLogName",
"(",
"logName",
")",
".",
"setResource",
"(",
"resource",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Creates a {@code LogEntry} object given the log name, the monitored resource and the entry
payload.
|
[
"Creates",
"a",
"{"
] |
train
|
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java#L519-L521
|
jenkinsci/jenkins
|
core/src/main/java/hudson/Util.java
|
Util.loadFile
|
@Nonnull
public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException {
"""
Reads the entire contents of the text file at <code>logfile</code> into a
string using <code>charset</code> for decoding. If no such file exists,
an empty string is returned.
@param logfile The text file to read in its entirety.
@param charset The charset to use for decoding the bytes in <code>logfile</code>.
@return The entire text content of <code>logfile</code>.
@throws IOException If an error occurs while reading the file.
"""
// Note: Until charset handling is resolved (e.g. by implementing
// https://issues.jenkins-ci.org/browse/JENKINS-48923 ), this method
// must be able to handle character encoding errors. As reported at
// https://issues.jenkins-ci.org/browse/JENKINS-49112 Run.getLog() calls
// loadFile() to fully read the generated log file. This file might
// contain unmappable and/or malformed byte sequences. We need to make
// sure that in such cases, no CharacterCodingException is thrown.
//
// One approach that cannot be used is to call Files.newBufferedReader()
// because there is a difference in how an InputStreamReader constructed
// from a Charset and the reader returned by Files.newBufferedReader()
// handle malformed and unmappable byte sequences for the specified
// encoding; the latter is more picky and will throw an exception.
// See: https://issues.jenkins-ci.org/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989
try {
return FileUtils.readFileToString(logfile, charset);
} catch (FileNotFoundException e) {
return "";
} catch (Exception e) {
throw new IOException("Failed to fully read " + logfile, e);
}
}
|
java
|
@Nonnull
public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException {
// Note: Until charset handling is resolved (e.g. by implementing
// https://issues.jenkins-ci.org/browse/JENKINS-48923 ), this method
// must be able to handle character encoding errors. As reported at
// https://issues.jenkins-ci.org/browse/JENKINS-49112 Run.getLog() calls
// loadFile() to fully read the generated log file. This file might
// contain unmappable and/or malformed byte sequences. We need to make
// sure that in such cases, no CharacterCodingException is thrown.
//
// One approach that cannot be used is to call Files.newBufferedReader()
// because there is a difference in how an InputStreamReader constructed
// from a Charset and the reader returned by Files.newBufferedReader()
// handle malformed and unmappable byte sequences for the specified
// encoding; the latter is more picky and will throw an exception.
// See: https://issues.jenkins-ci.org/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989
try {
return FileUtils.readFileToString(logfile, charset);
} catch (FileNotFoundException e) {
return "";
} catch (Exception e) {
throw new IOException("Failed to fully read " + logfile, e);
}
}
|
[
"@",
"Nonnull",
"public",
"static",
"String",
"loadFile",
"(",
"@",
"Nonnull",
"File",
"logfile",
",",
"@",
"Nonnull",
"Charset",
"charset",
")",
"throws",
"IOException",
"{",
"// Note: Until charset handling is resolved (e.g. by implementing",
"// https://issues.jenkins-ci.org/browse/JENKINS-48923 ), this method",
"// must be able to handle character encoding errors. As reported at",
"// https://issues.jenkins-ci.org/browse/JENKINS-49112 Run.getLog() calls",
"// loadFile() to fully read the generated log file. This file might",
"// contain unmappable and/or malformed byte sequences. We need to make",
"// sure that in such cases, no CharacterCodingException is thrown.",
"//",
"// One approach that cannot be used is to call Files.newBufferedReader()",
"// because there is a difference in how an InputStreamReader constructed",
"// from a Charset and the reader returned by Files.newBufferedReader()",
"// handle malformed and unmappable byte sequences for the specified",
"// encoding; the latter is more picky and will throw an exception.",
"// See: https://issues.jenkins-ci.org/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989",
"try",
"{",
"return",
"FileUtils",
".",
"readFileToString",
"(",
"logfile",
",",
"charset",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"return",
"\"\"",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to fully read \"",
"+",
"logfile",
",",
"e",
")",
";",
"}",
"}"
] |
Reads the entire contents of the text file at <code>logfile</code> into a
string using <code>charset</code> for decoding. If no such file exists,
an empty string is returned.
@param logfile The text file to read in its entirety.
@param charset The charset to use for decoding the bytes in <code>logfile</code>.
@return The entire text content of <code>logfile</code>.
@throws IOException If an error occurs while reading the file.
|
[
"Reads",
"the",
"entire",
"contents",
"of",
"the",
"text",
"file",
"at",
"<code",
">",
"logfile<",
"/",
"code",
">",
"into",
"a",
"string",
"using",
"<code",
">",
"charset<",
"/",
"code",
">",
"for",
"decoding",
".",
"If",
"no",
"such",
"file",
"exists",
"an",
"empty",
"string",
"is",
"returned",
"."
] |
train
|
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L213-L236
|
michael-rapp/AndroidUtil
|
library/src/main/java/de/mrapp/android/util/ElevationUtil.java
|
ElevationUtil.getVerticalShadowWidth
|
private static float getVerticalShadowWidth(@NonNull Context context, final int elevation,
@NonNull final Orientation orientation,
final boolean parallelLight) {
"""
Returns the width of a shadow, which is located next to a corner of an elevated view in
vertical direction.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param elevation
The elevation, which should be emulated, in dp as an {@link Integer} value. The
elevation must be at least 0 and at maximum the value of the constant
<code>MAX_ELEVATION</code>
@param orientation
The orientation of the shadow in relation to the elevated view as a value of the enum
{@link Orientation}. The orientation may either be <code>TOP_LEFT</code>,
<code>TOP_RIGHT</code>, <code>BOTTOM_LEFT</code> or <code>BOTTOM_RIGHT</code>
@param parallelLight
True, if the parallel light should be emulated, false otherwise
@return The width of the shadow in pixels as a {@link Float} value
"""
switch (orientation) {
case TOP_LEFT:
case BOTTOM_LEFT:
return getShadowWidth(context, elevation, Orientation.LEFT, parallelLight);
case TOP_RIGHT:
case BOTTOM_RIGHT:
return getShadowWidth(context, elevation, Orientation.RIGHT, parallelLight);
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
|
java
|
private static float getVerticalShadowWidth(@NonNull Context context, final int elevation,
@NonNull final Orientation orientation,
final boolean parallelLight) {
switch (orientation) {
case TOP_LEFT:
case BOTTOM_LEFT:
return getShadowWidth(context, elevation, Orientation.LEFT, parallelLight);
case TOP_RIGHT:
case BOTTOM_RIGHT:
return getShadowWidth(context, elevation, Orientation.RIGHT, parallelLight);
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
|
[
"private",
"static",
"float",
"getVerticalShadowWidth",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"final",
"int",
"elevation",
",",
"@",
"NonNull",
"final",
"Orientation",
"orientation",
",",
"final",
"boolean",
"parallelLight",
")",
"{",
"switch",
"(",
"orientation",
")",
"{",
"case",
"TOP_LEFT",
":",
"case",
"BOTTOM_LEFT",
":",
"return",
"getShadowWidth",
"(",
"context",
",",
"elevation",
",",
"Orientation",
".",
"LEFT",
",",
"parallelLight",
")",
";",
"case",
"TOP_RIGHT",
":",
"case",
"BOTTOM_RIGHT",
":",
"return",
"getShadowWidth",
"(",
"context",
",",
"elevation",
",",
"Orientation",
".",
"RIGHT",
",",
"parallelLight",
")",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid orientation: \"",
"+",
"orientation",
")",
";",
"}",
"}"
] |
Returns the width of a shadow, which is located next to a corner of an elevated view in
vertical direction.
@param context
The context, which should be used, as an instance of the class {@link Context}. The
context may not be null
@param elevation
The elevation, which should be emulated, in dp as an {@link Integer} value. The
elevation must be at least 0 and at maximum the value of the constant
<code>MAX_ELEVATION</code>
@param orientation
The orientation of the shadow in relation to the elevated view as a value of the enum
{@link Orientation}. The orientation may either be <code>TOP_LEFT</code>,
<code>TOP_RIGHT</code>, <code>BOTTOM_LEFT</code> or <code>BOTTOM_RIGHT</code>
@param parallelLight
True, if the parallel light should be emulated, false otherwise
@return The width of the shadow in pixels as a {@link Float} value
|
[
"Returns",
"the",
"width",
"of",
"a",
"shadow",
"which",
"is",
"located",
"next",
"to",
"a",
"corner",
"of",
"an",
"elevated",
"view",
"in",
"vertical",
"direction",
"."
] |
train
|
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/ElevationUtil.java#L456-L469
|
apache/incubator-gobblin
|
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowStatusResource.java
|
FlowStatusResource.get
|
@Override
public FlowStatus get(ComplexResourceKey<FlowStatusId, EmptyRecord> key) {
"""
Retrieve the FlowStatus with the given key
@param key flow status id key containing group name and flow name
@return {@link FlowStatus} with flow status for the latest execution of the flow
"""
String flowGroup = key.getKey().getFlowGroup();
String flowName = key.getKey().getFlowName();
long flowExecutionId = key.getKey().getFlowExecutionId();
LOG.info("Get called with flowGroup " + flowGroup + " flowName " + flowName + " flowExecutionId " + flowExecutionId);
org.apache.gobblin.service.monitoring.FlowStatus flowStatus =
_flowStatusGenerator.getFlowStatus(flowName, flowGroup, flowExecutionId);
// this returns null to raise a 404 error if flowStatus is null
return convertFlowStatus(flowStatus);
}
|
java
|
@Override
public FlowStatus get(ComplexResourceKey<FlowStatusId, EmptyRecord> key) {
String flowGroup = key.getKey().getFlowGroup();
String flowName = key.getKey().getFlowName();
long flowExecutionId = key.getKey().getFlowExecutionId();
LOG.info("Get called with flowGroup " + flowGroup + " flowName " + flowName + " flowExecutionId " + flowExecutionId);
org.apache.gobblin.service.monitoring.FlowStatus flowStatus =
_flowStatusGenerator.getFlowStatus(flowName, flowGroup, flowExecutionId);
// this returns null to raise a 404 error if flowStatus is null
return convertFlowStatus(flowStatus);
}
|
[
"@",
"Override",
"public",
"FlowStatus",
"get",
"(",
"ComplexResourceKey",
"<",
"FlowStatusId",
",",
"EmptyRecord",
">",
"key",
")",
"{",
"String",
"flowGroup",
"=",
"key",
".",
"getKey",
"(",
")",
".",
"getFlowGroup",
"(",
")",
";",
"String",
"flowName",
"=",
"key",
".",
"getKey",
"(",
")",
".",
"getFlowName",
"(",
")",
";",
"long",
"flowExecutionId",
"=",
"key",
".",
"getKey",
"(",
")",
".",
"getFlowExecutionId",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Get called with flowGroup \"",
"+",
"flowGroup",
"+",
"\" flowName \"",
"+",
"flowName",
"+",
"\" flowExecutionId \"",
"+",
"flowExecutionId",
")",
";",
"org",
".",
"apache",
".",
"gobblin",
".",
"service",
".",
"monitoring",
".",
"FlowStatus",
"flowStatus",
"=",
"_flowStatusGenerator",
".",
"getFlowStatus",
"(",
"flowName",
",",
"flowGroup",
",",
"flowExecutionId",
")",
";",
"// this returns null to raise a 404 error if flowStatus is null",
"return",
"convertFlowStatus",
"(",
"flowStatus",
")",
";",
"}"
] |
Retrieve the FlowStatus with the given key
@param key flow status id key containing group name and flow name
@return {@link FlowStatus} with flow status for the latest execution of the flow
|
[
"Retrieve",
"the",
"FlowStatus",
"with",
"the",
"given",
"key"
] |
train
|
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowStatusResource.java#L61-L74
|
versionone/VersionOne.SDK.Java.ObjectModel
|
src/main/java/com/versionone/om/V1InstanceGetter.java
|
V1InstanceGetter.story
|
public Collection<Story> story(StoryFilter filter) {
"""
Get stories filtered by the criteria specified in the passed in filter.
@param filter Limit the items returned. If null, then all items returned.
@return Collection of items as specified in the filter.
"""
return get(Story.class, (filter != null) ? filter : new StoryFilter());
}
|
java
|
public Collection<Story> story(StoryFilter filter) {
return get(Story.class, (filter != null) ? filter : new StoryFilter());
}
|
[
"public",
"Collection",
"<",
"Story",
">",
"story",
"(",
"StoryFilter",
"filter",
")",
"{",
"return",
"get",
"(",
"Story",
".",
"class",
",",
"(",
"filter",
"!=",
"null",
")",
"?",
"filter",
":",
"new",
"StoryFilter",
"(",
")",
")",
";",
"}"
] |
Get stories filtered by the criteria specified in the passed in filter.
@param filter Limit the items returned. If null, then all items returned.
@return Collection of items as specified in the filter.
|
[
"Get",
"stories",
"filtered",
"by",
"the",
"criteria",
"specified",
"in",
"the",
"passed",
"in",
"filter",
"."
] |
train
|
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1InstanceGetter.java#L108-L110
|
timols/java-gitlab-api
|
src/main/java/org/gitlab/api/GitlabAPI.java
|
GitlabAPI.createProjectForGroup
|
public GitlabProject createProjectForGroup(String name, GitlabGroup group, String description, String visibility) throws IOException {
"""
Creates a group Project
@param name The name of the project
@param group The group for which the project should be crated
@param description The project description
@param visibility The project visibility level (private: 0, internal: 10, public: 20)
@return The GitLab Project
@throws IOException on gitlab api call error
"""
return createProject(name, group.getId(), description, null, null, null, null, null, null, visibility, null);
}
|
java
|
public GitlabProject createProjectForGroup(String name, GitlabGroup group, String description, String visibility) throws IOException {
return createProject(name, group.getId(), description, null, null, null, null, null, null, visibility, null);
}
|
[
"public",
"GitlabProject",
"createProjectForGroup",
"(",
"String",
"name",
",",
"GitlabGroup",
"group",
",",
"String",
"description",
",",
"String",
"visibility",
")",
"throws",
"IOException",
"{",
"return",
"createProject",
"(",
"name",
",",
"group",
".",
"getId",
"(",
")",
",",
"description",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"visibility",
",",
"null",
")",
";",
"}"
] |
Creates a group Project
@param name The name of the project
@param group The group for which the project should be crated
@param description The project description
@param visibility The project visibility level (private: 0, internal: 10, public: 20)
@return The GitLab Project
@throws IOException on gitlab api call error
|
[
"Creates",
"a",
"group",
"Project"
] |
train
|
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L1229-L1231
|
davidmoten/rxjava-jdbc
|
src/main/java/com/github/davidmoten/rx/jdbc/QuerySelect.java
|
QuerySelect.executeOnce
|
private <T> Func1<List<Parameter>, Observable<T>> executeOnce(
final ResultSetMapper<? extends T> function) {
"""
Returns a {@link Func1} that itself returns the results of pushing one
set of parameters through a select query.
@param query
@return
"""
return new Func1<List<Parameter>, Observable<T>>() {
@Override
public Observable<T> call(List<Parameter> params) {
return executeOnce(params, function);
}
};
}
|
java
|
private <T> Func1<List<Parameter>, Observable<T>> executeOnce(
final ResultSetMapper<? extends T> function) {
return new Func1<List<Parameter>, Observable<T>>() {
@Override
public Observable<T> call(List<Parameter> params) {
return executeOnce(params, function);
}
};
}
|
[
"private",
"<",
"T",
">",
"Func1",
"<",
"List",
"<",
"Parameter",
">",
",",
"Observable",
"<",
"T",
">",
">",
"executeOnce",
"(",
"final",
"ResultSetMapper",
"<",
"?",
"extends",
"T",
">",
"function",
")",
"{",
"return",
"new",
"Func1",
"<",
"List",
"<",
"Parameter",
">",
",",
"Observable",
"<",
"T",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"T",
">",
"call",
"(",
"List",
"<",
"Parameter",
">",
"params",
")",
"{",
"return",
"executeOnce",
"(",
"params",
",",
"function",
")",
";",
"}",
"}",
";",
"}"
] |
Returns a {@link Func1} that itself returns the results of pushing one
set of parameters through a select query.
@param query
@return
|
[
"Returns",
"a",
"{",
"@link",
"Func1",
"}",
"that",
"itself",
"returns",
"the",
"results",
"of",
"pushing",
"one",
"set",
"of",
"parameters",
"through",
"a",
"select",
"query",
"."
] |
train
|
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/QuerySelect.java#L118-L126
|
Whiley/WhileyCompiler
|
src/main/java/wyc/io/WhileyFileParser.java
|
WhileyFileParser.parseRecordType
|
private Type parseRecordType(EnclosingScope scope) {
"""
Parse a set, map or record type, which are of the form:
<pre>
SetType ::= '{' Type '}'
MapType ::= '{' Type "=>" Type '}'
RecordType ::= '{' Type Identifier (',' Type Identifier)* [ ',' "..." ] '}'
</pre>
Disambiguating these three forms is relatively straightforward as all
three must be terminated by a right curly brace. Therefore, after parsing
the first Type, we simply check what follows. One complication is the
potential for "mixed types" where the field name and type and intertwined
(e.g. function read()->[byte]).
@return
"""
int start = index;
match(LeftCurly);
ArrayList<Type.Field> types = new ArrayList<>();
Pair<Type, Identifier> p = parseMixedType(scope);
types.add(new Type.Field(p.getSecond(), p.getFirst()));
HashSet<Identifier> names = new HashSet<>();
names.add(p.getSecond());
// Now, we continue to parse any remaining fields.
boolean isOpen = false;
while (eventuallyMatch(RightCurly) == null) {
match(Comma);
if (tryAndMatch(true, DotDotDot) != null) {
// this signals an "open" record type
match(RightCurly);
isOpen = true;
break;
} else {
p = parseMixedType(scope);
Identifier id = p.getSecond();
if (names.contains(id)) {
syntaxError("duplicate record key", id);
}
names.add(id);
types.add(new Type.Field(id, p.getFirst()));
}
}
// Done
Tuple<Type.Field> fields = new Tuple<>(types);
return annotateSourceLocation(new Type.Record(isOpen, fields), start);
}
|
java
|
private Type parseRecordType(EnclosingScope scope) {
int start = index;
match(LeftCurly);
ArrayList<Type.Field> types = new ArrayList<>();
Pair<Type, Identifier> p = parseMixedType(scope);
types.add(new Type.Field(p.getSecond(), p.getFirst()));
HashSet<Identifier> names = new HashSet<>();
names.add(p.getSecond());
// Now, we continue to parse any remaining fields.
boolean isOpen = false;
while (eventuallyMatch(RightCurly) == null) {
match(Comma);
if (tryAndMatch(true, DotDotDot) != null) {
// this signals an "open" record type
match(RightCurly);
isOpen = true;
break;
} else {
p = parseMixedType(scope);
Identifier id = p.getSecond();
if (names.contains(id)) {
syntaxError("duplicate record key", id);
}
names.add(id);
types.add(new Type.Field(id, p.getFirst()));
}
}
// Done
Tuple<Type.Field> fields = new Tuple<>(types);
return annotateSourceLocation(new Type.Record(isOpen, fields), start);
}
|
[
"private",
"Type",
"parseRecordType",
"(",
"EnclosingScope",
"scope",
")",
"{",
"int",
"start",
"=",
"index",
";",
"match",
"(",
"LeftCurly",
")",
";",
"ArrayList",
"<",
"Type",
".",
"Field",
">",
"types",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Pair",
"<",
"Type",
",",
"Identifier",
">",
"p",
"=",
"parseMixedType",
"(",
"scope",
")",
";",
"types",
".",
"add",
"(",
"new",
"Type",
".",
"Field",
"(",
"p",
".",
"getSecond",
"(",
")",
",",
"p",
".",
"getFirst",
"(",
")",
")",
")",
";",
"HashSet",
"<",
"Identifier",
">",
"names",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"names",
".",
"add",
"(",
"p",
".",
"getSecond",
"(",
")",
")",
";",
"// Now, we continue to parse any remaining fields.",
"boolean",
"isOpen",
"=",
"false",
";",
"while",
"(",
"eventuallyMatch",
"(",
"RightCurly",
")",
"==",
"null",
")",
"{",
"match",
"(",
"Comma",
")",
";",
"if",
"(",
"tryAndMatch",
"(",
"true",
",",
"DotDotDot",
")",
"!=",
"null",
")",
"{",
"// this signals an \"open\" record type",
"match",
"(",
"RightCurly",
")",
";",
"isOpen",
"=",
"true",
";",
"break",
";",
"}",
"else",
"{",
"p",
"=",
"parseMixedType",
"(",
"scope",
")",
";",
"Identifier",
"id",
"=",
"p",
".",
"getSecond",
"(",
")",
";",
"if",
"(",
"names",
".",
"contains",
"(",
"id",
")",
")",
"{",
"syntaxError",
"(",
"\"duplicate record key\"",
",",
"id",
")",
";",
"}",
"names",
".",
"add",
"(",
"id",
")",
";",
"types",
".",
"add",
"(",
"new",
"Type",
".",
"Field",
"(",
"id",
",",
"p",
".",
"getFirst",
"(",
")",
")",
")",
";",
"}",
"}",
"// Done",
"Tuple",
"<",
"Type",
".",
"Field",
">",
"fields",
"=",
"new",
"Tuple",
"<>",
"(",
"types",
")",
";",
"return",
"annotateSourceLocation",
"(",
"new",
"Type",
".",
"Record",
"(",
"isOpen",
",",
"fields",
")",
",",
"start",
")",
";",
"}"
] |
Parse a set, map or record type, which are of the form:
<pre>
SetType ::= '{' Type '}'
MapType ::= '{' Type "=>" Type '}'
RecordType ::= '{' Type Identifier (',' Type Identifier)* [ ',' "..." ] '}'
</pre>
Disambiguating these three forms is relatively straightforward as all
three must be terminated by a right curly brace. Therefore, after parsing
the first Type, we simply check what follows. One complication is the
potential for "mixed types" where the field name and type and intertwined
(e.g. function read()->[byte]).
@return
|
[
"Parse",
"a",
"set",
"map",
"or",
"record",
"type",
"which",
"are",
"of",
"the",
"form",
":"
] |
train
|
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L3754-L3784
|
shevek/jcpp
|
src/main/java/org/anarres/cpp/NumericValue.java
|
NumericValue.toBigDecimal
|
@Nonnull
public BigDecimal toBigDecimal() {
"""
So, it turns out that parsing arbitrary bases into arbitrary
precision numbers is nontrivial, and this routine gets it wrong
in many important cases.
"""
int scale = 0;
String text = getIntegerPart();
String t_fraction = getFractionalPart();
if (t_fraction != null) {
text += getFractionalPart();
// XXX Wrong for anything but base 10.
scale += t_fraction.length();
}
String t_exponent = getExponent();
if (t_exponent != null)
scale -= Integer.parseInt(t_exponent);
BigInteger unscaled = new BigInteger(text, getBase());
return new BigDecimal(unscaled, scale);
}
|
java
|
@Nonnull
public BigDecimal toBigDecimal() {
int scale = 0;
String text = getIntegerPart();
String t_fraction = getFractionalPart();
if (t_fraction != null) {
text += getFractionalPart();
// XXX Wrong for anything but base 10.
scale += t_fraction.length();
}
String t_exponent = getExponent();
if (t_exponent != null)
scale -= Integer.parseInt(t_exponent);
BigInteger unscaled = new BigInteger(text, getBase());
return new BigDecimal(unscaled, scale);
}
|
[
"@",
"Nonnull",
"public",
"BigDecimal",
"toBigDecimal",
"(",
")",
"{",
"int",
"scale",
"=",
"0",
";",
"String",
"text",
"=",
"getIntegerPart",
"(",
")",
";",
"String",
"t_fraction",
"=",
"getFractionalPart",
"(",
")",
";",
"if",
"(",
"t_fraction",
"!=",
"null",
")",
"{",
"text",
"+=",
"getFractionalPart",
"(",
")",
";",
"// XXX Wrong for anything but base 10.",
"scale",
"+=",
"t_fraction",
".",
"length",
"(",
")",
";",
"}",
"String",
"t_exponent",
"=",
"getExponent",
"(",
")",
";",
"if",
"(",
"t_exponent",
"!=",
"null",
")",
"scale",
"-=",
"Integer",
".",
"parseInt",
"(",
"t_exponent",
")",
";",
"BigInteger",
"unscaled",
"=",
"new",
"BigInteger",
"(",
"text",
",",
"getBase",
"(",
")",
")",
";",
"return",
"new",
"BigDecimal",
"(",
"unscaled",
",",
"scale",
")",
";",
"}"
] |
So, it turns out that parsing arbitrary bases into arbitrary
precision numbers is nontrivial, and this routine gets it wrong
in many important cases.
|
[
"So",
"it",
"turns",
"out",
"that",
"parsing",
"arbitrary",
"bases",
"into",
"arbitrary",
"precision",
"numbers",
"is",
"nontrivial",
"and",
"this",
"routine",
"gets",
"it",
"wrong",
"in",
"many",
"important",
"cases",
"."
] |
train
|
https://github.com/shevek/jcpp/blob/71462c702097cabf8304202c740f780285fc35a8/src/main/java/org/anarres/cpp/NumericValue.java#L96-L111
|
milaboratory/milib
|
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
|
SequenceQuality.getRange
|
@Override
public SequenceQuality getRange(Range range) {
"""
Returns substring of current quality scores line.
@param range range
@return substring of current quality scores line
"""
byte[] rdata = Arrays.copyOfRange(data, range.getLower(), range.getUpper());
if (range.isReverse())
ArraysUtils.reverse(rdata);
return new SequenceQuality(rdata, true);
}
|
java
|
@Override
public SequenceQuality getRange(Range range) {
byte[] rdata = Arrays.copyOfRange(data, range.getLower(), range.getUpper());
if (range.isReverse())
ArraysUtils.reverse(rdata);
return new SequenceQuality(rdata, true);
}
|
[
"@",
"Override",
"public",
"SequenceQuality",
"getRange",
"(",
"Range",
"range",
")",
"{",
"byte",
"[",
"]",
"rdata",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"data",
",",
"range",
".",
"getLower",
"(",
")",
",",
"range",
".",
"getUpper",
"(",
")",
")",
";",
"if",
"(",
"range",
".",
"isReverse",
"(",
")",
")",
"ArraysUtils",
".",
"reverse",
"(",
"rdata",
")",
";",
"return",
"new",
"SequenceQuality",
"(",
"rdata",
",",
"true",
")",
";",
"}"
] |
Returns substring of current quality scores line.
@param range range
@return substring of current quality scores line
|
[
"Returns",
"substring",
"of",
"current",
"quality",
"scores",
"line",
"."
] |
train
|
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L202-L208
|
appium/java-client
|
src/main/java/io/appium/java_client/imagecomparison/FeaturesMatchingResult.java
|
FeaturesMatchingResult.getRect2
|
public Rectangle getRect2() {
"""
Returns a rect for the `points2` list.
@return The bounding rect for the `points2` list or a zero rect if not enough matching points were found.
"""
verifyPropertyPresence(RECT2);
//noinspection unchecked
return mapToRect((Map<String, Object>) getCommandResult().get(RECT2));
}
|
java
|
public Rectangle getRect2() {
verifyPropertyPresence(RECT2);
//noinspection unchecked
return mapToRect((Map<String, Object>) getCommandResult().get(RECT2));
}
|
[
"public",
"Rectangle",
"getRect2",
"(",
")",
"{",
"verifyPropertyPresence",
"(",
"RECT2",
")",
";",
"//noinspection unchecked",
"return",
"mapToRect",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"getCommandResult",
"(",
")",
".",
"get",
"(",
"RECT2",
")",
")",
";",
"}"
] |
Returns a rect for the `points2` list.
@return The bounding rect for the `points2` list or a zero rect if not enough matching points were found.
|
[
"Returns",
"a",
"rect",
"for",
"the",
"points2",
"list",
"."
] |
train
|
https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/imagecomparison/FeaturesMatchingResult.java#L104-L108
|
jingwei/krati
|
krati-main/src/main/java/krati/core/StoreConfig.java
|
StoreConfig.getInt
|
public int getInt(String pName, int defaultValue) {
"""
Gets an integer property via a string property name.
@param pName - the property name
@param defaultValue - the default property value
@return an integer property
"""
String pValue = _properties.getProperty(pName);
return parseInt(pName, pValue, defaultValue);
}
|
java
|
public int getInt(String pName, int defaultValue) {
String pValue = _properties.getProperty(pName);
return parseInt(pName, pValue, defaultValue);
}
|
[
"public",
"int",
"getInt",
"(",
"String",
"pName",
",",
"int",
"defaultValue",
")",
"{",
"String",
"pValue",
"=",
"_properties",
".",
"getProperty",
"(",
"pName",
")",
";",
"return",
"parseInt",
"(",
"pName",
",",
"pValue",
",",
"defaultValue",
")",
";",
"}"
] |
Gets an integer property via a string property name.
@param pName - the property name
@param defaultValue - the default property value
@return an integer property
|
[
"Gets",
"an",
"integer",
"property",
"via",
"a",
"string",
"property",
"name",
"."
] |
train
|
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/core/StoreConfig.java#L423-L426
|
jenkinsci/jenkins
|
core/src/main/java/hudson/EnvVars.java
|
EnvVars.overrideExpandingAll
|
public EnvVars overrideExpandingAll(@Nonnull Map<String,String> all) {
"""
Overrides all values in the map by the given map. Expressions in values will be expanded.
See {@link #override(String, String)}.
@return {@code this}
"""
for (String key : new OverrideOrderCalculator(this, all).getOrderedVariableNames()) {
override(key, expand(all.get(key)));
}
return this;
}
|
java
|
public EnvVars overrideExpandingAll(@Nonnull Map<String,String> all) {
for (String key : new OverrideOrderCalculator(this, all).getOrderedVariableNames()) {
override(key, expand(all.get(key)));
}
return this;
}
|
[
"public",
"EnvVars",
"overrideExpandingAll",
"(",
"@",
"Nonnull",
"Map",
"<",
"String",
",",
"String",
">",
"all",
")",
"{",
"for",
"(",
"String",
"key",
":",
"new",
"OverrideOrderCalculator",
"(",
"this",
",",
"all",
")",
".",
"getOrderedVariableNames",
"(",
")",
")",
"{",
"override",
"(",
"key",
",",
"expand",
"(",
"all",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Overrides all values in the map by the given map. Expressions in values will be expanded.
See {@link #override(String, String)}.
@return {@code this}
|
[
"Overrides",
"all",
"values",
"in",
"the",
"map",
"by",
"the",
"given",
"map",
".",
"Expressions",
"in",
"values",
"will",
"be",
"expanded",
".",
"See",
"{"
] |
train
|
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/EnvVars.java#L350-L355
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java
|
GraphicalModel.addStaticConditionalFactor
|
public StaticFactor addStaticConditionalFactor(int[] antecedents, int consequent,
int[] antecedentDimensions, int consequentDimension,
BiFunction<int[], Integer, Double> conditionalProbaility) {
"""
Add a conditional factor, as per a Bayes net.
Note that unlike the case with other factors, this function takes as input <b>probabilities</b> and not
unnormalized factor values.
In other words, we do not exponentiate the values coming from the assignment function into a log-linear model.
@param antecedents The antecedents of the conditional probability. There can be many of these.
@param consequent The consequent of the conditional probability. There is only one of these.
@param antecedentDimensions The variable dimmensions of the antecedents.
@param consequentDimension The variable dimmension of the consequent.
@param conditionalProbaility The assignment function, taking as input an assignment of the antecedents,
and an assignment of the consequent, and producing as output a <b>probability</b>
(value between 0 and 1) for this assignment.
This can be an unnormallized probability, but it should not be a log probability, as you'd
expect from a Markov net factor.
@return a reference to the created factor. This can be safely ignored, as the factor is already saved in the model
"""
// Create variables for the global factor
int[] allDimensions = new int[antecedentDimensions.length + 1];
System.arraycopy(antecedentDimensions, 0, allDimensions, 0, antecedentDimensions.length);
allDimensions[allDimensions.length - 1] = consequentDimension;
int[] allNeighbors = new int[antecedents.length + 1];
System.arraycopy(antecedents, 0, allNeighbors, 0, antecedents.length);
allNeighbors[allNeighbors.length - 1] = consequent;
NDArrayDoubles totalFactor = new NDArrayDoubles(allDimensions);
// Compute each conditional table
NDArrayDoubles antecedentOnly = new NDArrayDoubles(antecedentDimensions);
for (int[] assignment : antecedentOnly) {
double localPartitionFunction = 0.0;
for (int consequentValue = 0; consequentValue < consequentDimension; ++consequentValue) {
localPartitionFunction += conditionalProbaility.apply(assignment, consequentValue);
}
for (int consequentValue = 0; consequentValue < consequentDimension; ++consequentValue) {
int[] totalAssignment = new int[assignment.length + 1];
System.arraycopy(assignment, 0, totalAssignment, 0, assignment.length);
totalAssignment[totalAssignment.length - 1] = consequentValue;
totalFactor.setAssignmentValue(totalAssignment, Math.log(conditionalProbaility.apply(assignment, consequentValue)) - Math.log(localPartitionFunction));
}
}
// Create the joint factor
return addStaticFactor(totalFactor, allNeighbors);
}
|
java
|
public StaticFactor addStaticConditionalFactor(int[] antecedents, int consequent,
int[] antecedentDimensions, int consequentDimension,
BiFunction<int[], Integer, Double> conditionalProbaility) {
// Create variables for the global factor
int[] allDimensions = new int[antecedentDimensions.length + 1];
System.arraycopy(antecedentDimensions, 0, allDimensions, 0, antecedentDimensions.length);
allDimensions[allDimensions.length - 1] = consequentDimension;
int[] allNeighbors = new int[antecedents.length + 1];
System.arraycopy(antecedents, 0, allNeighbors, 0, antecedents.length);
allNeighbors[allNeighbors.length - 1] = consequent;
NDArrayDoubles totalFactor = new NDArrayDoubles(allDimensions);
// Compute each conditional table
NDArrayDoubles antecedentOnly = new NDArrayDoubles(antecedentDimensions);
for (int[] assignment : antecedentOnly) {
double localPartitionFunction = 0.0;
for (int consequentValue = 0; consequentValue < consequentDimension; ++consequentValue) {
localPartitionFunction += conditionalProbaility.apply(assignment, consequentValue);
}
for (int consequentValue = 0; consequentValue < consequentDimension; ++consequentValue) {
int[] totalAssignment = new int[assignment.length + 1];
System.arraycopy(assignment, 0, totalAssignment, 0, assignment.length);
totalAssignment[totalAssignment.length - 1] = consequentValue;
totalFactor.setAssignmentValue(totalAssignment, Math.log(conditionalProbaility.apply(assignment, consequentValue)) - Math.log(localPartitionFunction));
}
}
// Create the joint factor
return addStaticFactor(totalFactor, allNeighbors);
}
|
[
"public",
"StaticFactor",
"addStaticConditionalFactor",
"(",
"int",
"[",
"]",
"antecedents",
",",
"int",
"consequent",
",",
"int",
"[",
"]",
"antecedentDimensions",
",",
"int",
"consequentDimension",
",",
"BiFunction",
"<",
"int",
"[",
"]",
",",
"Integer",
",",
"Double",
">",
"conditionalProbaility",
")",
"{",
"// Create variables for the global factor",
"int",
"[",
"]",
"allDimensions",
"=",
"new",
"int",
"[",
"antecedentDimensions",
".",
"length",
"+",
"1",
"]",
";",
"System",
".",
"arraycopy",
"(",
"antecedentDimensions",
",",
"0",
",",
"allDimensions",
",",
"0",
",",
"antecedentDimensions",
".",
"length",
")",
";",
"allDimensions",
"[",
"allDimensions",
".",
"length",
"-",
"1",
"]",
"=",
"consequentDimension",
";",
"int",
"[",
"]",
"allNeighbors",
"=",
"new",
"int",
"[",
"antecedents",
".",
"length",
"+",
"1",
"]",
";",
"System",
".",
"arraycopy",
"(",
"antecedents",
",",
"0",
",",
"allNeighbors",
",",
"0",
",",
"antecedents",
".",
"length",
")",
";",
"allNeighbors",
"[",
"allNeighbors",
".",
"length",
"-",
"1",
"]",
"=",
"consequent",
";",
"NDArrayDoubles",
"totalFactor",
"=",
"new",
"NDArrayDoubles",
"(",
"allDimensions",
")",
";",
"// Compute each conditional table",
"NDArrayDoubles",
"antecedentOnly",
"=",
"new",
"NDArrayDoubles",
"(",
"antecedentDimensions",
")",
";",
"for",
"(",
"int",
"[",
"]",
"assignment",
":",
"antecedentOnly",
")",
"{",
"double",
"localPartitionFunction",
"=",
"0.0",
";",
"for",
"(",
"int",
"consequentValue",
"=",
"0",
";",
"consequentValue",
"<",
"consequentDimension",
";",
"++",
"consequentValue",
")",
"{",
"localPartitionFunction",
"+=",
"conditionalProbaility",
".",
"apply",
"(",
"assignment",
",",
"consequentValue",
")",
";",
"}",
"for",
"(",
"int",
"consequentValue",
"=",
"0",
";",
"consequentValue",
"<",
"consequentDimension",
";",
"++",
"consequentValue",
")",
"{",
"int",
"[",
"]",
"totalAssignment",
"=",
"new",
"int",
"[",
"assignment",
".",
"length",
"+",
"1",
"]",
";",
"System",
".",
"arraycopy",
"(",
"assignment",
",",
"0",
",",
"totalAssignment",
",",
"0",
",",
"assignment",
".",
"length",
")",
";",
"totalAssignment",
"[",
"totalAssignment",
".",
"length",
"-",
"1",
"]",
"=",
"consequentValue",
";",
"totalFactor",
".",
"setAssignmentValue",
"(",
"totalAssignment",
",",
"Math",
".",
"log",
"(",
"conditionalProbaility",
".",
"apply",
"(",
"assignment",
",",
"consequentValue",
")",
")",
"-",
"Math",
".",
"log",
"(",
"localPartitionFunction",
")",
")",
";",
"}",
"}",
"// Create the joint factor",
"return",
"addStaticFactor",
"(",
"totalFactor",
",",
"allNeighbors",
")",
";",
"}"
] |
Add a conditional factor, as per a Bayes net.
Note that unlike the case with other factors, this function takes as input <b>probabilities</b> and not
unnormalized factor values.
In other words, we do not exponentiate the values coming from the assignment function into a log-linear model.
@param antecedents The antecedents of the conditional probability. There can be many of these.
@param consequent The consequent of the conditional probability. There is only one of these.
@param antecedentDimensions The variable dimmensions of the antecedents.
@param consequentDimension The variable dimmension of the consequent.
@param conditionalProbaility The assignment function, taking as input an assignment of the antecedents,
and an assignment of the consequent, and producing as output a <b>probability</b>
(value between 0 and 1) for this assignment.
This can be an unnormallized probability, but it should not be a log probability, as you'd
expect from a Markov net factor.
@return a reference to the created factor. This can be safely ignored, as the factor is already saved in the model
|
[
"Add",
"a",
"conditional",
"factor",
"as",
"per",
"a",
"Bayes",
"net",
".",
"Note",
"that",
"unlike",
"the",
"case",
"with",
"other",
"factors",
"this",
"function",
"takes",
"as",
"input",
"<b",
">",
"probabilities<",
"/",
"b",
">",
"and",
"not",
"unnormalized",
"factor",
"values",
".",
"In",
"other",
"words",
"we",
"do",
"not",
"exponentiate",
"the",
"values",
"coming",
"from",
"the",
"assignment",
"function",
"into",
"a",
"log",
"-",
"linear",
"model",
"."
] |
train
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/GraphicalModel.java#L369-L398
|
RKumsher/utils
|
src/main/java/com/github/rkumsher/collection/IterableUtils.java
|
IterableUtils.randomFrom
|
@SafeVarargs
public static <T> T randomFrom(Iterable<T> iterable, T... excludes) {
"""
Returns a random element from the given {@link Iterable} that's not in the values to exclude.
@param iterable {@link Iterable} to return random element from
@param excludes values to exclude
@param <T> the type of elements in the given iterable
@return random element from the given {@link Iterable} that's not in the values to exclude
@throws IllegalArgumentException if the iterable is empty
"""
return randomFrom(iterable, Arrays.asList(excludes));
}
|
java
|
@SafeVarargs
public static <T> T randomFrom(Iterable<T> iterable, T... excludes) {
return randomFrom(iterable, Arrays.asList(excludes));
}
|
[
"@",
"SafeVarargs",
"public",
"static",
"<",
"T",
">",
"T",
"randomFrom",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"T",
"...",
"excludes",
")",
"{",
"return",
"randomFrom",
"(",
"iterable",
",",
"Arrays",
".",
"asList",
"(",
"excludes",
")",
")",
";",
"}"
] |
Returns a random element from the given {@link Iterable} that's not in the values to exclude.
@param iterable {@link Iterable} to return random element from
@param excludes values to exclude
@param <T> the type of elements in the given iterable
@return random element from the given {@link Iterable} that's not in the values to exclude
@throws IllegalArgumentException if the iterable is empty
|
[
"Returns",
"a",
"random",
"element",
"from",
"the",
"given",
"{",
"@link",
"Iterable",
"}",
"that",
"s",
"not",
"in",
"the",
"values",
"to",
"exclude",
"."
] |
train
|
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/collection/IterableUtils.java#L43-L46
|
gallandarakhneorg/afc
|
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java
|
GeoLocationUtil.epsilonEqualsDistance
|
@Pure
public static boolean epsilonEqualsDistance(Point2D<?, ?> p1, Point2D<?, ?> p2) {
"""
Replies if the specified points are approximatively equal.
This function uses the distance precision.
@param p1 the first point.
@param p2 the second point.
@return <code>true</code> if both points are equal, otherwise <code>false</code>
"""
final double distance = p1.getDistance(p2);
return distance >= -distancePrecision && distance <= distancePrecision;
}
|
java
|
@Pure
public static boolean epsilonEqualsDistance(Point2D<?, ?> p1, Point2D<?, ?> p2) {
final double distance = p1.getDistance(p2);
return distance >= -distancePrecision && distance <= distancePrecision;
}
|
[
"@",
"Pure",
"public",
"static",
"boolean",
"epsilonEqualsDistance",
"(",
"Point2D",
"<",
"?",
",",
"?",
">",
"p1",
",",
"Point2D",
"<",
"?",
",",
"?",
">",
"p2",
")",
"{",
"final",
"double",
"distance",
"=",
"p1",
".",
"getDistance",
"(",
"p2",
")",
";",
"return",
"distance",
">=",
"-",
"distancePrecision",
"&&",
"distance",
"<=",
"distancePrecision",
";",
"}"
] |
Replies if the specified points are approximatively equal.
This function uses the distance precision.
@param p1 the first point.
@param p2 the second point.
@return <code>true</code> if both points are equal, otherwise <code>false</code>
|
[
"Replies",
"if",
"the",
"specified",
"points",
"are",
"approximatively",
"equal",
".",
"This",
"function",
"uses",
"the",
"distance",
"precision",
"."
] |
train
|
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java#L121-L125
|
structurizr/java
|
structurizr-core/src/com/structurizr/model/Container.java
|
Container.addComponent
|
public Component addComponent(String name, String description) {
"""
Adds a component to this container.
@param name the name of the component
@param description a description of the component
@return the resulting Component instance
@throws IllegalArgumentException if the component name is null or empty, or a component with the same name already exists
"""
return this.addComponent(name, description, null);
}
|
java
|
public Component addComponent(String name, String description) {
return this.addComponent(name, description, null);
}
|
[
"public",
"Component",
"addComponent",
"(",
"String",
"name",
",",
"String",
"description",
")",
"{",
"return",
"this",
".",
"addComponent",
"(",
"name",
",",
"description",
",",
"null",
")",
";",
"}"
] |
Adds a component to this container.
@param name the name of the component
@param description a description of the component
@return the resulting Component instance
@throws IllegalArgumentException if the component name is null or empty, or a component with the same name already exists
|
[
"Adds",
"a",
"component",
"to",
"this",
"container",
"."
] |
train
|
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/Container.java#L72-L74
|
chanjarster/weixin-java-tools
|
weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java
|
WxCryptUtil.createSign
|
public static String createSign(Map<String, String> packageParams, String signKey) {
"""
微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3)
@param packageParams 原始参数
@param signKey 加密Key(即 商户Key)
@param charset 编码
@return 签名字符串
"""
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.putAll(packageParams);
List<String> keys = new ArrayList<String>(packageParams.keySet());
Collections.sort(keys);
StringBuffer toSign = new StringBuffer();
for (String key : keys) {
String value = packageParams.get(key);
if (null != value && !"".equals(value) && !"sign".equals(key)
&& !"key".equals(key)) {
toSign.append(key + "=" + value + "&");
}
}
toSign.append("key=" + signKey);
String sign = DigestUtils.md5Hex(toSign.toString())
.toUpperCase();
return sign;
}
|
java
|
public static String createSign(Map<String, String> packageParams, String signKey) {
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.putAll(packageParams);
List<String> keys = new ArrayList<String>(packageParams.keySet());
Collections.sort(keys);
StringBuffer toSign = new StringBuffer();
for (String key : keys) {
String value = packageParams.get(key);
if (null != value && !"".equals(value) && !"sign".equals(key)
&& !"key".equals(key)) {
toSign.append(key + "=" + value + "&");
}
}
toSign.append("key=" + signKey);
String sign = DigestUtils.md5Hex(toSign.toString())
.toUpperCase();
return sign;
}
|
[
"public",
"static",
"String",
"createSign",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"packageParams",
",",
"String",
"signKey",
")",
"{",
"SortedMap",
"<",
"String",
",",
"String",
">",
"sortedMap",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"sortedMap",
".",
"putAll",
"(",
"packageParams",
")",
";",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"packageParams",
".",
"keySet",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"keys",
")",
";",
"StringBuffer",
"toSign",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"keys",
")",
"{",
"String",
"value",
"=",
"packageParams",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"null",
"!=",
"value",
"&&",
"!",
"\"\"",
".",
"equals",
"(",
"value",
")",
"&&",
"!",
"\"sign\"",
".",
"equals",
"(",
"key",
")",
"&&",
"!",
"\"key\"",
".",
"equals",
"(",
"key",
")",
")",
"{",
"toSign",
".",
"append",
"(",
"key",
"+",
"\"=\"",
"+",
"value",
"+",
"\"&\"",
")",
";",
"}",
"}",
"toSign",
".",
"append",
"(",
"\"key=\"",
"+",
"signKey",
")",
";",
"String",
"sign",
"=",
"DigestUtils",
".",
"md5Hex",
"(",
"toSign",
".",
"toString",
"(",
")",
")",
".",
"toUpperCase",
"(",
")",
";",
"return",
"sign",
";",
"}"
] |
微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3)
@param packageParams 原始参数
@param signKey 加密Key(即 商户Key)
@param charset 编码
@return 签名字符串
|
[
"微信公众号支付签名算法",
"(",
"详见",
":",
"http",
":",
"//",
"pay",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki",
"/",
"doc",
"/",
"api",
"/",
"index",
".",
"php?chapter",
"=",
"4_3",
")"
] |
train
|
https://github.com/chanjarster/weixin-java-tools/blob/2a0b1c30c0f60c2de466cb8933c945bc0d391edf/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java#L234-L254
|
asterisk-java/asterisk-java
|
src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java
|
AsteriskChannelImpl.extensionVisited
|
void extensionVisited(Date date, Extension extension) {
"""
Adds a visted dialplan entry to the history.
@param date the date the extension has been visited.
@param extension the visted dialplan entry to add.
"""
final Extension oldCurrentExtension = getCurrentExtension();
final ExtensionHistoryEntry historyEntry;
historyEntry = new ExtensionHistoryEntry(date, extension);
synchronized (extensionHistory)
{
extensionHistory.add(historyEntry);
}
firePropertyChange(PROPERTY_CURRENT_EXTENSION, oldCurrentExtension, extension);
}
|
java
|
void extensionVisited(Date date, Extension extension)
{
final Extension oldCurrentExtension = getCurrentExtension();
final ExtensionHistoryEntry historyEntry;
historyEntry = new ExtensionHistoryEntry(date, extension);
synchronized (extensionHistory)
{
extensionHistory.add(historyEntry);
}
firePropertyChange(PROPERTY_CURRENT_EXTENSION, oldCurrentExtension, extension);
}
|
[
"void",
"extensionVisited",
"(",
"Date",
"date",
",",
"Extension",
"extension",
")",
"{",
"final",
"Extension",
"oldCurrentExtension",
"=",
"getCurrentExtension",
"(",
")",
";",
"final",
"ExtensionHistoryEntry",
"historyEntry",
";",
"historyEntry",
"=",
"new",
"ExtensionHistoryEntry",
"(",
"date",
",",
"extension",
")",
";",
"synchronized",
"(",
"extensionHistory",
")",
"{",
"extensionHistory",
".",
"add",
"(",
"historyEntry",
")",
";",
"}",
"firePropertyChange",
"(",
"PROPERTY_CURRENT_EXTENSION",
",",
"oldCurrentExtension",
",",
"extension",
")",
";",
"}"
] |
Adds a visted dialplan entry to the history.
@param date the date the extension has been visited.
@param extension the visted dialplan entry to add.
|
[
"Adds",
"a",
"visted",
"dialplan",
"entry",
"to",
"the",
"history",
"."
] |
train
|
https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L399-L412
|
fcrepo4/fcrepo4
|
fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java
|
ContentExposingResource.getBinaryContent
|
private Response getBinaryContent(final String rangeValue, final FedoraResource resource)
throws IOException {
"""
Get the binary content of a datastream
@param rangeValue the range value
@param resource the fedora resource
@return Binary blob
@throws IOException if io exception occurred
"""
final FedoraBinary binary = (FedoraBinary)resource;
final CacheControl cc = new CacheControl();
cc.setMaxAge(0);
cc.setMustRevalidate(true);
final Response.ResponseBuilder builder;
if (rangeValue != null && rangeValue.startsWith("bytes")) {
final Range range = Range.convert(rangeValue);
final long contentSize = binary.getContentSize();
final String endAsString;
if (range.end() == -1) {
endAsString = Long.toString(contentSize - 1);
} else {
endAsString = Long.toString(range.end());
}
final String contentRangeValue =
String.format("bytes %s-%s/%s", range.start(),
endAsString, contentSize);
if (range.end() > contentSize ||
(range.end() == -1 && range.start() > contentSize)) {
builder = status(REQUESTED_RANGE_NOT_SATISFIABLE)
.header("Content-Range", contentRangeValue);
} else {
@SuppressWarnings("resource")
final RangeRequestInputStream rangeInputStream =
new RangeRequestInputStream(binary.getContent(), range.start(), range.size());
builder = status(PARTIAL_CONTENT).entity(rangeInputStream)
.header("Content-Range", contentRangeValue)
.header(CONTENT_LENGTH, range.size());
}
} else {
@SuppressWarnings("resource")
final InputStream content = binary.getContent();
builder = ok(content);
}
// we set the content-type explicitly to avoid content-negotiation from getting in the way
// getBinaryResourceMediaType will try to use the mime type on the resource, falling back on
// 'application/octet-stream' if the mime type is syntactically invalid
return builder.type(getBinaryResourceMediaType(resource).toString())
.cacheControl(cc)
.build();
}
|
java
|
private Response getBinaryContent(final String rangeValue, final FedoraResource resource)
throws IOException {
final FedoraBinary binary = (FedoraBinary)resource;
final CacheControl cc = new CacheControl();
cc.setMaxAge(0);
cc.setMustRevalidate(true);
final Response.ResponseBuilder builder;
if (rangeValue != null && rangeValue.startsWith("bytes")) {
final Range range = Range.convert(rangeValue);
final long contentSize = binary.getContentSize();
final String endAsString;
if (range.end() == -1) {
endAsString = Long.toString(contentSize - 1);
} else {
endAsString = Long.toString(range.end());
}
final String contentRangeValue =
String.format("bytes %s-%s/%s", range.start(),
endAsString, contentSize);
if (range.end() > contentSize ||
(range.end() == -1 && range.start() > contentSize)) {
builder = status(REQUESTED_RANGE_NOT_SATISFIABLE)
.header("Content-Range", contentRangeValue);
} else {
@SuppressWarnings("resource")
final RangeRequestInputStream rangeInputStream =
new RangeRequestInputStream(binary.getContent(), range.start(), range.size());
builder = status(PARTIAL_CONTENT).entity(rangeInputStream)
.header("Content-Range", contentRangeValue)
.header(CONTENT_LENGTH, range.size());
}
} else {
@SuppressWarnings("resource")
final InputStream content = binary.getContent();
builder = ok(content);
}
// we set the content-type explicitly to avoid content-negotiation from getting in the way
// getBinaryResourceMediaType will try to use the mime type on the resource, falling back on
// 'application/octet-stream' if the mime type is syntactically invalid
return builder.type(getBinaryResourceMediaType(resource).toString())
.cacheControl(cc)
.build();
}
|
[
"private",
"Response",
"getBinaryContent",
"(",
"final",
"String",
"rangeValue",
",",
"final",
"FedoraResource",
"resource",
")",
"throws",
"IOException",
"{",
"final",
"FedoraBinary",
"binary",
"=",
"(",
"FedoraBinary",
")",
"resource",
";",
"final",
"CacheControl",
"cc",
"=",
"new",
"CacheControl",
"(",
")",
";",
"cc",
".",
"setMaxAge",
"(",
"0",
")",
";",
"cc",
".",
"setMustRevalidate",
"(",
"true",
")",
";",
"final",
"Response",
".",
"ResponseBuilder",
"builder",
";",
"if",
"(",
"rangeValue",
"!=",
"null",
"&&",
"rangeValue",
".",
"startsWith",
"(",
"\"bytes\"",
")",
")",
"{",
"final",
"Range",
"range",
"=",
"Range",
".",
"convert",
"(",
"rangeValue",
")",
";",
"final",
"long",
"contentSize",
"=",
"binary",
".",
"getContentSize",
"(",
")",
";",
"final",
"String",
"endAsString",
";",
"if",
"(",
"range",
".",
"end",
"(",
")",
"==",
"-",
"1",
")",
"{",
"endAsString",
"=",
"Long",
".",
"toString",
"(",
"contentSize",
"-",
"1",
")",
";",
"}",
"else",
"{",
"endAsString",
"=",
"Long",
".",
"toString",
"(",
"range",
".",
"end",
"(",
")",
")",
";",
"}",
"final",
"String",
"contentRangeValue",
"=",
"String",
".",
"format",
"(",
"\"bytes %s-%s/%s\"",
",",
"range",
".",
"start",
"(",
")",
",",
"endAsString",
",",
"contentSize",
")",
";",
"if",
"(",
"range",
".",
"end",
"(",
")",
">",
"contentSize",
"||",
"(",
"range",
".",
"end",
"(",
")",
"==",
"-",
"1",
"&&",
"range",
".",
"start",
"(",
")",
">",
"contentSize",
")",
")",
"{",
"builder",
"=",
"status",
"(",
"REQUESTED_RANGE_NOT_SATISFIABLE",
")",
".",
"header",
"(",
"\"Content-Range\"",
",",
"contentRangeValue",
")",
";",
"}",
"else",
"{",
"@",
"SuppressWarnings",
"(",
"\"resource\"",
")",
"final",
"RangeRequestInputStream",
"rangeInputStream",
"=",
"new",
"RangeRequestInputStream",
"(",
"binary",
".",
"getContent",
"(",
")",
",",
"range",
".",
"start",
"(",
")",
",",
"range",
".",
"size",
"(",
")",
")",
";",
"builder",
"=",
"status",
"(",
"PARTIAL_CONTENT",
")",
".",
"entity",
"(",
"rangeInputStream",
")",
".",
"header",
"(",
"\"Content-Range\"",
",",
"contentRangeValue",
")",
".",
"header",
"(",
"CONTENT_LENGTH",
",",
"range",
".",
"size",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"@",
"SuppressWarnings",
"(",
"\"resource\"",
")",
"final",
"InputStream",
"content",
"=",
"binary",
".",
"getContent",
"(",
")",
";",
"builder",
"=",
"ok",
"(",
"content",
")",
";",
"}",
"// we set the content-type explicitly to avoid content-negotiation from getting in the way",
"// getBinaryResourceMediaType will try to use the mime type on the resource, falling back on",
"// 'application/octet-stream' if the mime type is syntactically invalid",
"return",
"builder",
".",
"type",
"(",
"getBinaryResourceMediaType",
"(",
"resource",
")",
".",
"toString",
"(",
")",
")",
".",
"cacheControl",
"(",
"cc",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Get the binary content of a datastream
@param rangeValue the range value
@param resource the fedora resource
@return Binary blob
@throws IOException if io exception occurred
|
[
"Get",
"the",
"binary",
"content",
"of",
"a",
"datastream"
] |
train
|
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java#L395-L450
|
Stratio/bdt
|
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
|
DatabaseSpec.createBasicMapping
|
@Given("^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$")
public void createBasicMapping(String index_name, String table, String column, String keyspace) throws Exception {
"""
Create a basic Index.
@param index_name index name
@param table the table where index will be created.
@param column the column where index will be saved
@param keyspace keyspace used
@throws Exception exception
"""
String query = "CREATE INDEX " + index_name + " ON " + table + " (" + column + ");";
commonspec.getCassandraClient().executeQuery(query);
}
|
java
|
@Given("^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$")
public void createBasicMapping(String index_name, String table, String column, String keyspace) throws Exception {
String query = "CREATE INDEX " + index_name + " ON " + table + " (" + column + ");";
commonspec.getCassandraClient().executeQuery(query);
}
|
[
"@",
"Given",
"(",
"\"^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$\"",
")",
"public",
"void",
"createBasicMapping",
"(",
"String",
"index_name",
",",
"String",
"table",
",",
"String",
"column",
",",
"String",
"keyspace",
")",
"throws",
"Exception",
"{",
"String",
"query",
"=",
"\"CREATE INDEX \"",
"+",
"index_name",
"+",
"\" ON \"",
"+",
"table",
"+",
"\" (\"",
"+",
"column",
"+",
"\");\"",
";",
"commonspec",
".",
"getCassandraClient",
"(",
")",
".",
"executeQuery",
"(",
"query",
")",
";",
"}"
] |
Create a basic Index.
@param index_name index name
@param table the table where index will be created.
@param column the column where index will be saved
@param keyspace keyspace used
@throws Exception exception
|
[
"Create",
"a",
"basic",
"Index",
"."
] |
train
|
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L80-L84
|
yanzhenjie/AndServer
|
api/src/main/java/com/yanzhenjie/andserver/ComponentRegister.java
|
ComponentRegister.getDexFilePaths
|
public static List<String> getDexFilePaths(Context context) {
"""
Obtain all the dex path.
@see com.android.support.MultiDex#loadExistingExtractions(Context, String)
@see com.android.support.MultiDex#clearOldDexDir(Context)
"""
ApplicationInfo appInfo = context.getApplicationInfo();
File sourceApk = new File(appInfo.sourceDir);
List<String> sourcePaths = new ArrayList<>();
sourcePaths.add(appInfo.sourceDir);
if (!isVMMultidexCapable()) {
String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
File dexDir = new File(appInfo.dataDir, CODE_CACHE_SECONDARY_DIRECTORY);
for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
File extractedFile = new File(dexDir, fileName);
if (extractedFile.isFile()) {
sourcePaths.add(extractedFile.getAbsolutePath());
}
}
}
if (AndServer.isDebug()) {
sourcePaths.addAll(loadInstantRunDexFile(appInfo));
}
return sourcePaths;
}
|
java
|
public static List<String> getDexFilePaths(Context context) {
ApplicationInfo appInfo = context.getApplicationInfo();
File sourceApk = new File(appInfo.sourceDir);
List<String> sourcePaths = new ArrayList<>();
sourcePaths.add(appInfo.sourceDir);
if (!isVMMultidexCapable()) {
String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
File dexDir = new File(appInfo.dataDir, CODE_CACHE_SECONDARY_DIRECTORY);
for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
File extractedFile = new File(dexDir, fileName);
if (extractedFile.isFile()) {
sourcePaths.add(extractedFile.getAbsolutePath());
}
}
}
if (AndServer.isDebug()) {
sourcePaths.addAll(loadInstantRunDexFile(appInfo));
}
return sourcePaths;
}
|
[
"public",
"static",
"List",
"<",
"String",
">",
"getDexFilePaths",
"(",
"Context",
"context",
")",
"{",
"ApplicationInfo",
"appInfo",
"=",
"context",
".",
"getApplicationInfo",
"(",
")",
";",
"File",
"sourceApk",
"=",
"new",
"File",
"(",
"appInfo",
".",
"sourceDir",
")",
";",
"List",
"<",
"String",
">",
"sourcePaths",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"sourcePaths",
".",
"add",
"(",
"appInfo",
".",
"sourceDir",
")",
";",
"if",
"(",
"!",
"isVMMultidexCapable",
"(",
")",
")",
"{",
"String",
"extractedFilePrefix",
"=",
"sourceApk",
".",
"getName",
"(",
")",
"+",
"EXTRACTED_NAME_EXT",
";",
"int",
"totalDexNumber",
"=",
"getMultiDexPreferences",
"(",
"context",
")",
".",
"getInt",
"(",
"KEY_DEX_NUMBER",
",",
"1",
")",
";",
"File",
"dexDir",
"=",
"new",
"File",
"(",
"appInfo",
".",
"dataDir",
",",
"CODE_CACHE_SECONDARY_DIRECTORY",
")",
";",
"for",
"(",
"int",
"secondaryNumber",
"=",
"2",
";",
"secondaryNumber",
"<=",
"totalDexNumber",
";",
"secondaryNumber",
"++",
")",
"{",
"String",
"fileName",
"=",
"extractedFilePrefix",
"+",
"secondaryNumber",
"+",
"EXTRACTED_SUFFIX",
";",
"File",
"extractedFile",
"=",
"new",
"File",
"(",
"dexDir",
",",
"fileName",
")",
";",
"if",
"(",
"extractedFile",
".",
"isFile",
"(",
")",
")",
"{",
"sourcePaths",
".",
"add",
"(",
"extractedFile",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"}",
"if",
"(",
"AndServer",
".",
"isDebug",
"(",
")",
")",
"{",
"sourcePaths",
".",
"addAll",
"(",
"loadInstantRunDexFile",
"(",
"appInfo",
")",
")",
";",
"}",
"return",
"sourcePaths",
";",
"}"
] |
Obtain all the dex path.
@see com.android.support.MultiDex#loadExistingExtractions(Context, String)
@see com.android.support.MultiDex#clearOldDexDir(Context)
|
[
"Obtain",
"all",
"the",
"dex",
"path",
"."
] |
train
|
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/ComponentRegister.java#L123-L148
|
googleapis/google-api-java-client
|
google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/DefaultCredentialProvider.java
|
DefaultCredentialProvider.getDefaultCredential
|
final GoogleCredential getDefaultCredential(HttpTransport transport, JsonFactory jsonFactory)
throws IOException {
"""
{@link Beta} <br/>
Returns the Application Default Credentials.
<p>Returns the Application Default Credentials which are credentials that identify and
authorize the whole application. This is the built-in service account if running on Google
Compute Engine or the credentials file from the path in the environment variable
GOOGLE_APPLICATION_CREDENTIALS.</p>
@param transport the transport for Http calls.
@param jsonFactory the factory for Json parsing and formatting.
@return the credential instance.
@throws IOException if the credential cannot be created in the current environment.
"""
synchronized (this) {
if (cachedCredential == null) {
cachedCredential = getDefaultCredentialUnsynchronized(transport, jsonFactory);
}
if (cachedCredential != null) {
return cachedCredential;
}
}
throw new IOException(String.format(
"The Application Default Credentials are not available. They are available if running "
+ "on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, "
+ "the environment variable %s must be defined pointing to a file defining "
+ "the credentials. See %s for more information.",
CREDENTIAL_ENV_VAR,
HELP_PERMALINK));
}
|
java
|
final GoogleCredential getDefaultCredential(HttpTransport transport, JsonFactory jsonFactory)
throws IOException {
synchronized (this) {
if (cachedCredential == null) {
cachedCredential = getDefaultCredentialUnsynchronized(transport, jsonFactory);
}
if (cachedCredential != null) {
return cachedCredential;
}
}
throw new IOException(String.format(
"The Application Default Credentials are not available. They are available if running "
+ "on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, "
+ "the environment variable %s must be defined pointing to a file defining "
+ "the credentials. See %s for more information.",
CREDENTIAL_ENV_VAR,
HELP_PERMALINK));
}
|
[
"final",
"GoogleCredential",
"getDefaultCredential",
"(",
"HttpTransport",
"transport",
",",
"JsonFactory",
"jsonFactory",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"cachedCredential",
"==",
"null",
")",
"{",
"cachedCredential",
"=",
"getDefaultCredentialUnsynchronized",
"(",
"transport",
",",
"jsonFactory",
")",
";",
"}",
"if",
"(",
"cachedCredential",
"!=",
"null",
")",
"{",
"return",
"cachedCredential",
";",
"}",
"}",
"throw",
"new",
"IOException",
"(",
"String",
".",
"format",
"(",
"\"The Application Default Credentials are not available. They are available if running \"",
"+",
"\"on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, \"",
"+",
"\"the environment variable %s must be defined pointing to a file defining \"",
"+",
"\"the credentials. See %s for more information.\"",
",",
"CREDENTIAL_ENV_VAR",
",",
"HELP_PERMALINK",
")",
")",
";",
"}"
] |
{@link Beta} <br/>
Returns the Application Default Credentials.
<p>Returns the Application Default Credentials which are credentials that identify and
authorize the whole application. This is the built-in service account if running on Google
Compute Engine or the credentials file from the path in the environment variable
GOOGLE_APPLICATION_CREDENTIALS.</p>
@param transport the transport for Http calls.
@param jsonFactory the factory for Json parsing and formatting.
@return the credential instance.
@throws IOException if the credential cannot be created in the current environment.
|
[
"{",
"@link",
"Beta",
"}",
"<br",
"/",
">",
"Returns",
"the",
"Application",
"Default",
"Credentials",
"."
] |
train
|
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client/src/main/java/com/google/api/client/googleapis/auth/oauth2/DefaultCredentialProvider.java#L87-L105
|
google/error-prone-javac
|
src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java
|
JShellTool.startmsg
|
void startmsg(String key, Object... args) {
"""
Print command-line error using resource bundle look-up, MessageFormat
@param key the resource key
@param args
"""
cmderr.println(messageFormat(key, args));
}
|
java
|
void startmsg(String key, Object... args) {
cmderr.println(messageFormat(key, args));
}
|
[
"void",
"startmsg",
"(",
"String",
"key",
",",
"Object",
"...",
"args",
")",
"{",
"cmderr",
".",
"println",
"(",
"messageFormat",
"(",
"key",
",",
"args",
")",
")",
";",
"}"
] |
Print command-line error using resource bundle look-up, MessageFormat
@param key the resource key
@param args
|
[
"Print",
"command",
"-",
"line",
"error",
"using",
"resource",
"bundle",
"look",
"-",
"up",
"MessageFormat"
] |
train
|
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java#L826-L828
|
googleads/googleads-java-lib
|
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/batchjob/BatchJobHelperImpl.java
|
BatchJobHelperImpl.getServiceTypeMappings
|
static List<TypeMapping> getServiceTypeMappings() {
"""
Returns all of the service type mappings required to serialize/deserialize Axis objects.
"""
// Build the list of type mappings based on BatchJobOpsService for this version of the API.
ImmutableList.Builder<TypeMapping> mappings = ImmutableList.builder();
try {
mappings.add(
new BatchJobOpsServiceSoapBindingStub() {
@Override
public Call _createCall() throws ServiceException {
try {
return super.createCall();
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
}._createCall().getTypeMapping());
} catch (Exception e) {
throw new RuntimeException("Failed to initialize service type mappings", e);
}
return mappings.build();
}
|
java
|
static List<TypeMapping> getServiceTypeMappings() {
// Build the list of type mappings based on BatchJobOpsService for this version of the API.
ImmutableList.Builder<TypeMapping> mappings = ImmutableList.builder();
try {
mappings.add(
new BatchJobOpsServiceSoapBindingStub() {
@Override
public Call _createCall() throws ServiceException {
try {
return super.createCall();
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
}._createCall().getTypeMapping());
} catch (Exception e) {
throw new RuntimeException("Failed to initialize service type mappings", e);
}
return mappings.build();
}
|
[
"static",
"List",
"<",
"TypeMapping",
">",
"getServiceTypeMappings",
"(",
")",
"{",
"// Build the list of type mappings based on BatchJobOpsService for this version of the API.",
"ImmutableList",
".",
"Builder",
"<",
"TypeMapping",
">",
"mappings",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"try",
"{",
"mappings",
".",
"add",
"(",
"new",
"BatchJobOpsServiceSoapBindingStub",
"(",
")",
"{",
"@",
"Override",
"public",
"Call",
"_createCall",
"(",
")",
"throws",
"ServiceException",
"{",
"try",
"{",
"return",
"super",
".",
"createCall",
"(",
")",
";",
"}",
"catch",
"(",
"RemoteException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}",
".",
"_createCall",
"(",
")",
".",
"getTypeMapping",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to initialize service type mappings\"",
",",
"e",
")",
";",
"}",
"return",
"mappings",
".",
"build",
"(",
")",
";",
"}"
] |
Returns all of the service type mappings required to serialize/deserialize Axis objects.
|
[
"Returns",
"all",
"of",
"the",
"service",
"type",
"mappings",
"required",
"to",
"serialize",
"/",
"deserialize",
"Axis",
"objects",
"."
] |
train
|
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/batchjob/BatchJobHelperImpl.java#L137-L158
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/ConsoleLogHandler.java
|
ConsoleLogHandler.setWriter
|
public void setWriter(Object sysLogHolder, Object sysErrHolder) {
"""
Set the writers for SystemOut and SystemErr respectfully
@param sysLogHolder SystemLogHolder object for SystemOut
@param sysErrHolder SystemLogHolder object for SystemErr
"""
this.sysOutHolder = (SystemLogHolder) sysLogHolder;
this.sysErrHolder = (SystemLogHolder) sysErrHolder;
}
|
java
|
public void setWriter(Object sysLogHolder, Object sysErrHolder) {
this.sysOutHolder = (SystemLogHolder) sysLogHolder;
this.sysErrHolder = (SystemLogHolder) sysErrHolder;
}
|
[
"public",
"void",
"setWriter",
"(",
"Object",
"sysLogHolder",
",",
"Object",
"sysErrHolder",
")",
"{",
"this",
".",
"sysOutHolder",
"=",
"(",
"SystemLogHolder",
")",
"sysLogHolder",
";",
"this",
".",
"sysErrHolder",
"=",
"(",
"SystemLogHolder",
")",
"sysErrHolder",
";",
"}"
] |
Set the writers for SystemOut and SystemErr respectfully
@param sysLogHolder SystemLogHolder object for SystemOut
@param sysErrHolder SystemLogHolder object for SystemErr
|
[
"Set",
"the",
"writers",
"for",
"SystemOut",
"and",
"SystemErr",
"respectfully"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/ConsoleLogHandler.java#L189-L192
|
xmlunit/xmlunit
|
xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java
|
DefaultComparisonFormatter.getFormattedNodeXml
|
protected String getFormattedNodeXml(final Node nodeToConvert, boolean formatXml) {
"""
Formats a node with the help of an identity XML transformation.
@param nodeToConvert the node to format
@param formatXml true if the Comparison was generated with {@link
org.xmlunit.builder.DiffBuilder#ignoreWhitespace()} - this affects the indentation of the generated output
@return the fomatted XML
@since XMLUnit 2.4.0
"""
String formattedNodeXml;
try {
final int numberOfBlanksToIndent = formatXml ? 2 : -1;
final Transformer transformer = createXmlTransformer(numberOfBlanksToIndent);
final StringWriter buffer = new StringWriter();
transformer.transform(new DOMSource(nodeToConvert), new StreamResult(buffer));
formattedNodeXml = buffer.toString();
} catch (final Exception e) {
formattedNodeXml = "ERROR " + e.getMessage();
}
return formattedNodeXml;
}
|
java
|
protected String getFormattedNodeXml(final Node nodeToConvert, boolean formatXml) {
String formattedNodeXml;
try {
final int numberOfBlanksToIndent = formatXml ? 2 : -1;
final Transformer transformer = createXmlTransformer(numberOfBlanksToIndent);
final StringWriter buffer = new StringWriter();
transformer.transform(new DOMSource(nodeToConvert), new StreamResult(buffer));
formattedNodeXml = buffer.toString();
} catch (final Exception e) {
formattedNodeXml = "ERROR " + e.getMessage();
}
return formattedNodeXml;
}
|
[
"protected",
"String",
"getFormattedNodeXml",
"(",
"final",
"Node",
"nodeToConvert",
",",
"boolean",
"formatXml",
")",
"{",
"String",
"formattedNodeXml",
";",
"try",
"{",
"final",
"int",
"numberOfBlanksToIndent",
"=",
"formatXml",
"?",
"2",
":",
"-",
"1",
";",
"final",
"Transformer",
"transformer",
"=",
"createXmlTransformer",
"(",
"numberOfBlanksToIndent",
")",
";",
"final",
"StringWriter",
"buffer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"transformer",
".",
"transform",
"(",
"new",
"DOMSource",
"(",
"nodeToConvert",
")",
",",
"new",
"StreamResult",
"(",
"buffer",
")",
")",
";",
"formattedNodeXml",
"=",
"buffer",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"formattedNodeXml",
"=",
"\"ERROR \"",
"+",
"e",
".",
"getMessage",
"(",
")",
";",
"}",
"return",
"formattedNodeXml",
";",
"}"
] |
Formats a node with the help of an identity XML transformation.
@param nodeToConvert the node to format
@param formatXml true if the Comparison was generated with {@link
org.xmlunit.builder.DiffBuilder#ignoreWhitespace()} - this affects the indentation of the generated output
@return the fomatted XML
@since XMLUnit 2.4.0
|
[
"Formats",
"a",
"node",
"with",
"the",
"help",
"of",
"an",
"identity",
"XML",
"transformation",
"."
] |
train
|
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-core/src/main/java/org/xmlunit/diff/DefaultComparisonFormatter.java#L433-L445
|
alkacon/opencms-core
|
src/org/opencms/jsp/CmsJspTagLabel.java
|
CmsJspTagLabel.wpLabelTagAction
|
public static String wpLabelTagAction(String label, ServletRequest req) {
"""
Internal action method.<p>
@param label the label to look up
@param req the current request
@return String the value of the selected label
"""
CmsObject cms = CmsFlexController.getCmsObject(req);
CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(cms.getRequestContext().getLocale());
return messages.key(label);
}
|
java
|
public static String wpLabelTagAction(String label, ServletRequest req) {
CmsObject cms = CmsFlexController.getCmsObject(req);
CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(cms.getRequestContext().getLocale());
return messages.key(label);
}
|
[
"public",
"static",
"String",
"wpLabelTagAction",
"(",
"String",
"label",
",",
"ServletRequest",
"req",
")",
"{",
"CmsObject",
"cms",
"=",
"CmsFlexController",
".",
"getCmsObject",
"(",
"req",
")",
";",
"CmsMessages",
"messages",
"=",
"OpenCms",
".",
"getWorkplaceManager",
"(",
")",
".",
"getMessages",
"(",
"cms",
".",
"getRequestContext",
"(",
")",
".",
"getLocale",
"(",
")",
")",
";",
"return",
"messages",
".",
"key",
"(",
"label",
")",
";",
"}"
] |
Internal action method.<p>
@param label the label to look up
@param req the current request
@return String the value of the selected label
|
[
"Internal",
"action",
"method",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagLabel.java#L68-L73
|
kaazing/gateway
|
service/http.directory/src/main/java/org/kaazing/gateway/service/http/directory/HttpDirectoryService.java
|
HttpDirectoryService.resolvePatternSpecificity
|
private void resolvePatternSpecificity(Map<String, PatternCacheControl> patterns) {
"""
Matches the patterns from the map and determines each pattern's specificity
@param patterns - the map with the patterns to be matched
"""
List<String> patternList = new ArrayList<>();
patternList.addAll(patterns.keySet());
int patternCount = patternList.size();
for (int i = 0; i < patternCount - 1; i++) {
String specificPattern = patternList.get(i);
for (int j = i + 1; j < patternCount; j++) {
String generalPattern = patternList.get(j);
checkPatternMatching(patterns, specificPattern, generalPattern);
checkPatternMatching(patterns, generalPattern, specificPattern);
}
}
}
|
java
|
private void resolvePatternSpecificity(Map<String, PatternCacheControl> patterns) {
List<String> patternList = new ArrayList<>();
patternList.addAll(patterns.keySet());
int patternCount = patternList.size();
for (int i = 0; i < patternCount - 1; i++) {
String specificPattern = patternList.get(i);
for (int j = i + 1; j < patternCount; j++) {
String generalPattern = patternList.get(j);
checkPatternMatching(patterns, specificPattern, generalPattern);
checkPatternMatching(patterns, generalPattern, specificPattern);
}
}
}
|
[
"private",
"void",
"resolvePatternSpecificity",
"(",
"Map",
"<",
"String",
",",
"PatternCacheControl",
">",
"patterns",
")",
"{",
"List",
"<",
"String",
">",
"patternList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"patternList",
".",
"addAll",
"(",
"patterns",
".",
"keySet",
"(",
")",
")",
";",
"int",
"patternCount",
"=",
"patternList",
".",
"size",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"patternCount",
"-",
"1",
";",
"i",
"++",
")",
"{",
"String",
"specificPattern",
"=",
"patternList",
".",
"get",
"(",
"i",
")",
";",
"for",
"(",
"int",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
"patternCount",
";",
"j",
"++",
")",
"{",
"String",
"generalPattern",
"=",
"patternList",
".",
"get",
"(",
"j",
")",
";",
"checkPatternMatching",
"(",
"patterns",
",",
"specificPattern",
",",
"generalPattern",
")",
";",
"checkPatternMatching",
"(",
"patterns",
",",
"generalPattern",
",",
"specificPattern",
")",
";",
"}",
"}",
"}"
] |
Matches the patterns from the map and determines each pattern's specificity
@param patterns - the map with the patterns to be matched
|
[
"Matches",
"the",
"patterns",
"from",
"the",
"map",
"and",
"determines",
"each",
"pattern",
"s",
"specificity"
] |
train
|
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/service/http.directory/src/main/java/org/kaazing/gateway/service/http/directory/HttpDirectoryService.java#L155-L169
|
alkacon/opencms-core
|
src/org/opencms/jsp/CmsJspTagScaleImage.java
|
CmsJspTagScaleImage.imageTagAction
|
public static CmsJspImageBean imageTagAction(
CmsObject cms,
String imageUri,
CmsImageScaler targetScaler,
List<String> hiDpiVariantList)
throws CmsException {
"""
Internal action method to create the scaled image bean.<p>
@param cms the cms context
@param imageUri the image URI
@param targetScaler the target image scaler
@param hiDpiVariantList optional list of hi-DPI variant sizes to produce, e.g. 1.3x, 1.5x, 2x, 3x
@return the created ScaledImageBean bean
@throws CmsException in case something goes wrong
"""
CmsJspImageBean image = new CmsJspImageBean(cms, imageUri, targetScaler);
// now handle (preset) hi-DPI variants
if ((hiDpiVariantList != null) && (hiDpiVariantList.size() > 0)) {
for (String hiDpiVariant : hiDpiVariantList) {
CmsJspImageBean hiDpiVersion = image.createHiDpiVariation(hiDpiVariant);
if (hiDpiVersion != null) {
image.addHiDpiImage(hiDpiVariant, hiDpiVersion);
}
}
}
return image;
}
|
java
|
public static CmsJspImageBean imageTagAction(
CmsObject cms,
String imageUri,
CmsImageScaler targetScaler,
List<String> hiDpiVariantList)
throws CmsException {
CmsJspImageBean image = new CmsJspImageBean(cms, imageUri, targetScaler);
// now handle (preset) hi-DPI variants
if ((hiDpiVariantList != null) && (hiDpiVariantList.size() > 0)) {
for (String hiDpiVariant : hiDpiVariantList) {
CmsJspImageBean hiDpiVersion = image.createHiDpiVariation(hiDpiVariant);
if (hiDpiVersion != null) {
image.addHiDpiImage(hiDpiVariant, hiDpiVersion);
}
}
}
return image;
}
|
[
"public",
"static",
"CmsJspImageBean",
"imageTagAction",
"(",
"CmsObject",
"cms",
",",
"String",
"imageUri",
",",
"CmsImageScaler",
"targetScaler",
",",
"List",
"<",
"String",
">",
"hiDpiVariantList",
")",
"throws",
"CmsException",
"{",
"CmsJspImageBean",
"image",
"=",
"new",
"CmsJspImageBean",
"(",
"cms",
",",
"imageUri",
",",
"targetScaler",
")",
";",
"// now handle (preset) hi-DPI variants",
"if",
"(",
"(",
"hiDpiVariantList",
"!=",
"null",
")",
"&&",
"(",
"hiDpiVariantList",
".",
"size",
"(",
")",
">",
"0",
")",
")",
"{",
"for",
"(",
"String",
"hiDpiVariant",
":",
"hiDpiVariantList",
")",
"{",
"CmsJspImageBean",
"hiDpiVersion",
"=",
"image",
".",
"createHiDpiVariation",
"(",
"hiDpiVariant",
")",
";",
"if",
"(",
"hiDpiVersion",
"!=",
"null",
")",
"{",
"image",
".",
"addHiDpiImage",
"(",
"hiDpiVariant",
",",
"hiDpiVersion",
")",
";",
"}",
"}",
"}",
"return",
"image",
";",
"}"
] |
Internal action method to create the scaled image bean.<p>
@param cms the cms context
@param imageUri the image URI
@param targetScaler the target image scaler
@param hiDpiVariantList optional list of hi-DPI variant sizes to produce, e.g. 1.3x, 1.5x, 2x, 3x
@return the created ScaledImageBean bean
@throws CmsException in case something goes wrong
|
[
"Internal",
"action",
"method",
"to",
"create",
"the",
"scaled",
"image",
"bean",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagScaleImage.java#L101-L122
|
Nexmo/nexmo-java
|
src/main/java/com/nexmo/client/account/AccountClient.java
|
AccountClient.createSecret
|
public SecretResponse createSecret(String apiKey, String secret) throws IOException, NexmoClientException {
"""
Create a secret to be used with a specific API key.
@param apiKey The API key that the secret is to be used with.
@param secret The contents of the secret.
@return SecretResponse object which contains the created secret from the API.
@throws IOException if a network error occurred contacting the Nexmo Account API
@throws NexmoClientException if there was a problem wit hthe Nexmo request or response object indicating that the request was unsuccessful.
"""
return createSecret(new CreateSecretRequest(apiKey, secret));
}
|
java
|
public SecretResponse createSecret(String apiKey, String secret) throws IOException, NexmoClientException {
return createSecret(new CreateSecretRequest(apiKey, secret));
}
|
[
"public",
"SecretResponse",
"createSecret",
"(",
"String",
"apiKey",
",",
"String",
"secret",
")",
"throws",
"IOException",
",",
"NexmoClientException",
"{",
"return",
"createSecret",
"(",
"new",
"CreateSecretRequest",
"(",
"apiKey",
",",
"secret",
")",
")",
";",
"}"
] |
Create a secret to be used with a specific API key.
@param apiKey The API key that the secret is to be used with.
@param secret The contents of the secret.
@return SecretResponse object which contains the created secret from the API.
@throws IOException if a network error occurred contacting the Nexmo Account API
@throws NexmoClientException if there was a problem wit hthe Nexmo request or response object indicating that the request was unsuccessful.
|
[
"Create",
"a",
"secret",
"to",
"be",
"used",
"with",
"a",
"specific",
"API",
"key",
"."
] |
train
|
https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/account/AccountClient.java#L178-L180
|
salesforce/Argus
|
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/SuspensionRecord.java
|
SuspensionRecord.findByUserAndSubsystem
|
public static SuspensionRecord findByUserAndSubsystem(EntityManager em, PrincipalUser user, SubSystem subSystem) {
"""
Find the suspension record for a given user-subsystem combination.
@param em The EntityManager to use.
@param user The user for which to retrieve record.
@param subSystem THe subsystem for which to retrieve record.
@return The suspension record for the given user-subsystem combination. Null if no such record exists.
"""
TypedQuery<SuspensionRecord> query = em.createNamedQuery("SuspensionRecord.findByUserAndSubsystem", SuspensionRecord.class);
try {
query.setParameter("user", user);
query.setParameter("subSystem", subSystem);
query.setHint("javax.persistence.cache.storeMode", "REFRESH");
return query.getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
|
java
|
public static SuspensionRecord findByUserAndSubsystem(EntityManager em, PrincipalUser user, SubSystem subSystem) {
TypedQuery<SuspensionRecord> query = em.createNamedQuery("SuspensionRecord.findByUserAndSubsystem", SuspensionRecord.class);
try {
query.setParameter("user", user);
query.setParameter("subSystem", subSystem);
query.setHint("javax.persistence.cache.storeMode", "REFRESH");
return query.getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
|
[
"public",
"static",
"SuspensionRecord",
"findByUserAndSubsystem",
"(",
"EntityManager",
"em",
",",
"PrincipalUser",
"user",
",",
"SubSystem",
"subSystem",
")",
"{",
"TypedQuery",
"<",
"SuspensionRecord",
">",
"query",
"=",
"em",
".",
"createNamedQuery",
"(",
"\"SuspensionRecord.findByUserAndSubsystem\"",
",",
"SuspensionRecord",
".",
"class",
")",
";",
"try",
"{",
"query",
".",
"setParameter",
"(",
"\"user\"",
",",
"user",
")",
";",
"query",
".",
"setParameter",
"(",
"\"subSystem\"",
",",
"subSystem",
")",
";",
"query",
".",
"setHint",
"(",
"\"javax.persistence.cache.storeMode\"",
",",
"\"REFRESH\"",
")",
";",
"return",
"query",
".",
"getSingleResult",
"(",
")",
";",
"}",
"catch",
"(",
"NoResultException",
"ex",
")",
"{",
"return",
"null",
";",
"}",
"}"
] |
Find the suspension record for a given user-subsystem combination.
@param em The EntityManager to use.
@param user The user for which to retrieve record.
@param subSystem THe subsystem for which to retrieve record.
@return The suspension record for the given user-subsystem combination. Null if no such record exists.
|
[
"Find",
"the",
"suspension",
"record",
"for",
"a",
"given",
"user",
"-",
"subsystem",
"combination",
"."
] |
train
|
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/SuspensionRecord.java#L171-L182
|
landawn/AbacusUtil
|
src/com/landawn/abacus/util/N.java
|
N.deepEquals
|
public static boolean deepEquals(final Object a, final Object b) {
"""
compare {@code a} and {@code b} by
{@link Arrays#equals(Object[], Object[])} if both of them are array.
@param a
@param b
@return boolean
"""
if ((a == null) ? b == null : (b == null ? false : a.equals(b))) {
return true;
}
if ((a != null) && (b != null) && a.getClass().isArray() && a.getClass().equals(b.getClass())) {
return typeOf(a.getClass()).deepEquals(a, b);
}
return false;
}
|
java
|
public static boolean deepEquals(final Object a, final Object b) {
if ((a == null) ? b == null : (b == null ? false : a.equals(b))) {
return true;
}
if ((a != null) && (b != null) && a.getClass().isArray() && a.getClass().equals(b.getClass())) {
return typeOf(a.getClass()).deepEquals(a, b);
}
return false;
}
|
[
"public",
"static",
"boolean",
"deepEquals",
"(",
"final",
"Object",
"a",
",",
"final",
"Object",
"b",
")",
"{",
"if",
"(",
"(",
"a",
"==",
"null",
")",
"?",
"b",
"==",
"null",
":",
"(",
"b",
"==",
"null",
"?",
"false",
":",
"a",
".",
"equals",
"(",
"b",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"(",
"a",
"!=",
"null",
")",
"&&",
"(",
"b",
"!=",
"null",
")",
"&&",
"a",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
"&&",
"a",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"b",
".",
"getClass",
"(",
")",
")",
")",
"{",
"return",
"typeOf",
"(",
"a",
".",
"getClass",
"(",
")",
")",
".",
"deepEquals",
"(",
"a",
",",
"b",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
compare {@code a} and {@code b} by
{@link Arrays#equals(Object[], Object[])} if both of them are array.
@param a
@param b
@return boolean
|
[
"compare",
"{",
"@code",
"a",
"}",
"and",
"{",
"@code",
"b",
"}",
"by",
"{",
"@link",
"Arrays#equals",
"(",
"Object",
"[]",
"Object",
"[]",
")",
"}",
"if",
"both",
"of",
"them",
"are",
"array",
"."
] |
train
|
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L7070-L7080
|
moparisthebest/beehive
|
beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/ServletUtils.java
|
ServletUtils.dumpServletContext
|
public static void dumpServletContext( ServletContext context, PrintStream output ) {
"""
Print attributes in the given ServletContext.
@param context the current ServletContext.
@param output a PrintStream to which to output ServletContext attributes; if <code>null</null>,
<code>System.err</code> is used.
"""
if ( output == null )
{
output = System.err;
}
output.println( "*** ServletContext " + context );
for ( Enumeration e = context.getAttributeNames(); e.hasMoreElements(); )
{
String name = ( String ) e.nextElement();
output.println( " attribute " + name + " = " + context.getAttribute( name ) );
}
}
|
java
|
public static void dumpServletContext( ServletContext context, PrintStream output )
{
if ( output == null )
{
output = System.err;
}
output.println( "*** ServletContext " + context );
for ( Enumeration e = context.getAttributeNames(); e.hasMoreElements(); )
{
String name = ( String ) e.nextElement();
output.println( " attribute " + name + " = " + context.getAttribute( name ) );
}
}
|
[
"public",
"static",
"void",
"dumpServletContext",
"(",
"ServletContext",
"context",
",",
"PrintStream",
"output",
")",
"{",
"if",
"(",
"output",
"==",
"null",
")",
"{",
"output",
"=",
"System",
".",
"err",
";",
"}",
"output",
".",
"println",
"(",
"\"*** ServletContext \"",
"+",
"context",
")",
";",
"for",
"(",
"Enumeration",
"e",
"=",
"context",
".",
"getAttributeNames",
"(",
")",
";",
"e",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"String",
"name",
"=",
"(",
"String",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"output",
".",
"println",
"(",
"\" attribute \"",
"+",
"name",
"+",
"\" = \"",
"+",
"context",
".",
"getAttribute",
"(",
"name",
")",
")",
";",
"}",
"}"
] |
Print attributes in the given ServletContext.
@param context the current ServletContext.
@param output a PrintStream to which to output ServletContext attributes; if <code>null</null>,
<code>System.err</code> is used.
|
[
"Print",
"attributes",
"in",
"the",
"given",
"ServletContext",
"."
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/ServletUtils.java#L96-L110
|
Activiti/Activiti
|
activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java
|
VariableScopeImpl.setVariable
|
public void setVariable(String variableName, Object value, boolean fetchAllVariables) {
"""
The default {@link #setVariable(String, Object)} fetches all variables
(for historical and backwards compatible reasons) while setting the variables.
Setting the fetchAllVariables parameter to true is the default behaviour
(ie fetching all variables) Setting the fetchAllVariables parameter to false does not do that.
"""
setVariable(variableName, value, getSourceActivityExecution(), fetchAllVariables);
}
|
java
|
public void setVariable(String variableName, Object value, boolean fetchAllVariables) {
setVariable(variableName, value, getSourceActivityExecution(), fetchAllVariables);
}
|
[
"public",
"void",
"setVariable",
"(",
"String",
"variableName",
",",
"Object",
"value",
",",
"boolean",
"fetchAllVariables",
")",
"{",
"setVariable",
"(",
"variableName",
",",
"value",
",",
"getSourceActivityExecution",
"(",
")",
",",
"fetchAllVariables",
")",
";",
"}"
] |
The default {@link #setVariable(String, Object)} fetches all variables
(for historical and backwards compatible reasons) while setting the variables.
Setting the fetchAllVariables parameter to true is the default behaviour
(ie fetching all variables) Setting the fetchAllVariables parameter to false does not do that.
|
[
"The",
"default",
"{",
"@link",
"#setVariable",
"(",
"String",
"Object",
")",
"}",
"fetches",
"all",
"variables",
"(",
"for",
"historical",
"and",
"backwards",
"compatible",
"reasons",
")",
"while",
"setting",
"the",
"variables",
"."
] |
train
|
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java#L627-L629
|
mkotsur/restito
|
src/main/java/com/xebialabs/restito/semantics/Action.java
|
Action.resourceContent
|
public static Action resourceContent(final String resourcePath) {
"""
Writes content and content-type of resource file to response.
Tries to detect content type based on file extension. If can not detect - content-type is not set.
For now there are following bindings:
<ul>
<li>.xml - `application/xml`</li>
<li>.json - `application/xml`</li>
</ul>
"""
return new Action(input -> {
final HttpResponsePacket responsePacket = input.getResponse();
String encoding = responsePacket == null ? input.getCharacterEncoding() : responsePacket.getCharacterEncoding();
return resourceContent(resourcePath, encoding).apply(input);
});
}
|
java
|
public static Action resourceContent(final String resourcePath) {
return new Action(input -> {
final HttpResponsePacket responsePacket = input.getResponse();
String encoding = responsePacket == null ? input.getCharacterEncoding() : responsePacket.getCharacterEncoding();
return resourceContent(resourcePath, encoding).apply(input);
});
}
|
[
"public",
"static",
"Action",
"resourceContent",
"(",
"final",
"String",
"resourcePath",
")",
"{",
"return",
"new",
"Action",
"(",
"input",
"->",
"{",
"final",
"HttpResponsePacket",
"responsePacket",
"=",
"input",
".",
"getResponse",
"(",
")",
";",
"String",
"encoding",
"=",
"responsePacket",
"==",
"null",
"?",
"input",
".",
"getCharacterEncoding",
"(",
")",
":",
"responsePacket",
".",
"getCharacterEncoding",
"(",
")",
";",
"return",
"resourceContent",
"(",
"resourcePath",
",",
"encoding",
")",
".",
"apply",
"(",
"input",
")",
";",
"}",
")",
";",
"}"
] |
Writes content and content-type of resource file to response.
Tries to detect content type based on file extension. If can not detect - content-type is not set.
For now there are following bindings:
<ul>
<li>.xml - `application/xml`</li>
<li>.json - `application/xml`</li>
</ul>
|
[
"Writes",
"content",
"and",
"content",
"-",
"type",
"of",
"resource",
"file",
"to",
"response",
".",
"Tries",
"to",
"detect",
"content",
"type",
"based",
"on",
"file",
"extension",
".",
"If",
"can",
"not",
"detect",
"-",
"content",
"-",
"type",
"is",
"not",
"set",
".",
"For",
"now",
"there",
"are",
"following",
"bindings",
":",
"<ul",
">",
"<li",
">",
".",
"xml",
"-",
"application",
"/",
"xml",
"<",
"/",
"li",
">",
"<li",
">",
".",
"json",
"-",
"application",
"/",
"xml",
"<",
"/",
"li",
">",
"<",
"/",
"ul",
">"
] |
train
|
https://github.com/mkotsur/restito/blob/b999293616ca84fdea1ffe929e92a5db29c7e415/src/main/java/com/xebialabs/restito/semantics/Action.java#L80-L86
|
GCRC/nunaliit
|
nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/AuthServlet.java
|
AuthServlet.performAdjustCookies
|
private void performAdjustCookies(HttpServletRequest request, HttpServletResponse response) throws Exception {
"""
Adjusts the information cookie based on the authentication token
@param request
@param response
@throws ServletException
@throws IOException
"""
boolean loggedIn = false;
User user = null;
try {
Cookie cookie = getCookieFromRequest(request);
if( null != cookie ) {
user = CookieAuthentication.verifyCookieString(userRepository, cookie.getValue());
loggedIn = true;
}
} catch(Exception e) {
// Ignore
}
if( null == user ) {
user = userRepository.getDefaultUser();
}
acceptRequest(response, loggedIn, user);
}
|
java
|
private void performAdjustCookies(HttpServletRequest request, HttpServletResponse response) throws Exception {
boolean loggedIn = false;
User user = null;
try {
Cookie cookie = getCookieFromRequest(request);
if( null != cookie ) {
user = CookieAuthentication.verifyCookieString(userRepository, cookie.getValue());
loggedIn = true;
}
} catch(Exception e) {
// Ignore
}
if( null == user ) {
user = userRepository.getDefaultUser();
}
acceptRequest(response, loggedIn, user);
}
|
[
"private",
"void",
"performAdjustCookies",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"Exception",
"{",
"boolean",
"loggedIn",
"=",
"false",
";",
"User",
"user",
"=",
"null",
";",
"try",
"{",
"Cookie",
"cookie",
"=",
"getCookieFromRequest",
"(",
"request",
")",
";",
"if",
"(",
"null",
"!=",
"cookie",
")",
"{",
"user",
"=",
"CookieAuthentication",
".",
"verifyCookieString",
"(",
"userRepository",
",",
"cookie",
".",
"getValue",
"(",
")",
")",
";",
"loggedIn",
"=",
"true",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Ignore",
"}",
"if",
"(",
"null",
"==",
"user",
")",
"{",
"user",
"=",
"userRepository",
".",
"getDefaultUser",
"(",
")",
";",
"}",
"acceptRequest",
"(",
"response",
",",
"loggedIn",
",",
"user",
")",
";",
"}"
] |
Adjusts the information cookie based on the authentication token
@param request
@param response
@throws ServletException
@throws IOException
|
[
"Adjusts",
"the",
"information",
"cookie",
"based",
"on",
"the",
"authentication",
"token"
] |
train
|
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/AuthServlet.java#L186-L205
|
raydac/java-binary-block-parser
|
jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPOut.java
|
JBBPOut.Var
|
public JBBPOut Var(final JBBPOutVarProcessor processor, final Object... args) throws IOException {
"""
Output data externally.
@param processor a processor which will get the stream to write data, must
not be null
@param args optional arguments to be provided to the processor
@return the DSL context
@throws IOException it will be thrown for transport errors
@throws NullPointerException it will be thrown for null as a processor
"""
assertNotEnded();
JBBPUtils.assertNotNull(processor, "Var processor must not be null");
if (this.processCommands) {
this.processCommands = processor.processVarOut(this, this.outStream, args);
}
return this;
}
|
java
|
public JBBPOut Var(final JBBPOutVarProcessor processor, final Object... args) throws IOException {
assertNotEnded();
JBBPUtils.assertNotNull(processor, "Var processor must not be null");
if (this.processCommands) {
this.processCommands = processor.processVarOut(this, this.outStream, args);
}
return this;
}
|
[
"public",
"JBBPOut",
"Var",
"(",
"final",
"JBBPOutVarProcessor",
"processor",
",",
"final",
"Object",
"...",
"args",
")",
"throws",
"IOException",
"{",
"assertNotEnded",
"(",
")",
";",
"JBBPUtils",
".",
"assertNotNull",
"(",
"processor",
",",
"\"Var processor must not be null\"",
")",
";",
"if",
"(",
"this",
".",
"processCommands",
")",
"{",
"this",
".",
"processCommands",
"=",
"processor",
".",
"processVarOut",
"(",
"this",
",",
"this",
".",
"outStream",
",",
"args",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Output data externally.
@param processor a processor which will get the stream to write data, must
not be null
@param args optional arguments to be provided to the processor
@return the DSL context
@throws IOException it will be thrown for transport errors
@throws NullPointerException it will be thrown for null as a processor
|
[
"Output",
"data",
"externally",
"."
] |
train
|
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPOut.java#L938-L945
|
lets-blade/blade
|
src/main/java/com/blade/kit/PasswordKit.java
|
PasswordKit.checkPassword
|
public static boolean checkPassword(String plaintext, String storedHash) {
"""
This method can be used to verify a computed hash from a plaintext (e.g. during a login
request) with that of a stored hash from a database. The password hash from the database
must be passed as the second variable.
@param plaintext The account's plaintext password, as provided during a login request
@param storedHash The account's stored password hash, retrieved from the authorization database
@return boolean - true if the password matches the password of the stored hash, false otherwise
"""
boolean password_verified;
if (null == storedHash || !storedHash.startsWith("$2a$"))
throw new IllegalArgumentException("Invalid hash provided for comparison");
password_verified = BCrypt.checkpw(plaintext, storedHash);
return (password_verified);
}
|
java
|
public static boolean checkPassword(String plaintext, String storedHash) {
boolean password_verified;
if (null == storedHash || !storedHash.startsWith("$2a$"))
throw new IllegalArgumentException("Invalid hash provided for comparison");
password_verified = BCrypt.checkpw(plaintext, storedHash);
return (password_verified);
}
|
[
"public",
"static",
"boolean",
"checkPassword",
"(",
"String",
"plaintext",
",",
"String",
"storedHash",
")",
"{",
"boolean",
"password_verified",
";",
"if",
"(",
"null",
"==",
"storedHash",
"||",
"!",
"storedHash",
".",
"startsWith",
"(",
"\"$2a$\"",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid hash provided for comparison\"",
")",
";",
"password_verified",
"=",
"BCrypt",
".",
"checkpw",
"(",
"plaintext",
",",
"storedHash",
")",
";",
"return",
"(",
"password_verified",
")",
";",
"}"
] |
This method can be used to verify a computed hash from a plaintext (e.g. during a login
request) with that of a stored hash from a database. The password hash from the database
must be passed as the second variable.
@param plaintext The account's plaintext password, as provided during a login request
@param storedHash The account's stored password hash, retrieved from the authorization database
@return boolean - true if the password matches the password of the stored hash, false otherwise
|
[
"This",
"method",
"can",
"be",
"used",
"to",
"verify",
"a",
"computed",
"hash",
"from",
"a",
"plaintext",
"(",
"e",
".",
"g",
".",
"during",
"a",
"login",
"request",
")",
"with",
"that",
"of",
"a",
"stored",
"hash",
"from",
"a",
"database",
".",
"The",
"password",
"hash",
"from",
"the",
"database",
"must",
"be",
"passed",
"as",
"the",
"second",
"variable",
"."
] |
train
|
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/kit/PasswordKit.java#L58-L64
|
intive-FDV/DynamicJasper
|
src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJAreaChartBuilder.java
|
DJAreaChartBuilder.addSerie
|
public DJAreaChartBuilder addSerie(AbstractColumn column, String label) {
"""
Adds the specified serie column to the dataset with custom label.
@param column the serie column
@param label column the custom label
"""
getDataset().addSerie(column, label);
return this;
}
|
java
|
public DJAreaChartBuilder addSerie(AbstractColumn column, String label) {
getDataset().addSerie(column, label);
return this;
}
|
[
"public",
"DJAreaChartBuilder",
"addSerie",
"(",
"AbstractColumn",
"column",
",",
"String",
"label",
")",
"{",
"getDataset",
"(",
")",
".",
"addSerie",
"(",
"column",
",",
"label",
")",
";",
"return",
"this",
";",
"}"
] |
Adds the specified serie column to the dataset with custom label.
@param column the serie column
@param label column the custom label
|
[
"Adds",
"the",
"specified",
"serie",
"column",
"to",
"the",
"dataset",
"with",
"custom",
"label",
"."
] |
train
|
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJAreaChartBuilder.java#L366-L369
|
Azure/azure-sdk-for-java
|
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java
|
SchedulesInner.getAsync
|
public Observable<ScheduleInner> getAsync(String resourceGroupName, String automationAccountName, String scheduleName) {
"""
Retrieve the schedule identified by schedule name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param scheduleName The schedule name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ScheduleInner object
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName).map(new Func1<ServiceResponse<ScheduleInner>, ScheduleInner>() {
@Override
public ScheduleInner call(ServiceResponse<ScheduleInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<ScheduleInner> getAsync(String resourceGroupName, String automationAccountName, String scheduleName) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, scheduleName).map(new Func1<ServiceResponse<ScheduleInner>, ScheduleInner>() {
@Override
public ScheduleInner call(ServiceResponse<ScheduleInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"ScheduleInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"scheduleName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"scheduleName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ScheduleInner",
">",
",",
"ScheduleInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ScheduleInner",
"call",
"(",
"ServiceResponse",
"<",
"ScheduleInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Retrieve the schedule identified by schedule name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param scheduleName The schedule name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ScheduleInner object
|
[
"Retrieve",
"the",
"schedule",
"identified",
"by",
"schedule",
"name",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/SchedulesInner.java#L330-L337
|
anotheria/moskito
|
moskito-core/src/main/java/net/anotheria/moskito/core/util/storage/Storage.java
|
Storage.putAll
|
public void putAll(Storage<? extends K, ? extends V> anotherStorage) {
"""
Puts all elements from anotherStorage to this storage.
@param anotherStorage
"""
wrapper.putAll(anotherStorage.getWrapper());
stats.setSize(wrapper.size());
}
|
java
|
public void putAll(Storage<? extends K, ? extends V> anotherStorage){
wrapper.putAll(anotherStorage.getWrapper());
stats.setSize(wrapper.size());
}
|
[
"public",
"void",
"putAll",
"(",
"Storage",
"<",
"?",
"extends",
"K",
",",
"?",
"extends",
"V",
">",
"anotherStorage",
")",
"{",
"wrapper",
".",
"putAll",
"(",
"anotherStorage",
".",
"getWrapper",
"(",
")",
")",
";",
"stats",
".",
"setSize",
"(",
"wrapper",
".",
"size",
"(",
")",
")",
";",
"}"
] |
Puts all elements from anotherStorage to this storage.
@param anotherStorage
|
[
"Puts",
"all",
"elements",
"from",
"anotherStorage",
"to",
"this",
"storage",
"."
] |
train
|
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/util/storage/Storage.java#L166-L169
|
neo4j-contrib/neo4j-apoc-procedures
|
src/main/java/apoc/schema/Schemas.java
|
Schemas.constraintsExistsForRelationship
|
private Boolean constraintsExistsForRelationship(String type, List<String> propertyNames) {
"""
Checks if a constraint exists for a given type and a list of properties
This method checks for constraints on relationships
@param type
@param propertyNames
@return true if the constraint exists otherwise it returns false
"""
Schema schema = db.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(RelationshipType.withName(type)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
|
java
|
private Boolean constraintsExistsForRelationship(String type, List<String> propertyNames) {
Schema schema = db.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(RelationshipType.withName(type)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
|
[
"private",
"Boolean",
"constraintsExistsForRelationship",
"(",
"String",
"type",
",",
"List",
"<",
"String",
">",
"propertyNames",
")",
"{",
"Schema",
"schema",
"=",
"db",
".",
"schema",
"(",
")",
";",
"for",
"(",
"ConstraintDefinition",
"constraintDefinition",
":",
"Iterables",
".",
"asList",
"(",
"schema",
".",
"getConstraints",
"(",
"RelationshipType",
".",
"withName",
"(",
"type",
")",
")",
")",
")",
"{",
"List",
"<",
"String",
">",
"properties",
"=",
"Iterables",
".",
"asList",
"(",
"constraintDefinition",
".",
"getPropertyKeys",
"(",
")",
")",
";",
"if",
"(",
"properties",
".",
"equals",
"(",
"propertyNames",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks if a constraint exists for a given type and a list of properties
This method checks for constraints on relationships
@param type
@param propertyNames
@return true if the constraint exists otherwise it returns false
|
[
"Checks",
"if",
"a",
"constraint",
"exists",
"for",
"a",
"given",
"type",
"and",
"a",
"list",
"of",
"properties",
"This",
"method",
"checks",
"for",
"constraints",
"on",
"relationships"
] |
train
|
https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/e8386975d1c512c0e4388a1a61f5496121c04f86/src/main/java/apoc/schema/Schemas.java#L254-L266
|
CodeNarc/CodeNarc
|
src/main/java/org/codenarc/util/AstUtil.java
|
AstUtil.hasAnyAnnotation
|
public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {
"""
Return true only if the node has any of the named annotations
@param node - the AST Node to check
@param names - the names of the annotations
@return true only if the node has any of the named annotations
"""
for (String name : names) {
if (hasAnnotation(node, name)) {
return true;
}
}
return false;
}
|
java
|
public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) {
for (String name : names) {
if (hasAnnotation(node, name)) {
return true;
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"hasAnyAnnotation",
"(",
"AnnotatedNode",
"node",
",",
"String",
"...",
"names",
")",
"{",
"for",
"(",
"String",
"name",
":",
"names",
")",
"{",
"if",
"(",
"hasAnnotation",
"(",
"node",
",",
"name",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Return true only if the node has any of the named annotations
@param node - the AST Node to check
@param names - the names of the annotations
@return true only if the node has any of the named annotations
|
[
"Return",
"true",
"only",
"if",
"the",
"node",
"has",
"any",
"of",
"the",
"named",
"annotations"
] |
train
|
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L499-L506
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java
|
TwitterEndpointServices.signAndCreateAuthzHeader
|
private String signAndCreateAuthzHeader(String endpointUrl, Map<String, String> parameters) {
"""
Generates the Authorization header with all the requisite content for the specified endpoint request by computing the
signature, adding it to the parameters, and generating the Authorization header string.
@param endpointUrl
@param parameters
@return
"""
String signature = computeSignature(requestMethod, endpointUrl, parameters);
parameters.put(TwitterConstants.PARAM_OAUTH_SIGNATURE, signature);
String authzHeaderString = createAuthorizationHeaderString(parameters);
return authzHeaderString;
}
|
java
|
private String signAndCreateAuthzHeader(String endpointUrl, Map<String, String> parameters) {
String signature = computeSignature(requestMethod, endpointUrl, parameters);
parameters.put(TwitterConstants.PARAM_OAUTH_SIGNATURE, signature);
String authzHeaderString = createAuthorizationHeaderString(parameters);
return authzHeaderString;
}
|
[
"private",
"String",
"signAndCreateAuthzHeader",
"(",
"String",
"endpointUrl",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"String",
"signature",
"=",
"computeSignature",
"(",
"requestMethod",
",",
"endpointUrl",
",",
"parameters",
")",
";",
"parameters",
".",
"put",
"(",
"TwitterConstants",
".",
"PARAM_OAUTH_SIGNATURE",
",",
"signature",
")",
";",
"String",
"authzHeaderString",
"=",
"createAuthorizationHeaderString",
"(",
"parameters",
")",
";",
"return",
"authzHeaderString",
";",
"}"
] |
Generates the Authorization header with all the requisite content for the specified endpoint request by computing the
signature, adding it to the parameters, and generating the Authorization header string.
@param endpointUrl
@param parameters
@return
|
[
"Generates",
"the",
"Authorization",
"header",
"with",
"all",
"the",
"requisite",
"content",
"for",
"the",
"specified",
"endpoint",
"request",
"by",
"computing",
"the",
"signature",
"adding",
"it",
"to",
"the",
"parameters",
"and",
"generating",
"the",
"Authorization",
"header",
"string",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java#L408-L415
|
camunda/camunda-bpm-platform
|
engine/src/main/java/org/camunda/bpm/engine/impl/util/ReflectUtil.java
|
ReflectUtil.getMethod
|
public static Method getMethod(Class<?> declaringType, String methodName, Class<?>... parameterTypes) {
"""
Finds a method by name and parameter types.
@param declaringType the name of the class
@param methodName the name of the method to look for
@param parameterTypes the types of the parameters
"""
return findMethod(declaringType, methodName, parameterTypes);
}
|
java
|
public static Method getMethod(Class<?> declaringType, String methodName, Class<?>... parameterTypes) {
return findMethod(declaringType, methodName, parameterTypes);
}
|
[
"public",
"static",
"Method",
"getMethod",
"(",
"Class",
"<",
"?",
">",
"declaringType",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"parameterTypes",
")",
"{",
"return",
"findMethod",
"(",
"declaringType",
",",
"methodName",
",",
"parameterTypes",
")",
";",
"}"
] |
Finds a method by name and parameter types.
@param declaringType the name of the class
@param methodName the name of the method to look for
@param parameterTypes the types of the parameters
|
[
"Finds",
"a",
"method",
"by",
"name",
"and",
"parameter",
"types",
"."
] |
train
|
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/util/ReflectUtil.java#L397-L399
|
UrielCh/ovh-java-sdk
|
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
|
ApiOvhTelephony.billingAccount_timeCondition_serviceName_condition_id_GET
|
public OvhTimeCondition billingAccount_timeCondition_serviceName_condition_id_GET(String billingAccount, String serviceName, Long id) throws IOException {
"""
Get this object properties
REST: GET /telephony/{billingAccount}/timeCondition/{serviceName}/condition/{id}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param id [required] Id of the object
"""
String qPath = "/telephony/{billingAccount}/timeCondition/{serviceName}/condition/{id}";
StringBuilder sb = path(qPath, billingAccount, serviceName, id);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTimeCondition.class);
}
|
java
|
public OvhTimeCondition billingAccount_timeCondition_serviceName_condition_id_GET(String billingAccount, String serviceName, Long id) throws IOException {
String qPath = "/telephony/{billingAccount}/timeCondition/{serviceName}/condition/{id}";
StringBuilder sb = path(qPath, billingAccount, serviceName, id);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTimeCondition.class);
}
|
[
"public",
"OvhTimeCondition",
"billingAccount_timeCondition_serviceName_condition_id_GET",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"Long",
"id",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/timeCondition/{serviceName}/condition/{id}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"billingAccount",
",",
"serviceName",
",",
"id",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhTimeCondition",
".",
"class",
")",
";",
"}"
] |
Get this object properties
REST: GET /telephony/{billingAccount}/timeCondition/{serviceName}/condition/{id}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
@param id [required] Id of the object
|
[
"Get",
"this",
"object",
"properties"
] |
train
|
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L5825-L5830
|
google/j2objc
|
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/Function3Args.java
|
Function3Args.fixupVariables
|
public void fixupVariables(java.util.Vector vars, int globalsSize) {
"""
This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame).
"""
super.fixupVariables(vars, globalsSize);
if(null != m_arg2)
m_arg2.fixupVariables(vars, globalsSize);
}
|
java
|
public void fixupVariables(java.util.Vector vars, int globalsSize)
{
super.fixupVariables(vars, globalsSize);
if(null != m_arg2)
m_arg2.fixupVariables(vars, globalsSize);
}
|
[
"public",
"void",
"fixupVariables",
"(",
"java",
".",
"util",
".",
"Vector",
"vars",
",",
"int",
"globalsSize",
")",
"{",
"super",
".",
"fixupVariables",
"(",
"vars",
",",
"globalsSize",
")",
";",
"if",
"(",
"null",
"!=",
"m_arg2",
")",
"m_arg2",
".",
"fixupVariables",
"(",
"vars",
",",
"globalsSize",
")",
";",
"}"
] |
This function is used to fixup variables from QNames to stack frame
indexes at stylesheet build time.
@param vars List of QNames that correspond to variables. This list
should be searched backwards for the first qualified name that
corresponds to the variable reference qname. The position of the
QName in the vector from the start of the vector will be its position
in the stack frame (but variables above the globalsTop value will need
to be offset to the current stack frame).
|
[
"This",
"function",
"is",
"used",
"to",
"fixup",
"variables",
"from",
"QNames",
"to",
"stack",
"frame",
"indexes",
"at",
"stylesheet",
"build",
"time",
"."
] |
train
|
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/Function3Args.java#L61-L66
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java
|
DataFormatHelper.padHexString
|
public static final String padHexString(int num, int width) {
"""
Returns the provided integer, padded to the specified number of characters with zeros.
@param num
Input number as an integer
@param width
Number of characters to return, including padding
@return input number as zero-padded string
"""
final String zeroPad = "0000000000000000";
String str = Integer.toHexString(num);
final int length = str.length();
if (length >= width)
return str;
StringBuilder buffer = new StringBuilder(zeroPad.substring(0, width));
buffer.replace(width - length, width, str);
return buffer.toString();
}
|
java
|
public static final String padHexString(int num, int width) {
final String zeroPad = "0000000000000000";
String str = Integer.toHexString(num);
final int length = str.length();
if (length >= width)
return str;
StringBuilder buffer = new StringBuilder(zeroPad.substring(0, width));
buffer.replace(width - length, width, str);
return buffer.toString();
}
|
[
"public",
"static",
"final",
"String",
"padHexString",
"(",
"int",
"num",
",",
"int",
"width",
")",
"{",
"final",
"String",
"zeroPad",
"=",
"\"0000000000000000\"",
";",
"String",
"str",
"=",
"Integer",
".",
"toHexString",
"(",
"num",
")",
";",
"final",
"int",
"length",
"=",
"str",
".",
"length",
"(",
")",
";",
"if",
"(",
"length",
">=",
"width",
")",
"return",
"str",
";",
"StringBuilder",
"buffer",
"=",
"new",
"StringBuilder",
"(",
"zeroPad",
".",
"substring",
"(",
"0",
",",
"width",
")",
")",
";",
"buffer",
".",
"replace",
"(",
"width",
"-",
"length",
",",
"width",
",",
"str",
")",
";",
"return",
"buffer",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns the provided integer, padded to the specified number of characters with zeros.
@param num
Input number as an integer
@param width
Number of characters to return, including padding
@return input number as zero-padded string
|
[
"Returns",
"the",
"provided",
"integer",
"padded",
"to",
"the",
"specified",
"number",
"of",
"characters",
"with",
"zeros",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java#L202-L214
|
facebookarchive/hadoop-20
|
src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamUtil.java
|
StreamUtil.goodClassOrNull
|
public static Class goodClassOrNull(Configuration conf, String className, String defaultPackage) {
"""
It may seem strange to silently switch behaviour when a String
is not a classname; the reason is simplified Usage:<pre>
-mapper [classname | program ]
instead of the explicit Usage:
[-mapper program | -javamapper classname], -mapper and -javamapper are mutually exclusive.
(repeat for -reducer, -combiner) </pre>
"""
if (className.indexOf('.') == -1 && defaultPackage != null) {
className = defaultPackage + "." + className;
}
Class clazz = null;
try {
clazz = conf.getClassByName(className);
} catch (ClassNotFoundException cnf) {
}
return clazz;
}
|
java
|
public static Class goodClassOrNull(Configuration conf, String className, String defaultPackage) {
if (className.indexOf('.') == -1 && defaultPackage != null) {
className = defaultPackage + "." + className;
}
Class clazz = null;
try {
clazz = conf.getClassByName(className);
} catch (ClassNotFoundException cnf) {
}
return clazz;
}
|
[
"public",
"static",
"Class",
"goodClassOrNull",
"(",
"Configuration",
"conf",
",",
"String",
"className",
",",
"String",
"defaultPackage",
")",
"{",
"if",
"(",
"className",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
"&&",
"defaultPackage",
"!=",
"null",
")",
"{",
"className",
"=",
"defaultPackage",
"+",
"\".\"",
"+",
"className",
";",
"}",
"Class",
"clazz",
"=",
"null",
";",
"try",
"{",
"clazz",
"=",
"conf",
".",
"getClassByName",
"(",
"className",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"cnf",
")",
"{",
"}",
"return",
"clazz",
";",
"}"
] |
It may seem strange to silently switch behaviour when a String
is not a classname; the reason is simplified Usage:<pre>
-mapper [classname | program ]
instead of the explicit Usage:
[-mapper program | -javamapper classname], -mapper and -javamapper are mutually exclusive.
(repeat for -reducer, -combiner) </pre>
|
[
"It",
"may",
"seem",
"strange",
"to",
"silently",
"switch",
"behaviour",
"when",
"a",
"String",
"is",
"not",
"a",
"classname",
";",
"the",
"reason",
"is",
"simplified",
"Usage",
":",
"<pre",
">",
"-",
"mapper",
"[",
"classname",
"|",
"program",
"]",
"instead",
"of",
"the",
"explicit",
"Usage",
":",
"[",
"-",
"mapper",
"program",
"|",
"-",
"javamapper",
"classname",
"]",
"-",
"mapper",
"and",
"-",
"javamapper",
"are",
"mutually",
"exclusive",
".",
"(",
"repeat",
"for",
"-",
"reducer",
"-",
"combiner",
")",
"<",
"/",
"pre",
">"
] |
train
|
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamUtil.java#L55-L65
|
line/armeria
|
core/src/main/java/com/linecorp/armeria/common/stream/AbstractStreamMessageDuplicator.java
|
AbstractStreamMessageDuplicator.duplicateStream
|
public U duplicateStream(boolean lastStream) {
"""
Creates a new {@link U} instance that publishes data from the {@code publisher} you create
this factory with. If you specify the {@code lastStream} as {@code true}, it will prevent further
creation of duplicate stream.
"""
if (!processor.isDuplicable()) {
throw new IllegalStateException("duplicator is closed or last downstream is added.");
}
return doDuplicateStream(new ChildStreamMessage<>(this, processor, lastStream));
}
|
java
|
public U duplicateStream(boolean lastStream) {
if (!processor.isDuplicable()) {
throw new IllegalStateException("duplicator is closed or last downstream is added.");
}
return doDuplicateStream(new ChildStreamMessage<>(this, processor, lastStream));
}
|
[
"public",
"U",
"duplicateStream",
"(",
"boolean",
"lastStream",
")",
"{",
"if",
"(",
"!",
"processor",
".",
"isDuplicable",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"duplicator is closed or last downstream is added.\"",
")",
";",
"}",
"return",
"doDuplicateStream",
"(",
"new",
"ChildStreamMessage",
"<>",
"(",
"this",
",",
"processor",
",",
"lastStream",
")",
")",
";",
"}"
] |
Creates a new {@link U} instance that publishes data from the {@code publisher} you create
this factory with. If you specify the {@code lastStream} as {@code true}, it will prevent further
creation of duplicate stream.
|
[
"Creates",
"a",
"new",
"{"
] |
train
|
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/stream/AbstractStreamMessageDuplicator.java#L124-L129
|
cloudfoundry/cf-java-client
|
cloudfoundry-util/src/main/java/org/cloudfoundry/util/JobUtils.java
|
JobUtils.waitForCompletion
|
public static <R extends Resource<JobEntity>> Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, R resource) {
"""
Waits for a job to complete
@param cloudFoundryClient the client to use to request job status
@param completionTimeout the amount of time to wait for the job to complete.
@param resource the resource representing the job
@param <R> the Job resource type
@return {@code onComplete} once job has completed
"""
return waitForCompletion(cloudFoundryClient, completionTimeout, ResourceUtils.getEntity(resource));
}
|
java
|
public static <R extends Resource<JobEntity>> Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, R resource) {
return waitForCompletion(cloudFoundryClient, completionTimeout, ResourceUtils.getEntity(resource));
}
|
[
"public",
"static",
"<",
"R",
"extends",
"Resource",
"<",
"JobEntity",
">",
">",
"Mono",
"<",
"Void",
">",
"waitForCompletion",
"(",
"CloudFoundryClient",
"cloudFoundryClient",
",",
"Duration",
"completionTimeout",
",",
"R",
"resource",
")",
"{",
"return",
"waitForCompletion",
"(",
"cloudFoundryClient",
",",
"completionTimeout",
",",
"ResourceUtils",
".",
"getEntity",
"(",
"resource",
")",
")",
";",
"}"
] |
Waits for a job to complete
@param cloudFoundryClient the client to use to request job status
@param completionTimeout the amount of time to wait for the job to complete.
@param resource the resource representing the job
@param <R> the Job resource type
@return {@code onComplete} once job has completed
|
[
"Waits",
"for",
"a",
"job",
"to",
"complete"
] |
train
|
https://github.com/cloudfoundry/cf-java-client/blob/caa1cb889cfe8717614c071703d833a1540784df/cloudfoundry-util/src/main/java/org/cloudfoundry/util/JobUtils.java#L56-L58
|
KyoriPowered/text
|
api/src/main/java/net/kyori/text/TranslatableComponent.java
|
TranslatableComponent.of
|
public static TranslatableComponent of(final @NonNull String key, final @Nullable TextColor color, final @NonNull Set<TextDecoration> decorations, final @NonNull List<Component> args) {
"""
Creates a translatable component with a translation key and arguments.
@param key the translation key
@param color the color
@param decorations the decorations
@param args the translation arguments
@return the translatable component
"""
return builder()
.color(color)
.decorations(decorations, true)
.key(key)
.args(args)
.build();
}
|
java
|
public static TranslatableComponent of(final @NonNull String key, final @Nullable TextColor color, final @NonNull Set<TextDecoration> decorations, final @NonNull List<Component> args) {
return builder()
.color(color)
.decorations(decorations, true)
.key(key)
.args(args)
.build();
}
|
[
"public",
"static",
"TranslatableComponent",
"of",
"(",
"final",
"@",
"NonNull",
"String",
"key",
",",
"final",
"@",
"Nullable",
"TextColor",
"color",
",",
"final",
"@",
"NonNull",
"Set",
"<",
"TextDecoration",
">",
"decorations",
",",
"final",
"@",
"NonNull",
"List",
"<",
"Component",
">",
"args",
")",
"{",
"return",
"builder",
"(",
")",
".",
"color",
"(",
"color",
")",
".",
"decorations",
"(",
"decorations",
",",
"true",
")",
".",
"key",
"(",
"key",
")",
".",
"args",
"(",
"args",
")",
".",
"build",
"(",
")",
";",
"}"
] |
Creates a translatable component with a translation key and arguments.
@param key the translation key
@param color the color
@param decorations the decorations
@param args the translation arguments
@return the translatable component
|
[
"Creates",
"a",
"translatable",
"component",
"with",
"a",
"translation",
"key",
"and",
"arguments",
"."
] |
train
|
https://github.com/KyoriPowered/text/blob/4496c593bf89e8fb036dd6efe26f8ac60f7655c9/api/src/main/java/net/kyori/text/TranslatableComponent.java#L182-L189
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedExecutorBuilderImpl.java
|
ManagedExecutorBuilderImpl.failOnOverlapOfClearedPropagated
|
private void failOnOverlapOfClearedPropagated() {
"""
Fail with error indentifying the overlap(s) in context types between:
cleared, propagated.
@throws IllegalStateException identifying the overlap.
"""
HashSet<String> overlap = new HashSet<String>(cleared);
overlap.retainAll(propagated);
if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
throw new ConcurrentModificationException();
throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1151.context.lists.overlap", overlap));
}
|
java
|
private void failOnOverlapOfClearedPropagated() {
HashSet<String> overlap = new HashSet<String>(cleared);
overlap.retainAll(propagated);
if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
throw new ConcurrentModificationException();
throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1151.context.lists.overlap", overlap));
}
|
[
"private",
"void",
"failOnOverlapOfClearedPropagated",
"(",
")",
"{",
"HashSet",
"<",
"String",
">",
"overlap",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
"cleared",
")",
";",
"overlap",
".",
"retainAll",
"(",
"propagated",
")",
";",
"if",
"(",
"overlap",
".",
"isEmpty",
"(",
")",
")",
"// only possible if builder is concurrently modified during build",
"throw",
"new",
"ConcurrentModificationException",
"(",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"Tr",
".",
"formatMessage",
"(",
"tc",
",",
"\"CWWKC1151.context.lists.overlap\"",
",",
"overlap",
")",
")",
";",
"}"
] |
Fail with error indentifying the overlap(s) in context types between:
cleared, propagated.
@throws IllegalStateException identifying the overlap.
|
[
"Fail",
"with",
"error",
"indentifying",
"the",
"overlap",
"(",
"s",
")",
"in",
"context",
"types",
"between",
":",
"cleared",
"propagated",
"."
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedExecutorBuilderImpl.java#L152-L158
|
netty/netty
|
resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
|
DnsNameResolver.resolveAll
|
public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals,
Promise<List<DnsRecord>> promise) {
"""
Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
{@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
{@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
{@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
@param question the question
@param additionals additional records ({@code OPT})
@param promise the {@link Promise} which will be fulfilled when the resolution is finished
@return the list of the {@link DnsRecord}s as the result of the resolution
"""
final DnsRecord[] additionalsArray = toArray(additionals, true);
return resolveAll(question, additionalsArray, promise);
}
|
java
|
public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals,
Promise<List<DnsRecord>> promise) {
final DnsRecord[] additionalsArray = toArray(additionals, true);
return resolveAll(question, additionalsArray, promise);
}
|
[
"public",
"final",
"Future",
"<",
"List",
"<",
"DnsRecord",
">",
">",
"resolveAll",
"(",
"DnsQuestion",
"question",
",",
"Iterable",
"<",
"DnsRecord",
">",
"additionals",
",",
"Promise",
"<",
"List",
"<",
"DnsRecord",
">",
">",
"promise",
")",
"{",
"final",
"DnsRecord",
"[",
"]",
"additionalsArray",
"=",
"toArray",
"(",
"additionals",
",",
"true",
")",
";",
"return",
"resolveAll",
"(",
"question",
",",
"additionalsArray",
",",
"promise",
")",
";",
"}"
] |
Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
{@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
{@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
{@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
@param question the question
@param additionals additional records ({@code OPT})
@param promise the {@link Promise} which will be fulfilled when the resolution is finished
@return the list of the {@link DnsRecord}s as the result of the resolution
|
[
"Resolves",
"the",
"{",
"@link",
"DnsRecord",
"}",
"s",
"that",
"are",
"matched",
"by",
"the",
"specified",
"{",
"@link",
"DnsQuestion",
"}",
".",
"Unlike",
"{",
"@link",
"#query",
"(",
"DnsQuestion",
")",
"}",
"this",
"method",
"handles",
"redirection",
"CNAMEs",
"and",
"multiple",
"name",
"servers",
".",
"If",
"the",
"specified",
"{",
"@link",
"DnsQuestion",
"}",
"is",
"{",
"@code",
"A",
"}",
"or",
"{",
"@code",
"AAAA",
"}",
"this",
"method",
"looks",
"up",
"the",
"configured",
"{",
"@link",
"HostsFileEntries",
"}",
"before",
"sending",
"a",
"query",
"to",
"the",
"name",
"servers",
".",
"If",
"a",
"match",
"is",
"found",
"in",
"the",
"{",
"@link",
"HostsFileEntries",
"}",
"a",
"synthetic",
"{",
"@code",
"A",
"}",
"or",
"{",
"@code",
"AAAA",
"}",
"record",
"will",
"be",
"returned",
"."
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java#L744-L748
|
pravega/pravega
|
controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java
|
ZkOrderedStore.tryDeleteSealedCollection
|
private CompletableFuture<Void> tryDeleteSealedCollection(String scope, String stream, Integer collectionNum) {
"""
Collection should be sealed while calling this method
@param scope scope
@param stream stream
@param collectionNum collection to delete
@return future which when completed will have the collection deleted if it is empty or ignored otherwise.
"""
// purge garbage znodes
// attempt to delete entities node
// delete collection
return getLatestCollection(scope, stream)
.thenCompose(latestcollectionNum ->
// 1. purge
storeHelper.getChildren(getEntitiesPath(scope, stream, collectionNum))
.thenCompose(entitiesPos -> {
String entitiesPath = getEntitiesPath(scope, stream, collectionNum);
// delete entities greater than max pos
return Futures.allOf(entitiesPos.stream().filter(pos -> getPositionFromPath(pos) > rollOverAfter)
.map(pos -> storeHelper.deletePath(ZKPaths.makePath(entitiesPath, pos), false))
.collect(Collectors.toList()));
}))
.thenCompose(x -> {
// 2. Try deleting entities root path.
// if we are able to delete entities node then we can delete the whole thing
return Futures.exceptionallyExpecting(storeHelper.deletePath(getEntitiesPath(scope, stream, collectionNum), false)
.thenCompose(v -> storeHelper.deleteTree(getCollectionPath(scope, stream, collectionNum))),
e -> Exceptions.unwrap(e) instanceof StoreException.DataNotEmptyException, null);
});
}
|
java
|
private CompletableFuture<Void> tryDeleteSealedCollection(String scope, String stream, Integer collectionNum) {
// purge garbage znodes
// attempt to delete entities node
// delete collection
return getLatestCollection(scope, stream)
.thenCompose(latestcollectionNum ->
// 1. purge
storeHelper.getChildren(getEntitiesPath(scope, stream, collectionNum))
.thenCompose(entitiesPos -> {
String entitiesPath = getEntitiesPath(scope, stream, collectionNum);
// delete entities greater than max pos
return Futures.allOf(entitiesPos.stream().filter(pos -> getPositionFromPath(pos) > rollOverAfter)
.map(pos -> storeHelper.deletePath(ZKPaths.makePath(entitiesPath, pos), false))
.collect(Collectors.toList()));
}))
.thenCompose(x -> {
// 2. Try deleting entities root path.
// if we are able to delete entities node then we can delete the whole thing
return Futures.exceptionallyExpecting(storeHelper.deletePath(getEntitiesPath(scope, stream, collectionNum), false)
.thenCompose(v -> storeHelper.deleteTree(getCollectionPath(scope, stream, collectionNum))),
e -> Exceptions.unwrap(e) instanceof StoreException.DataNotEmptyException, null);
});
}
|
[
"private",
"CompletableFuture",
"<",
"Void",
">",
"tryDeleteSealedCollection",
"(",
"String",
"scope",
",",
"String",
"stream",
",",
"Integer",
"collectionNum",
")",
"{",
"// purge garbage znodes",
"// attempt to delete entities node",
"// delete collection",
"return",
"getLatestCollection",
"(",
"scope",
",",
"stream",
")",
".",
"thenCompose",
"(",
"latestcollectionNum",
"->",
"// 1. purge",
"storeHelper",
".",
"getChildren",
"(",
"getEntitiesPath",
"(",
"scope",
",",
"stream",
",",
"collectionNum",
")",
")",
".",
"thenCompose",
"(",
"entitiesPos",
"->",
"{",
"String",
"entitiesPath",
"=",
"getEntitiesPath",
"(",
"scope",
",",
"stream",
",",
"collectionNum",
")",
";",
"// delete entities greater than max pos",
"return",
"Futures",
".",
"allOf",
"(",
"entitiesPos",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"pos",
"->",
"getPositionFromPath",
"(",
"pos",
")",
">",
"rollOverAfter",
")",
".",
"map",
"(",
"pos",
"->",
"storeHelper",
".",
"deletePath",
"(",
"ZKPaths",
".",
"makePath",
"(",
"entitiesPath",
",",
"pos",
")",
",",
"false",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
")",
";",
"}",
")",
")",
".",
"thenCompose",
"(",
"x",
"->",
"{",
"// 2. Try deleting entities root path. ",
"// if we are able to delete entities node then we can delete the whole thing",
"return",
"Futures",
".",
"exceptionallyExpecting",
"(",
"storeHelper",
".",
"deletePath",
"(",
"getEntitiesPath",
"(",
"scope",
",",
"stream",
",",
"collectionNum",
")",
",",
"false",
")",
".",
"thenCompose",
"(",
"v",
"->",
"storeHelper",
".",
"deleteTree",
"(",
"getCollectionPath",
"(",
"scope",
",",
"stream",
",",
"collectionNum",
")",
")",
")",
",",
"e",
"->",
"Exceptions",
".",
"unwrap",
"(",
"e",
")",
"instanceof",
"StoreException",
".",
"DataNotEmptyException",
",",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Collection should be sealed while calling this method
@param scope scope
@param stream stream
@param collectionNum collection to delete
@return future which when completed will have the collection deleted if it is empty or ignored otherwise.
|
[
"Collection",
"should",
"be",
"sealed",
"while",
"calling",
"this",
"method"
] |
train
|
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/ZkOrderedStore.java#L263-L286
|
arxanchain/java-common
|
src/main/java/com/arxanfintech/common/util/ByteUtils.java
|
ByteUtils.toBase58
|
public static String toBase58(byte[] b) {
"""
convert a byte array to a human readable base58 string. Base58 is a Bitcoin
specific encoding similar to widely used base64 but avoids using characters
of similar shape, such as 1 and l or O an 0
@param b
byte data
@return base58 data
"""
if (b.length == 0) {
return "";
}
int lz = 0;
while (lz < b.length && b[lz] == 0) {
++lz;
}
StringBuilder s = new StringBuilder();
BigInteger n = new BigInteger(1, b);
while (n.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] r = n.divideAndRemainder(BigInteger.valueOf(58));
n = r[0];
char digit = b58[r[1].intValue()];
s.append(digit);
}
while (lz > 0) {
--lz;
s.append("1");
}
return s.reverse().toString();
}
|
java
|
public static String toBase58(byte[] b) {
if (b.length == 0) {
return "";
}
int lz = 0;
while (lz < b.length && b[lz] == 0) {
++lz;
}
StringBuilder s = new StringBuilder();
BigInteger n = new BigInteger(1, b);
while (n.compareTo(BigInteger.ZERO) > 0) {
BigInteger[] r = n.divideAndRemainder(BigInteger.valueOf(58));
n = r[0];
char digit = b58[r[1].intValue()];
s.append(digit);
}
while (lz > 0) {
--lz;
s.append("1");
}
return s.reverse().toString();
}
|
[
"public",
"static",
"String",
"toBase58",
"(",
"byte",
"[",
"]",
"b",
")",
"{",
"if",
"(",
"b",
".",
"length",
"==",
"0",
")",
"{",
"return",
"\"\"",
";",
"}",
"int",
"lz",
"=",
"0",
";",
"while",
"(",
"lz",
"<",
"b",
".",
"length",
"&&",
"b",
"[",
"lz",
"]",
"==",
"0",
")",
"{",
"++",
"lz",
";",
"}",
"StringBuilder",
"s",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"BigInteger",
"n",
"=",
"new",
"BigInteger",
"(",
"1",
",",
"b",
")",
";",
"while",
"(",
"n",
".",
"compareTo",
"(",
"BigInteger",
".",
"ZERO",
")",
">",
"0",
")",
"{",
"BigInteger",
"[",
"]",
"r",
"=",
"n",
".",
"divideAndRemainder",
"(",
"BigInteger",
".",
"valueOf",
"(",
"58",
")",
")",
";",
"n",
"=",
"r",
"[",
"0",
"]",
";",
"char",
"digit",
"=",
"b58",
"[",
"r",
"[",
"1",
"]",
".",
"intValue",
"(",
")",
"]",
";",
"s",
".",
"append",
"(",
"digit",
")",
";",
"}",
"while",
"(",
"lz",
">",
"0",
")",
"{",
"--",
"lz",
";",
"s",
".",
"append",
"(",
"\"1\"",
")",
";",
"}",
"return",
"s",
".",
"reverse",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] |
convert a byte array to a human readable base58 string. Base58 is a Bitcoin
specific encoding similar to widely used base64 but avoids using characters
of similar shape, such as 1 and l or O an 0
@param b
byte data
@return base58 data
|
[
"convert",
"a",
"byte",
"array",
"to",
"a",
"human",
"readable",
"base58",
"string",
".",
"Base58",
"is",
"a",
"Bitcoin",
"specific",
"encoding",
"similar",
"to",
"widely",
"used",
"base64",
"but",
"avoids",
"using",
"characters",
"of",
"similar",
"shape",
"such",
"as",
"1",
"and",
"l",
"or",
"O",
"an",
"0"
] |
train
|
https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/util/ByteUtils.java#L52-L75
|
wmdietl/jsr308-langtools
|
src/share/classes/com/sun/tools/javac/jvm/Gen.java
|
Gen.implementInterfaceMethods
|
void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
"""
Add abstract methods for all methods defined in one of
the interfaces of a given class,
provided they are not already implemented in the class.
@param c The class whose interfaces are searched for methods
for which Miranda methods should be added.
@param site The class in which a definition may be needed.
"""
for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
ClassSymbol i = (ClassSymbol)l.head.tsym;
for (Scope.Entry e = i.members().elems;
e != null;
e = e.sibling)
{
if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
{
MethodSymbol absMeth = (MethodSymbol)e.sym;
MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
if (implMeth == null)
addAbstractMethod(site, absMeth);
else if ((implMeth.flags() & IPROXY) != 0)
adjustAbstractMethod(site, implMeth, absMeth);
}
}
implementInterfaceMethods(i, site);
}
}
|
java
|
void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
ClassSymbol i = (ClassSymbol)l.head.tsym;
for (Scope.Entry e = i.members().elems;
e != null;
e = e.sibling)
{
if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
{
MethodSymbol absMeth = (MethodSymbol)e.sym;
MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
if (implMeth == null)
addAbstractMethod(site, absMeth);
else if ((implMeth.flags() & IPROXY) != 0)
adjustAbstractMethod(site, implMeth, absMeth);
}
}
implementInterfaceMethods(i, site);
}
}
|
[
"void",
"implementInterfaceMethods",
"(",
"ClassSymbol",
"c",
",",
"ClassSymbol",
"site",
")",
"{",
"for",
"(",
"List",
"<",
"Type",
">",
"l",
"=",
"types",
".",
"interfaces",
"(",
"c",
".",
"type",
")",
";",
"l",
".",
"nonEmpty",
"(",
")",
";",
"l",
"=",
"l",
".",
"tail",
")",
"{",
"ClassSymbol",
"i",
"=",
"(",
"ClassSymbol",
")",
"l",
".",
"head",
".",
"tsym",
";",
"for",
"(",
"Scope",
".",
"Entry",
"e",
"=",
"i",
".",
"members",
"(",
")",
".",
"elems",
";",
"e",
"!=",
"null",
";",
"e",
"=",
"e",
".",
"sibling",
")",
"{",
"if",
"(",
"e",
".",
"sym",
".",
"kind",
"==",
"MTH",
"&&",
"(",
"e",
".",
"sym",
".",
"flags",
"(",
")",
"&",
"STATIC",
")",
"==",
"0",
")",
"{",
"MethodSymbol",
"absMeth",
"=",
"(",
"MethodSymbol",
")",
"e",
".",
"sym",
";",
"MethodSymbol",
"implMeth",
"=",
"absMeth",
".",
"binaryImplementation",
"(",
"site",
",",
"types",
")",
";",
"if",
"(",
"implMeth",
"==",
"null",
")",
"addAbstractMethod",
"(",
"site",
",",
"absMeth",
")",
";",
"else",
"if",
"(",
"(",
"implMeth",
".",
"flags",
"(",
")",
"&",
"IPROXY",
")",
"!=",
"0",
")",
"adjustAbstractMethod",
"(",
"site",
",",
"implMeth",
",",
"absMeth",
")",
";",
"}",
"}",
"implementInterfaceMethods",
"(",
"i",
",",
"site",
")",
";",
"}",
"}"
] |
Add abstract methods for all methods defined in one of
the interfaces of a given class,
provided they are not already implemented in the class.
@param c The class whose interfaces are searched for methods
for which Miranda methods should be added.
@param site The class in which a definition may be needed.
|
[
"Add",
"abstract",
"methods",
"for",
"all",
"methods",
"defined",
"in",
"one",
"of",
"the",
"interfaces",
"of",
"a",
"given",
"class",
"provided",
"they",
"are",
"not",
"already",
"implemented",
"in",
"the",
"class",
"."
] |
train
|
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/jvm/Gen.java#L663-L682
|
jbundle/jbundle
|
thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/transport/EncodedTransport.java
|
EncodedTransport.addParam
|
public void addParam(String strParam, String strValue) {
"""
Add this method param to the param list.
(By default, uses the property method... override this to use an app specific method).
NOTE: The param name DOES NOT need to be saved, as params are always added and retrieved in order.
@param strParam The param name.
@param strValue The param value.
"""
if (strValue == null)
strValue = NULL;
m_properties.setProperty(strParam, strValue);
}
|
java
|
public void addParam(String strParam, String strValue)
{
if (strValue == null)
strValue = NULL;
m_properties.setProperty(strParam, strValue);
}
|
[
"public",
"void",
"addParam",
"(",
"String",
"strParam",
",",
"String",
"strValue",
")",
"{",
"if",
"(",
"strValue",
"==",
"null",
")",
"strValue",
"=",
"NULL",
";",
"m_properties",
".",
"setProperty",
"(",
"strParam",
",",
"strValue",
")",
";",
"}"
] |
Add this method param to the param list.
(By default, uses the property method... override this to use an app specific method).
NOTE: The param name DOES NOT need to be saved, as params are always added and retrieved in order.
@param strParam The param name.
@param strValue The param value.
|
[
"Add",
"this",
"method",
"param",
"to",
"the",
"param",
"list",
".",
"(",
"By",
"default",
"uses",
"the",
"property",
"method",
"...",
"override",
"this",
"to",
"use",
"an",
"app",
"specific",
"method",
")",
".",
"NOTE",
":",
"The",
"param",
"name",
"DOES",
"NOT",
"need",
"to",
"be",
"saved",
"as",
"params",
"are",
"always",
"added",
"and",
"retrieved",
"in",
"order",
"."
] |
train
|
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/transport/EncodedTransport.java#L57-L62
|
neo4j/neo4j-java-driver
|
driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java
|
CertificateTool.saveX509Cert
|
public static void saveX509Cert( String certStr, File certFile ) throws IOException {
"""
Save a certificate to a file in base 64 binary format with BEGIN and END strings
@param certStr
@param certFile
@throws IOException
"""
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
|
java
|
public static void saveX509Cert( String certStr, File certFile ) throws IOException
{
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
|
[
"public",
"static",
"void",
"saveX509Cert",
"(",
"String",
"certStr",
",",
"File",
"certFile",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedWriter",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"certFile",
")",
")",
")",
"{",
"writer",
".",
"write",
"(",
"BEGIN_CERT",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"writer",
".",
"write",
"(",
"certStr",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"writer",
".",
"write",
"(",
"END_CERT",
")",
";",
"writer",
".",
"newLine",
"(",
")",
";",
"}",
"}"
] |
Save a certificate to a file in base 64 binary format with BEGIN and END strings
@param certStr
@param certFile
@throws IOException
|
[
"Save",
"a",
"certificate",
"to",
"a",
"file",
"in",
"base",
"64",
"binary",
"format",
"with",
"BEGIN",
"and",
"END",
"strings"
] |
train
|
https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/util/CertificateTool.java#L49-L62
|
lucee/Lucee
|
core/src/main/java/lucee/runtime/tag/Col.java
|
Col.setAlign
|
public void setAlign(String align) throws ApplicationException {
"""
set the value align Column alignment, Left, Right, or Center.
@param align value to set
@throws ApplicationException
"""
align = StringUtil.toLowerCase(align);
if (align.equals("left")) this.align = Table.ALIGN_LEFT;
else if (align.equals("center")) this.align = Table.ALIGN_CENTER;
else if (align.equals("right")) this.align = Table.ALIGN_RIGHT;
else throw new ApplicationException("value [" + align + "] of attribute align from tag col is invalid", "valid values are [left, center, right]");
}
|
java
|
public void setAlign(String align) throws ApplicationException {
align = StringUtil.toLowerCase(align);
if (align.equals("left")) this.align = Table.ALIGN_LEFT;
else if (align.equals("center")) this.align = Table.ALIGN_CENTER;
else if (align.equals("right")) this.align = Table.ALIGN_RIGHT;
else throw new ApplicationException("value [" + align + "] of attribute align from tag col is invalid", "valid values are [left, center, right]");
}
|
[
"public",
"void",
"setAlign",
"(",
"String",
"align",
")",
"throws",
"ApplicationException",
"{",
"align",
"=",
"StringUtil",
".",
"toLowerCase",
"(",
"align",
")",
";",
"if",
"(",
"align",
".",
"equals",
"(",
"\"left\"",
")",
")",
"this",
".",
"align",
"=",
"Table",
".",
"ALIGN_LEFT",
";",
"else",
"if",
"(",
"align",
".",
"equals",
"(",
"\"center\"",
")",
")",
"this",
".",
"align",
"=",
"Table",
".",
"ALIGN_CENTER",
";",
"else",
"if",
"(",
"align",
".",
"equals",
"(",
"\"right\"",
")",
")",
"this",
".",
"align",
"=",
"Table",
".",
"ALIGN_RIGHT",
";",
"else",
"throw",
"new",
"ApplicationException",
"(",
"\"value [\"",
"+",
"align",
"+",
"\"] of attribute align from tag col is invalid\"",
",",
"\"valid values are [left, center, right]\"",
")",
";",
"}"
] |
set the value align Column alignment, Left, Right, or Center.
@param align value to set
@throws ApplicationException
|
[
"set",
"the",
"value",
"align",
"Column",
"alignment",
"Left",
"Right",
"or",
"Center",
"."
] |
train
|
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/Col.java#L94-L100
|
Samsung/GearVRf
|
GVRf/Framework/framework/src/main/java/org/gearvrf/debug/cli/ShellFactory.java
|
ShellFactory.createConsoleShell
|
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
"""
One of facade methods for operating the Shell.
Run the obtained Shell with commandLoop().
@see org.gearvrf.debug.cli.Shell#Shell(org.gearvrf.debug.cli.Shell.Settings, org.gearvrf.debug.cli.CommandTable, java.util.List)
@param prompt Prompt to be displayed
@param appName The app name string
@param handlers Command handlers
@return Shell that can be either further customized or run directly by calling commandLoop().
"""
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();
modifAuxHandlers.put("!", io);
Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
new CommandTable(new DashJoinedNamer(true)), path);
theShell.setAppName(appName);
theShell.addMainHandler(theShell, "!");
theShell.addMainHandler(new HelpCommandHandler(), "?");
for (Object h : handlers) {
theShell.addMainHandler(h, "");
}
return theShell;
}
|
java
|
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();
modifAuxHandlers.put("!", io);
Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
new CommandTable(new DashJoinedNamer(true)), path);
theShell.setAppName(appName);
theShell.addMainHandler(theShell, "!");
theShell.addMainHandler(new HelpCommandHandler(), "?");
for (Object h : handlers) {
theShell.addMainHandler(h, "");
}
return theShell;
}
|
[
"public",
"static",
"Shell",
"createConsoleShell",
"(",
"String",
"prompt",
",",
"String",
"appName",
",",
"Object",
"...",
"handlers",
")",
"{",
"ConsoleIO",
"io",
"=",
"new",
"ConsoleIO",
"(",
")",
";",
"List",
"<",
"String",
">",
"path",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"1",
")",
";",
"path",
".",
"add",
"(",
"prompt",
")",
";",
"MultiMap",
"<",
"String",
",",
"Object",
">",
"modifAuxHandlers",
"=",
"new",
"ArrayHashMultiMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"modifAuxHandlers",
".",
"put",
"(",
"\"!\"",
",",
"io",
")",
";",
"Shell",
"theShell",
"=",
"new",
"Shell",
"(",
"new",
"Shell",
".",
"Settings",
"(",
"io",
",",
"io",
",",
"modifAuxHandlers",
",",
"false",
")",
",",
"new",
"CommandTable",
"(",
"new",
"DashJoinedNamer",
"(",
"true",
")",
")",
",",
"path",
")",
";",
"theShell",
".",
"setAppName",
"(",
"appName",
")",
";",
"theShell",
".",
"addMainHandler",
"(",
"theShell",
",",
"\"!\"",
")",
";",
"theShell",
".",
"addMainHandler",
"(",
"new",
"HelpCommandHandler",
"(",
")",
",",
"\"?\"",
")",
";",
"for",
"(",
"Object",
"h",
":",
"handlers",
")",
"{",
"theShell",
".",
"addMainHandler",
"(",
"h",
",",
"\"\"",
")",
";",
"}",
"return",
"theShell",
";",
"}"
] |
One of facade methods for operating the Shell.
Run the obtained Shell with commandLoop().
@see org.gearvrf.debug.cli.Shell#Shell(org.gearvrf.debug.cli.Shell.Settings, org.gearvrf.debug.cli.CommandTable, java.util.List)
@param prompt Prompt to be displayed
@param appName The app name string
@param handlers Command handlers
@return Shell that can be either further customized or run directly by calling commandLoop().
|
[
"One",
"of",
"facade",
"methods",
"for",
"operating",
"the",
"Shell",
"."
] |
train
|
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/debug/cli/ShellFactory.java#L35-L55
|
Azure/azure-sdk-for-java
|
policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java
|
PolicyEventsInner.listQueryResultsForPolicyDefinitionAsync
|
public Observable<PolicyEventsQueryResultsInner> listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) {
"""
Queries policy events for the subscription level policy definition.
@param subscriptionId Microsoft Azure subscription ID.
@param policyDefinitionName Policy definition name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PolicyEventsQueryResultsInner object
"""
return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<PolicyEventsQueryResultsInner>, PolicyEventsQueryResultsInner>() {
@Override
public PolicyEventsQueryResultsInner call(ServiceResponse<PolicyEventsQueryResultsInner> response) {
return response.body();
}
});
}
|
java
|
public Observable<PolicyEventsQueryResultsInner> listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) {
return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<PolicyEventsQueryResultsInner>, PolicyEventsQueryResultsInner>() {
@Override
public PolicyEventsQueryResultsInner call(ServiceResponse<PolicyEventsQueryResultsInner> response) {
return response.body();
}
});
}
|
[
"public",
"Observable",
"<",
"PolicyEventsQueryResultsInner",
">",
"listQueryResultsForPolicyDefinitionAsync",
"(",
"String",
"subscriptionId",
",",
"String",
"policyDefinitionName",
",",
"QueryOptions",
"queryOptions",
")",
"{",
"return",
"listQueryResultsForPolicyDefinitionWithServiceResponseAsync",
"(",
"subscriptionId",
",",
"policyDefinitionName",
",",
"queryOptions",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"PolicyEventsQueryResultsInner",
">",
",",
"PolicyEventsQueryResultsInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"PolicyEventsQueryResultsInner",
"call",
"(",
"ServiceResponse",
"<",
"PolicyEventsQueryResultsInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Queries policy events for the subscription level policy definition.
@param subscriptionId Microsoft Azure subscription ID.
@param policyDefinitionName Policy definition name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PolicyEventsQueryResultsInner object
|
[
"Queries",
"policy",
"events",
"for",
"the",
"subscription",
"level",
"policy",
"definition",
"."
] |
train
|
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyEventsInner.java#L1192-L1199
|
VoltDB/voltdb
|
src/frontend/org/voltdb/types/VoltDecimalHelper.java
|
VoltDecimalHelper.serializeBigDecimal
|
static public void serializeBigDecimal(BigDecimal bd, ByteBuffer buf) {
"""
Serialize the {@link java.math.BigDecimal BigDecimal} to Volt's fixed precision and scale 16-byte format.
@param bd {@link java.math.BigDecimal BigDecimal} to serialize
@param buf {@link java.nio.ByteBuffer ByteBuffer} to serialize the <code>BigDecimal</code> to
@throws RuntimeException Thrown if the precision is out of range, or the scale is out of range and rounding is not enabled.
"""
if (bd == null) {
serializeNull(buf);
return;
}
int decimalScale = bd.scale();
if (decimalScale > kDefaultScale) {
bd = roundToScale(bd, kDefaultScale, getRoundingMode());
decimalScale = bd.scale();
}
int overallPrecision = bd.precision();
final int wholeNumberPrecision = overallPrecision - decimalScale;
if (wholeNumberPrecision > 26) {
throw new RuntimeException("Precision of " + bd + " to the left of the decimal point is " +
wholeNumberPrecision + " and the max is 26");
}
final int scalingFactor = Math.max(0, kDefaultScale - decimalScale);
BigInteger scalableBI = bd.unscaledValue();
//* enable to debug */ System.out.println("DEBUG BigDecimal: " + bd);
//* enable to debug */ System.out.println("DEBUG unscaled: " + scalableBI);
scalableBI = scalableBI.multiply(scaleFactors[scalingFactor]);
//* enable to debug */ System.out.println("DEBUG scaled to picos: " + scalableBI);
final byte wholePicos[] = scalableBI.toByteArray();
if (wholePicos.length > 16) {
throw new RuntimeException("Precision of " + bd + " is > 38 digits");
}
boolean isNegative = (scalableBI.signum() < 0);
buf.put(expandToLength16(wholePicos, isNegative));
}
|
java
|
static public void serializeBigDecimal(BigDecimal bd, ByteBuffer buf)
{
if (bd == null) {
serializeNull(buf);
return;
}
int decimalScale = bd.scale();
if (decimalScale > kDefaultScale) {
bd = roundToScale(bd, kDefaultScale, getRoundingMode());
decimalScale = bd.scale();
}
int overallPrecision = bd.precision();
final int wholeNumberPrecision = overallPrecision - decimalScale;
if (wholeNumberPrecision > 26) {
throw new RuntimeException("Precision of " + bd + " to the left of the decimal point is " +
wholeNumberPrecision + " and the max is 26");
}
final int scalingFactor = Math.max(0, kDefaultScale - decimalScale);
BigInteger scalableBI = bd.unscaledValue();
//* enable to debug */ System.out.println("DEBUG BigDecimal: " + bd);
//* enable to debug */ System.out.println("DEBUG unscaled: " + scalableBI);
scalableBI = scalableBI.multiply(scaleFactors[scalingFactor]);
//* enable to debug */ System.out.println("DEBUG scaled to picos: " + scalableBI);
final byte wholePicos[] = scalableBI.toByteArray();
if (wholePicos.length > 16) {
throw new RuntimeException("Precision of " + bd + " is > 38 digits");
}
boolean isNegative = (scalableBI.signum() < 0);
buf.put(expandToLength16(wholePicos, isNegative));
}
|
[
"static",
"public",
"void",
"serializeBigDecimal",
"(",
"BigDecimal",
"bd",
",",
"ByteBuffer",
"buf",
")",
"{",
"if",
"(",
"bd",
"==",
"null",
")",
"{",
"serializeNull",
"(",
"buf",
")",
";",
"return",
";",
"}",
"int",
"decimalScale",
"=",
"bd",
".",
"scale",
"(",
")",
";",
"if",
"(",
"decimalScale",
">",
"kDefaultScale",
")",
"{",
"bd",
"=",
"roundToScale",
"(",
"bd",
",",
"kDefaultScale",
",",
"getRoundingMode",
"(",
")",
")",
";",
"decimalScale",
"=",
"bd",
".",
"scale",
"(",
")",
";",
"}",
"int",
"overallPrecision",
"=",
"bd",
".",
"precision",
"(",
")",
";",
"final",
"int",
"wholeNumberPrecision",
"=",
"overallPrecision",
"-",
"decimalScale",
";",
"if",
"(",
"wholeNumberPrecision",
">",
"26",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Precision of \"",
"+",
"bd",
"+",
"\" to the left of the decimal point is \"",
"+",
"wholeNumberPrecision",
"+",
"\" and the max is 26\"",
")",
";",
"}",
"final",
"int",
"scalingFactor",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"kDefaultScale",
"-",
"decimalScale",
")",
";",
"BigInteger",
"scalableBI",
"=",
"bd",
".",
"unscaledValue",
"(",
")",
";",
"//* enable to debug */ System.out.println(\"DEBUG BigDecimal: \" + bd);",
"//* enable to debug */ System.out.println(\"DEBUG unscaled: \" + scalableBI);",
"scalableBI",
"=",
"scalableBI",
".",
"multiply",
"(",
"scaleFactors",
"[",
"scalingFactor",
"]",
")",
";",
"//* enable to debug */ System.out.println(\"DEBUG scaled to picos: \" + scalableBI);",
"final",
"byte",
"wholePicos",
"[",
"]",
"=",
"scalableBI",
".",
"toByteArray",
"(",
")",
";",
"if",
"(",
"wholePicos",
".",
"length",
">",
"16",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Precision of \"",
"+",
"bd",
"+",
"\" is > 38 digits\"",
")",
";",
"}",
"boolean",
"isNegative",
"=",
"(",
"scalableBI",
".",
"signum",
"(",
")",
"<",
"0",
")",
";",
"buf",
".",
"put",
"(",
"expandToLength16",
"(",
"wholePicos",
",",
"isNegative",
")",
")",
";",
"}"
] |
Serialize the {@link java.math.BigDecimal BigDecimal} to Volt's fixed precision and scale 16-byte format.
@param bd {@link java.math.BigDecimal BigDecimal} to serialize
@param buf {@link java.nio.ByteBuffer ByteBuffer} to serialize the <code>BigDecimal</code> to
@throws RuntimeException Thrown if the precision is out of range, or the scale is out of range and rounding is not enabled.
|
[
"Serialize",
"the",
"{"
] |
train
|
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/types/VoltDecimalHelper.java#L233-L262
|
box/box-java-sdk
|
src/main/java/com/box/sdk/BoxFileUploadSession.java
|
BoxFileUploadSession.uploadPart
|
public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,
long totalSizeOfFile) {
"""
Uploads bytes to an open upload session.
@param data data
@param offset the byte position where the chunk begins in the file.
@param partSize the part size returned as part of the upload session instance creation.
Only the last chunk can have a lesser value.
@param totalSizeOfFile The total size of the file being uploaded.
@return the part instance that contains the part id, offset and part size.
"""
URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);
MessageDigest digestInstance = null;
try {
digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);
} catch (NoSuchAlgorithmException ae) {
throw new BoxAPIException("Digest algorithm not found", ae);
}
//Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.
byte[] digestBytes = digestInstance.digest(data);
String digest = Base64.encode(digestBytes);
request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);
//Content-Range: bytes offset-part/totalSize
request.addHeader(HttpHeaders.CONTENT_RANGE,
"bytes " + offset + "-" + (offset + partSize - 1) + "/" + totalSizeOfFile);
//Creates the body
request.setBody(new ByteArrayInputStream(data));
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part"));
return part;
}
|
java
|
public BoxFileUploadSessionPart uploadPart(byte[] data, long offset, int partSize,
long totalSizeOfFile) {
URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);
request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);
MessageDigest digestInstance = null;
try {
digestInstance = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1);
} catch (NoSuchAlgorithmException ae) {
throw new BoxAPIException("Digest algorithm not found", ae);
}
//Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.
byte[] digestBytes = digestInstance.digest(data);
String digest = Base64.encode(digestBytes);
request.addHeader(HttpHeaders.DIGEST, DIGEST_HEADER_PREFIX_SHA + digest);
//Content-Range: bytes offset-part/totalSize
request.addHeader(HttpHeaders.CONTENT_RANGE,
"bytes " + offset + "-" + (offset + partSize - 1) + "/" + totalSizeOfFile);
//Creates the body
request.setBody(new ByteArrayInputStream(data));
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
BoxFileUploadSessionPart part = new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part"));
return part;
}
|
[
"public",
"BoxFileUploadSessionPart",
"uploadPart",
"(",
"byte",
"[",
"]",
"data",
",",
"long",
"offset",
",",
"int",
"partSize",
",",
"long",
"totalSizeOfFile",
")",
"{",
"URL",
"uploadPartURL",
"=",
"this",
".",
"sessionInfo",
".",
"getSessionEndpoints",
"(",
")",
".",
"getUploadPartEndpoint",
"(",
")",
";",
"BoxAPIRequest",
"request",
"=",
"new",
"BoxAPIRequest",
"(",
"this",
".",
"getAPI",
"(",
")",
",",
"uploadPartURL",
",",
"HttpMethod",
".",
"PUT",
")",
";",
"request",
".",
"addHeader",
"(",
"HttpHeaders",
".",
"CONTENT_TYPE",
",",
"ContentType",
".",
"APPLICATION_OCTET_STREAM",
")",
";",
"MessageDigest",
"digestInstance",
"=",
"null",
";",
"try",
"{",
"digestInstance",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"DIGEST_ALGORITHM_SHA1",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"ae",
")",
"{",
"throw",
"new",
"BoxAPIException",
"(",
"\"Digest algorithm not found\"",
",",
"ae",
")",
";",
"}",
"//Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64.",
"byte",
"[",
"]",
"digestBytes",
"=",
"digestInstance",
".",
"digest",
"(",
"data",
")",
";",
"String",
"digest",
"=",
"Base64",
".",
"encode",
"(",
"digestBytes",
")",
";",
"request",
".",
"addHeader",
"(",
"HttpHeaders",
".",
"DIGEST",
",",
"DIGEST_HEADER_PREFIX_SHA",
"+",
"digest",
")",
";",
"//Content-Range: bytes offset-part/totalSize",
"request",
".",
"addHeader",
"(",
"HttpHeaders",
".",
"CONTENT_RANGE",
",",
"\"bytes \"",
"+",
"offset",
"+",
"\"-\"",
"+",
"(",
"offset",
"+",
"partSize",
"-",
"1",
")",
"+",
"\"/\"",
"+",
"totalSizeOfFile",
")",
";",
"//Creates the body",
"request",
".",
"setBody",
"(",
"new",
"ByteArrayInputStream",
"(",
"data",
")",
")",
";",
"BoxJSONResponse",
"response",
"=",
"(",
"BoxJSONResponse",
")",
"request",
".",
"send",
"(",
")",
";",
"JsonObject",
"jsonObject",
"=",
"JsonObject",
".",
"readFrom",
"(",
"response",
".",
"getJSON",
"(",
")",
")",
";",
"BoxFileUploadSessionPart",
"part",
"=",
"new",
"BoxFileUploadSessionPart",
"(",
"(",
"JsonObject",
")",
"jsonObject",
".",
"get",
"(",
"\"part\"",
")",
")",
";",
"return",
"part",
";",
"}"
] |
Uploads bytes to an open upload session.
@param data data
@param offset the byte position where the chunk begins in the file.
@param partSize the part size returned as part of the upload session instance creation.
Only the last chunk can have a lesser value.
@param totalSizeOfFile The total size of the file being uploaded.
@return the part instance that contains the part id, offset and part size.
|
[
"Uploads",
"bytes",
"to",
"an",
"open",
"upload",
"session",
"."
] |
train
|
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFileUploadSession.java#L269-L297
|
netty/netty
|
common/src/main/java/io/netty/util/AsciiString.java
|
AsciiString.forEachByte
|
public int forEachByte(int index, int length, ByteProcessor visitor) throws Exception {
"""
Iterates over the specified area of this buffer with the specified {@code processor} in ascending order.
(i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}).
@return {@code -1} if the processor iterated to or beyond the end of the specified area.
The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}.
"""
if (isOutOfBounds(index, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length
+ ") <= " + "length(" + length() + ')');
}
return forEachByte0(index, length, visitor);
}
|
java
|
public int forEachByte(int index, int length, ByteProcessor visitor) throws Exception {
if (isOutOfBounds(index, length, length())) {
throw new IndexOutOfBoundsException("expected: " + "0 <= index(" + index + ") <= start + length(" + length
+ ") <= " + "length(" + length() + ')');
}
return forEachByte0(index, length, visitor);
}
|
[
"public",
"int",
"forEachByte",
"(",
"int",
"index",
",",
"int",
"length",
",",
"ByteProcessor",
"visitor",
")",
"throws",
"Exception",
"{",
"if",
"(",
"isOutOfBounds",
"(",
"index",
",",
"length",
",",
"length",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"expected: \"",
"+",
"\"0 <= index(\"",
"+",
"index",
"+",
"\") <= start + length(\"",
"+",
"length",
"+",
"\") <= \"",
"+",
"\"length(\"",
"+",
"length",
"(",
")",
"+",
"'",
"'",
")",
";",
"}",
"return",
"forEachByte0",
"(",
"index",
",",
"length",
",",
"visitor",
")",
";",
"}"
] |
Iterates over the specified area of this buffer with the specified {@code processor} in ascending order.
(i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}).
@return {@code -1} if the processor iterated to or beyond the end of the specified area.
The last-visited index If the {@link ByteProcessor#process(byte)} returned {@code false}.
|
[
"Iterates",
"over",
"the",
"specified",
"area",
"of",
"this",
"buffer",
"with",
"the",
"specified",
"{",
"@code",
"processor",
"}",
"in",
"ascending",
"order",
".",
"(",
"i",
".",
"e",
".",
"{",
"@code",
"index",
"}",
"{",
"@code",
"(",
"index",
"+",
"1",
")",
"}",
"..",
"{",
"@code",
"(",
"index",
"+",
"length",
"-",
"1",
")",
"}",
")",
"."
] |
train
|
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/AsciiString.java#L269-L275
|
dnsjava/dnsjava
|
org/xbill/DNS/SimpleResolver.java
|
SimpleResolver.sendAsync
|
public Object
sendAsync(final Message query, final ResolverListener listener) {
"""
Asynchronously sends a message to a single server, registering a listener
to receive a callback on success or exception. Multiple asynchronous
lookups can be performed in parallel. Since the callback may be invoked
before the function returns, external synchronization is necessary.
@param query The query to send
@param listener The object containing the callbacks.
@return An identifier, which is also a parameter in the callback
"""
final Object id;
synchronized (this) {
id = new Integer(uniqueID++);
}
Record question = query.getQuestion();
String qname;
if (question != null)
qname = question.getName().toString();
else
qname = "(none)";
String name = this.getClass() + ": " + qname;
Thread thread = new ResolveThread(this, query, id, listener);
thread.setName(name);
thread.setDaemon(true);
thread.start();
return id;
}
|
java
|
public Object
sendAsync(final Message query, final ResolverListener listener) {
final Object id;
synchronized (this) {
id = new Integer(uniqueID++);
}
Record question = query.getQuestion();
String qname;
if (question != null)
qname = question.getName().toString();
else
qname = "(none)";
String name = this.getClass() + ": " + qname;
Thread thread = new ResolveThread(this, query, id, listener);
thread.setName(name);
thread.setDaemon(true);
thread.start();
return id;
}
|
[
"public",
"Object",
"sendAsync",
"(",
"final",
"Message",
"query",
",",
"final",
"ResolverListener",
"listener",
")",
"{",
"final",
"Object",
"id",
";",
"synchronized",
"(",
"this",
")",
"{",
"id",
"=",
"new",
"Integer",
"(",
"uniqueID",
"++",
")",
";",
"}",
"Record",
"question",
"=",
"query",
".",
"getQuestion",
"(",
")",
";",
"String",
"qname",
";",
"if",
"(",
"question",
"!=",
"null",
")",
"qname",
"=",
"question",
".",
"getName",
"(",
")",
".",
"toString",
"(",
")",
";",
"else",
"qname",
"=",
"\"(none)\"",
";",
"String",
"name",
"=",
"this",
".",
"getClass",
"(",
")",
"+",
"\": \"",
"+",
"qname",
";",
"Thread",
"thread",
"=",
"new",
"ResolveThread",
"(",
"this",
",",
"query",
",",
"id",
",",
"listener",
")",
";",
"thread",
".",
"setName",
"(",
"name",
")",
";",
"thread",
".",
"setDaemon",
"(",
"true",
")",
";",
"thread",
".",
"start",
"(",
")",
";",
"return",
"id",
";",
"}"
] |
Asynchronously sends a message to a single server, registering a listener
to receive a callback on success or exception. Multiple asynchronous
lookups can be performed in parallel. Since the callback may be invoked
before the function returns, external synchronization is necessary.
@param query The query to send
@param listener The object containing the callbacks.
@return An identifier, which is also a parameter in the callback
|
[
"Asynchronously",
"sends",
"a",
"message",
"to",
"a",
"single",
"server",
"registering",
"a",
"listener",
"to",
"receive",
"a",
"callback",
"on",
"success",
"or",
"exception",
".",
"Multiple",
"asynchronous",
"lookups",
"can",
"be",
"performed",
"in",
"parallel",
".",
"Since",
"the",
"callback",
"may",
"be",
"invoked",
"before",
"the",
"function",
"returns",
"external",
"synchronization",
"is",
"necessary",
"."
] |
train
|
https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/SimpleResolver.java#L308-L326
|
reactor/reactor-netty
|
src/main/java/reactor/netty/ByteBufFlux.java
|
ByteBufFlux.fromPath
|
public static ByteBufFlux fromPath(Path path,
int maxChunkSize,
ByteBufAllocator allocator) {
"""
Open a {@link java.nio.channels.FileChannel} from a path and stream
{@link ByteBuf} chunks with a given maximum size into the returned
{@link ByteBufFlux}, using the provided {@link ByteBufAllocator}.
@param path the path to the resource to stream
@param maxChunkSize the maximum per-item ByteBuf size
@param allocator the channel {@link ByteBufAllocator}
@return a {@link ByteBufFlux}
"""
Objects.requireNonNull(path, "path");
Objects.requireNonNull(allocator, "allocator");
if (maxChunkSize < 1) {
throw new IllegalArgumentException("chunk size must be strictly positive, " + "was: " + maxChunkSize);
}
return new ByteBufFlux(Flux.generate(() -> FileChannel.open(path), (fc, sink) -> {
ByteBuf buf = allocator.buffer();
try {
if (buf.writeBytes(fc, maxChunkSize) < 0) {
buf.release();
sink.complete();
}
else {
sink.next(buf);
}
}
catch (IOException e) {
buf.release();
sink.error(e);
}
return fc;
}), allocator);
}
|
java
|
public static ByteBufFlux fromPath(Path path,
int maxChunkSize,
ByteBufAllocator allocator) {
Objects.requireNonNull(path, "path");
Objects.requireNonNull(allocator, "allocator");
if (maxChunkSize < 1) {
throw new IllegalArgumentException("chunk size must be strictly positive, " + "was: " + maxChunkSize);
}
return new ByteBufFlux(Flux.generate(() -> FileChannel.open(path), (fc, sink) -> {
ByteBuf buf = allocator.buffer();
try {
if (buf.writeBytes(fc, maxChunkSize) < 0) {
buf.release();
sink.complete();
}
else {
sink.next(buf);
}
}
catch (IOException e) {
buf.release();
sink.error(e);
}
return fc;
}), allocator);
}
|
[
"public",
"static",
"ByteBufFlux",
"fromPath",
"(",
"Path",
"path",
",",
"int",
"maxChunkSize",
",",
"ByteBufAllocator",
"allocator",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"path",
",",
"\"path\"",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"allocator",
",",
"\"allocator\"",
")",
";",
"if",
"(",
"maxChunkSize",
"<",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"chunk size must be strictly positive, \"",
"+",
"\"was: \"",
"+",
"maxChunkSize",
")",
";",
"}",
"return",
"new",
"ByteBufFlux",
"(",
"Flux",
".",
"generate",
"(",
"(",
")",
"->",
"FileChannel",
".",
"open",
"(",
"path",
")",
",",
"(",
"fc",
",",
"sink",
")",
"->",
"{",
"ByteBuf",
"buf",
"=",
"allocator",
".",
"buffer",
"(",
")",
";",
"try",
"{",
"if",
"(",
"buf",
".",
"writeBytes",
"(",
"fc",
",",
"maxChunkSize",
")",
"<",
"0",
")",
"{",
"buf",
".",
"release",
"(",
")",
";",
"sink",
".",
"complete",
"(",
")",
";",
"}",
"else",
"{",
"sink",
".",
"next",
"(",
"buf",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"buf",
".",
"release",
"(",
")",
";",
"sink",
".",
"error",
"(",
"e",
")",
";",
"}",
"return",
"fc",
";",
"}",
")",
",",
"allocator",
")",
";",
"}"
] |
Open a {@link java.nio.channels.FileChannel} from a path and stream
{@link ByteBuf} chunks with a given maximum size into the returned
{@link ByteBufFlux}, using the provided {@link ByteBufAllocator}.
@param path the path to the resource to stream
@param maxChunkSize the maximum per-item ByteBuf size
@param allocator the channel {@link ByteBufAllocator}
@return a {@link ByteBufFlux}
|
[
"Open",
"a",
"{",
"@link",
"java",
".",
"nio",
".",
"channels",
".",
"FileChannel",
"}",
"from",
"a",
"path",
"and",
"stream",
"{",
"@link",
"ByteBuf",
"}",
"chunks",
"with",
"a",
"given",
"maximum",
"size",
"into",
"the",
"returned",
"{",
"@link",
"ByteBufFlux",
"}",
"using",
"the",
"provided",
"{",
"@link",
"ByteBufAllocator",
"}",
"."
] |
train
|
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/ByteBufFlux.java#L148-L173
|
timols/java-gitlab-api
|
src/main/java/org/gitlab/api/GitlabAPI.java
|
GitlabAPI.createProject
|
@Deprecated
public GitlabProject createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, Boolean publik, String visibility, String importUrl) throws IOException {
"""
Creates a Project
@param name The name of the project
@param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
@param description A description for the project, null otherwise
@param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
@param wallEnabled Whether The Wall should be enabled, otherwise null indicates to use GitLab default
@param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
@param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
@param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
@param visibility The visibility level of the project, otherwise null indicates to use GitLab default
@param importUrl The Import URL for the project, otherwise null
@return the Gitlab Project
@throws IOException on gitlab api call error
"""
Query query = new Query()
.append("name", name)
.appendIf("namespace_id", namespaceId)
.appendIf("description", description)
.appendIf("issues_enabled", issuesEnabled)
.appendIf("wall_enabled", wallEnabled)
.appendIf("merge_requests_enabled", mergeRequestsEnabled)
.appendIf("wiki_enabled", wikiEnabled)
.appendIf("snippets_enabled", snippetsEnabled)
.appendIf("visibility", visibility)
.appendIf("import_url", importUrl);
String tailUrl = GitlabProject.URL + query.toString();
return dispatch().to(tailUrl, GitlabProject.class);
}
|
java
|
@Deprecated
public GitlabProject createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean wallEnabled, Boolean mergeRequestsEnabled, Boolean wikiEnabled, Boolean snippetsEnabled, Boolean publik, String visibility, String importUrl) throws IOException {
Query query = new Query()
.append("name", name)
.appendIf("namespace_id", namespaceId)
.appendIf("description", description)
.appendIf("issues_enabled", issuesEnabled)
.appendIf("wall_enabled", wallEnabled)
.appendIf("merge_requests_enabled", mergeRequestsEnabled)
.appendIf("wiki_enabled", wikiEnabled)
.appendIf("snippets_enabled", snippetsEnabled)
.appendIf("visibility", visibility)
.appendIf("import_url", importUrl);
String tailUrl = GitlabProject.URL + query.toString();
return dispatch().to(tailUrl, GitlabProject.class);
}
|
[
"@",
"Deprecated",
"public",
"GitlabProject",
"createProject",
"(",
"String",
"name",
",",
"Integer",
"namespaceId",
",",
"String",
"description",
",",
"Boolean",
"issuesEnabled",
",",
"Boolean",
"wallEnabled",
",",
"Boolean",
"mergeRequestsEnabled",
",",
"Boolean",
"wikiEnabled",
",",
"Boolean",
"snippetsEnabled",
",",
"Boolean",
"publik",
",",
"String",
"visibility",
",",
"String",
"importUrl",
")",
"throws",
"IOException",
"{",
"Query",
"query",
"=",
"new",
"Query",
"(",
")",
".",
"append",
"(",
"\"name\"",
",",
"name",
")",
".",
"appendIf",
"(",
"\"namespace_id\"",
",",
"namespaceId",
")",
".",
"appendIf",
"(",
"\"description\"",
",",
"description",
")",
".",
"appendIf",
"(",
"\"issues_enabled\"",
",",
"issuesEnabled",
")",
".",
"appendIf",
"(",
"\"wall_enabled\"",
",",
"wallEnabled",
")",
".",
"appendIf",
"(",
"\"merge_requests_enabled\"",
",",
"mergeRequestsEnabled",
")",
".",
"appendIf",
"(",
"\"wiki_enabled\"",
",",
"wikiEnabled",
")",
".",
"appendIf",
"(",
"\"snippets_enabled\"",
",",
"snippetsEnabled",
")",
".",
"appendIf",
"(",
"\"visibility\"",
",",
"visibility",
")",
".",
"appendIf",
"(",
"\"import_url\"",
",",
"importUrl",
")",
";",
"String",
"tailUrl",
"=",
"GitlabProject",
".",
"URL",
"+",
"query",
".",
"toString",
"(",
")",
";",
"return",
"dispatch",
"(",
")",
".",
"to",
"(",
"tailUrl",
",",
"GitlabProject",
".",
"class",
")",
";",
"}"
] |
Creates a Project
@param name The name of the project
@param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
@param description A description for the project, null otherwise
@param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
@param wallEnabled Whether The Wall should be enabled, otherwise null indicates to use GitLab default
@param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
@param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
@param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
@param visibility The visibility level of the project, otherwise null indicates to use GitLab default
@param importUrl The Import URL for the project, otherwise null
@return the Gitlab Project
@throws IOException on gitlab api call error
|
[
"Creates",
"a",
"Project"
] |
train
|
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L1249-L1266
|
jhalterman/lyra
|
src/main/java/net/jodah/lyra/internal/ChannelHandler.java
|
ChannelHandler.recoverRelatedExchanges
|
private void recoverRelatedExchanges(Set<String> recoveredExchanges, List<Binding> queueBindings)
throws Exception {
"""
Recovers exchanges and bindings related to the {@code queueBindings} that are not present in
{@code recoveredExchanges}, adding recovered exchanges to the {@code recoveredExchanges}.
"""
if (config.isExchangeRecoveryEnabled() && queueBindings != null)
synchronized (queueBindings) {
for (Binding queueBinding : queueBindings) {
String exchangeName = queueBinding.source;
if (recoveredExchanges.add(exchangeName)) {
ResourceDeclaration exchangeDeclaration = connectionHandler.exchangeDeclarations.get(exchangeName);
if (exchangeDeclaration != null)
recoverExchange(exchangeName, exchangeDeclaration);
recoverExchangeBindings(connectionHandler.exchangeBindings.get(exchangeName));
}
}
}
}
|
java
|
private void recoverRelatedExchanges(Set<String> recoveredExchanges, List<Binding> queueBindings)
throws Exception {
if (config.isExchangeRecoveryEnabled() && queueBindings != null)
synchronized (queueBindings) {
for (Binding queueBinding : queueBindings) {
String exchangeName = queueBinding.source;
if (recoveredExchanges.add(exchangeName)) {
ResourceDeclaration exchangeDeclaration = connectionHandler.exchangeDeclarations.get(exchangeName);
if (exchangeDeclaration != null)
recoverExchange(exchangeName, exchangeDeclaration);
recoverExchangeBindings(connectionHandler.exchangeBindings.get(exchangeName));
}
}
}
}
|
[
"private",
"void",
"recoverRelatedExchanges",
"(",
"Set",
"<",
"String",
">",
"recoveredExchanges",
",",
"List",
"<",
"Binding",
">",
"queueBindings",
")",
"throws",
"Exception",
"{",
"if",
"(",
"config",
".",
"isExchangeRecoveryEnabled",
"(",
")",
"&&",
"queueBindings",
"!=",
"null",
")",
"synchronized",
"(",
"queueBindings",
")",
"{",
"for",
"(",
"Binding",
"queueBinding",
":",
"queueBindings",
")",
"{",
"String",
"exchangeName",
"=",
"queueBinding",
".",
"source",
";",
"if",
"(",
"recoveredExchanges",
".",
"add",
"(",
"exchangeName",
")",
")",
"{",
"ResourceDeclaration",
"exchangeDeclaration",
"=",
"connectionHandler",
".",
"exchangeDeclarations",
".",
"get",
"(",
"exchangeName",
")",
";",
"if",
"(",
"exchangeDeclaration",
"!=",
"null",
")",
"recoverExchange",
"(",
"exchangeName",
",",
"exchangeDeclaration",
")",
";",
"recoverExchangeBindings",
"(",
"connectionHandler",
".",
"exchangeBindings",
".",
"get",
"(",
"exchangeName",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
Recovers exchanges and bindings related to the {@code queueBindings} that are not present in
{@code recoveredExchanges}, adding recovered exchanges to the {@code recoveredExchanges}.
|
[
"Recovers",
"exchanges",
"and",
"bindings",
"related",
"to",
"the",
"{"
] |
train
|
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/ChannelHandler.java#L454-L468
|
Axway/Grapes
|
utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java
|
GrapesClient.postLicense
|
public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
"""
Post a license to the server
@param license
@param user
@param password
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException
"""
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST license";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
}
|
java
|
public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST license";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
}
|
[
"public",
"void",
"postLicense",
"(",
"final",
"License",
"license",
",",
"final",
"String",
"user",
",",
"final",
"String",
"password",
")",
"throws",
"GrapesCommunicationException",
",",
"AuthenticationException",
"{",
"final",
"Client",
"client",
"=",
"getClient",
"(",
"user",
",",
"password",
")",
";",
"final",
"WebResource",
"resource",
"=",
"client",
".",
"resource",
"(",
"serverURL",
")",
".",
"path",
"(",
"RequestUtils",
".",
"licenseResourcePath",
"(",
")",
")",
";",
"final",
"ClientResponse",
"response",
"=",
"resource",
".",
"type",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
".",
"post",
"(",
"ClientResponse",
".",
"class",
",",
"license",
")",
";",
"client",
".",
"destroy",
"(",
")",
";",
"if",
"(",
"ClientResponse",
".",
"Status",
".",
"CREATED",
".",
"getStatusCode",
"(",
")",
"!=",
"response",
".",
"getStatus",
"(",
")",
")",
"{",
"final",
"String",
"message",
"=",
"\"Failed to POST license\"",
";",
"if",
"(",
"LOG",
".",
"isErrorEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"String",
".",
"format",
"(",
"HTTP_STATUS_TEMPLATE_MSG",
",",
"message",
",",
"response",
".",
"getStatus",
"(",
")",
")",
")",
";",
"}",
"throw",
"new",
"GrapesCommunicationException",
"(",
"message",
",",
"response",
".",
"getStatus",
"(",
")",
")",
";",
"}",
"}"
] |
Post a license to the server
@param license
@param user
@param password
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException
|
[
"Post",
"a",
"license",
"to",
"the",
"server"
] |
train
|
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L668-L681
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.invokeMethod
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments)
throws Exception {
"""
Invoke a private or inner class method. This might be useful to test
private methods.
@param <T> the generic type
@param clazz the clazz
@param methodToExecute the method to execute
@param arguments the arguments
@return the t
@throws Exception the exception
"""
return (T) doInvokeMethod(clazz, null, methodToExecute, arguments);
}
|
java
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments)
throws Exception {
return (T) doInvokeMethod(clazz, null, methodToExecute, arguments);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"invokeMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodToExecute",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"return",
"(",
"T",
")",
"doInvokeMethod",
"(",
"clazz",
",",
"null",
",",
"methodToExecute",
",",
"arguments",
")",
";",
"}"
] |
Invoke a private or inner class method. This might be useful to test
private methods.
@param <T> the generic type
@param clazz the clazz
@param methodToExecute the method to execute
@param arguments the arguments
@return the t
@throws Exception the exception
|
[
"Invoke",
"a",
"private",
"or",
"inner",
"class",
"method",
".",
"This",
"might",
"be",
"useful",
"to",
"test",
"private",
"methods",
"."
] |
train
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L793-L797
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/StatefulASActivationStrategy.java
|
StatefulASActivationStrategy.atEnlist
|
@Override
void atEnlist(ContainerTx tx, BeanO bean) {
"""
Overridden to enlist the bean in the current activity session,
if one exists. <p>
This method is called when a user transaction or user activity
session is beginning or ending. An activity session will only
be active for the case where beginSession is being called. <p>
"""
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "atEnlist (" + tx + ", " + bean + ")");
// Get the current ContainerAS
ContainerAS as = ContainerAS.getContainerAS(tx);
// Allow the parent to properly enlist the bean in the transaction.
// Really, just takes a pin, as processTxContextChange did the enlist.
super.atEnlist(tx, bean);
// If there is an AS, then perform any ActivitySession specific stuff...
if (as != null)
{
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "atEnlist : running in AS : " + as);
// Make sure the beanO is associated with the current TX
bean.setContainerTx(tx);
// Enlist the bean with the AS; a no-op if already enlisted.
// Another pin is not needed, nor does one need to be dropped.
//
// Here are the possible scenarios:
// 1 - UAS.beginSession: a pin will have been taken for the method
// call... that becomes the AS pin.
// 2 - UAS completion: AS is not active, AS pin is now the pin
// for the current method call.
// 3 - UTx.begin: either an AS is not present or the bean is already
// enlisted with the AS and pinned. If there is an AS, there is
// no method pin, as atAtivate would not have taken one.
// 4 - UTx completion - if an AS is present, it already has a pin
// and a method pin was not taken. If no AS, then method has
// a pin.
//
// Net is, we must insure the bean is enlisted with the AS, as it
// takes over ownership of one of the pins. If not enlisted here,
// then the next activate will take an extra pin. d655854
as.enlist(bean);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "atEnlist");
}
|
java
|
@Override
void atEnlist(ContainerTx tx, BeanO bean)
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "atEnlist (" + tx + ", " + bean + ")");
// Get the current ContainerAS
ContainerAS as = ContainerAS.getContainerAS(tx);
// Allow the parent to properly enlist the bean in the transaction.
// Really, just takes a pin, as processTxContextChange did the enlist.
super.atEnlist(tx, bean);
// If there is an AS, then perform any ActivitySession specific stuff...
if (as != null)
{
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "atEnlist : running in AS : " + as);
// Make sure the beanO is associated with the current TX
bean.setContainerTx(tx);
// Enlist the bean with the AS; a no-op if already enlisted.
// Another pin is not needed, nor does one need to be dropped.
//
// Here are the possible scenarios:
// 1 - UAS.beginSession: a pin will have been taken for the method
// call... that becomes the AS pin.
// 2 - UAS completion: AS is not active, AS pin is now the pin
// for the current method call.
// 3 - UTx.begin: either an AS is not present or the bean is already
// enlisted with the AS and pinned. If there is an AS, there is
// no method pin, as atAtivate would not have taken one.
// 4 - UTx completion - if an AS is present, it already has a pin
// and a method pin was not taken. If no AS, then method has
// a pin.
//
// Net is, we must insure the bean is enlisted with the AS, as it
// takes over ownership of one of the pins. If not enlisted here,
// then the next activate will take an extra pin. d655854
as.enlist(bean);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "atEnlist");
}
|
[
"@",
"Override",
"void",
"atEnlist",
"(",
"ContainerTx",
"tx",
",",
"BeanO",
"bean",
")",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
";",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"atEnlist (\"",
"+",
"tx",
"+",
"\", \"",
"+",
"bean",
"+",
"\")\"",
")",
";",
"// Get the current ContainerAS",
"ContainerAS",
"as",
"=",
"ContainerAS",
".",
"getContainerAS",
"(",
"tx",
")",
";",
"// Allow the parent to properly enlist the bean in the transaction.",
"// Really, just takes a pin, as processTxContextChange did the enlist.",
"super",
".",
"atEnlist",
"(",
"tx",
",",
"bean",
")",
";",
"// If there is an AS, then perform any ActivitySession specific stuff...",
"if",
"(",
"as",
"!=",
"null",
")",
"{",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"atEnlist : running in AS : \"",
"+",
"as",
")",
";",
"// Make sure the beanO is associated with the current TX",
"bean",
".",
"setContainerTx",
"(",
"tx",
")",
";",
"// Enlist the bean with the AS; a no-op if already enlisted.",
"// Another pin is not needed, nor does one need to be dropped.",
"//",
"// Here are the possible scenarios:",
"// 1 - UAS.beginSession: a pin will have been taken for the method",
"// call... that becomes the AS pin.",
"// 2 - UAS completion: AS is not active, AS pin is now the pin",
"// for the current method call.",
"// 3 - UTx.begin: either an AS is not present or the bean is already",
"// enlisted with the AS and pinned. If there is an AS, there is",
"// no method pin, as atAtivate would not have taken one.",
"// 4 - UTx completion - if an AS is present, it already has a pin",
"// and a method pin was not taken. If no AS, then method has",
"// a pin.",
"//",
"// Net is, we must insure the bean is enlisted with the AS, as it",
"// takes over ownership of one of the pins. If not enlisted here,",
"// then the next activate will take an extra pin. d655854",
"as",
".",
"enlist",
"(",
"bean",
")",
";",
"}",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"exit",
"(",
"tc",
",",
"\"atEnlist\"",
")",
";",
"}"
] |
Overridden to enlist the bean in the current activity session,
if one exists. <p>
This method is called when a user transaction or user activity
session is beginning or ending. An activity session will only
be active for the case where beginSession is being called. <p>
|
[
"Overridden",
"to",
"enlist",
"the",
"bean",
"in",
"the",
"current",
"activity",
"session",
"if",
"one",
"exists",
".",
"<p",
">"
] |
train
|
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/StatefulASActivationStrategy.java#L248-L294
|
tango-controls/JTango
|
server/src/main/java/org/tango/server/servant/DeviceImpl.java
|
DeviceImpl.read_attribute_history_4
|
@Override
public DevAttrHistory_4 read_attribute_history_4(final String attributeName, final int maxSize) throws DevFailed {
"""
read an attribute history. IDL 4 version. The history is filled only be
attribute polling
@param attributeName The attribute to retrieve
@param maxSize The history maximum size returned
@throws DevFailed
"""
MDC.setContextMap(contextMap);
xlogger.entry();
checkInitialization();
deviceMonitoring.startRequest("read_attribute_history_4");
DevAttrHistory_4 result = null;
try {
final AttributeImpl attr = AttributeGetterSetter.getAttribute(attributeName, attributeList);
if (!attr.isPolled()) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_POLLED, attr.getName() + " is not polled");
}
result = attr.getHistory().getAttrHistory4(maxSize);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
}
return result;
}
|
java
|
@Override
public DevAttrHistory_4 read_attribute_history_4(final String attributeName, final int maxSize) throws DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
checkInitialization();
deviceMonitoring.startRequest("read_attribute_history_4");
DevAttrHistory_4 result = null;
try {
final AttributeImpl attr = AttributeGetterSetter.getAttribute(attributeName, attributeList);
if (!attr.isPolled()) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.ATTR_NOT_POLLED, attr.getName() + " is not polled");
}
result = attr.getHistory().getAttrHistory4(maxSize);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
}
return result;
}
|
[
"@",
"Override",
"public",
"DevAttrHistory_4",
"read_attribute_history_4",
"(",
"final",
"String",
"attributeName",
",",
"final",
"int",
"maxSize",
")",
"throws",
"DevFailed",
"{",
"MDC",
".",
"setContextMap",
"(",
"contextMap",
")",
";",
"xlogger",
".",
"entry",
"(",
")",
";",
"checkInitialization",
"(",
")",
";",
"deviceMonitoring",
".",
"startRequest",
"(",
"\"read_attribute_history_4\"",
")",
";",
"DevAttrHistory_4",
"result",
"=",
"null",
";",
"try",
"{",
"final",
"AttributeImpl",
"attr",
"=",
"AttributeGetterSetter",
".",
"getAttribute",
"(",
"attributeName",
",",
"attributeList",
")",
";",
"if",
"(",
"!",
"attr",
".",
"isPolled",
"(",
")",
")",
"{",
"throw",
"DevFailedUtils",
".",
"newDevFailed",
"(",
"ExceptionMessages",
".",
"ATTR_NOT_POLLED",
",",
"attr",
".",
"getName",
"(",
")",
"+",
"\" is not polled\"",
")",
";",
"}",
"result",
"=",
"attr",
".",
"getHistory",
"(",
")",
".",
"getAttrHistory4",
"(",
"maxSize",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"deviceMonitoring",
".",
"addError",
"(",
")",
";",
"if",
"(",
"e",
"instanceof",
"DevFailed",
")",
"{",
"throw",
"(",
"DevFailed",
")",
"e",
";",
"}",
"else",
"{",
"// with CORBA, the stack trace is not visible by the client if",
"// not inserted in DevFailed.",
"throw",
"DevFailedUtils",
".",
"newDevFailed",
"(",
"e",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
read an attribute history. IDL 4 version. The history is filled only be
attribute polling
@param attributeName The attribute to retrieve
@param maxSize The history maximum size returned
@throws DevFailed
|
[
"read",
"an",
"attribute",
"history",
".",
"IDL",
"4",
"version",
".",
"The",
"history",
"is",
"filled",
"only",
"be",
"attribute",
"polling"
] |
train
|
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L961-L985
|
alkacon/opencms-core
|
src/org/opencms/workplace/CmsWorkplace.java
|
CmsWorkplace.pageHtmlStyle
|
public String pageHtmlStyle(int segment, String title, String stylesheet) {
"""
Returns the default html for a workplace page, including setting of DOCTYPE and
inserting a header with the content-type, allowing the selection of an individual style sheet.<p>
@param segment the HTML segment (START / END)
@param title the title of the page, if null no title tag is inserted
@param stylesheet the used style sheet, if null the default stylesheet 'workplace.css' is inserted
@return the default html for a workplace page
"""
if (segment == HTML_START) {
StringBuffer result = new StringBuffer(512);
result.append("<!DOCTYPE html>\n");
result.append("<html>\n<head>\n");
if (title != null) {
result.append("<title>");
result.append(title);
result.append("</title>\n");
}
result.append("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=");
result.append(getEncoding());
result.append("\">\n");
result.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
result.append(getStyleUri(getJsp(), stylesheet == null ? "workplace.css" : stylesheet));
result.append("\">\n");
return result.toString();
} else {
return "</html>";
}
}
|
java
|
public String pageHtmlStyle(int segment, String title, String stylesheet) {
if (segment == HTML_START) {
StringBuffer result = new StringBuffer(512);
result.append("<!DOCTYPE html>\n");
result.append("<html>\n<head>\n");
if (title != null) {
result.append("<title>");
result.append(title);
result.append("</title>\n");
}
result.append("<meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=");
result.append(getEncoding());
result.append("\">\n");
result.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
result.append(getStyleUri(getJsp(), stylesheet == null ? "workplace.css" : stylesheet));
result.append("\">\n");
return result.toString();
} else {
return "</html>";
}
}
|
[
"public",
"String",
"pageHtmlStyle",
"(",
"int",
"segment",
",",
"String",
"title",
",",
"String",
"stylesheet",
")",
"{",
"if",
"(",
"segment",
"==",
"HTML_START",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"512",
")",
";",
"result",
".",
"append",
"(",
"\"<!DOCTYPE html>\\n\"",
")",
";",
"result",
".",
"append",
"(",
"\"<html>\\n<head>\\n\"",
")",
";",
"if",
"(",
"title",
"!=",
"null",
")",
"{",
"result",
".",
"append",
"(",
"\"<title>\"",
")",
";",
"result",
".",
"append",
"(",
"title",
")",
";",
"result",
".",
"append",
"(",
"\"</title>\\n\"",
")",
";",
"}",
"result",
".",
"append",
"(",
"\"<meta HTTP-EQUIV=\\\"Content-Type\\\" CONTENT=\\\"text/html; charset=\"",
")",
";",
"result",
".",
"append",
"(",
"getEncoding",
"(",
")",
")",
";",
"result",
".",
"append",
"(",
"\"\\\">\\n\"",
")",
";",
"result",
".",
"append",
"(",
"\"<link rel=\\\"stylesheet\\\" type=\\\"text/css\\\" href=\\\"\"",
")",
";",
"result",
".",
"append",
"(",
"getStyleUri",
"(",
"getJsp",
"(",
")",
",",
"stylesheet",
"==",
"null",
"?",
"\"workplace.css\"",
":",
"stylesheet",
")",
")",
";",
"result",
".",
"append",
"(",
"\"\\\">\\n\"",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"\"</html>\"",
";",
"}",
"}"
] |
Returns the default html for a workplace page, including setting of DOCTYPE and
inserting a header with the content-type, allowing the selection of an individual style sheet.<p>
@param segment the HTML segment (START / END)
@param title the title of the page, if null no title tag is inserted
@param stylesheet the used style sheet, if null the default stylesheet 'workplace.css' is inserted
@return the default html for a workplace page
|
[
"Returns",
"the",
"default",
"html",
"for",
"a",
"workplace",
"page",
"including",
"setting",
"of",
"DOCTYPE",
"and",
"inserting",
"a",
"header",
"with",
"the",
"content",
"-",
"type",
"allowing",
"the",
"selection",
"of",
"an",
"individual",
"style",
"sheet",
".",
"<p",
">"
] |
train
|
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplace.java#L1991-L2013
|
JodaOrg/joda-beans
|
src/main/java/org/joda/beans/ser/CollectSerIteratorFactory.java
|
CollectSerIteratorFactory.createIterable
|
@Override
public SerIterable createIterable(final MetaProperty<?> prop, Class<?> beanClass) {
"""
Creates an iterator wrapper for a meta-property value.
@param prop the meta-property defining the value, not null
@param beanClass the class of the bean, not the meta-property, for better generics, not null
@return the iterator, null if not a collection-like type
"""
if (Grid.class.isAssignableFrom(prop.propertyType())) {
Class<?> valueType = JodaBeanUtils.collectionType(prop, beanClass);
List<Class<?>> valueTypeTypes = JodaBeanUtils.collectionTypeTypes(prop, beanClass);
return grid(valueType, valueTypeTypes);
}
return super.createIterable(prop, beanClass);
}
|
java
|
@Override
public SerIterable createIterable(final MetaProperty<?> prop, Class<?> beanClass) {
if (Grid.class.isAssignableFrom(prop.propertyType())) {
Class<?> valueType = JodaBeanUtils.collectionType(prop, beanClass);
List<Class<?>> valueTypeTypes = JodaBeanUtils.collectionTypeTypes(prop, beanClass);
return grid(valueType, valueTypeTypes);
}
return super.createIterable(prop, beanClass);
}
|
[
"@",
"Override",
"public",
"SerIterable",
"createIterable",
"(",
"final",
"MetaProperty",
"<",
"?",
">",
"prop",
",",
"Class",
"<",
"?",
">",
"beanClass",
")",
"{",
"if",
"(",
"Grid",
".",
"class",
".",
"isAssignableFrom",
"(",
"prop",
".",
"propertyType",
"(",
")",
")",
")",
"{",
"Class",
"<",
"?",
">",
"valueType",
"=",
"JodaBeanUtils",
".",
"collectionType",
"(",
"prop",
",",
"beanClass",
")",
";",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"valueTypeTypes",
"=",
"JodaBeanUtils",
".",
"collectionTypeTypes",
"(",
"prop",
",",
"beanClass",
")",
";",
"return",
"grid",
"(",
"valueType",
",",
"valueTypeTypes",
")",
";",
"}",
"return",
"super",
".",
"createIterable",
"(",
"prop",
",",
"beanClass",
")",
";",
"}"
] |
Creates an iterator wrapper for a meta-property value.
@param prop the meta-property defining the value, not null
@param beanClass the class of the bean, not the meta-property, for better generics, not null
@return the iterator, null if not a collection-like type
|
[
"Creates",
"an",
"iterator",
"wrapper",
"for",
"a",
"meta",
"-",
"property",
"value",
"."
] |
train
|
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/CollectSerIteratorFactory.java#L100-L108
|
moparisthebest/beehive
|
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlImplementation.java
|
AptControlImplementation.initClients
|
protected ArrayList<AptClientField> initClients() {
"""
Initializes the list of ClientFields declared directly by this ControlImpl
"""
ArrayList<AptClientField> clients = new ArrayList<AptClientField>();
if ( _implDecl == null || _implDecl.getFields() == null )
return clients;
Collection<FieldDeclaration> declaredFields = _implDecl.getFields();
for (FieldDeclaration fieldDecl : declaredFields)
{
if (fieldDecl.getAnnotation(Client.class) != null)
clients.add(new AptClientField(this, fieldDecl));
}
return clients;
}
|
java
|
protected ArrayList<AptClientField> initClients()
{
ArrayList<AptClientField> clients = new ArrayList<AptClientField>();
if ( _implDecl == null || _implDecl.getFields() == null )
return clients;
Collection<FieldDeclaration> declaredFields = _implDecl.getFields();
for (FieldDeclaration fieldDecl : declaredFields)
{
if (fieldDecl.getAnnotation(Client.class) != null)
clients.add(new AptClientField(this, fieldDecl));
}
return clients;
}
|
[
"protected",
"ArrayList",
"<",
"AptClientField",
">",
"initClients",
"(",
")",
"{",
"ArrayList",
"<",
"AptClientField",
">",
"clients",
"=",
"new",
"ArrayList",
"<",
"AptClientField",
">",
"(",
")",
";",
"if",
"(",
"_implDecl",
"==",
"null",
"||",
"_implDecl",
".",
"getFields",
"(",
")",
"==",
"null",
")",
"return",
"clients",
";",
"Collection",
"<",
"FieldDeclaration",
">",
"declaredFields",
"=",
"_implDecl",
".",
"getFields",
"(",
")",
";",
"for",
"(",
"FieldDeclaration",
"fieldDecl",
":",
"declaredFields",
")",
"{",
"if",
"(",
"fieldDecl",
".",
"getAnnotation",
"(",
"Client",
".",
"class",
")",
"!=",
"null",
")",
"clients",
".",
"add",
"(",
"new",
"AptClientField",
"(",
"this",
",",
"fieldDecl",
")",
")",
";",
"}",
"return",
"clients",
";",
"}"
] |
Initializes the list of ClientFields declared directly by this ControlImpl
|
[
"Initializes",
"the",
"list",
"of",
"ClientFields",
"declared",
"directly",
"by",
"this",
"ControlImpl"
] |
train
|
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptControlImplementation.java#L188-L202
|
elibom/jogger
|
src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java
|
AbstractFileRoutesLoader.isValidCharForPath
|
private boolean isValidCharForPath(char c, boolean openedKey) {
"""
Helper method. Tells if a char is valid in a the path of a route line.
@param c the char that we are validating.
@param openedKey if there is already an opened key ({) char before.
@return true if the char is valid, false otherwise.
"""
char[] invalidChars = { '?', '#', ' ' };
for (char invalidChar : invalidChars) {
if (c == invalidChar) {
return false;
}
}
if (openedKey) {
char[] moreInvalidChars = { '/', '{' };
for (char invalidChar : moreInvalidChars) {
if (c == invalidChar) {
return false;
}
}
}
return true;
}
|
java
|
private boolean isValidCharForPath(char c, boolean openedKey) {
char[] invalidChars = { '?', '#', ' ' };
for (char invalidChar : invalidChars) {
if (c == invalidChar) {
return false;
}
}
if (openedKey) {
char[] moreInvalidChars = { '/', '{' };
for (char invalidChar : moreInvalidChars) {
if (c == invalidChar) {
return false;
}
}
}
return true;
}
|
[
"private",
"boolean",
"isValidCharForPath",
"(",
"char",
"c",
",",
"boolean",
"openedKey",
")",
"{",
"char",
"[",
"]",
"invalidChars",
"=",
"{",
"'",
"'",
",",
"'",
"'",
",",
"'",
"'",
"}",
";",
"for",
"(",
"char",
"invalidChar",
":",
"invalidChars",
")",
"{",
"if",
"(",
"c",
"==",
"invalidChar",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"openedKey",
")",
"{",
"char",
"[",
"]",
"moreInvalidChars",
"=",
"{",
"'",
"'",
",",
"'",
"'",
"}",
";",
"for",
"(",
"char",
"invalidChar",
":",
"moreInvalidChars",
")",
"{",
"if",
"(",
"c",
"==",
"invalidChar",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] |
Helper method. Tells if a char is valid in a the path of a route line.
@param c the char that we are validating.
@param openedKey if there is already an opened key ({) char before.
@return true if the char is valid, false otherwise.
|
[
"Helper",
"method",
".",
"Tells",
"if",
"a",
"char",
"is",
"valid",
"in",
"a",
"the",
"path",
"of",
"a",
"route",
"line",
"."
] |
train
|
https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java#L201-L219
|
google/closure-compiler
|
src/com/google/javascript/jscomp/TypeValidator.java
|
TypeValidator.expectValidAsyncReturnType
|
void expectValidAsyncReturnType(Node n, JSType type) {
"""
Expect the type to be a supertype of `Promise`.
<p>`Promise` is the <em>lower</em> bound of the declared return type, since that's what async
functions always return; the user can't return an instance of a more specific type.
"""
if (promiseOfUnknownType.isSubtypeOf(type)) {
return;
}
JSError err = JSError.make(n, INVALID_ASYNC_RETURN_TYPE, type.toString());
registerMismatch(type, promiseOfUnknownType, err);
report(err);
}
|
java
|
void expectValidAsyncReturnType(Node n, JSType type) {
if (promiseOfUnknownType.isSubtypeOf(type)) {
return;
}
JSError err = JSError.make(n, INVALID_ASYNC_RETURN_TYPE, type.toString());
registerMismatch(type, promiseOfUnknownType, err);
report(err);
}
|
[
"void",
"expectValidAsyncReturnType",
"(",
"Node",
"n",
",",
"JSType",
"type",
")",
"{",
"if",
"(",
"promiseOfUnknownType",
".",
"isSubtypeOf",
"(",
"type",
")",
")",
"{",
"return",
";",
"}",
"JSError",
"err",
"=",
"JSError",
".",
"make",
"(",
"n",
",",
"INVALID_ASYNC_RETURN_TYPE",
",",
"type",
".",
"toString",
"(",
")",
")",
";",
"registerMismatch",
"(",
"type",
",",
"promiseOfUnknownType",
",",
"err",
")",
";",
"report",
"(",
"err",
")",
";",
"}"
] |
Expect the type to be a supertype of `Promise`.
<p>`Promise` is the <em>lower</em> bound of the declared return type, since that's what async
functions always return; the user can't return an instance of a more specific type.
|
[
"Expect",
"the",
"type",
"to",
"be",
"a",
"supertype",
"of",
"Promise",
"."
] |
train
|
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeValidator.java#L342-L350
|
Ordinastie/MalisisCore
|
src/main/java/net/malisis/core/registry/ClientRegistry.java
|
ClientRegistry.getBlockRendererOverride
|
private IBlockRenderer getBlockRendererOverride(IBlockAccess world, BlockPos pos, IBlockState state) {
"""
Gets the {@link BlockRendererOverride} for the {@link IBlockState} at the {@link BlockPos}.
@param world the world
@param pos the pos
@param state the state
@return the block renderer override
"""
for (BlockRendererOverride overrides : blockRendererOverrides)
{
IBlockRenderer renderer = overrides.get(world, pos, state);
if (renderer != null)
return renderer;
}
return null;
}
|
java
|
private IBlockRenderer getBlockRendererOverride(IBlockAccess world, BlockPos pos, IBlockState state)
{
for (BlockRendererOverride overrides : blockRendererOverrides)
{
IBlockRenderer renderer = overrides.get(world, pos, state);
if (renderer != null)
return renderer;
}
return null;
}
|
[
"private",
"IBlockRenderer",
"getBlockRendererOverride",
"(",
"IBlockAccess",
"world",
",",
"BlockPos",
"pos",
",",
"IBlockState",
"state",
")",
"{",
"for",
"(",
"BlockRendererOverride",
"overrides",
":",
"blockRendererOverrides",
")",
"{",
"IBlockRenderer",
"renderer",
"=",
"overrides",
".",
"get",
"(",
"world",
",",
"pos",
",",
"state",
")",
";",
"if",
"(",
"renderer",
"!=",
"null",
")",
"return",
"renderer",
";",
"}",
"return",
"null",
";",
"}"
] |
Gets the {@link BlockRendererOverride} for the {@link IBlockState} at the {@link BlockPos}.
@param world the world
@param pos the pos
@param state the state
@return the block renderer override
|
[
"Gets",
"the",
"{",
"@link",
"BlockRendererOverride",
"}",
"for",
"the",
"{",
"@link",
"IBlockState",
"}",
"at",
"the",
"{",
"@link",
"BlockPos",
"}",
"."
] |
train
|
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/registry/ClientRegistry.java#L260-L270
|
samskivert/samskivert
|
src/main/java/com/samskivert/util/CollectionUtil.java
|
CollectionUtil.addAll
|
@ReplacedBy("com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))")
public static <T, C extends Collection<T>> C addAll (C col, Enumeration<? extends T> enm) {
"""
Adds all items returned by the enumeration to the supplied collection
and returns the supplied collection.
"""
while (enm.hasMoreElements()) {
col.add(enm.nextElement());
}
return col;
}
|
java
|
@ReplacedBy("com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))")
public static <T, C extends Collection<T>> C addAll (C col, Enumeration<? extends T> enm)
{
while (enm.hasMoreElements()) {
col.add(enm.nextElement());
}
return col;
}
|
[
"@",
"ReplacedBy",
"(",
"\"com.google.common.collect.Iterators#addAll(Collection, com.google.common.collect.Iterators#forEnumeration(Enumeration))\"",
")",
"public",
"static",
"<",
"T",
",",
"C",
"extends",
"Collection",
"<",
"T",
">",
">",
"C",
"addAll",
"(",
"C",
"col",
",",
"Enumeration",
"<",
"?",
"extends",
"T",
">",
"enm",
")",
"{",
"while",
"(",
"enm",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"col",
".",
"add",
"(",
"enm",
".",
"nextElement",
"(",
")",
")",
";",
"}",
"return",
"col",
";",
"}"
] |
Adds all items returned by the enumeration to the supplied collection
and returns the supplied collection.
|
[
"Adds",
"all",
"items",
"returned",
"by",
"the",
"enumeration",
"to",
"the",
"supplied",
"collection",
"and",
"returns",
"the",
"supplied",
"collection",
"."
] |
train
|
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/CollectionUtil.java#L30-L37
|
lestard/advanced-bindings
|
src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java
|
MathBindings.subtractExact
|
public static IntegerBinding subtractExact(final int x, final ObservableIntegerValue y) {
"""
Binding for {@link java.lang.Math#subtractExact(int, int)}
@param x the first value
@param y the second value to subtract from the first
@return the result
@throws ArithmeticException if the result overflows an int
"""
return createIntegerBinding(() -> Math.subtractExact(x, y.get()), y);
}
|
java
|
public static IntegerBinding subtractExact(final int x, final ObservableIntegerValue y) {
return createIntegerBinding(() -> Math.subtractExact(x, y.get()), y);
}
|
[
"public",
"static",
"IntegerBinding",
"subtractExact",
"(",
"final",
"int",
"x",
",",
"final",
"ObservableIntegerValue",
"y",
")",
"{",
"return",
"createIntegerBinding",
"(",
"(",
")",
"->",
"Math",
".",
"subtractExact",
"(",
"x",
",",
"y",
".",
"get",
"(",
")",
")",
",",
"y",
")",
";",
"}"
] |
Binding for {@link java.lang.Math#subtractExact(int, int)}
@param x the first value
@param y the second value to subtract from the first
@return the result
@throws ArithmeticException if the result overflows an int
|
[
"Binding",
"for",
"{",
"@link",
"java",
".",
"lang",
".",
"Math#subtractExact",
"(",
"int",
"int",
")",
"}"
] |
train
|
https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java#L1415-L1417
|
uwolfer/gerrit-rest-java-client
|
src/main/java/com/urswolfer/gerrit/client/rest/http/GerritRestClient.java
|
GerritRestClient.getXsrfCookie
|
private Optional<String> getXsrfCookie() {
"""
In Gerrit >= 2.12 the XSRF token got moved to a cookie.
Introduced in: https://gerrit-review.googlesource.com/72031/
"""
Optional<Cookie> xsrfCookie = findCookie("XSRF_TOKEN");
if (xsrfCookie.isPresent()) {
return Optional.of(xsrfCookie.get().getValue());
}
return Optional.absent();
}
|
java
|
private Optional<String> getXsrfCookie() {
Optional<Cookie> xsrfCookie = findCookie("XSRF_TOKEN");
if (xsrfCookie.isPresent()) {
return Optional.of(xsrfCookie.get().getValue());
}
return Optional.absent();
}
|
[
"private",
"Optional",
"<",
"String",
">",
"getXsrfCookie",
"(",
")",
"{",
"Optional",
"<",
"Cookie",
">",
"xsrfCookie",
"=",
"findCookie",
"(",
"\"XSRF_TOKEN\"",
")",
";",
"if",
"(",
"xsrfCookie",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"xsrfCookie",
".",
"get",
"(",
")",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] |
In Gerrit >= 2.12 the XSRF token got moved to a cookie.
Introduced in: https://gerrit-review.googlesource.com/72031/
|
[
"In",
"Gerrit",
">",
"=",
"2",
".",
"12",
"the",
"XSRF",
"token",
"got",
"moved",
"to",
"a",
"cookie",
".",
"Introduced",
"in",
":",
"https",
":",
"//",
"gerrit",
"-",
"review",
".",
"googlesource",
".",
"com",
"/",
"72031",
"/"
] |
train
|
https://github.com/uwolfer/gerrit-rest-java-client/blob/fa66cd76270cd12cff9e30e0d96826fe0253d209/src/main/java/com/urswolfer/gerrit/client/rest/http/GerritRestClient.java#L349-L355
|
voldemort/voldemort
|
src/java/voldemort/store/quota/QuotaLimitingStore.java
|
QuotaLimitingStore.checkRateLimit
|
private void checkRateLimit(String quotaKey, Tracked trackedOp) {
"""
Ensure the current throughput levels for the tracked operation does not
exceed set quota limits. Throws an exception if exceeded quota.
@param quotaKey
@param trackedOp
"""
String quotaValue = null;
try {
if(!metadataStore.getQuotaEnforcingEnabledUnlocked()) {
return;
}
quotaValue = quotaStore.cacheGet(quotaKey);
// Store may not have any quotas
if(quotaValue == null) {
return;
}
// But, if it does
float currentRate = getThroughput(trackedOp);
float allowedRate = Float.parseFloat(quotaValue);
// TODO the histogram should be reasonably accurate to do all
// these things.. (ghost qps and all)
// Report the current quota usage level
quotaStats.reportQuotaUsed(trackedOp, Utils.safeGetPercentage(currentRate, allowedRate));
// check if we have exceeded rate.
if(currentRate > allowedRate) {
quotaStats.reportRateLimitedOp(trackedOp);
throw new QuotaExceededException("Exceeded rate limit for " + quotaKey
+ ". Maximum allowed : " + allowedRate
+ " Current: " + currentRate);
}
} catch(NumberFormatException nfe) {
// move on, if we cannot parse quota value properly
logger.debug("Invalid formatting of quota value for key " + quotaKey + " : "
+ quotaValue);
}
}
|
java
|
private void checkRateLimit(String quotaKey, Tracked trackedOp) {
String quotaValue = null;
try {
if(!metadataStore.getQuotaEnforcingEnabledUnlocked()) {
return;
}
quotaValue = quotaStore.cacheGet(quotaKey);
// Store may not have any quotas
if(quotaValue == null) {
return;
}
// But, if it does
float currentRate = getThroughput(trackedOp);
float allowedRate = Float.parseFloat(quotaValue);
// TODO the histogram should be reasonably accurate to do all
// these things.. (ghost qps and all)
// Report the current quota usage level
quotaStats.reportQuotaUsed(trackedOp, Utils.safeGetPercentage(currentRate, allowedRate));
// check if we have exceeded rate.
if(currentRate > allowedRate) {
quotaStats.reportRateLimitedOp(trackedOp);
throw new QuotaExceededException("Exceeded rate limit for " + quotaKey
+ ". Maximum allowed : " + allowedRate
+ " Current: " + currentRate);
}
} catch(NumberFormatException nfe) {
// move on, if we cannot parse quota value properly
logger.debug("Invalid formatting of quota value for key " + quotaKey + " : "
+ quotaValue);
}
}
|
[
"private",
"void",
"checkRateLimit",
"(",
"String",
"quotaKey",
",",
"Tracked",
"trackedOp",
")",
"{",
"String",
"quotaValue",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"!",
"metadataStore",
".",
"getQuotaEnforcingEnabledUnlocked",
"(",
")",
")",
"{",
"return",
";",
"}",
"quotaValue",
"=",
"quotaStore",
".",
"cacheGet",
"(",
"quotaKey",
")",
";",
"// Store may not have any quotas",
"if",
"(",
"quotaValue",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// But, if it does",
"float",
"currentRate",
"=",
"getThroughput",
"(",
"trackedOp",
")",
";",
"float",
"allowedRate",
"=",
"Float",
".",
"parseFloat",
"(",
"quotaValue",
")",
";",
"// TODO the histogram should be reasonably accurate to do all",
"// these things.. (ghost qps and all)",
"// Report the current quota usage level",
"quotaStats",
".",
"reportQuotaUsed",
"(",
"trackedOp",
",",
"Utils",
".",
"safeGetPercentage",
"(",
"currentRate",
",",
"allowedRate",
")",
")",
";",
"// check if we have exceeded rate.",
"if",
"(",
"currentRate",
">",
"allowedRate",
")",
"{",
"quotaStats",
".",
"reportRateLimitedOp",
"(",
"trackedOp",
")",
";",
"throw",
"new",
"QuotaExceededException",
"(",
"\"Exceeded rate limit for \"",
"+",
"quotaKey",
"+",
"\". Maximum allowed : \"",
"+",
"allowedRate",
"+",
"\" Current: \"",
"+",
"currentRate",
")",
";",
"}",
"}",
"catch",
"(",
"NumberFormatException",
"nfe",
")",
"{",
"// move on, if we cannot parse quota value properly",
"logger",
".",
"debug",
"(",
"\"Invalid formatting of quota value for key \"",
"+",
"quotaKey",
"+",
"\" : \"",
"+",
"quotaValue",
")",
";",
"}",
"}"
] |
Ensure the current throughput levels for the tracked operation does not
exceed set quota limits. Throws an exception if exceeded quota.
@param quotaKey
@param trackedOp
|
[
"Ensure",
"the",
"current",
"throughput",
"levels",
"for",
"the",
"tracked",
"operation",
"does",
"not",
"exceed",
"set",
"quota",
"limits",
".",
"Throws",
"an",
"exception",
"if",
"exceeded",
"quota",
"."
] |
train
|
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/quota/QuotaLimitingStore.java#L88-L120
|
contentful/contentful.java
|
src/main/java/com/contentful/java/cda/LocalizedResource.java
|
LocalizedResource.getField
|
public <T> T getField(String locale, String key) {
"""
Extracts a field from the fields set of the active locale, result type is inferred.
@param locale locale to be used.
@param key field key.
@param <T> type.
@return field value, null if it doesn't exist.
"""
return localize(locale).getField(key);
}
|
java
|
public <T> T getField(String locale, String key) {
return localize(locale).getField(key);
}
|
[
"public",
"<",
"T",
">",
"T",
"getField",
"(",
"String",
"locale",
",",
"String",
"key",
")",
"{",
"return",
"localize",
"(",
"locale",
")",
".",
"getField",
"(",
"key",
")",
";",
"}"
] |
Extracts a field from the fields set of the active locale, result type is inferred.
@param locale locale to be used.
@param key field key.
@param <T> type.
@return field value, null if it doesn't exist.
|
[
"Extracts",
"a",
"field",
"from",
"the",
"fields",
"set",
"of",
"the",
"active",
"locale",
"result",
"type",
"is",
"inferred",
"."
] |
train
|
https://github.com/contentful/contentful.java/blob/6ecc2ace454c674b218b99489dc50697b1dbffcb/src/main/java/com/contentful/java/cda/LocalizedResource.java#L87-L89
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.