repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/HystrixRequestCache.java
HystrixRequestCache.getRequestCacheKey
private ValueCacheKey getRequestCacheKey(String cacheKey) { if (cacheKey != null) { /* create the cache key we will use to retrieve/store that include the type key prefix */ return new ValueCacheKey(rcKey, cacheKey); } return null; }
java
private ValueCacheKey getRequestCacheKey(String cacheKey) { if (cacheKey != null) { /* create the cache key we will use to retrieve/store that include the type key prefix */ return new ValueCacheKey(rcKey, cacheKey); } return null; }
[ "private", "ValueCacheKey", "getRequestCacheKey", "(", "String", "cacheKey", ")", "{", "if", "(", "cacheKey", "!=", "null", ")", "{", "/* create the cache key we will use to retrieve/store that include the type key prefix */", "return", "new", "ValueCacheKey", "(", "rcKey", ...
Request CacheKey: HystrixRequestCache.prefix + concurrencyStrategy + HystrixCommand.getCacheKey (as injected via get/put to this class) <p> We prefix with {@link HystrixCommandKey} or {@link HystrixCollapserKey} since the cache is heterogeneous and we don't want to accidentally return cached Futures from different types. @return ValueCacheKey
[ "Request", "CacheKey", ":", "HystrixRequestCache", ".", "prefix", "+", "concurrencyStrategy", "+", "HystrixCommand", ".", "getCacheKey", "(", "as", "injected", "via", "get", "/", "put", "to", "this", "class", ")", "<p", ">", "We", "prefix", "with", "{", "@li...
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/HystrixRequestCache.java#L171-L177
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/SmartTable.java
SmartTable.setHTML
public void setHTML (int row, int column, String text, int colSpan, String... styles) { setHTML(row, column, text); if (colSpan > 0) { getFlexCellFormatter().setColSpan(row, column, colSpan); } setStyleNames(row, column, styles); }
java
public void setHTML (int row, int column, String text, int colSpan, String... styles) { setHTML(row, column, text); if (colSpan > 0) { getFlexCellFormatter().setColSpan(row, column, colSpan); } setStyleNames(row, column, styles); }
[ "public", "void", "setHTML", "(", "int", "row", ",", "int", "column", ",", "String", "text", ",", "int", "colSpan", ",", "String", "...", "styles", ")", "{", "setHTML", "(", "row", ",", "column", ",", "text", ")", ";", "if", "(", "colSpan", ">", "0...
Sets the HTML in the specified cell, with the specified style and column span.
[ "Sets", "the", "HTML", "in", "the", "specified", "cell", "with", "the", "specified", "style", "and", "column", "span", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/SmartTable.java#L282-L289
gwtbootstrap3/gwtbootstrap3
gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/ScrollSpy.java
ScrollSpy.scrollSpy
public static ScrollSpy scrollSpy(final UIObject spyOn, final String selector) { return new ScrollSpy(spyOn.getElement(), selector); }
java
public static ScrollSpy scrollSpy(final UIObject spyOn, final String selector) { return new ScrollSpy(spyOn.getElement(), selector); }
[ "public", "static", "ScrollSpy", "scrollSpy", "(", "final", "UIObject", "spyOn", ",", "final", "String", "selector", ")", "{", "return", "new", "ScrollSpy", "(", "spyOn", ".", "getElement", "(", ")", ",", "selector", ")", ";", "}" ]
Attaches ScrollSpy to specified object with specified target selector. @param spyOn Spy on this object @param selector CSS selector of target element @return ScrollSpy
[ "Attaches", "ScrollSpy", "to", "specified", "object", "with", "specified", "target", "selector", "." ]
train
https://github.com/gwtbootstrap3/gwtbootstrap3/blob/54bdbd0b12ba7a436b278c007df960d1adf2e641/gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/ScrollSpy.java#L86-L88
HeidelTime/heideltime
src/de/unihd/dbs/uima/annotator/heideltime/utilities/Logger.java
Logger.printError
public static void printError(Class<?> c, String msg) { String preamble; if(c != null) preamble = "["+c.getSimpleName()+"]"; else preamble = ""; synchronized(System.err) { System.err.println(preamble+" "+msg); } }
java
public static void printError(Class<?> c, String msg) { String preamble; if(c != null) preamble = "["+c.getSimpleName()+"]"; else preamble = ""; synchronized(System.err) { System.err.println(preamble+" "+msg); } }
[ "public", "static", "void", "printError", "(", "Class", "<", "?", ">", "c", ",", "String", "msg", ")", "{", "String", "preamble", ";", "if", "(", "c", "!=", "null", ")", "preamble", "=", "\"[\"", "+", "c", ".", "getSimpleName", "(", ")", "+", "\"]\...
print an ERROR-Level message with package name @param component Component from which the message originates @param msg ERROR-Level message
[ "print", "an", "ERROR", "-", "Level", "message", "with", "package", "name" ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/utilities/Logger.java#L54-L64
jqno/equalsverifier
src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/Cache.java
Cache.put
public <T> void put(TypeTag tag, T red, T black, T redCopy) { cache.put(tag, new Tuple<>(red, black, redCopy)); }
java
public <T> void put(TypeTag tag, T red, T black, T redCopy) { cache.put(tag, new Tuple<>(red, black, redCopy)); }
[ "public", "<", "T", ">", "void", "put", "(", "TypeTag", "tag", ",", "T", "red", ",", "T", "black", ",", "T", "redCopy", ")", "{", "cache", ".", "put", "(", "tag", ",", "new", "Tuple", "<>", "(", "red", ",", "black", ",", "redCopy", ")", ")", ...
Adds a prefabricated value to the cache for the given type. @param tag A description of the type. Takes generics into account. @param red A "red" value for the given type. @param black A "black" value for the given type. @param redCopy A shallow copy of the given red value.
[ "Adds", "a", "prefabricated", "value", "to", "the", "cache", "for", "the", "given", "type", "." ]
train
https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/Cache.java#L21-L23
elki-project/elki
elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java
DBIDUtil.intersectionSize
public static int intersectionSize(DBIDs first, DBIDs second) { // If exactly one is a Set, use it as second parameter. if(second instanceof SetDBIDs) { if(!(first instanceof SetDBIDs)) { return internalIntersectionSize(first, second); } } else if(first instanceof SetDBIDs) { return internalIntersectionSize(second, first); } // Both are the same type: both set or both non set. // Smaller goes first. return first.size() <= second.size() ? internalIntersectionSize(first, second) : internalIntersectionSize(second, first); }
java
public static int intersectionSize(DBIDs first, DBIDs second) { // If exactly one is a Set, use it as second parameter. if(second instanceof SetDBIDs) { if(!(first instanceof SetDBIDs)) { return internalIntersectionSize(first, second); } } else if(first instanceof SetDBIDs) { return internalIntersectionSize(second, first); } // Both are the same type: both set or both non set. // Smaller goes first. return first.size() <= second.size() ? internalIntersectionSize(first, second) : internalIntersectionSize(second, first); }
[ "public", "static", "int", "intersectionSize", "(", "DBIDs", "first", ",", "DBIDs", "second", ")", "{", "// If exactly one is a Set, use it as second parameter.", "if", "(", "second", "instanceof", "SetDBIDs", ")", "{", "if", "(", "!", "(", "first", "instanceof", ...
Compute the set intersection size of two sets. @param first First set @param second Second set @return size
[ "Compute", "the", "set", "intersection", "size", "of", "two", "sets", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L332-L345
quattor/pan
panc/src/main/java/org/quattor/pan/dml/data/AbstractElement.java
AbstractElement.rgetList
public ListResource rgetList(Term[] terms, int index) throws InvalidTermException { throw new EvaluationException(MessageUtils.format( MSG_ILLEGAL_DEREFERENCE, this.getTypeAsString())); }
java
public ListResource rgetList(Term[] terms, int index) throws InvalidTermException { throw new EvaluationException(MessageUtils.format( MSG_ILLEGAL_DEREFERENCE, this.getTypeAsString())); }
[ "public", "ListResource", "rgetList", "(", "Term", "[", "]", "terms", ",", "int", "index", ")", "throws", "InvalidTermException", "{", "throw", "new", "EvaluationException", "(", "MessageUtils", ".", "format", "(", "MSG_ILLEGAL_DEREFERENCE", ",", "this", ".", "g...
This is a special lookup function that will retrieve a list from the resource. If the resource does not exist, an empty list will be created. All necessary parent resources are created. The returned list is guaranteed to be a writable resource. @param terms list of terms to use for dereference @param index the term to use in the given list of term @return writable list
[ "This", "is", "a", "special", "lookup", "function", "that", "will", "retrieve", "a", "list", "from", "the", "resource", ".", "If", "the", "resource", "does", "not", "exist", "an", "empty", "list", "will", "be", "created", ".", "All", "necessary", "parent",...
train
https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/dml/data/AbstractElement.java#L240-L244
looly/hutool
hutool-core/src/main/java/cn/hutool/core/exceptions/ExceptionUtil.java
ExceptionUtil.isFromOrSuppressedThrowable
public static boolean isFromOrSuppressedThrowable(Throwable throwable, Class<? extends Throwable> exceptionClass, boolean checkCause) { return convertFromOrSuppressedThrowable(throwable, exceptionClass, checkCause) != null; }
java
public static boolean isFromOrSuppressedThrowable(Throwable throwable, Class<? extends Throwable> exceptionClass, boolean checkCause) { return convertFromOrSuppressedThrowable(throwable, exceptionClass, checkCause) != null; }
[ "public", "static", "boolean", "isFromOrSuppressedThrowable", "(", "Throwable", "throwable", ",", "Class", "<", "?", "extends", "Throwable", ">", "exceptionClass", ",", "boolean", "checkCause", ")", "{", "return", "convertFromOrSuppressedThrowable", "(", "throwable", ...
判断指定异常是否来自或者包含指定异常 @param throwable 异常 @param exceptionClass 定义的引起异常的类 @param checkCause 判断cause @return true 来自或者包含 @since 4.4.1
[ "判断指定异常是否来自或者包含指定异常" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/exceptions/ExceptionUtil.java#L269-L271
JadiraOrg/jadira
jms/src/main/java/org/jadira/jms/template/BatchedJmsTemplate.java
BatchedJmsTemplate.receiveSelectedAndConvertBatch
public List<Object> receiveSelectedAndConvertBatch(String destinationName, String messageSelector) throws JmsException { return receiveSelectedAndConvertBatch(destinationName, messageSelector, getBatchSize()); }
java
public List<Object> receiveSelectedAndConvertBatch(String destinationName, String messageSelector) throws JmsException { return receiveSelectedAndConvertBatch(destinationName, messageSelector, getBatchSize()); }
[ "public", "List", "<", "Object", ">", "receiveSelectedAndConvertBatch", "(", "String", "destinationName", ",", "String", "messageSelector", ")", "throws", "JmsException", "{", "return", "receiveSelectedAndConvertBatch", "(", "destinationName", ",", "messageSelector", ",",...
Receive a batch of up to default batch size for given destination name and message selector and convert each message in the batch. Other than batching this method is the same as {@link JmsTemplate#receiveSelectedAndConvert(String, String)} @return A list of {@link Message} @param destinationName The destination name @param messageSelector The Selector @throws JmsException The {@link JmsException}
[ "Receive", "a", "batch", "of", "up", "to", "default", "batch", "size", "for", "given", "destination", "name", "and", "message", "selector", "and", "convert", "each", "message", "in", "the", "batch", ".", "Other", "than", "batching", "this", "method", "is", ...
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/jms/src/main/java/org/jadira/jms/template/BatchedJmsTemplate.java#L413-L416
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/transfer/TransferManager.java
TransferManager.resumeDownload
public Download resumeDownload(PersistableDownload persistableDownload) { assertParameterNotNull(persistableDownload, "PausedDownload is mandatory to resume a download."); GetObjectRequest request = new GetObjectRequest( persistableDownload.getBucketName(), persistableDownload.getKey(), persistableDownload.getVersionId()); if (persistableDownload.getRange() != null && persistableDownload.getRange().length == 2) { long[] range = persistableDownload.getRange(); request.setRange(range[0], range[1]); } request.setRequesterPays(persistableDownload.isRequesterPays()); request.setResponseHeaders(persistableDownload.getResponseHeaders()); return doDownload(request, new File(persistableDownload.getFile()), null, null, APPEND_MODE, 0, persistableDownload); }
java
public Download resumeDownload(PersistableDownload persistableDownload) { assertParameterNotNull(persistableDownload, "PausedDownload is mandatory to resume a download."); GetObjectRequest request = new GetObjectRequest( persistableDownload.getBucketName(), persistableDownload.getKey(), persistableDownload.getVersionId()); if (persistableDownload.getRange() != null && persistableDownload.getRange().length == 2) { long[] range = persistableDownload.getRange(); request.setRange(range[0], range[1]); } request.setRequesterPays(persistableDownload.isRequesterPays()); request.setResponseHeaders(persistableDownload.getResponseHeaders()); return doDownload(request, new File(persistableDownload.getFile()), null, null, APPEND_MODE, 0, persistableDownload); }
[ "public", "Download", "resumeDownload", "(", "PersistableDownload", "persistableDownload", ")", "{", "assertParameterNotNull", "(", "persistableDownload", ",", "\"PausedDownload is mandatory to resume a download.\"", ")", ";", "GetObjectRequest", "request", "=", "new", "GetObje...
Resumes an download operation. This download operation uses the same configuration as the original download. Any data already fetched will be skipped, and only the remaining data is retrieved from Amazon S3. @param persistableDownload the download to resume. @return A new <code>Download</code> object to use to check the state of the download, listen for progress notifications, and otherwise manage the download. @throws AmazonClientException If any errors are encountered in the client while making the request or handling the response. @throws AmazonServiceException If any errors occurred in Amazon S3 while processing the request.
[ "Resumes", "an", "download", "operation", ".", "This", "download", "operation", "uses", "the", "same", "configuration", "as", "the", "original", "download", ".", "Any", "data", "already", "fetched", "will", "be", "skipped", "and", "only", "the", "remaining", "...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/transfer/TransferManager.java#L2279-L2296
Waikato/jclasslocator
src/main/java/nz/ac/waikato/cms/locator/ClassLister.java
ClassLister.updateClassnames
protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { if (!list.containsKey(superclass)) { list.put(superclass, names); } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } }
java
protected void updateClassnames(HashMap<String,List<String>> list, String superclass, List<String> names) { if (!list.containsKey(superclass)) { list.put(superclass, names); } else { for (String name: names) { if (!list.get(superclass).contains(name)) list.get(superclass).add(name); } } }
[ "protected", "void", "updateClassnames", "(", "HashMap", "<", "String", ",", "List", "<", "String", ">", ">", "list", ",", "String", "superclass", ",", "List", "<", "String", ">", "names", ")", "{", "if", "(", "!", "list", ".", "containsKey", "(", "sup...
Updates list for the superclass. @param list the list to update @param superclass the superclass @param names the names to add
[ "Updates", "list", "for", "the", "superclass", "." ]
train
https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/ClassLister.java#L233-L243
threerings/playn
core/src/playn/core/gl/GLContext.java
GLContext.pushFramebuffer
public void pushFramebuffer(int fbuf, int width, int height) { assert pushedFramebuffer == -1 : "Already have a pushed framebuffer"; pushedFramebuffer = lastFramebuffer; pushedWidth = curFbufWidth; pushedHeight = curFbufHeight; bindFramebuffer(fbuf, width, height); }
java
public void pushFramebuffer(int fbuf, int width, int height) { assert pushedFramebuffer == -1 : "Already have a pushed framebuffer"; pushedFramebuffer = lastFramebuffer; pushedWidth = curFbufWidth; pushedHeight = curFbufHeight; bindFramebuffer(fbuf, width, height); }
[ "public", "void", "pushFramebuffer", "(", "int", "fbuf", ",", "int", "width", ",", "int", "height", ")", "{", "assert", "pushedFramebuffer", "==", "-", "1", ":", "\"Already have a pushed framebuffer\"", ";", "pushedFramebuffer", "=", "lastFramebuffer", ";", "pushe...
Stores the metadata for the currently bound frame buffer, and binds the supplied framebuffer. This must be followed by a call to {@link #popFramebuffer}. Also, it is not allowed to push a framebuffer if a framebuffer is already pushed. Only one level of nesting is supported.
[ "Stores", "the", "metadata", "for", "the", "currently", "bound", "frame", "buffer", "and", "binds", "the", "supplied", "framebuffer", ".", "This", "must", "be", "followed", "by", "a", "call", "to", "{" ]
train
https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/core/src/playn/core/gl/GLContext.java#L263-L269
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/WikisApi.java
WikisApi.getPage
public WikiPage getPage(Object projectIdOrPath, String slug) throws GitLabApiException { Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "wikis", slug); return (response.readEntity(WikiPage.class)); }
java
public WikiPage getPage(Object projectIdOrPath, String slug) throws GitLabApiException { Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "wikis", slug); return (response.readEntity(WikiPage.class)); }
[ "public", "WikiPage", "getPage", "(", "Object", "projectIdOrPath", ",", "String", "slug", ")", "throws", "GitLabApiException", "{", "Response", "response", "=", "get", "(", "Response", ".", "Status", ".", "OK", ",", "null", ",", "\"projects\"", ",", "getProjec...
Get a single page of project wiki. <pre><code>GitLab Endpoint: GET /projects/:id/wikis/:slug</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param slug the slug of the project's wiki page @return the specified project Snippet @throws GitLabApiException if any exception occurs
[ "Get", "a", "single", "page", "of", "project", "wiki", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/WikisApi.java#L89-L93
Baidu-AIP/java-sdk
src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java
AipImageSearch.productSearchUrl
public JSONObject productSearchUrl(String url, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.PRODUCT_SEARCH); postOperation(request); return requestServer(request); }
java
public JSONObject productSearchUrl(String url, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.PRODUCT_SEARCH); postOperation(request); return requestServer(request); }
[ "public", "JSONObject", "productSearchUrl", "(", "String", "url", ",", "HashMap", "<", "String", ",", "String", ">", "options", ")", "{", "AipRequest", "request", "=", "new", "AipRequest", "(", ")", ";", "preOperation", "(", "request", ")", ";", "request", ...
商品检索—检索接口 完成入库后,可使用该接口实现商品检索。**支持传入指定分类维度(具体变量class_id1、class_id2)进行检索,返回结果支持翻页(具体变量pn、rn)。****请注意,检索接口不返回原图,仅反馈当前填写的brief信息,请调用入库接口时尽量填写可关联至本地图库的图片id或者图片url等信息** @param url - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 @param options - 可选参数对象,key: value都为string类型 options - options列表: class_id1 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 class_id2 商品分类维度1,支持1-60范围内的整数。检索时可圈定该分类维度进行检索 pn 分页功能,起始位置,例:0。未指定分页时,默认返回前300个结果;接口返回数量最大限制1000条,例如:起始位置为900,截取条数500条,接口也只返回第900 - 1000条的结果,共计100条 rn 分页功能,截取条数,例:250 @return JSONObject
[ "商品检索—检索接口", "完成入库后,可使用该接口实现商品检索。", "**", "支持传入指定分类维度(具体变量class_id1、class_id2)进行检索,返回结果支持翻页(具体变量pn、rn)。", "****", "请注意,检索接口不返回原图,仅反馈当前填写的brief信息,请调用入库接口时尽量填写可关联至本地图库的图片id或者图片url等信息", "**" ]
train
https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java#L820-L831
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/triangulate/ResidualsTriangulateProjective.java
ResidualsTriangulateProjective.setObservations
public void setObservations( List<Point2D_F64> observations , List<DMatrixRMaj> cameraMatrices ) { if( observations.size() != cameraMatrices.size() ) throw new IllegalArgumentException("Different size lists"); this.observations = observations; this.cameraMatrices = cameraMatrices; }
java
public void setObservations( List<Point2D_F64> observations , List<DMatrixRMaj> cameraMatrices ) { if( observations.size() != cameraMatrices.size() ) throw new IllegalArgumentException("Different size lists"); this.observations = observations; this.cameraMatrices = cameraMatrices; }
[ "public", "void", "setObservations", "(", "List", "<", "Point2D_F64", ">", "observations", ",", "List", "<", "DMatrixRMaj", ">", "cameraMatrices", ")", "{", "if", "(", "observations", ".", "size", "(", ")", "!=", "cameraMatrices", ".", "size", "(", ")", ")...
Configures inputs. @param observations Observations of the feature at different locations. Pixels. @param cameraMatrices Camera matrices
[ "Configures", "inputs", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/triangulate/ResidualsTriangulateProjective.java#L51-L57
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/fills/GradientFill.java
GradientFill.colorAt
public Color colorAt(float x, float y) { float dx1 = end.getX() - start.getX(); float dy1 = end.getY() - start.getY(); float dx2 = -dy1; float dy2 = dx1; float denom = (dy2 * dx1) - (dx2 * dy1); if (denom == 0) { return Color.black; } float ua = (dx2 * (start.getY() - y)) - (dy2 * (start.getX() - x)); ua /= denom; float ub = (dx1 * (start.getY() - y)) - (dy1 * (start.getX() - x)); ub /= denom; float u = ua; if (u < 0) { u = 0; } if (u > 1) { u = 1; } float v = 1 - u; // u is the proportion down the line we are Color col = new Color(1,1,1,1); col.r = (u * endCol.r) + (v * startCol.r); col.b = (u * endCol.b) + (v * startCol.b); col.g = (u * endCol.g) + (v * startCol.g); col.a = (u * endCol.a) + (v * startCol.a); return col; }
java
public Color colorAt(float x, float y) { float dx1 = end.getX() - start.getX(); float dy1 = end.getY() - start.getY(); float dx2 = -dy1; float dy2 = dx1; float denom = (dy2 * dx1) - (dx2 * dy1); if (denom == 0) { return Color.black; } float ua = (dx2 * (start.getY() - y)) - (dy2 * (start.getX() - x)); ua /= denom; float ub = (dx1 * (start.getY() - y)) - (dy1 * (start.getX() - x)); ub /= denom; float u = ua; if (u < 0) { u = 0; } if (u > 1) { u = 1; } float v = 1 - u; // u is the proportion down the line we are Color col = new Color(1,1,1,1); col.r = (u * endCol.r) + (v * startCol.r); col.b = (u * endCol.b) + (v * startCol.b); col.g = (u * endCol.g) + (v * startCol.g); col.a = (u * endCol.a) + (v * startCol.a); return col; }
[ "public", "Color", "colorAt", "(", "float", "x", ",", "float", "y", ")", "{", "float", "dx1", "=", "end", ".", "getX", "(", ")", "-", "start", ".", "getX", "(", ")", ";", "float", "dy1", "=", "end", ".", "getY", "(", ")", "-", "start", ".", "...
Get the colour that should be applied at the specified location @param x The x coordinate of the point being coloured @param y The y coordinate of the point being coloured @return The colour that should be applied based on the control points of this gradient
[ "Get", "the", "colour", "that", "should", "be", "applied", "at", "the", "specified", "location" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/fills/GradientFill.java#L212-L245
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java
ZooKeeperHelper.mkdirp
static void mkdirp(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { boolean createPath = false; for (String path : pathParts(znode)) { if (!createPath) { Stat stat = zookeeper.exists(path, false); if (stat == null) { createPath = true; } } if (createPath) { create(zookeeper, path); } } }
java
static void mkdirp(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { boolean createPath = false; for (String path : pathParts(znode)) { if (!createPath) { Stat stat = zookeeper.exists(path, false); if (stat == null) { createPath = true; } } if (createPath) { create(zookeeper, path); } } }
[ "static", "void", "mkdirp", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "boolean", "createPath", "=", "false", ";", "for", "(", "String", "path", ":", "pathParts", "(", "znode", ")"...
Recursively create empty znodes (if missing) analogous to {@code mkdir -p}. @param zookeeper ZooKeeper instance to work with. @param znode Path to create. @throws org.apache.zookeeper.KeeperException @throws InterruptedException
[ "Recursively", "create", "empty", "znodes", "(", "if", "missing", ")", "analogous", "to", "{", "@code", "mkdir", "-", "p", "}", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ZooKeeperHelper.java#L40-L53
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/MediaApi.java
MediaApi.readyForMedia
public ApiSuccessResponse readyForMedia(String mediatype, ReadyForMediaData readyForMediaData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = readyForMediaWithHttpInfo(mediatype, readyForMediaData); return resp.getData(); }
java
public ApiSuccessResponse readyForMedia(String mediatype, ReadyForMediaData readyForMediaData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = readyForMediaWithHttpInfo(mediatype, readyForMediaData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "readyForMedia", "(", "String", "mediatype", ",", "ReadyForMediaData", "readyForMediaData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "readyForMediaWithHttpInfo", "(", "mediatype", ",", ...
Set the agent state to Ready Set the current agent&#39;s state to Ready on the specified media channel. @param mediatype The media channel. (required) @param readyForMediaData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Set", "the", "agent", "state", "to", "Ready", "Set", "the", "current", "agent&#39", ";", "s", "state", "to", "Ready", "on", "the", "specified", "media", "channel", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L3501-L3504
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java
SynchronizedUniqueIDGeneratorFactory.generatorFor
public static synchronized IDGenerator generatorFor(ZooKeeperConnection zooKeeperConnection, String znode, Mode mode) throws IOException { if (!instances.containsKey(znode)) { final int clusterId = ClusterID.get(zooKeeperConnection.getActiveConnection(), znode); SynchronizedGeneratorIdentity generatorIdentityHolder = new SynchronizedGeneratorIdentity(zooKeeperConnection, znode, clusterId, null); return generatorFor(generatorIdentityHolder, mode); } return instances.get(znode); }
java
public static synchronized IDGenerator generatorFor(ZooKeeperConnection zooKeeperConnection, String znode, Mode mode) throws IOException { if (!instances.containsKey(znode)) { final int clusterId = ClusterID.get(zooKeeperConnection.getActiveConnection(), znode); SynchronizedGeneratorIdentity generatorIdentityHolder = new SynchronizedGeneratorIdentity(zooKeeperConnection, znode, clusterId, null); return generatorFor(generatorIdentityHolder, mode); } return instances.get(znode); }
[ "public", "static", "synchronized", "IDGenerator", "generatorFor", "(", "ZooKeeperConnection", "zooKeeperConnection", ",", "String", "znode", ",", "Mode", "mode", ")", "throws", "IOException", "{", "if", "(", "!", "instances", ".", "containsKey", "(", "znode", ")"...
Get the synchronized ID generator instance. @param zooKeeperConnection Connection to the ZooKeeper quorum. @param znode Base-path of the resource pool in ZooKeeper. @param mode Generator mode. @return An instance of this class. @throws IOException Thrown when something went wrong trying to find the cluster ID or trying to claim a generator ID.
[ "Get", "the", "synchronized", "ID", "generator", "instance", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/SynchronizedUniqueIDGeneratorFactory.java#L53-L66
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializationContext.java
JsonDeserializationContext.traceError
public JsonDeserializationException traceError( String message, JsonReader reader ) { getLogger().log( Level.SEVERE, message ); traceReaderInfo( reader ); return new JsonDeserializationException( message ); }
java
public JsonDeserializationException traceError( String message, JsonReader reader ) { getLogger().log( Level.SEVERE, message ); traceReaderInfo( reader ); return new JsonDeserializationException( message ); }
[ "public", "JsonDeserializationException", "traceError", "(", "String", "message", ",", "JsonReader", "reader", ")", "{", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "message", ")", ";", "traceReaderInfo", "(", "reader", ")", ";", "re...
Trace an error with current reader state and returns a corresponding exception. @param message error message @param reader current reader @return a {@link JsonDeserializationException} with the given message
[ "Trace", "an", "error", "with", "current", "reader", "state", "and", "returns", "a", "corresponding", "exception", "." ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonDeserializationContext.java#L359-L363
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
TypeUtils.mapTypeVariablesToArguments
private static <T> void mapTypeVariablesToArguments(final Class<T> cls, final ParameterizedType parameterizedType, final Map<TypeVariable<?>, Type> typeVarAssigns) { // capture the type variables from the owner type that have assignments final Type ownerType = parameterizedType.getOwnerType(); if (ownerType instanceof ParameterizedType) { // recursion to make sure the owner's owner type gets processed mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns); } // parameterizedType is a generic interface/class (or it's in the owner // hierarchy of said interface/class) implemented/extended by the class // cls. Find out which type variables of cls are type arguments of // parameterizedType: final Type[] typeArgs = parameterizedType.getActualTypeArguments(); // of the cls's type variables that are arguments of parameterizedType, // find out which ones can be determined from the super type's arguments final TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters(); // use List view of type parameters of cls so the contains() method can be used: final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls .getTypeParameters()); for (int i = 0; i < typeArgs.length; i++) { final TypeVariable<?> typeVar = typeVars[i]; final Type typeArg = typeArgs[i]; // argument of parameterizedType is a type variable of cls if (typeVarList.contains(typeArg) // type variable of parameterizedType has an assignment in // the super type. && typeVarAssigns.containsKey(typeVar)) { // map the assignment to the cls's type variable typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar)); } } }
java
private static <T> void mapTypeVariablesToArguments(final Class<T> cls, final ParameterizedType parameterizedType, final Map<TypeVariable<?>, Type> typeVarAssigns) { // capture the type variables from the owner type that have assignments final Type ownerType = parameterizedType.getOwnerType(); if (ownerType instanceof ParameterizedType) { // recursion to make sure the owner's owner type gets processed mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns); } // parameterizedType is a generic interface/class (or it's in the owner // hierarchy of said interface/class) implemented/extended by the class // cls. Find out which type variables of cls are type arguments of // parameterizedType: final Type[] typeArgs = parameterizedType.getActualTypeArguments(); // of the cls's type variables that are arguments of parameterizedType, // find out which ones can be determined from the super type's arguments final TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters(); // use List view of type parameters of cls so the contains() method can be used: final List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls .getTypeParameters()); for (int i = 0; i < typeArgs.length; i++) { final TypeVariable<?> typeVar = typeVars[i]; final Type typeArg = typeArgs[i]; // argument of parameterizedType is a type variable of cls if (typeVarList.contains(typeArg) // type variable of parameterizedType has an assignment in // the super type. && typeVarAssigns.containsKey(typeVar)) { // map the assignment to the cls's type variable typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar)); } } }
[ "private", "static", "<", "T", ">", "void", "mapTypeVariablesToArguments", "(", "final", "Class", "<", "T", ">", "cls", ",", "final", "ParameterizedType", "parameterizedType", ",", "final", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "typeVa...
<p>Performs a mapping of type variables.</p> @param <T> the generic type of the class in question @param cls the class in question @param parameterizedType the parameterized type @param typeVarAssigns the map to be filled
[ "<p", ">", "Performs", "a", "mapping", "of", "type", "variables", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java#L1006-L1043
tempodb/tempodb-java
src/main/java/com/tempodb/Client.java
Client.deleteDataPoints
public Result<Void> deleteDataPoints(Series series, Interval interval) { checkNotNull(series); checkNotNull(interval); URI uri = null; try { URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/data/", API_VERSION, urlencode(series.getKey()))); addIntervalToURI(builder, interval); uri = builder.build(); } catch (URISyntaxException e) { String message = String.format("Could not build URI with inputs: key: %s, interval: %s", series.getKey(), interval); throw new IllegalArgumentException(message, e); } HttpRequest request = buildRequest(uri.toString(), HttpMethod.DELETE); Result<Void> result = execute(request, Void.class); return result; }
java
public Result<Void> deleteDataPoints(Series series, Interval interval) { checkNotNull(series); checkNotNull(interval); URI uri = null; try { URIBuilder builder = new URIBuilder(String.format("/%s/series/key/%s/data/", API_VERSION, urlencode(series.getKey()))); addIntervalToURI(builder, interval); uri = builder.build(); } catch (URISyntaxException e) { String message = String.format("Could not build URI with inputs: key: %s, interval: %s", series.getKey(), interval); throw new IllegalArgumentException(message, e); } HttpRequest request = buildRequest(uri.toString(), HttpMethod.DELETE); Result<Void> result = execute(request, Void.class); return result; }
[ "public", "Result", "<", "Void", ">", "deleteDataPoints", "(", "Series", "series", ",", "Interval", "interval", ")", "{", "checkNotNull", "(", "series", ")", ";", "checkNotNull", "(", "interval", ")", ";", "URI", "uri", "=", "null", ";", "try", "{", "URI...
Deletes a range of datapoints for a Series specified by key. @param series The series @param interval The start/end datetime interval to delete. @return Void @since 1.0.0
[ "Deletes", "a", "range", "of", "datapoints", "for", "a", "Series", "specified", "by", "key", "." ]
train
https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L195-L212
grpc/grpc-java
netty/src/main/java/io/grpc/netty/NettyClientHandler.java
NettyClientHandler.onRstStreamRead
private void onRstStreamRead(int streamId, long errorCode) { NettyClientStream.TransportState stream = clientStream(connection().stream(streamId)); if (stream != null) { Status status = GrpcUtil.Http2Error.statusForCode((int) errorCode) .augmentDescription("Received Rst Stream"); stream.transportReportStatus( status, errorCode == Http2Error.REFUSED_STREAM.code() ? RpcProgress.REFUSED : RpcProgress.PROCESSED, false /*stop delivery*/, new Metadata()); if (keepAliveManager != null) { keepAliveManager.onDataReceived(); } } }
java
private void onRstStreamRead(int streamId, long errorCode) { NettyClientStream.TransportState stream = clientStream(connection().stream(streamId)); if (stream != null) { Status status = GrpcUtil.Http2Error.statusForCode((int) errorCode) .augmentDescription("Received Rst Stream"); stream.transportReportStatus( status, errorCode == Http2Error.REFUSED_STREAM.code() ? RpcProgress.REFUSED : RpcProgress.PROCESSED, false /*stop delivery*/, new Metadata()); if (keepAliveManager != null) { keepAliveManager.onDataReceived(); } } }
[ "private", "void", "onRstStreamRead", "(", "int", "streamId", ",", "long", "errorCode", ")", "{", "NettyClientStream", ".", "TransportState", "stream", "=", "clientStream", "(", "connection", "(", ")", ".", "stream", "(", "streamId", ")", ")", ";", "if", "("...
Handler for an inbound HTTP/2 RST_STREAM frame, terminating a stream.
[ "Handler", "for", "an", "inbound", "HTTP", "/", "2", "RST_STREAM", "frame", "terminating", "a", "stream", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/NettyClientHandler.java#L381-L396
apache/incubator-druid
indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java
TaskLockbox.tryLock
public LockResult tryLock( final TaskLockType lockType, final Task task, final Interval interval ) { giant.lock(); try { if (!activeTasks.contains(task.getId())) { throw new ISE("Unable to grant lock to inactive Task [%s]", task.getId()); } Preconditions.checkArgument(interval.toDurationMillis() > 0, "interval empty"); final TaskLockPosse posseToUse = createOrFindLockPosse(task, interval, lockType); if (posseToUse != null && !posseToUse.getTaskLock().isRevoked()) { // Add to existing TaskLockPosse, if necessary if (posseToUse.addTask(task)) { log.info("Added task[%s] to TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId()); // Update task storage facility. If it fails, revoke the lock. try { taskStorage.addLock(task.getId(), posseToUse.getTaskLock()); return LockResult.ok(posseToUse.getTaskLock()); } catch (Exception e) { log.makeAlert("Failed to persist lock in storage") .addData("task", task.getId()) .addData("dataSource", posseToUse.getTaskLock().getDataSource()) .addData("interval", posseToUse.getTaskLock().getInterval()) .addData("version", posseToUse.getTaskLock().getVersion()) .emit(); unlock(task, interval); return LockResult.fail(false); } } else { log.info("Task[%s] already present in TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId()); return LockResult.ok(posseToUse.getTaskLock()); } } else { final boolean lockRevoked = posseToUse != null && posseToUse.getTaskLock().isRevoked(); return LockResult.fail(lockRevoked); } } finally { giant.unlock(); } }
java
public LockResult tryLock( final TaskLockType lockType, final Task task, final Interval interval ) { giant.lock(); try { if (!activeTasks.contains(task.getId())) { throw new ISE("Unable to grant lock to inactive Task [%s]", task.getId()); } Preconditions.checkArgument(interval.toDurationMillis() > 0, "interval empty"); final TaskLockPosse posseToUse = createOrFindLockPosse(task, interval, lockType); if (posseToUse != null && !posseToUse.getTaskLock().isRevoked()) { // Add to existing TaskLockPosse, if necessary if (posseToUse.addTask(task)) { log.info("Added task[%s] to TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId()); // Update task storage facility. If it fails, revoke the lock. try { taskStorage.addLock(task.getId(), posseToUse.getTaskLock()); return LockResult.ok(posseToUse.getTaskLock()); } catch (Exception e) { log.makeAlert("Failed to persist lock in storage") .addData("task", task.getId()) .addData("dataSource", posseToUse.getTaskLock().getDataSource()) .addData("interval", posseToUse.getTaskLock().getInterval()) .addData("version", posseToUse.getTaskLock().getVersion()) .emit(); unlock(task, interval); return LockResult.fail(false); } } else { log.info("Task[%s] already present in TaskLock[%s]", task.getId(), posseToUse.getTaskLock().getGroupId()); return LockResult.ok(posseToUse.getTaskLock()); } } else { final boolean lockRevoked = posseToUse != null && posseToUse.getTaskLock().isRevoked(); return LockResult.fail(lockRevoked); } } finally { giant.unlock(); } }
[ "public", "LockResult", "tryLock", "(", "final", "TaskLockType", "lockType", ",", "final", "Task", "task", ",", "final", "Interval", "interval", ")", "{", "giant", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "!", "activeTasks", ".", "contains", "(...
Attempt to acquire a lock for a task, without removing it from the queue. Can safely be called multiple times on the same task until the lock is preempted. @param lockType type of lock to be acquired @param task task that wants a lock @param interval interval to lock @return {@link LockResult} containing a new or an existing lock if succeeded. Otherwise, {@link LockResult} with a {@link LockResult#revoked} flag. @throws IllegalStateException if the task is not a valid active task
[ "Attempt", "to", "acquire", "a", "lock", "for", "a", "task", "without", "removing", "it", "from", "the", "queue", ".", "Can", "safely", "be", "called", "multiple", "times", "on", "the", "same", "task", "until", "the", "lock", "is", "preempted", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/indexing-service/src/main/java/org/apache/druid/indexing/overlord/TaskLockbox.java#L275-L322
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/EmbedBuilder.java
EmbedBuilder.setAuthor
public EmbedBuilder setAuthor(String name, String url, String iconUrl) { //We only check if the name is null because its presence is what determines if the // the author will appear in the embed. if (name == null) { this.author = null; } else { urlCheck(url); urlCheck(iconUrl); this.author = new MessageEmbed.AuthorInfo(name, url, iconUrl, null); } return this; }
java
public EmbedBuilder setAuthor(String name, String url, String iconUrl) { //We only check if the name is null because its presence is what determines if the // the author will appear in the embed. if (name == null) { this.author = null; } else { urlCheck(url); urlCheck(iconUrl); this.author = new MessageEmbed.AuthorInfo(name, url, iconUrl, null); } return this; }
[ "public", "EmbedBuilder", "setAuthor", "(", "String", "name", ",", "String", "url", ",", "String", "iconUrl", ")", "{", "//We only check if the name is null because its presence is what determines if the", "// the author will appear in the embed.", "if", "(", "name", "==", "n...
Sets the Author of the embed. The author appears in the top left of the embed and can have a small image beside it along with the author's name being made clickable by way of providing a url. <p><b><a href="http://i.imgur.com/JgZtxIM.png">Example</a></b> <p><b>Uploading images with Embeds</b> <br>When uploading an <u>image</u> (using {@link net.dv8tion.jda.core.entities.MessageChannel#sendFile(java.io.File, net.dv8tion.jda.core.entities.Message) MessageChannel.sendFile(...)}) you can reference said image using the specified filename as URI {@code attachment://filename.ext}. <p><u>Example</u> <pre><code> MessageChannel channel; // = reference of a MessageChannel MessageBuilder message = new MessageBuilder(); EmbedBuilder embed = new EmbedBuilder(); InputStream file = new URL("https://http.cat/500").openStream(); embed.setAuthor("Minn", null, "attachment://cat.png") // we specify this in sendFile as "cat.png" .setDescription("This is a cute cat :3"); message.setEmbed(embed.build()); channel.sendFile(file, "cat.png", message.build()).queue(); </code></pre> @param name the name of the author of the embed. If this is not set, the author will not appear in the embed @param url the url of the author of the embed @param iconUrl the url of the icon for the author @throws java.lang.IllegalArgumentException <ul> <li>If the length of {@code url} is longer than {@link net.dv8tion.jda.core.entities.MessageEmbed#URL_MAX_LENGTH}.</li> <li>If the provided {@code url} is not a properly formatted http or https url.</li> <li>If the length of {@code iconUrl} is longer than {@link net.dv8tion.jda.core.entities.MessageEmbed#URL_MAX_LENGTH}.</li> <li>If the provided {@code iconUrl} is not a properly formatted http or https url.</li> </ul> @return the builder after the author has been set
[ "Sets", "the", "Author", "of", "the", "embed", ".", "The", "author", "appears", "in", "the", "top", "left", "of", "the", "embed", "and", "can", "have", "a", "small", "image", "beside", "it", "along", "with", "the", "author", "s", "name", "being", "made...
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/EmbedBuilder.java#L607-L622
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.scaleToRatio
public static void scaleToRatio( Rectangle2D fixed, Rectangle2D toScale, boolean doShrink ) { double origWidth = fixed.getWidth(); double origHeight = fixed.getHeight(); double toAdaptWidth = toScale.getWidth(); double toAdaptHeight = toScale.getHeight(); double scaleWidth = 0; double scaleHeight = 0; scaleWidth = toAdaptWidth / origWidth; scaleHeight = toAdaptHeight / origHeight; double scaleFactor; if (doShrink) { scaleFactor = Math.min(scaleWidth, scaleHeight); } else { scaleFactor = Math.max(scaleWidth, scaleHeight); } double newWidth = origWidth * scaleFactor; double newHeight = origHeight * scaleFactor; double dw = (toAdaptWidth - newWidth) / 2.0; double dh = (toAdaptHeight - newHeight) / 2.0; double newX = toScale.getX() + dw; double newY = toScale.getY() + dh; double newW = toAdaptWidth - 2 * dw; double newH = toAdaptHeight - 2 * dh; toScale.setRect(newX, newY, newW, newH); }
java
public static void scaleToRatio( Rectangle2D fixed, Rectangle2D toScale, boolean doShrink ) { double origWidth = fixed.getWidth(); double origHeight = fixed.getHeight(); double toAdaptWidth = toScale.getWidth(); double toAdaptHeight = toScale.getHeight(); double scaleWidth = 0; double scaleHeight = 0; scaleWidth = toAdaptWidth / origWidth; scaleHeight = toAdaptHeight / origHeight; double scaleFactor; if (doShrink) { scaleFactor = Math.min(scaleWidth, scaleHeight); } else { scaleFactor = Math.max(scaleWidth, scaleHeight); } double newWidth = origWidth * scaleFactor; double newHeight = origHeight * scaleFactor; double dw = (toAdaptWidth - newWidth) / 2.0; double dh = (toAdaptHeight - newHeight) / 2.0; double newX = toScale.getX() + dw; double newY = toScale.getY() + dh; double newW = toAdaptWidth - 2 * dw; double newH = toAdaptHeight - 2 * dh; toScale.setRect(newX, newY, newW, newH); }
[ "public", "static", "void", "scaleToRatio", "(", "Rectangle2D", "fixed", ",", "Rectangle2D", "toScale", ",", "boolean", "doShrink", ")", "{", "double", "origWidth", "=", "fixed", ".", "getWidth", "(", ")", ";", "double", "origHeight", "=", "fixed", ".", "get...
Extends or shrinks a rectangle following the ration of a fixed one. <p>This keeps the center point of the rectangle fixed.</p> @param fixed the fixed {@link Rectangle2D} to use for the ratio. @param toScale the {@link Rectangle2D} to adapt to the ratio of the fixed one. @param doShrink if <code>true</code>, the adapted rectangle is shrinked as opposed to extended.
[ "Extends", "or", "shrinks", "a", "rectangle", "following", "the", "ration", "of", "a", "fixed", "one", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L679-L708
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.deleteAllProperties
public void deleteAllProperties(CmsDbContext dbc, String resourcename) throws CmsException { CmsResource resource = null; List<CmsResource> resources = new ArrayList<CmsResource>(); try { // read the resource resource = readResource(dbc, resourcename, CmsResourceFilter.IGNORE_EXPIRATION); // check the security m_securityManager.checkPermissions( dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); // delete the property values if (resource.getSiblingCount() > 1) { // the resource has siblings- delete only the (structure) properties of this sibling getVfsDriver(dbc).deletePropertyObjects( dbc, dbc.currentProject().getUuid(), resource, CmsProperty.DELETE_OPTION_DELETE_STRUCTURE_VALUES); resources.addAll(readSiblings(dbc, resource, CmsResourceFilter.ALL)); } else { // the resource has no other siblings- delete all (structure+resource) properties getVfsDriver(dbc).deletePropertyObjects( dbc, dbc.currentProject().getUuid(), resource, CmsProperty.DELETE_OPTION_DELETE_STRUCTURE_AND_RESOURCE_VALUES); resources.add(resource); } } finally { // clear the driver manager cache m_monitor.flushCache(CmsMemoryMonitor.CacheType.PROPERTY, CmsMemoryMonitor.CacheType.PROPERTY_LIST); // fire an event that all properties of a resource have been deleted OpenCms.fireCmsEvent( new CmsEvent( I_CmsEventListener.EVENT_RESOURCES_AND_PROPERTIES_MODIFIED, Collections.<String, Object> singletonMap(I_CmsEventListener.KEY_RESOURCES, resources))); } }
java
public void deleteAllProperties(CmsDbContext dbc, String resourcename) throws CmsException { CmsResource resource = null; List<CmsResource> resources = new ArrayList<CmsResource>(); try { // read the resource resource = readResource(dbc, resourcename, CmsResourceFilter.IGNORE_EXPIRATION); // check the security m_securityManager.checkPermissions( dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); // delete the property values if (resource.getSiblingCount() > 1) { // the resource has siblings- delete only the (structure) properties of this sibling getVfsDriver(dbc).deletePropertyObjects( dbc, dbc.currentProject().getUuid(), resource, CmsProperty.DELETE_OPTION_DELETE_STRUCTURE_VALUES); resources.addAll(readSiblings(dbc, resource, CmsResourceFilter.ALL)); } else { // the resource has no other siblings- delete all (structure+resource) properties getVfsDriver(dbc).deletePropertyObjects( dbc, dbc.currentProject().getUuid(), resource, CmsProperty.DELETE_OPTION_DELETE_STRUCTURE_AND_RESOURCE_VALUES); resources.add(resource); } } finally { // clear the driver manager cache m_monitor.flushCache(CmsMemoryMonitor.CacheType.PROPERTY, CmsMemoryMonitor.CacheType.PROPERTY_LIST); // fire an event that all properties of a resource have been deleted OpenCms.fireCmsEvent( new CmsEvent( I_CmsEventListener.EVENT_RESOURCES_AND_PROPERTIES_MODIFIED, Collections.<String, Object> singletonMap(I_CmsEventListener.KEY_RESOURCES, resources))); } }
[ "public", "void", "deleteAllProperties", "(", "CmsDbContext", "dbc", ",", "String", "resourcename", ")", "throws", "CmsException", "{", "CmsResource", "resource", "=", "null", ";", "List", "<", "CmsResource", ">", "resources", "=", "new", "ArrayList", "<", "CmsR...
Deletes all property values of a file or folder.<p> If there are no other siblings than the specified resource, both the structure and resource property values get deleted. If the specified resource has siblings, only the structure property values get deleted.<p> @param dbc the current database context @param resourcename the name of the resource for which all properties should be deleted @throws CmsException if operation was not successful
[ "Deletes", "all", "property", "values", "of", "a", "file", "or", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L2252-L2298
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getCommitSessionRequest
public BoxRequestsFile.CommitUploadSession getCommitSessionRequest(List<BoxUploadSessionPart> uploadedParts, BoxUploadSession uploadSession) { return new BoxRequestsFile.CommitUploadSession(uploadedParts, null, null, null, uploadSession, mSession); }
java
public BoxRequestsFile.CommitUploadSession getCommitSessionRequest(List<BoxUploadSessionPart> uploadedParts, BoxUploadSession uploadSession) { return new BoxRequestsFile.CommitUploadSession(uploadedParts, null, null, null, uploadSession, mSession); }
[ "public", "BoxRequestsFile", ".", "CommitUploadSession", "getCommitSessionRequest", "(", "List", "<", "BoxUploadSessionPart", ">", "uploadedParts", ",", "BoxUploadSession", "uploadSession", ")", "{", "return", "new", "BoxRequestsFile", ".", "CommitUploadSession", "(", "up...
Commit an upload session after all parts have been uploaded, creating the new file or the version @param uploadedParts the list of uploaded parts to be committed. @param uploadSession the BoxUploadSession @return the created file instance.
[ "Commit", "an", "upload", "session", "after", "all", "parts", "have", "been", "uploaded", "creating", "the", "new", "file", "or", "the", "version" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L670-L672
bohnman/squiggly-java
src/main/java/com/github/bohnman/squiggly/util/SquigglyUtils.java
SquigglyUtils.objectify
public static <T> T objectify(ObjectMapper mapper, Object source, Class<T> targetType) { return objectify(mapper, source, mapper.getTypeFactory().constructType(targetType)); }
java
public static <T> T objectify(ObjectMapper mapper, Object source, Class<T> targetType) { return objectify(mapper, source, mapper.getTypeFactory().constructType(targetType)); }
[ "public", "static", "<", "T", ">", "T", "objectify", "(", "ObjectMapper", "mapper", ",", "Object", "source", ",", "Class", "<", "T", ">", "targetType", ")", "{", "return", "objectify", "(", "mapper", ",", "source", ",", "mapper", ".", "getTypeFactory", "...
Converts an object to an instance of the target type. Unlike {@link ObjectMapper#convertValue(Object, Class)}, this method will apply Squiggly filters. It does so by first converting the source to bytes and then re-reading it. @param mapper the object mapper @param source the source to convert @param targetType the target class type @return target instance
[ "Converts", "an", "object", "to", "an", "instance", "of", "the", "target", "type", ".", "Unlike", "{", "@link", "ObjectMapper#convertValue", "(", "Object", "Class", ")", "}", "this", "method", "will", "apply", "Squiggly", "filters", ".", "It", "does", "so", ...
train
https://github.com/bohnman/squiggly-java/blob/ba0c0b924ab718225d1ad180273ee63ea6c4f55a/src/main/java/com/github/bohnman/squiggly/util/SquigglyUtils.java#L162-L164
ThreeTen/threetenbp
src/main/java/org/threeten/bp/format/DateTimeFormatterBuilder.java
DateTimeFormatterBuilder.appendValue
public DateTimeFormatterBuilder appendValue(TemporalField field) { Jdk8Methods.requireNonNull(field, "field"); appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL)); return this; }
java
public DateTimeFormatterBuilder appendValue(TemporalField field) { Jdk8Methods.requireNonNull(field, "field"); appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL)); return this; }
[ "public", "DateTimeFormatterBuilder", "appendValue", "(", "TemporalField", "field", ")", "{", "Jdk8Methods", ".", "requireNonNull", "(", "field", ",", "\"field\"", ")", ";", "appendValue", "(", "new", "NumberPrinterParser", "(", "field", ",", "1", ",", "19", ","...
Appends the value of a date-time field to the formatter using a normal output style. <p> The value of the field will be output during a print. If the value cannot be obtained then an exception will be thrown. <p> The value will be printed as per the normal print of an integer value. Only negative numbers will be signed. No padding will be added. <p> The parser for a variable width value such as this normally behaves greedily, requiring one digit, but accepting as many digits as possible. This behavior can be affected by 'adjacent value parsing'. See {@link #appendValue(TemporalField, int)} for full details. @param field the field to append, not null @return this, for chaining, not null
[ "Appends", "the", "value", "of", "a", "date", "-", "time", "field", "to", "the", "formatter", "using", "a", "normal", "output", "style", ".", "<p", ">", "The", "value", "of", "the", "field", "will", "be", "output", "during", "a", "print", ".", "If", ...
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/format/DateTimeFormatterBuilder.java#L347-L351
alkacon/opencms-core
src/org/opencms/configuration/preferences/CmsStartViewPreference.java
CmsStartViewPreference.getViewSelectOptions
public static SelectOptions getViewSelectOptions(CmsObject cms, String value) { Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; List<I_CmsWorkplaceAppConfiguration> apps = OpenCms.getWorkplaceAppManager().getDefaultQuickLaunchConfigurations(); for (I_CmsWorkplaceAppConfiguration app : apps) { if (OpenCms.getRoleManager().hasRole( cms, cms.getRequestContext().getCurrentUser().getName(), app.getRequiredRole())) { values.add(app.getId()); options.add(app.getName(locale)); } } SelectOptions optionBean = new SelectOptions(options, values, selectedIndex); return optionBean; }
java
public static SelectOptions getViewSelectOptions(CmsObject cms, String value) { Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; List<I_CmsWorkplaceAppConfiguration> apps = OpenCms.getWorkplaceAppManager().getDefaultQuickLaunchConfigurations(); for (I_CmsWorkplaceAppConfiguration app : apps) { if (OpenCms.getRoleManager().hasRole( cms, cms.getRequestContext().getCurrentUser().getName(), app.getRequiredRole())) { values.add(app.getId()); options.add(app.getName(locale)); } } SelectOptions optionBean = new SelectOptions(options, values, selectedIndex); return optionBean; }
[ "public", "static", "SelectOptions", "getViewSelectOptions", "(", "CmsObject", "cms", ",", "String", "value", ")", "{", "Locale", "locale", "=", "OpenCms", ".", "getWorkplaceManager", "(", ")", ".", "getWorkplaceLocale", "(", "cms", ")", ";", "List", "<", "Str...
Gets the select options for the view selector.<p> @param cms the CMS context @param value the current value @return the select options
[ "Gets", "the", "select", "options", "for", "the", "view", "selector", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/preferences/CmsStartViewPreference.java#L73-L95
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
CheckpointCoordinator.triggerSynchronousSavepoint
public CompletableFuture<CompletedCheckpoint> triggerSynchronousSavepoint( final long timestamp, final boolean advanceToEndOfEventTime, @Nullable final String targetLocation) { final CheckpointProperties properties = CheckpointProperties.forSyncSavepoint(); return triggerSavepointInternal(timestamp, properties, advanceToEndOfEventTime, targetLocation); }
java
public CompletableFuture<CompletedCheckpoint> triggerSynchronousSavepoint( final long timestamp, final boolean advanceToEndOfEventTime, @Nullable final String targetLocation) { final CheckpointProperties properties = CheckpointProperties.forSyncSavepoint(); return triggerSavepointInternal(timestamp, properties, advanceToEndOfEventTime, targetLocation); }
[ "public", "CompletableFuture", "<", "CompletedCheckpoint", ">", "triggerSynchronousSavepoint", "(", "final", "long", "timestamp", ",", "final", "boolean", "advanceToEndOfEventTime", ",", "@", "Nullable", "final", "String", "targetLocation", ")", "{", "final", "Checkpoin...
Triggers a synchronous savepoint with the given savepoint directory as a target. @param timestamp The timestamp for the savepoint. @param advanceToEndOfEventTime Flag indicating if the source should inject a {@code MAX_WATERMARK} in the pipeline to fire any registered event-time timers. @param targetLocation Target location for the savepoint, optional. If null, the state backend's configured default will be used. @return A future to the completed checkpoint @throws IllegalStateException If no savepoint directory has been specified and no default savepoint directory has been configured
[ "Triggers", "a", "synchronous", "savepoint", "with", "the", "given", "savepoint", "directory", "as", "a", "target", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java#L391-L398
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java
DeployerResolverOverriderConverter.overrideUseMavenPatterns
private void overrideUseMavenPatterns(T overrider, Class overriderClass) { if (useMavenPatternsOverrideList.contains(overriderClass.getSimpleName())) { try { Field useMavenPatternsField = overriderClass.getDeclaredField("useMavenPatterns"); useMavenPatternsField.setAccessible(true); Object useMavenPatterns = useMavenPatternsField.get(overrider); if (useMavenPatterns == null) { Field notM2CompatibleField = overriderClass.getDeclaredField("notM2Compatible"); notM2CompatibleField.setAccessible(true); Object notM2Compatible = notM2CompatibleField.get(overrider); if (notM2Compatible instanceof Boolean && notM2Compatible != null) { useMavenPatternsField.set(overrider, !(Boolean)notM2Compatible); } } } catch (NoSuchFieldException | IllegalAccessException e) { converterErrors.add(getConversionErrorMessage(overrider, e)); } } }
java
private void overrideUseMavenPatterns(T overrider, Class overriderClass) { if (useMavenPatternsOverrideList.contains(overriderClass.getSimpleName())) { try { Field useMavenPatternsField = overriderClass.getDeclaredField("useMavenPatterns"); useMavenPatternsField.setAccessible(true); Object useMavenPatterns = useMavenPatternsField.get(overrider); if (useMavenPatterns == null) { Field notM2CompatibleField = overriderClass.getDeclaredField("notM2Compatible"); notM2CompatibleField.setAccessible(true); Object notM2Compatible = notM2CompatibleField.get(overrider); if (notM2Compatible instanceof Boolean && notM2Compatible != null) { useMavenPatternsField.set(overrider, !(Boolean)notM2Compatible); } } } catch (NoSuchFieldException | IllegalAccessException e) { converterErrors.add(getConversionErrorMessage(overrider, e)); } } }
[ "private", "void", "overrideUseMavenPatterns", "(", "T", "overrider", ",", "Class", "overriderClass", ")", "{", "if", "(", "useMavenPatternsOverrideList", ".", "contains", "(", "overriderClass", ".", "getSimpleName", "(", ")", ")", ")", "{", "try", "{", "Field",...
Convert the Boolean notM2Compatible parameter to Boolean useMavenPatterns (after applying !) This convertion comes after a name change (!notM2Compatible -> useMavenPatterns)
[ "Convert", "the", "Boolean", "notM2Compatible", "parameter", "to", "Boolean", "useMavenPatterns", "(", "after", "applying", "!", ")", "This", "convertion", "comes", "after", "a", "name", "change", "(", "!notM2Compatible", "-", ">", "useMavenPatterns", ")" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/converters/DeployerResolverOverriderConverter.java#L231-L250
carrotsearch/hppc
hppc/src/main/templates/com/carrotsearch/hppc/KTypeVTypeHashMap.java
KTypeVTypeHashMap.equalElements
protected boolean equalElements(KTypeVTypeHashMap<?, ?> other) { if (other.size() != size()) { return false; } for (KTypeVTypeCursor<?, ?> c : other) { KType key = Intrinsics.<KType> cast(c.key); if (!containsKey(key) || !Intrinsics.<VType> equals(c.value, get(key))) { return false; } } return true; }
java
protected boolean equalElements(KTypeVTypeHashMap<?, ?> other) { if (other.size() != size()) { return false; } for (KTypeVTypeCursor<?, ?> c : other) { KType key = Intrinsics.<KType> cast(c.key); if (!containsKey(key) || !Intrinsics.<VType> equals(c.value, get(key))) { return false; } } return true; }
[ "protected", "boolean", "equalElements", "(", "KTypeVTypeHashMap", "<", "?", ",", "?", ">", "other", ")", "{", "if", "(", "other", ".", "size", "(", ")", "!=", "size", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "KTypeVTypeCursor", "...
Return true if all keys of some other container exist in this container. #if ($TemplateOptions.KTypeGeneric) Equality comparison is performed with this object's {@link #equals(Object, Object)} method. #end #if ($TemplateOptions.VTypeGeneric) Values are compared using {@link Objects#equals(Object)} method. #end
[ "Return", "true", "if", "all", "keys", "of", "some", "other", "container", "exist", "in", "this", "container", ".", "#if", "(", "$TemplateOptions", ".", "KTypeGeneric", ")", "Equality", "comparison", "is", "performed", "with", "this", "object", "s", "{" ]
train
https://github.com/carrotsearch/hppc/blob/e359e9da358e846fcbffc64a765611df954ba3f6/hppc/src/main/templates/com/carrotsearch/hppc/KTypeVTypeHashMap.java#L647-L661
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/ResultUtil.java
ResultUtil.listSearchCaseInsensitive
public static int listSearchCaseInsensitive(List<String> source, String target) { for (int i = 0; i < source.size(); i++) { if (target.equalsIgnoreCase(source.get(i))) { return i; } } return -1; }
java
public static int listSearchCaseInsensitive(List<String> source, String target) { for (int i = 0; i < source.size(); i++) { if (target.equalsIgnoreCase(source.get(i))) { return i; } } return -1; }
[ "public", "static", "int", "listSearchCaseInsensitive", "(", "List", "<", "String", ">", "source", ",", "String", "target", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "source", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", ...
Given a list of String, do a case insensitive search for target string Used by resultsetMetadata to search for target column name @param source source string list @param target target string to match @return index in the source string list that matches the target string index starts from zero
[ "Given", "a", "list", "of", "String", "do", "a", "case", "insensitive", "search", "for", "target", "string", "Used", "by", "resultsetMetadata", "to", "search", "for", "target", "column", "name" ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/ResultUtil.java#L1001-L1011
lucee/Lucee
core/src/main/java/lucee/commons/io/res/util/ResourceSnippet.java
ResourceSnippet.createResourceSnippet
public static ResourceSnippet createResourceSnippet(Resource res, int startChar, int endChar, String charset) { try { return createResourceSnippet(res.getInputStream(), startChar, endChar, charset); } catch (IOException ex) { return ResourceSnippet.Empty; } }
java
public static ResourceSnippet createResourceSnippet(Resource res, int startChar, int endChar, String charset) { try { return createResourceSnippet(res.getInputStream(), startChar, endChar, charset); } catch (IOException ex) { return ResourceSnippet.Empty; } }
[ "public", "static", "ResourceSnippet", "createResourceSnippet", "(", "Resource", "res", ",", "int", "startChar", ",", "int", "endChar", ",", "String", "charset", ")", "{", "try", "{", "return", "createResourceSnippet", "(", "res", ".", "getInputStream", "(", ")"...
extract a ResourceSnippet from a Resource at the given char positions @param res - Resource from which to extract the snippet @param startChar - start position of the snippet @param endChar - end position of the snippet @param charset - use server's charset, default should be UTF-8 @return
[ "extract", "a", "ResourceSnippet", "from", "a", "Resource", "at", "the", "given", "char", "positions" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/res/util/ResourceSnippet.java#L120-L130
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContext.java
SslContext.newHandler
public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) { return newHandler(alloc, peerHost, peerPort, startTls); }
java
public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) { return newHandler(alloc, peerHost, peerPort, startTls); }
[ "public", "final", "SslHandler", "newHandler", "(", "ByteBufAllocator", "alloc", ",", "String", "peerHost", ",", "int", "peerPort", ")", "{", "return", "newHandler", "(", "alloc", ",", "peerHost", ",", "peerPort", ",", "startTls", ")", ";", "}" ]
Creates a new {@link SslHandler} @see #newHandler(ByteBufAllocator, String, int, Executor)
[ "Creates", "a", "new", "{", "@link", "SslHandler", "}" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslContext.java#L941-L943
Stratio/deep-spark
deep-core/src/main/java/com/stratio/deep/core/context/DeepSparkContext.java
DeepSparkContext.createS3RDD
public RDD<Cells> createS3RDD(ExtractorConfig<Cells> config) { Serializable bucket = config.getValues().get(ExtractorConstants.S3_BUCKET); Serializable path = config.getValues().get(ExtractorConstants.FS_FILE_PATH); final TextFileDataTable textFileDataTable = UtilFS.createTextFileMetaDataFromConfig(config, this); String filePath = path.toString(); if (config.getExtractorImplClassName().equals(ExtractorConstants.S3)) { filePath = ExtractorConstants.S3_PREFIX + bucket.toString() + path.toString(); } Configuration hadoopConf = this.sc().hadoopConfiguration(); hadoopConf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem"); hadoopConf.set("fs.s3n.awsAccessKeyId", config.getString(ExtractorConstants.S3_ACCESS_KEY_ID)); hadoopConf.set("fs.s3n.awsSecretAccessKey", config.getString(ExtractorConstants.S3_SECRET_ACCESS_KEY)); return createRDDFromFilePath(filePath, textFileDataTable); }
java
public RDD<Cells> createS3RDD(ExtractorConfig<Cells> config) { Serializable bucket = config.getValues().get(ExtractorConstants.S3_BUCKET); Serializable path = config.getValues().get(ExtractorConstants.FS_FILE_PATH); final TextFileDataTable textFileDataTable = UtilFS.createTextFileMetaDataFromConfig(config, this); String filePath = path.toString(); if (config.getExtractorImplClassName().equals(ExtractorConstants.S3)) { filePath = ExtractorConstants.S3_PREFIX + bucket.toString() + path.toString(); } Configuration hadoopConf = this.sc().hadoopConfiguration(); hadoopConf.set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem"); hadoopConf.set("fs.s3n.awsAccessKeyId", config.getString(ExtractorConstants.S3_ACCESS_KEY_ID)); hadoopConf.set("fs.s3n.awsSecretAccessKey", config.getString(ExtractorConstants.S3_SECRET_ACCESS_KEY)); return createRDDFromFilePath(filePath, textFileDataTable); }
[ "public", "RDD", "<", "Cells", ">", "createS3RDD", "(", "ExtractorConfig", "<", "Cells", ">", "config", ")", "{", "Serializable", "bucket", "=", "config", ".", "getValues", "(", ")", ".", "get", "(", "ExtractorConstants", ".", "S3_BUCKET", ")", ";", "Seria...
Returns a Cells RDD from S3 fileSystem. @param config Amazon S3 ExtractorConfig. @return RDD of Cells.
[ "Returns", "a", "Cells", "RDD", "from", "S3", "fileSystem", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-core/src/main/java/com/stratio/deep/core/context/DeepSparkContext.java#L298-L314
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java
ExcelWriter.writeCellValue
public ExcelWriter writeCellValue(int x, int y, Object value) { final Cell cell = getOrCreateCell(x, y); CellUtil.setCellValue(cell, value, this.styleSet, false); return this; }
java
public ExcelWriter writeCellValue(int x, int y, Object value) { final Cell cell = getOrCreateCell(x, y); CellUtil.setCellValue(cell, value, this.styleSet, false); return this; }
[ "public", "ExcelWriter", "writeCellValue", "(", "int", "x", ",", "int", "y", ",", "Object", "value", ")", "{", "final", "Cell", "cell", "=", "getOrCreateCell", "(", "x", ",", "y", ")", ";", "CellUtil", ".", "setCellValue", "(", "cell", ",", "value", ",...
给指定单元格赋值,使用默认单元格样式 @param x X坐标,从0计数,既列号 @param y Y坐标,从0计数,既行号 @param value 值 @return this @since 4.0.2
[ "给指定单元格赋值,使用默认单元格样式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java#L751-L755
rometools/rome-certiorem
src/main/java/com/rometools/certiorem/hub/notify/standard/AbstractNotifier.java
AbstractNotifier.postNotification
protected SubscriptionSummary postNotification(final Subscriber subscriber, final String mimeType, final byte[] payload) { final SubscriptionSummary result = new SubscriptionSummary(); try { final URL target = new URL(subscriber.getCallback()); LOG.info("Posting notification to subscriber {}", subscriber.getCallback()); result.setHost(target.getHost()); final HttpURLConnection connection = (HttpURLConnection) target.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", mimeType); connection.setDoOutput(true); connection.connect(); final OutputStream os = connection.getOutputStream(); os.write(payload); os.close(); final int responseCode = connection.getResponseCode(); final String subscribers = connection.getHeaderField("X-Hub-On-Behalf-Of"); connection.disconnect(); if (responseCode != 200) { LOG.warn("Got code {} from {}", responseCode, target); result.setLastPublishSuccessful(false); return result; } if (subscribers != null) { try { result.setSubscribers(Integer.parseInt(subscribers)); } catch (final NumberFormatException nfe) { LOG.warn("Invalid subscriber value " + subscribers + " " + target, nfe); result.setSubscribers(-1); } } else { result.setSubscribers(-1); } } catch (final MalformedURLException ex) { LOG.warn(null, ex); result.setLastPublishSuccessful(false); } catch (final IOException ex) { LOG.error(null, ex); result.setLastPublishSuccessful(false); } return result; }
java
protected SubscriptionSummary postNotification(final Subscriber subscriber, final String mimeType, final byte[] payload) { final SubscriptionSummary result = new SubscriptionSummary(); try { final URL target = new URL(subscriber.getCallback()); LOG.info("Posting notification to subscriber {}", subscriber.getCallback()); result.setHost(target.getHost()); final HttpURLConnection connection = (HttpURLConnection) target.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", mimeType); connection.setDoOutput(true); connection.connect(); final OutputStream os = connection.getOutputStream(); os.write(payload); os.close(); final int responseCode = connection.getResponseCode(); final String subscribers = connection.getHeaderField("X-Hub-On-Behalf-Of"); connection.disconnect(); if (responseCode != 200) { LOG.warn("Got code {} from {}", responseCode, target); result.setLastPublishSuccessful(false); return result; } if (subscribers != null) { try { result.setSubscribers(Integer.parseInt(subscribers)); } catch (final NumberFormatException nfe) { LOG.warn("Invalid subscriber value " + subscribers + " " + target, nfe); result.setSubscribers(-1); } } else { result.setSubscribers(-1); } } catch (final MalformedURLException ex) { LOG.warn(null, ex); result.setLastPublishSuccessful(false); } catch (final IOException ex) { LOG.error(null, ex); result.setLastPublishSuccessful(false); } return result; }
[ "protected", "SubscriptionSummary", "postNotification", "(", "final", "Subscriber", "subscriber", ",", "final", "String", "mimeType", ",", "final", "byte", "[", "]", "payload", ")", "{", "final", "SubscriptionSummary", "result", "=", "new", "SubscriptionSummary", "(...
POSTs the payload to the subscriber's callback and returns a SubscriptionSummary with subscriber counts (where possible) and the success state of the notification. @param subscriber subscriber data. @param mimeType MIME type for the request @param payload payload of the feed to send @return SubscriptionSummary with the returned data.
[ "POSTs", "the", "payload", "to", "the", "subscriber", "s", "callback", "and", "returns", "a", "SubscriptionSummary", "with", "subscriber", "counts", "(", "where", "possible", ")", "and", "the", "success", "state", "of", "the", "notification", "." ]
train
https://github.com/rometools/rome-certiorem/blob/e5a003193dd2abd748e77961c0f216a7f5690712/src/main/java/com/rometools/certiorem/hub/notify/standard/AbstractNotifier.java#L114-L161
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java
HttpChannelConfig.parseIncomingBodyBufferSize
private void parseIncomingBodyBufferSize(Map<Object, Object> props) { Object value = props.get(HttpConfigConstants.PROPNAME_INCOMING_BODY_BUFFSIZE); if (null != value) { try { this.incomingBodyBuffSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_BUFFER_SIZE, HttpConfigConstants.MAX_BUFFER_SIZE); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Config: Incoming body buffer size is " + getIncomingBodyBufferSize()); } } catch (NumberFormatException nfe) { FFDCFilter.processException(nfe, getClass().getName() + ".parseIncomingBodyBufferSize", "1"); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Config: Invalid incoming body buffer size; " + value); } } } }
java
private void parseIncomingBodyBufferSize(Map<Object, Object> props) { Object value = props.get(HttpConfigConstants.PROPNAME_INCOMING_BODY_BUFFSIZE); if (null != value) { try { this.incomingBodyBuffSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_BUFFER_SIZE, HttpConfigConstants.MAX_BUFFER_SIZE); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Config: Incoming body buffer size is " + getIncomingBodyBufferSize()); } } catch (NumberFormatException nfe) { FFDCFilter.processException(nfe, getClass().getName() + ".parseIncomingBodyBufferSize", "1"); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Config: Invalid incoming body buffer size; " + value); } } } }
[ "private", "void", "parseIncomingBodyBufferSize", "(", "Map", "<", "Object", ",", "Object", ">", "props", ")", "{", "Object", "value", "=", "props", ".", "get", "(", "HttpConfigConstants", ".", "PROPNAME_INCOMING_BODY_BUFFSIZE", ")", ";", "if", "(", "null", "!...
Check the input configuration for the buffer size to use when reading the incoming body. @param props
[ "Check", "the", "input", "configuration", "for", "the", "buffer", "size", "to", "use", "when", "reading", "the", "incoming", "body", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L612-L627
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java
FaceListsImpl.addFaceFromUrlWithServiceResponseAsync
public Observable<ServiceResponse<PersistedFace>> addFaceFromUrlWithServiceResponseAsync(String faceListId, String url, AddFaceFromUrlOptionalParameter addFaceFromUrlOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (faceListId == null) { throw new IllegalArgumentException("Parameter faceListId is required and cannot be null."); } if (url == null) { throw new IllegalArgumentException("Parameter url is required and cannot be null."); } final String userData = addFaceFromUrlOptionalParameter != null ? addFaceFromUrlOptionalParameter.userData() : null; final List<Integer> targetFace = addFaceFromUrlOptionalParameter != null ? addFaceFromUrlOptionalParameter.targetFace() : null; return addFaceFromUrlWithServiceResponseAsync(faceListId, url, userData, targetFace); }
java
public Observable<ServiceResponse<PersistedFace>> addFaceFromUrlWithServiceResponseAsync(String faceListId, String url, AddFaceFromUrlOptionalParameter addFaceFromUrlOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } if (faceListId == null) { throw new IllegalArgumentException("Parameter faceListId is required and cannot be null."); } if (url == null) { throw new IllegalArgumentException("Parameter url is required and cannot be null."); } final String userData = addFaceFromUrlOptionalParameter != null ? addFaceFromUrlOptionalParameter.userData() : null; final List<Integer> targetFace = addFaceFromUrlOptionalParameter != null ? addFaceFromUrlOptionalParameter.targetFace() : null; return addFaceFromUrlWithServiceResponseAsync(faceListId, url, userData, targetFace); }
[ "public", "Observable", "<", "ServiceResponse", "<", "PersistedFace", ">", ">", "addFaceFromUrlWithServiceResponseAsync", "(", "String", "faceListId", ",", "String", "url", ",", "AddFaceFromUrlOptionalParameter", "addFaceFromUrlOptionalParameter", ")", "{", "if", "(", "th...
Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. @param faceListId Id referencing a particular face list. @param url Publicly reachable URL of an image @param addFaceFromUrlOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PersistedFace object
[ "Add", "a", "face", "to", "a", "face", "list", ".", "The", "input", "face", "is", "specified", "as", "an", "image", "with", "a", "targetFace", "rectangle", ".", "It", "returns", "a", "persistedFaceId", "representing", "the", "added", "face", "and", "persis...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java#L796-L810
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemUtils.java
ProxiedFileSystemUtils.createProxiedFileSystemUsingKeytab
static FileSystem createProxiedFileSystemUsingKeytab(String userNameToProxyAs, String superUserName, Path superUserKeytabLocation, URI fsURI, Configuration conf) throws IOException, InterruptedException { return loginAndProxyAsUser(userNameToProxyAs, superUserName, superUserKeytabLocation) .doAs(new ProxiedFileSystem(fsURI, conf)); }
java
static FileSystem createProxiedFileSystemUsingKeytab(String userNameToProxyAs, String superUserName, Path superUserKeytabLocation, URI fsURI, Configuration conf) throws IOException, InterruptedException { return loginAndProxyAsUser(userNameToProxyAs, superUserName, superUserKeytabLocation) .doAs(new ProxiedFileSystem(fsURI, conf)); }
[ "static", "FileSystem", "createProxiedFileSystemUsingKeytab", "(", "String", "userNameToProxyAs", ",", "String", "superUserName", ",", "Path", "superUserKeytabLocation", ",", "URI", "fsURI", ",", "Configuration", "conf", ")", "throws", "IOException", ",", "InterruptedExce...
Creates a {@link FileSystem} that can perform any operations allowed by the specified userNameToProxyAs. This method first logs in as the specified super user. If Hadoop security is enabled, then logging in entails authenticating via Kerberos. So logging in requires contacting the Kerberos infrastructure. A proxy user is then created on behalf of the logged in user, and a {@link FileSystem} object is created using the proxy user's UGI. @param userNameToProxyAs The name of the user the super user should proxy as @param superUserName The name of the super user with secure impersonation priveleges @param superUserKeytabLocation The location of the keytab file for the super user @param fsURI The {@link URI} for the {@link FileSystem} that should be created @param conf The {@link Configuration} for the {@link FileSystem} that should be created @return a {@link FileSystem} that can execute commands on behalf of the specified userNameToProxyAs
[ "Creates", "a", "{", "@link", "FileSystem", "}", "that", "can", "perform", "any", "operations", "allowed", "by", "the", "specified", "userNameToProxyAs", ".", "This", "method", "first", "logs", "in", "as", "the", "specified", "super", "user", ".", "If", "Had...
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemUtils.java#L127-L132
radkovo/jStyleParser
src/main/java/cz/vutbr/web/css/CSSFactory.java
CSSFactory.getUsedStyles
public static final StyleSheet getUsedStyles(Document doc, String encoding, URL base, MediaSpec media) { return getUsedStyles(doc, encoding, base, media, getNetworkProcessor()); }
java
public static final StyleSheet getUsedStyles(Document doc, String encoding, URL base, MediaSpec media) { return getUsedStyles(doc, encoding, base, media, getNetworkProcessor()); }
[ "public", "static", "final", "StyleSheet", "getUsedStyles", "(", "Document", "doc", ",", "String", "encoding", ",", "URL", "base", ",", "MediaSpec", "media", ")", "{", "return", "getUsedStyles", "(", "doc", ",", "encoding", ",", "base", ",", "media", ",", ...
This is the same as {@link CSSFactory#getUsedStyles(Document, String, URL, MediaSpec)} with the possibility of specifying a custom network processor. @param doc DOM tree @param encoding The default encoding used for the referenced style sheets @param base Base URL against which all files are searched @param media Selected media for style sheet @return the rules of all the style sheets used in the document including the inline styles
[ "This", "is", "the", "same", "as", "{", "@link", "CSSFactory#getUsedStyles", "(", "Document", "String", "URL", "MediaSpec", ")", "}", "with", "the", "possibility", "of", "specifying", "a", "custom", "network", "processor", "." ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/css/CSSFactory.java#L596-L599
maestrano/maestrano-java
src/main/java/com/maestrano/net/ConnecClient.java
ConnecClient.all
public <T> T all(String entityName, String groupId, Class<T> clazz) throws MnoException { return all(entityName, groupId, null, getAuthenticatedClient(), clazz); }
java
public <T> T all(String entityName, String groupId, Class<T> clazz) throws MnoException { return all(entityName, groupId, null, getAuthenticatedClient(), clazz); }
[ "public", "<", "T", ">", "T", "all", "(", "String", "entityName", ",", "String", "groupId", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "MnoException", "{", "return", "all", "(", "entityName", ",", "groupId", ",", "null", ",", "getAuthenticatedC...
Return the entities in a typed class. The typed class should contain a field "entityName" with the list of entity class. For example: <pre> {@code class Organizations{ private List<Organization> organizations; public List<Organization> getOrganizations(){ return organizations; } } class Organization{ public String getId(); //etc... } </pre> @param entityName @param groupId @param clazz @return @throws MnoException
[ "Return", "the", "entities", "in", "a", "typed", "class", ".", "The", "typed", "class", "should", "contain", "a", "field", "entityName", "with", "the", "list", "of", "entity", "class", ".", "For", "example", ":" ]
train
https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/net/ConnecClient.java#L155-L157
googleapis/google-cloud-java
google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/ContainerAnalysisV1Beta1Client.java
ContainerAnalysisV1Beta1Client.listScanConfigs
public final ListScanConfigsPagedResponse listScanConfigs(ProjectName parent, String filter) { ListScanConfigsRequest request = ListScanConfigsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setFilter(filter) .build(); return listScanConfigs(request); }
java
public final ListScanConfigsPagedResponse listScanConfigs(ProjectName parent, String filter) { ListScanConfigsRequest request = ListScanConfigsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setFilter(filter) .build(); return listScanConfigs(request); }
[ "public", "final", "ListScanConfigsPagedResponse", "listScanConfigs", "(", "ProjectName", "parent", ",", "String", "filter", ")", "{", "ListScanConfigsRequest", "request", "=", "ListScanConfigsRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", "==...
Lists scan configurations for the specified project. <p>Sample code: <pre><code> try (ContainerAnalysisV1Beta1Client containerAnalysisV1Beta1Client = ContainerAnalysisV1Beta1Client.create()) { ProjectName parent = ProjectName.of("[PROJECT]"); String filter = ""; for (ScanConfig element : containerAnalysisV1Beta1Client.listScanConfigs(parent, filter).iterateAll()) { // doThingsWith(element); } } </code></pre> @param parent The name of the project to list scan configurations for in the form of `projects/[PROJECT_ID]`. @param filter The filter expression. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Lists", "scan", "configurations", "for", "the", "specified", "project", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/ContainerAnalysisV1Beta1Client.java#L674-L681
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaSchemaRegistry.java
KafkaSchemaRegistry.getSchemaByKey
public S getSchemaByKey(K key) throws SchemaRegistryException { try { return cachedSchemasByKeys.get(key); } catch (ExecutionException e) { throw new SchemaRegistryException(String.format("Schema with key %s cannot be retrieved", key), e); } }
java
public S getSchemaByKey(K key) throws SchemaRegistryException { try { return cachedSchemasByKeys.get(key); } catch (ExecutionException e) { throw new SchemaRegistryException(String.format("Schema with key %s cannot be retrieved", key), e); } }
[ "public", "S", "getSchemaByKey", "(", "K", "key", ")", "throws", "SchemaRegistryException", "{", "try", "{", "return", "cachedSchemasByKeys", ".", "get", "(", "key", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "SchemaReg...
Get schema from schema registry by key. @throws SchemaRegistryException if failed to get schema by key.
[ "Get", "schema", "from", "schema", "registry", "by", "key", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaSchemaRegistry.java#L97-L103
Azure/azure-sdk-for-java
policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java
PolicyStatesInner.listQueryResultsForPolicyDefinitionAsync
public Observable<PolicyStatesQueryResultsInner> listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() { @Override public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) { return response.body(); } }); }
java
public Observable<PolicyStatesQueryResultsInner> listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<PolicyStatesQueryResultsInner>, PolicyStatesQueryResultsInner>() { @Override public PolicyStatesQueryResultsInner call(ServiceResponse<PolicyStatesQueryResultsInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PolicyStatesQueryResultsInner", ">", "listQueryResultsForPolicyDefinitionAsync", "(", "PolicyStatesResource", "policyStatesResource", ",", "String", "subscriptionId", ",", "String", "policyDefinitionName", ",", "QueryOptions", "queryOptions", ")", ...
Queries policy states for the subscription level policy definition. @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' @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 PolicyStatesQueryResultsInner object
[ "Queries", "policy", "states", "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/PolicyStatesInner.java#L2191-L2198
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/element/DefaultBtrpOperand.java
DefaultBtrpOperand.prettyType
public static String prettyType(int degree, Type t) { StringBuilder b = new StringBuilder(); for (int i = degree; i > 0; i--) { b.append("set<"); } b.append(t.toString().toLowerCase()); for (int i = 0; i < degree; i++) { b.append(">"); } return b.toString(); }
java
public static String prettyType(int degree, Type t) { StringBuilder b = new StringBuilder(); for (int i = degree; i > 0; i--) { b.append("set<"); } b.append(t.toString().toLowerCase()); for (int i = 0; i < degree; i++) { b.append(">"); } return b.toString(); }
[ "public", "static", "String", "prettyType", "(", "int", "degree", ",", "Type", "t", ")", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "degree", ";", "i", ">", "0", ";", "i", "--", ")", "{", "...
Pretty textual representation of a given element type. @param degree 0 for a literal, 1 for a set, 2 for a set of sets, ... @param t the literal @return a String
[ "Pretty", "textual", "representation", "of", "a", "given", "element", "type", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/element/DefaultBtrpOperand.java#L127-L137
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/qe/StorableIndexSet.java
StorableIndexSet.addIndexes
public void addIndexes(StorableInfo<S> info, Direction defaultDirection) { for (int i=info.getIndexCount(); --i>=0; ) { add(info.getIndex(i).setDefaultDirection(defaultDirection)); } }
java
public void addIndexes(StorableInfo<S> info, Direction defaultDirection) { for (int i=info.getIndexCount(); --i>=0; ) { add(info.getIndex(i).setDefaultDirection(defaultDirection)); } }
[ "public", "void", "addIndexes", "(", "StorableInfo", "<", "S", ">", "info", ",", "Direction", "defaultDirection", ")", "{", "for", "(", "int", "i", "=", "info", ".", "getIndexCount", "(", ")", ";", "--", "i", ">=", "0", ";", ")", "{", "add", "(", "...
Adds all the indexes of the given storable. @param defaultDirection default ordering direction to apply to each index property @throws IllegalArgumentException if any argument is null
[ "Adds", "all", "the", "indexes", "of", "the", "given", "storable", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/qe/StorableIndexSet.java#L86-L90
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java
FacebookEndpoint.finishPublishPermissionsRequest
private boolean finishPublishPermissionsRequest(Activity activity, int requestCode, int resultCode, Intent data) { boolean isSuccessful = false; Session session = Session.getActiveSession(); // isOpened() must be called after onActivityResult(). if (session != null && session.onActivityResult(activity, requestCode, resultCode, data) && session.isOpened() && session.getPermissions().contains(PERMISSION_PUBLISH_ACTIONS)) { isSuccessful = true; } return isSuccessful; }
java
private boolean finishPublishPermissionsRequest(Activity activity, int requestCode, int resultCode, Intent data) { boolean isSuccessful = false; Session session = Session.getActiveSession(); // isOpened() must be called after onActivityResult(). if (session != null && session.onActivityResult(activity, requestCode, resultCode, data) && session.isOpened() && session.getPermissions().contains(PERMISSION_PUBLISH_ACTIONS)) { isSuccessful = true; } return isSuccessful; }
[ "private", "boolean", "finishPublishPermissionsRequest", "(", "Activity", "activity", ",", "int", "requestCode", ",", "int", "resultCode", ",", "Intent", "data", ")", "{", "boolean", "isSuccessful", "=", "false", ";", "Session", "session", "=", "Session", ".", "...
Finishes a {@link com.groundupworks.wings.facebook.FacebookEndpoint#startPublishPermissionsRequest(android.app.Activity, android.support.v4.app.Fragment)}. @param activity the {@link Activity}. @param requestCode the integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from. @param resultCode the integer result code returned by the child activity through its setResult(). @param data an Intent, which can return result data to the caller (various data can be attached to Intent "extras"). @return true if publish permissions request is successful; false otherwise.
[ "Finishes", "a", "{", "@link", "com", ".", "groundupworks", ".", "wings", ".", "facebook", ".", "FacebookEndpoint#startPublishPermissionsRequest", "(", "android", ".", "app", ".", "Activity", "android", ".", "support", ".", "v4", ".", "app", ".", "Fragment", "...
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L429-L441
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java
ApplicationExtensions.setHeaderResponseDecorator
public static void setHeaderResponseDecorator(final Application application, final String footerFilterName) { application.setHeaderResponseDecorator(new IHeaderResponseDecorator() { @Override public IHeaderResponse decorate(final IHeaderResponse response) { return new JavaScriptFilteredIntoFooterHeaderResponse(response, footerFilterName); } }); }
java
public static void setHeaderResponseDecorator(final Application application, final String footerFilterName) { application.setHeaderResponseDecorator(new IHeaderResponseDecorator() { @Override public IHeaderResponse decorate(final IHeaderResponse response) { return new JavaScriptFilteredIntoFooterHeaderResponse(response, footerFilterName); } }); }
[ "public", "static", "void", "setHeaderResponseDecorator", "(", "final", "Application", "application", ",", "final", "String", "footerFilterName", ")", "{", "application", ".", "setHeaderResponseDecorator", "(", "new", "IHeaderResponseDecorator", "(", ")", "{", "@", "O...
Sets an {@link IHeaderResponseDecorator} for the given application to use to decorate header responses. @param application the application @param footerFilterName the footer filter name
[ "Sets", "an", "{", "@link", "IHeaderResponseDecorator", "}", "for", "the", "given", "application", "to", "use", "to", "decorate", "header", "responses", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java#L473-L484
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/V1InstanceGetter.java
V1InstanceGetter.environments
public Collection<Environment> environments(EnvironmentFilter filter) { return get(Environment.class, (filter != null) ? filter : new EnvironmentFilter()); }
java
public Collection<Environment> environments(EnvironmentFilter filter) { return get(Environment.class, (filter != null) ? filter : new EnvironmentFilter()); }
[ "public", "Collection", "<", "Environment", ">", "environments", "(", "EnvironmentFilter", "filter", ")", "{", "return", "get", "(", "Environment", ".", "class", ",", "(", "filter", "!=", "null", ")", "?", "filter", ":", "new", "EnvironmentFilter", "(", ")",...
Get Environment filtered by the criteria specified in the passed in filter. @param filter Limit the items returned. If null, then all items are returned. @return Collection of items as specified in the filter.
[ "Get", "Environment", "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#L400-L402
ical4j/ical4j
src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java
CalendarParserImpl.assertToken
private int assertToken(final StreamTokenizer tokeniser, Reader in, final String token, final boolean ignoreCase, final boolean isBeginToken) throws IOException, ParserException { // ensure next token is a word token.. String sval; int ntok; if(isBeginToken) { ntok = skipNewLines(tokeniser, in, token); sval = getSvalIgnoringBom(tokeniser, in, token); } else { ntok = assertToken(tokeniser, in, StreamTokenizer.TT_WORD); sval = tokeniser.sval; } if (ignoreCase) { if (!token.equalsIgnoreCase(sval)) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in)); } } else if (!token.equals(sval)) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in)); } if (log.isDebugEnabled()) { log.debug("[" + token + "]"); } return ntok; }
java
private int assertToken(final StreamTokenizer tokeniser, Reader in, final String token, final boolean ignoreCase, final boolean isBeginToken) throws IOException, ParserException { // ensure next token is a word token.. String sval; int ntok; if(isBeginToken) { ntok = skipNewLines(tokeniser, in, token); sval = getSvalIgnoringBom(tokeniser, in, token); } else { ntok = assertToken(tokeniser, in, StreamTokenizer.TT_WORD); sval = tokeniser.sval; } if (ignoreCase) { if (!token.equalsIgnoreCase(sval)) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in)); } } else if (!token.equals(sval)) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in)); } if (log.isDebugEnabled()) { log.debug("[" + token + "]"); } return ntok; }
[ "private", "int", "assertToken", "(", "final", "StreamTokenizer", "tokeniser", ",", "Reader", "in", ",", "final", "String", "token", ",", "final", "boolean", "ignoreCase", ",", "final", "boolean", "isBeginToken", ")", "throws", "IOException", ",", "ParserException...
Asserts that the next token in the stream matches the specified token. @param tokeniser stream tokeniser to perform assertion on @param in @param token expected token @param ignoreCase @param isBeginToken @return int value of the ttype field of the tokeniser @throws IOException when unable to read from stream @throws ParserException when next token in the stream does not match the expected token
[ "Asserts", "that", "the", "next", "token", "in", "the", "stream", "matches", "the", "specified", "token", "." ]
train
https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java#L502-L530
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_sslciphersuite_binding.java
sslvserver_sslciphersuite_binding.count_filtered
public static long count_filtered(nitro_service service, String vservername, String filter) throws Exception{ sslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding(); obj.set_vservername(vservername); options option = new options(); option.set_count(true); option.set_filter(filter); sslvserver_sslciphersuite_binding[] response = (sslvserver_sslciphersuite_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
java
public static long count_filtered(nitro_service service, String vservername, String filter) throws Exception{ sslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding(); obj.set_vservername(vservername); options option = new options(); option.set_count(true); option.set_filter(filter); sslvserver_sslciphersuite_binding[] response = (sslvserver_sslciphersuite_binding[]) obj.getfiltered(service, option); if (response != null) { return response[0].__count; } return 0; }
[ "public", "static", "long", "count_filtered", "(", "nitro_service", "service", ",", "String", "vservername", ",", "String", "filter", ")", "throws", "Exception", "{", "sslvserver_sslciphersuite_binding", "obj", "=", "new", "sslvserver_sslciphersuite_binding", "(", ")", ...
Use this API to count the filtered set of sslvserver_sslciphersuite_binding resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
[ "Use", "this", "API", "to", "count", "the", "filtered", "set", "of", "sslvserver_sslciphersuite_binding", "resources", ".", "filter", "string", "should", "be", "in", "JSON", "format", ".", "eg", ":", "port", ":", "80", "servicetype", ":", "HTTP", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_sslciphersuite_binding.java#L225-L236
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java
XmlUtil.toFile
public static void toFile(Document doc, String path, String charset) { if (StrUtil.isBlank(charset)) { charset = doc.getXmlEncoding(); } if (StrUtil.isBlank(charset)) { charset = CharsetUtil.UTF_8; } BufferedWriter writer = null; try { writer = FileUtil.getWriter(path, charset, false); write(doc, writer, charset, INDENT_DEFAULT); } finally { IoUtil.close(writer); } }
java
public static void toFile(Document doc, String path, String charset) { if (StrUtil.isBlank(charset)) { charset = doc.getXmlEncoding(); } if (StrUtil.isBlank(charset)) { charset = CharsetUtil.UTF_8; } BufferedWriter writer = null; try { writer = FileUtil.getWriter(path, charset, false); write(doc, writer, charset, INDENT_DEFAULT); } finally { IoUtil.close(writer); } }
[ "public", "static", "void", "toFile", "(", "Document", "doc", ",", "String", "path", ",", "String", "charset", ")", "{", "if", "(", "StrUtil", ".", "isBlank", "(", "charset", ")", ")", "{", "charset", "=", "doc", ".", "getXmlEncoding", "(", ")", ";", ...
将XML文档写入到文件<br> @param doc XML文档 @param path 文件路径绝对路径或相对ClassPath路径,不存在会自动创建 @param charset 自定义XML文件的编码,如果为{@code null} 读取XML文档中的编码,否则默认UTF-8
[ "将XML文档写入到文件<br", ">" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L298-L313
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/auth/LDAPIdentityValidator.java
LDAPIdentityValidator.formatDn
private String formatDn(String dnPattern, String username, ApiRequest request) { Map<String, String> valuesMap = request.getHeaders().toMap(); valuesMap.put("username", username); //$NON-NLS-1$ StrSubstitutor sub = new StrSubstitutor(valuesMap); return sub.replace(dnPattern); }
java
private String formatDn(String dnPattern, String username, ApiRequest request) { Map<String, String> valuesMap = request.getHeaders().toMap(); valuesMap.put("username", username); //$NON-NLS-1$ StrSubstitutor sub = new StrSubstitutor(valuesMap); return sub.replace(dnPattern); }
[ "private", "String", "formatDn", "(", "String", "dnPattern", ",", "String", "username", ",", "ApiRequest", "request", ")", "{", "Map", "<", "String", ",", "String", ">", "valuesMap", "=", "request", ".", "getHeaders", "(", ")", ".", "toMap", "(", ")", ";...
Formats the configured DN by replacing any properties it finds. @param dnPattern @param username @param request
[ "Formats", "the", "configured", "DN", "by", "replacing", "any", "properties", "it", "finds", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/auth/LDAPIdentityValidator.java#L269-L274
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/UnicodeFont.java
UnicodeFont.initializeFont
private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) { Map attributes = baseFont.getAttributes(); attributes.put(TextAttribute.SIZE, new Float(size)); attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR); attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR); try { attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField( "KERNING_ON").get(null)); } catch (Exception ignored) { } font = baseFont.deriveFont(attributes); FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font); ascent = metrics.getAscent(); descent = metrics.getDescent(); leading = metrics.getLeading(); // Determine width of space glyph (getGlyphPixelBounds gives a width of zero). char[] chars = " ".toCharArray(); GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT); spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width; }
java
private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) { Map attributes = baseFont.getAttributes(); attributes.put(TextAttribute.SIZE, new Float(size)); attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR); attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR); try { attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField( "KERNING_ON").get(null)); } catch (Exception ignored) { } font = baseFont.deriveFont(attributes); FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font); ascent = metrics.getAscent(); descent = metrics.getDescent(); leading = metrics.getLeading(); // Determine width of space glyph (getGlyphPixelBounds gives a width of zero). char[] chars = " ".toCharArray(); GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT); spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width; }
[ "private", "void", "initializeFont", "(", "Font", "baseFont", ",", "int", "size", ",", "boolean", "bold", ",", "boolean", "italic", ")", "{", "Map", "attributes", "=", "baseFont", ".", "getAttributes", "(", ")", ";", "attributes", ".", "put", "(", "TextAtt...
Initialise the font to be used based on configuration @param baseFont The AWT font to render @param size The point size of the font to generated @param bold True if the font should be rendered in bold typeface @param italic True if the font should be rendered in bold typeface
[ "Initialise", "the", "font", "to", "be", "used", "based", "on", "configuration" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/UnicodeFont.java#L227-L248
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java
ResourceLoader.getInputStream
public static InputStream getInputStream(final File baseDir, final String resource) throws IOException { File resourceFile = baseDir == null ? new File(resource) : new File(baseDir, resource); return getInputStream(resourceFile); }
java
public static InputStream getInputStream(final File baseDir, final String resource) throws IOException { File resourceFile = baseDir == null ? new File(resource) : new File(baseDir, resource); return getInputStream(resourceFile); }
[ "public", "static", "InputStream", "getInputStream", "(", "final", "File", "baseDir", ",", "final", "String", "resource", ")", "throws", "IOException", "{", "File", "resourceFile", "=", "baseDir", "==", "null", "?", "new", "File", "(", "resource", ")", ":", ...
Loads a resource as {@link InputStream}. @param baseDir If not {@code null}, the directory relative to which resources are loaded. @param resource The resource to be loaded. If {@code baseDir} is not {@code null}, it is loaded relative to {@code baseDir}. @return The stream
[ "Loads", "a", "resource", "as", "{", "@link", "InputStream", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java#L233-L236
finmath/finmath-lib
src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/LocalRiskMinimizingHedgePortfolio.java
LocalRiskMinimizingHedgePortfolio.getBasisFunctions
private RandomVariableInterface[] getBasisFunctions(RandomVariableInterface underlying) { double min = underlying.getMin(); double max = underlying.getMax(); ArrayList<RandomVariableInterface> basisFunctionList = new ArrayList<RandomVariableInterface>(); double[] discretization = (new TimeDiscretization(min, numberOfBins, (max-min)/numberOfBins)).getAsDoubleArray(); for(double discretizationStep : discretization) { RandomVariableInterface indicator = underlying.barrier(underlying.sub(discretizationStep), new RandomVariable(1.0), 0.0); basisFunctionList.add(indicator); } return basisFunctionList.toArray(new RandomVariableInterface[0]); }
java
private RandomVariableInterface[] getBasisFunctions(RandomVariableInterface underlying) { double min = underlying.getMin(); double max = underlying.getMax(); ArrayList<RandomVariableInterface> basisFunctionList = new ArrayList<RandomVariableInterface>(); double[] discretization = (new TimeDiscretization(min, numberOfBins, (max-min)/numberOfBins)).getAsDoubleArray(); for(double discretizationStep : discretization) { RandomVariableInterface indicator = underlying.barrier(underlying.sub(discretizationStep), new RandomVariable(1.0), 0.0); basisFunctionList.add(indicator); } return basisFunctionList.toArray(new RandomVariableInterface[0]); }
[ "private", "RandomVariableInterface", "[", "]", "getBasisFunctions", "(", "RandomVariableInterface", "underlying", ")", "{", "double", "min", "=", "underlying", ".", "getMin", "(", ")", ";", "double", "max", "=", "underlying", ".", "getMax", "(", ")", ";", "Ar...
Create basis functions for a binning. @param underlying @return
[ "Create", "basis", "functions", "for", "a", "binning", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/LocalRiskMinimizingHedgePortfolio.java#L155-L167
jbundle/jbundle
base/model/src/main/java/org/jbundle/base/model/Utility.java
Utility.transferURLStream
public static String transferURLStream(String strURL, String strFilename) { return Utility.transferURLStream(strURL, strFilename, null); }
java
public static String transferURLStream(String strURL, String strFilename) { return Utility.transferURLStream(strURL, strFilename, null); }
[ "public", "static", "String", "transferURLStream", "(", "String", "strURL", ",", "String", "strFilename", ")", "{", "return", "Utility", ".", "transferURLStream", "(", "strURL", ",", "strFilename", ",", "null", ")", ";", "}" ]
Transfer the data stream from this URL to a string or file. @param strURL The URL to read. @param strFilename If non-null, create this file and send the URL data here. @param strFilename If null, return the stream as a string. @return The stream as a string if filename is null.
[ "Transfer", "the", "data", "stream", "from", "this", "URL", "to", "a", "string", "or", "file", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L335-L338
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javadoc/TypeMaker.java
TypeMaker.getTypeString
static String getTypeString(DocEnv env, Type t, boolean full) { // TODO: should annotations be included here? if (t.isAnnotated()) { t = t.unannotatedType(); } switch (t.getTag()) { case ARRAY: StringBuilder s = new StringBuilder(); while (t.hasTag(ARRAY)) { s.append("[]"); t = env.types.elemtype(t); } s.insert(0, getTypeString(env, t, full)); return s.toString(); case CLASS: return ParameterizedTypeImpl. parameterizedTypeToString(env, (ClassType)t, full); case WILDCARD: Type.WildcardType a = (Type.WildcardType)t; return WildcardTypeImpl.wildcardTypeToString(env, a, full); default: return t.tsym.getQualifiedName().toString(); } }
java
static String getTypeString(DocEnv env, Type t, boolean full) { // TODO: should annotations be included here? if (t.isAnnotated()) { t = t.unannotatedType(); } switch (t.getTag()) { case ARRAY: StringBuilder s = new StringBuilder(); while (t.hasTag(ARRAY)) { s.append("[]"); t = env.types.elemtype(t); } s.insert(0, getTypeString(env, t, full)); return s.toString(); case CLASS: return ParameterizedTypeImpl. parameterizedTypeToString(env, (ClassType)t, full); case WILDCARD: Type.WildcardType a = (Type.WildcardType)t; return WildcardTypeImpl.wildcardTypeToString(env, a, full); default: return t.tsym.getQualifiedName().toString(); } }
[ "static", "String", "getTypeString", "(", "DocEnv", "env", ",", "Type", "t", ",", "boolean", "full", ")", "{", "// TODO: should annotations be included here?", "if", "(", "t", ".", "isAnnotated", "(", ")", ")", "{", "t", "=", "t", ".", "unannotatedType", "("...
Return the string representation of a type use. Bounds of type variables are not included; bounds of wildcard types are. Class names are qualified if "full" is true.
[ "Return", "the", "string", "representation", "of", "a", "type", "use", ".", "Bounds", "of", "type", "variables", "are", "not", "included", ";", "bounds", "of", "wildcard", "types", "are", ".", "Class", "names", "are", "qualified", "if", "full", "is", "true...
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javadoc/TypeMaker.java#L155-L178
looly/hutool
hutool-db/src/main/java/cn/hutool/db/meta/MetaUtil.java
MetaUtil.getColumnNames
public static String[] getColumnNames(DataSource ds, String tableName) { List<String> columnNames = new ArrayList<String>(); Connection conn = null; ResultSet rs = null; try { conn = ds.getConnection(); final DatabaseMetaData metaData = conn.getMetaData(); rs = metaData.getColumns(conn.getCatalog(), null, tableName, null); while (rs.next()) { columnNames.add(rs.getString("COLUMN_NAME")); } return columnNames.toArray(new String[columnNames.size()]); } catch (Exception e) { throw new DbRuntimeException("Get columns error!", e); } finally { DbUtil.close(rs, conn); } }
java
public static String[] getColumnNames(DataSource ds, String tableName) { List<String> columnNames = new ArrayList<String>(); Connection conn = null; ResultSet rs = null; try { conn = ds.getConnection(); final DatabaseMetaData metaData = conn.getMetaData(); rs = metaData.getColumns(conn.getCatalog(), null, tableName, null); while (rs.next()) { columnNames.add(rs.getString("COLUMN_NAME")); } return columnNames.toArray(new String[columnNames.size()]); } catch (Exception e) { throw new DbRuntimeException("Get columns error!", e); } finally { DbUtil.close(rs, conn); } }
[ "public", "static", "String", "[", "]", "getColumnNames", "(", "DataSource", "ds", ",", "String", "tableName", ")", "{", "List", "<", "String", ">", "columnNames", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Connection", "conn", "=", "nu...
获得表的所有列名 @param ds 数据源 @param tableName 表名 @return 列数组 @throws DbRuntimeException SQL执行异常
[ "获得表的所有列名" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/meta/MetaUtil.java#L125-L142
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.backupKeyAsync
public Observable<BackupKeyResult> backupKeyAsync(String vaultBaseUrl, String keyName) { return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1<ServiceResponse<BackupKeyResult>, BackupKeyResult>() { @Override public BackupKeyResult call(ServiceResponse<BackupKeyResult> response) { return response.body(); } }); }
java
public Observable<BackupKeyResult> backupKeyAsync(String vaultBaseUrl, String keyName) { return backupKeyWithServiceResponseAsync(vaultBaseUrl, keyName).map(new Func1<ServiceResponse<BackupKeyResult>, BackupKeyResult>() { @Override public BackupKeyResult call(ServiceResponse<BackupKeyResult> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BackupKeyResult", ">", "backupKeyAsync", "(", "String", "vaultBaseUrl", ",", "String", "keyName", ")", "{", "return", "backupKeyWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "keyName", ")", ".", "map", "(", "new", "Func1", "<",...
Requests that a backup of the specified key be downloaded to the client. The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical area. This operation requires the key/backup permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BackupKeyResult object
[ "Requests", "that", "a", "backup", "of", "the", "specified", "key", "be", "downloaded", "to", "the", "client", ".", "The", "Key", "Backup", "operation", "exports", "a", "key", "from", "Azure", "Key", "Vault", "in", "a", "protected", "form", ".", "Note", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L1992-L1999
liferay/com-liferay-commerce
commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java
CommerceDiscountRelPersistenceImpl.findByCommerceDiscountId
@Override public List<CommerceDiscountRel> findByCommerceDiscountId( long commerceDiscountId, int start, int end) { return findByCommerceDiscountId(commerceDiscountId, start, end, null); }
java
@Override public List<CommerceDiscountRel> findByCommerceDiscountId( long commerceDiscountId, int start, int end) { return findByCommerceDiscountId(commerceDiscountId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceDiscountRel", ">", "findByCommerceDiscountId", "(", "long", "commerceDiscountId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCommerceDiscountId", "(", "commerceDiscountId", ",", "start", ",", ...
Returns a range of all the commerce discount rels where commerceDiscountId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceDiscountRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceDiscountId the commerce discount ID @param start the lower bound of the range of commerce discount rels @param end the upper bound of the range of commerce discount rels (not inclusive) @return the range of matching commerce discount rels
[ "Returns", "a", "range", "of", "all", "the", "commerce", "discount", "rels", "where", "commerceDiscountId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java#L142-L146
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/net/TCPSlaveConnection.java
TCPSlaveConnection.setSocket
private void setSocket(Socket socket, boolean useRtuOverTcp) throws IOException { this.socket = socket; if (transport == null) { if (useRtuOverTcp) { logger.trace("setSocket() -> using RTU over TCP transport."); transport = new ModbusRTUTCPTransport(socket); } else { logger.trace("setSocket() -> using standard TCP transport."); transport = new ModbusTCPTransport(socket); } } else { transport.setSocket(socket); } connected = true; }
java
private void setSocket(Socket socket, boolean useRtuOverTcp) throws IOException { this.socket = socket; if (transport == null) { if (useRtuOverTcp) { logger.trace("setSocket() -> using RTU over TCP transport."); transport = new ModbusRTUTCPTransport(socket); } else { logger.trace("setSocket() -> using standard TCP transport."); transport = new ModbusTCPTransport(socket); } } else { transport.setSocket(socket); } connected = true; }
[ "private", "void", "setSocket", "(", "Socket", "socket", ",", "boolean", "useRtuOverTcp", ")", "throws", "IOException", "{", "this", ".", "socket", "=", "socket", ";", "if", "(", "transport", "==", "null", ")", "{", "if", "(", "useRtuOverTcp", ")", "{", ...
Prepares the associated <tt>ModbusTransport</tt> of this <tt>TCPMasterConnection</tt> for use. @param socket the socket to be used for communication. @param useRtuOverTcp True if the RTU protocol should be used over TCP @throws IOException if an I/O related error occurs.
[ "Prepares", "the", "associated", "<tt", ">", "ModbusTransport<", "/", "tt", ">", "of", "this", "<tt", ">", "TCPMasterConnection<", "/", "tt", ">", "for", "use", "." ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/net/TCPSlaveConnection.java#L108-L126
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/utils/LibraryUtils.java
LibraryUtils.setMessageAccountId
public static void setMessageAccountId(Message sqsMessage, String s3ObjectKey) { if (!sqsMessage.getAttributes().containsKey(SourceAttributeKeys.ACCOUNT_ID.getAttributeKey())) { String accountId = extractAccountIdFromObjectKey(s3ObjectKey); if (accountId != null) { sqsMessage.addAttributesEntry(SourceAttributeKeys.ACCOUNT_ID.getAttributeKey(), accountId); } } }
java
public static void setMessageAccountId(Message sqsMessage, String s3ObjectKey) { if (!sqsMessage.getAttributes().containsKey(SourceAttributeKeys.ACCOUNT_ID.getAttributeKey())) { String accountId = extractAccountIdFromObjectKey(s3ObjectKey); if (accountId != null) { sqsMessage.addAttributesEntry(SourceAttributeKeys.ACCOUNT_ID.getAttributeKey(), accountId); } } }
[ "public", "static", "void", "setMessageAccountId", "(", "Message", "sqsMessage", ",", "String", "s3ObjectKey", ")", "{", "if", "(", "!", "sqsMessage", ".", "getAttributes", "(", ")", ".", "containsKey", "(", "SourceAttributeKeys", ".", "ACCOUNT_ID", ".", "getAtt...
Add the account ID attribute to the <code>sqsMessage</code> if it does not exist. @param sqsMessage The SQS message. @param s3ObjectKey The S3 object key.
[ "Add", "the", "account", "ID", "attribute", "to", "the", "<code", ">", "sqsMessage<", "/", "code", ">", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/utils/LibraryUtils.java#L153-L160
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/deps/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheEncoder.java
AbstractBinaryMemcacheEncoder.encodeKey
private static void encodeKey(ByteBuf buf, byte[] key) { if (key == null || key.length == 0) { return; } buf.writeBytes(key); }
java
private static void encodeKey(ByteBuf buf, byte[] key) { if (key == null || key.length == 0) { return; } buf.writeBytes(key); }
[ "private", "static", "void", "encodeKey", "(", "ByteBuf", "buf", ",", "byte", "[", "]", "key", ")", "{", "if", "(", "key", "==", "null", "||", "key", ".", "length", "==", "0", ")", "{", "return", ";", "}", "buf", ".", "writeBytes", "(", "key", ")...
Encode the key. @param buf the {@link ByteBuf} to write into. @param key the key to encode.
[ "Encode", "the", "key", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/deps/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheEncoder.java#L65-L71
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/NGAExtensions.java
NGAExtensions.deleteProperties
public static void deleteProperties(GeoPackageCore geoPackage, String table) { if (table.equalsIgnoreCase(PropertiesCoreExtension.TABLE_NAME)) { deletePropertiesExtension(geoPackage); } }
java
public static void deleteProperties(GeoPackageCore geoPackage, String table) { if (table.equalsIgnoreCase(PropertiesCoreExtension.TABLE_NAME)) { deletePropertiesExtension(geoPackage); } }
[ "public", "static", "void", "deleteProperties", "(", "GeoPackageCore", "geoPackage", ",", "String", "table", ")", "{", "if", "(", "table", ".", "equalsIgnoreCase", "(", "PropertiesCoreExtension", ".", "TABLE_NAME", ")", ")", "{", "deletePropertiesExtension", "(", ...
Delete the Properties extension if the deleted table is the properties table @param geoPackage GeoPackage @param table table name @since 3.2.0
[ "Delete", "the", "Properties", "extension", "if", "the", "deleted", "table", "is", "the", "properties", "table" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/NGAExtensions.java#L253-L259
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java
TransformerRegistry.registerSubsystemTransformers
public TransformersSubRegistration registerSubsystemTransformers(final String name, final ModelVersionRange range, final ResourceTransformer subsystemTransformer, final OperationTransformer operationTransformer, boolean placeholder) { final PathAddress subsystemAddress = PathAddress.EMPTY_ADDRESS.append(PathElement.pathElement(SUBSYSTEM, name)); for(final ModelVersion version : range.getVersions()) { subsystem.createChildRegistry(subsystemAddress, version, subsystemTransformer, operationTransformer, placeholder); } return new TransformersSubRegistrationImpl(range, subsystem, subsystemAddress); }
java
public TransformersSubRegistration registerSubsystemTransformers(final String name, final ModelVersionRange range, final ResourceTransformer subsystemTransformer, final OperationTransformer operationTransformer, boolean placeholder) { final PathAddress subsystemAddress = PathAddress.EMPTY_ADDRESS.append(PathElement.pathElement(SUBSYSTEM, name)); for(final ModelVersion version : range.getVersions()) { subsystem.createChildRegistry(subsystemAddress, version, subsystemTransformer, operationTransformer, placeholder); } return new TransformersSubRegistrationImpl(range, subsystem, subsystemAddress); }
[ "public", "TransformersSubRegistration", "registerSubsystemTransformers", "(", "final", "String", "name", ",", "final", "ModelVersionRange", "range", ",", "final", "ResourceTransformer", "subsystemTransformer", ",", "final", "OperationTransformer", "operationTransformer", ",", ...
Register a subsystem transformer. @param name the subsystem name @param range the version range @param subsystemTransformer the resource transformer @param operationTransformer the operation transformer @param placeholder whether or not the registered transformers are placeholders @return the sub registry
[ "Register", "a", "subsystem", "transformer", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java#L149-L155
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java
JimfsFileStore.setInitialAttributes
void setInitialAttributes(File file, FileAttribute<?>... attrs) { state.checkOpen(); attributes.setInitialAttributes(file, attrs); }
java
void setInitialAttributes(File file, FileAttribute<?>... attrs) { state.checkOpen(); attributes.setInitialAttributes(file, attrs); }
[ "void", "setInitialAttributes", "(", "File", "file", ",", "FileAttribute", "<", "?", ">", "...", "attrs", ")", "{", "state", ".", "checkOpen", "(", ")", ";", "attributes", ".", "setInitialAttributes", "(", "file", ",", "attrs", ")", ";", "}" ]
Sets initial attributes on the given file. Sets default attributes first, then attempts to set the given user-provided attributes.
[ "Sets", "initial", "attributes", "on", "the", "given", "file", ".", "Sets", "default", "attributes", "first", "then", "attempts", "to", "set", "the", "given", "user", "-", "provided", "attributes", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java#L164-L167
mikepenz/FastAdapter
library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java
SubItemUtil.getAllItems
public static List<IItem> getAllItems(List<IItem> items, boolean countHeaders, IPredicate predicate) { return getAllItems(items, countHeaders, false, predicate); }
java
public static List<IItem> getAllItems(List<IItem> items, boolean countHeaders, IPredicate predicate) { return getAllItems(items, countHeaders, false, predicate); }
[ "public", "static", "List", "<", "IItem", ">", "getAllItems", "(", "List", "<", "IItem", ">", "items", ",", "boolean", "countHeaders", ",", "IPredicate", "predicate", ")", "{", "return", "getAllItems", "(", "items", ",", "countHeaders", ",", "false", ",", ...
retrieves a flat list of the items in the provided list, respecting subitems regardless of there current visibility @param items the list of items to process @param countHeaders if true, headers will be counted as well @return list of items in the adapter
[ "retrieves", "a", "flat", "list", "of", "the", "items", "in", "the", "provided", "list", "respecting", "subitems", "regardless", "of", "there", "current", "visibility" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/SubItemUtil.java#L115-L117
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/Interval.java
Interval.checkFlagExclusiveSet
public static boolean checkFlagExclusiveSet(int flags, int flag, int mask) { int f = flags & flag; if (f != 0) { return ((flags & mask & ~flag) != 0)? false:true; } else { return false; } }
java
public static boolean checkFlagExclusiveSet(int flags, int flag, int mask) { int f = flags & flag; if (f != 0) { return ((flags & mask & ~flag) != 0)? false:true; } else { return false; } }
[ "public", "static", "boolean", "checkFlagExclusiveSet", "(", "int", "flags", ",", "int", "flag", ",", "int", "mask", ")", "{", "int", "f", "=", "flags", "&", "flag", ";", "if", "(", "f", "!=", "0", ")", "{", "return", "(", "(", "flags", "&", "mask"...
Utility function to check if a particular flag is set exclusively given a particular set of flags and a mask @param flags flags to check @param flag bit for flag of interest (is this flag set or not) @param mask bitmask of bits to check @return true if flag is exclusively set for flags & mask
[ "Utility", "function", "to", "check", "if", "a", "particular", "flag", "is", "set", "exclusively", "given", "a", "particular", "set", "of", "flags", "and", "a", "mask" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/Interval.java#L746-L754
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updateEntityRoleAsync
public Observable<OperationStatus> updateEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateEntityRoleOptionalParameter updateEntityRoleOptionalParameter) { return updateEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> updateEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateEntityRoleOptionalParameter updateEntityRoleOptionalParameter) { return updateEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateEntityRoleOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "updateEntityRoleAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ",", "UpdateEntityRoleOptionalParameter", "updateEntityRoleOptionalParameter", ")", "{", "retu...
Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updateEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Update", "an", "entity", "role", "for", "a", "given", "entity", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L10873-L10880
jbake-org/jbake
jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java
JBakeConfigurationFactory.createDefaultJbakeConfiguration
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache) throws ConfigurationException { DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
java
public DefaultJBakeConfiguration createDefaultJbakeConfiguration(File sourceFolder, File destination, boolean isClearCache) throws ConfigurationException { DefaultJBakeConfiguration configuration = (DefaultJBakeConfiguration) getConfigUtil().loadConfig(sourceFolder); configuration.setDestinationFolder(destination); configuration.setClearCache(isClearCache); return configuration; }
[ "public", "DefaultJBakeConfiguration", "createDefaultJbakeConfiguration", "(", "File", "sourceFolder", ",", "File", "destination", ",", "boolean", "isClearCache", ")", "throws", "ConfigurationException", "{", "DefaultJBakeConfiguration", "configuration", "=", "(", "DefaultJBa...
Creates a {@link DefaultJBakeConfiguration} @param sourceFolder The source folder of the project @param destination The destination folder to render and copy files to @param isClearCache Whether to clear database cache or not @return A configuration by given parameters @throws ConfigurationException if loading the configuration fails
[ "Creates", "a", "{" ]
train
https://github.com/jbake-org/jbake/blob/beb9042a54bf0eb168821d524c88b9ea0bee88dc/jbake-core/src/main/java/org/jbake/app/configuration/JBakeConfigurationFactory.java#L27-L34
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java
ClassUtil.findEnumConstant
public static Object findEnumConstant(Class<?> type, String constantName) { return findEnumConstant(type, constantName, true); }
java
public static Object findEnumConstant(Class<?> type, String constantName) { return findEnumConstant(type, constantName, true); }
[ "public", "static", "Object", "findEnumConstant", "(", "Class", "<", "?", ">", "type", ",", "String", "constantName", ")", "{", "return", "findEnumConstant", "(", "type", ",", "constantName", ",", "true", ")", ";", "}" ]
Finds an instance of an Enum constant on a class. Useful for safely getting the value of an enum constant without an exception being thrown like the Enum.valueOf() method causes. Searches for enum constant where case is sensitive.
[ "Finds", "an", "instance", "of", "an", "Enum", "constant", "on", "a", "class", ".", "Useful", "for", "safely", "getting", "the", "value", "of", "an", "enum", "constant", "without", "an", "exception", "being", "thrown", "like", "the", "Enum", ".", "valueOf"...
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ClassUtil.java#L41-L43
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.createExternalStorageTileCache
public static TileCache createExternalStorageTileCache(File cacheDir, String id, int firstLevelSize, int tileSize, boolean persistent) { LOGGER.info("TILECACHE INMEMORY SIZE: " + Integer.toString(firstLevelSize)); TileCache firstLevelTileCache = new InMemoryTileCache(firstLevelSize); if (cacheDir != null) { String cacheDirectoryName = cacheDir.getAbsolutePath() + File.separator + id; File cacheDirectory = new File(cacheDirectoryName); if (cacheDirectory.exists() || cacheDirectory.mkdirs()) { int tileCacheFiles = estimateSizeOfFileSystemCache(cacheDirectoryName, firstLevelSize, tileSize); if (cacheDirectory.canWrite() && tileCacheFiles > 0) { try { LOGGER.info("TILECACHE FILE SIZE: " + Integer.toString(tileCacheFiles)); TileCache secondLevelTileCache = new FileSystemTileCache(tileCacheFiles, cacheDirectory, org.mapsforge.map.android.graphics.AndroidGraphicFactory.INSTANCE, persistent); return new TwoLevelTileCache(firstLevelTileCache, secondLevelTileCache); } catch (IllegalArgumentException e) { LOGGER.warning(e.getMessage()); } } } } return firstLevelTileCache; }
java
public static TileCache createExternalStorageTileCache(File cacheDir, String id, int firstLevelSize, int tileSize, boolean persistent) { LOGGER.info("TILECACHE INMEMORY SIZE: " + Integer.toString(firstLevelSize)); TileCache firstLevelTileCache = new InMemoryTileCache(firstLevelSize); if (cacheDir != null) { String cacheDirectoryName = cacheDir.getAbsolutePath() + File.separator + id; File cacheDirectory = new File(cacheDirectoryName); if (cacheDirectory.exists() || cacheDirectory.mkdirs()) { int tileCacheFiles = estimateSizeOfFileSystemCache(cacheDirectoryName, firstLevelSize, tileSize); if (cacheDirectory.canWrite() && tileCacheFiles > 0) { try { LOGGER.info("TILECACHE FILE SIZE: " + Integer.toString(tileCacheFiles)); TileCache secondLevelTileCache = new FileSystemTileCache(tileCacheFiles, cacheDirectory, org.mapsforge.map.android.graphics.AndroidGraphicFactory.INSTANCE, persistent); return new TwoLevelTileCache(firstLevelTileCache, secondLevelTileCache); } catch (IllegalArgumentException e) { LOGGER.warning(e.getMessage()); } } } } return firstLevelTileCache; }
[ "public", "static", "TileCache", "createExternalStorageTileCache", "(", "File", "cacheDir", ",", "String", "id", ",", "int", "firstLevelSize", ",", "int", "tileSize", ",", "boolean", "persistent", ")", "{", "LOGGER", ".", "info", "(", "\"TILECACHE INMEMORY SIZE: \""...
Utility function to create a two-level tile cache along with its backends. @param cacheDir the cache directory @param id name for the directory, which will be created as a subdirectory of the cache directory @param firstLevelSize size of the first level cache (tiles number) @param tileSize tile size @param persistent whether the second level tile cache should be persistent @return a new cache created on the external storage
[ "Utility", "function", "to", "create", "a", "two", "-", "level", "tile", "cache", "along", "with", "its", "backends", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L96-L119
aws/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/OpenXJsonSerDe.java
OpenXJsonSerDe.withColumnToJsonKeyMappings
public OpenXJsonSerDe withColumnToJsonKeyMappings(java.util.Map<String, String> columnToJsonKeyMappings) { setColumnToJsonKeyMappings(columnToJsonKeyMappings); return this; }
java
public OpenXJsonSerDe withColumnToJsonKeyMappings(java.util.Map<String, String> columnToJsonKeyMappings) { setColumnToJsonKeyMappings(columnToJsonKeyMappings); return this; }
[ "public", "OpenXJsonSerDe", "withColumnToJsonKeyMappings", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "columnToJsonKeyMappings", ")", "{", "setColumnToJsonKeyMappings", "(", "columnToJsonKeyMappings", ")", ";", "return", "this", ";", "}...
<p> Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. </p> @param columnToJsonKeyMappings Maps column names to JSON keys that aren't identical to the column names. This is useful when the JSON contains keys that are Hive keywords. For example, <code>timestamp</code> is a Hive keyword. If you have a JSON key named <code>timestamp</code>, set this parameter to <code>{"ts": "timestamp"}</code> to map this key to a column named <code>ts</code>. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Maps", "column", "names", "to", "JSON", "keys", "that", "aren", "t", "identical", "to", "the", "column", "names", ".", "This", "is", "useful", "when", "the", "JSON", "contains", "keys", "that", "are", "Hive", "keywords", ".", "For", "example"...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/OpenXJsonSerDe.java#L271-L274
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java
AffectedDeploymentOverlay.redeployLinksAndTransformOperation
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException { Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames); Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create(); if (deploymentNames.isEmpty()) { for (String s : runtimeNames) { ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue()); } } if(removeOperation != null) { opBuilder.addStep(removeOperation); } for (String deploymentName : deploymentNames) { opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName))); } List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS); if (transformers == null) { context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>()); } final ModelNode slave = opBuilder.build().getOperation(); transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress())); }
java
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException { Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames); Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create(); if (deploymentNames.isEmpty()) { for (String s : runtimeNames) { ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue()); } } if(removeOperation != null) { opBuilder.addStep(removeOperation); } for (String deploymentName : deploymentNames) { opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName))); } List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS); if (transformers == null) { context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>()); } final ModelNode slave = opBuilder.build().getOperation(); transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress())); }
[ "public", "static", "void", "redeployLinksAndTransformOperation", "(", "OperationContext", "context", ",", "ModelNode", "removeOperation", ",", "PathAddress", "deploymentsRootAddress", ",", "Set", "<", "String", ">", "runtimeNames", ")", "throws", "OperationFailedException"...
It will look for all the deployments under the deploymentsRootAddress with a runtimeName in the specified list of runtime names and then transform the operation so that every server having those deployments will redeploy the affected deployments. @see #transformOperation @param removeOperation @param context @param deploymentsRootAddress @param runtimeNames @throws OperationFailedException
[ "It", "will", "look", "for", "all", "the", "deployments", "under", "the", "deploymentsRootAddress", "with", "a", "runtimeName", "in", "the", "specified", "list", "of", "runtime", "names", "and", "then", "transform", "the", "operation", "so", "that", "every", "...
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deploymentoverlay/AffectedDeploymentOverlay.java#L196-L216
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Paginator.java
Paginator.setCurrentPageIndex
public void setCurrentPageIndex(int currentPageIndex, boolean skipCheck){ if( currentPageIndex < 1){ throw new IndexOutOfBoundsException("currentPageIndex cannot be < 1"); } if(!skipCheck){ if(currentPageIndex > pageCount()){ throw new IndexOutOfBoundsException("currentPageIndex it outside of record set boundaries. "); } } this.currentPageIndex = currentPageIndex; }
java
public void setCurrentPageIndex(int currentPageIndex, boolean skipCheck){ if( currentPageIndex < 1){ throw new IndexOutOfBoundsException("currentPageIndex cannot be < 1"); } if(!skipCheck){ if(currentPageIndex > pageCount()){ throw new IndexOutOfBoundsException("currentPageIndex it outside of record set boundaries. "); } } this.currentPageIndex = currentPageIndex; }
[ "public", "void", "setCurrentPageIndex", "(", "int", "currentPageIndex", ",", "boolean", "skipCheck", ")", "{", "if", "(", "currentPageIndex", "<", "1", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"currentPageIndex cannot be < 1\"", ")", ";", "}", ...
Sets an index of a current page. This method will make a quick count query to check that the index you are setting is within the boundaries. @param currentPageIndex index of a current page. @param skipCheck <code>true</code> to skip the upper boundary check (will not make a call to DB).
[ "Sets", "an", "index", "of", "a", "current", "page", ".", "This", "method", "will", "make", "a", "quick", "count", "query", "to", "check", "that", "the", "index", "you", "are", "setting", "is", "within", "the", "boundaries", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Paginator.java#L398-L409
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.addChildrenAfter
public final void addChildrenAfter(@Nullable Node children, @Nullable Node node) { if (children == null) { return; // removeChildren() returns null when there are none } checkArgument(node == null || node.parent == this); // NOTE: If there is only one sibling, its previous pointer must point to itself. // Null indicates a fully detached node. checkNotNull(children.previous, children); if (node == null) { addChildrenToFront(children); return; } for (Node child = children; child != null; child = child.next) { checkArgument(child.parent == null); child.parent = this; } Node lastSibling = children.previous; Node nodeAfter = node.next; lastSibling.next = nodeAfter; if (nodeAfter == null) { first.previous = lastSibling; } else { nodeAfter.previous = lastSibling; } node.next = children; children.previous = node; }
java
public final void addChildrenAfter(@Nullable Node children, @Nullable Node node) { if (children == null) { return; // removeChildren() returns null when there are none } checkArgument(node == null || node.parent == this); // NOTE: If there is only one sibling, its previous pointer must point to itself. // Null indicates a fully detached node. checkNotNull(children.previous, children); if (node == null) { addChildrenToFront(children); return; } for (Node child = children; child != null; child = child.next) { checkArgument(child.parent == null); child.parent = this; } Node lastSibling = children.previous; Node nodeAfter = node.next; lastSibling.next = nodeAfter; if (nodeAfter == null) { first.previous = lastSibling; } else { nodeAfter.previous = lastSibling; } node.next = children; children.previous = node; }
[ "public", "final", "void", "addChildrenAfter", "(", "@", "Nullable", "Node", "children", ",", "@", "Nullable", "Node", "node", ")", "{", "if", "(", "children", "==", "null", ")", "{", "return", ";", "// removeChildren() returns null when there are none", "}", "c...
Add all children after 'node'. If 'node' is null, add them to the front of this node. @param children first of a list of sibling nodes who have no parent. NOTE: Usually you would get this argument from a removeChildren() call. A single detached node will not work because its sibling pointers will not be correctly initialized.
[ "Add", "all", "children", "after", "node", ".", "If", "node", "is", "null", "add", "them", "to", "the", "front", "of", "this", "node", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L921-L949
UrielCh/ovh-java-sdk
ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java
ApiOvhDomain.data_smd_smdId_GET
public OvhSmd data_smd_smdId_GET(Long smdId) throws IOException { String qPath = "/domain/data/smd/{smdId}"; StringBuilder sb = path(qPath, smdId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSmd.class); }
java
public OvhSmd data_smd_smdId_GET(Long smdId) throws IOException { String qPath = "/domain/data/smd/{smdId}"; StringBuilder sb = path(qPath, smdId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSmd.class); }
[ "public", "OvhSmd", "data_smd_smdId_GET", "(", "Long", "smdId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/domain/data/smd/{smdId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "smdId", ")", ";", "String", "resp", "=", "ex...
Retrieve information about a SMD file REST: GET /domain/data/smd/{smdId} @param smdId [required] SMD ID
[ "Retrieve", "information", "about", "a", "SMD", "file" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L141-L146
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/quantiles/Util.java
Util.computeCombinedBufferItemCapacity
static int computeCombinedBufferItemCapacity(final int k, final long n) { final int totLevels = computeNumLevelsNeeded(k, n); if (totLevels == 0) { final int bbItems = computeBaseBufferItems(k, n); return Math.max(2 * DoublesSketch.MIN_K, ceilingPowerOf2(bbItems)); } return (2 + totLevels) * k; }
java
static int computeCombinedBufferItemCapacity(final int k, final long n) { final int totLevels = computeNumLevelsNeeded(k, n); if (totLevels == 0) { final int bbItems = computeBaseBufferItems(k, n); return Math.max(2 * DoublesSketch.MIN_K, ceilingPowerOf2(bbItems)); } return (2 + totLevels) * k; }
[ "static", "int", "computeCombinedBufferItemCapacity", "(", "final", "int", "k", ",", "final", "long", "n", ")", "{", "final", "int", "totLevels", "=", "computeNumLevelsNeeded", "(", "k", ",", "n", ")", ";", "if", "(", "totLevels", "==", "0", ")", "{", "f...
Returns the total item capacity of an updatable, non-compact combined buffer given <i>k</i> and <i>n</i>. If total levels = 0, this returns the ceiling power of 2 size for the base buffer or the MIN_BASE_BUF_SIZE, whichever is larger. @param k sketch parameter. This determines the accuracy of the sketch and the size of the updatable data structure, which is a function of <i>k</i> and <i>n</i>. @param n The number of items in the input stream @return the current item capacity of the combined buffer
[ "Returns", "the", "total", "item", "capacity", "of", "an", "updatable", "non", "-", "compact", "combined", "buffer", "given", "<i", ">", "k<", "/", "i", ">", "and", "<i", ">", "n<", "/", "i", ">", ".", "If", "total", "levels", "=", "0", "this", "re...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L339-L346
google/j2objc
jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java
DecimalFormat.expandAffix
private String expandAffix(String pattern, StringBuffer buffer) { buffer.setLength(0); for (int i=0; i<pattern.length(); ) { char c = pattern.charAt(i++); if (c == QUOTE) { c = pattern.charAt(i++); switch (c) { case CURRENCY_SIGN: if (i<pattern.length() && pattern.charAt(i) == CURRENCY_SIGN) { ++i; buffer.append(symbols.getInternationalCurrencySymbol()); } else { buffer.append(symbols.getCurrencySymbol()); } continue; case PATTERN_PERCENT: c = symbols.getPercent(); break; case PATTERN_PER_MILLE: c = symbols.getPerMill(); break; case PATTERN_MINUS: c = symbols.getMinusSign(); break; } } buffer.append(c); } return buffer.toString(); }
java
private String expandAffix(String pattern, StringBuffer buffer) { buffer.setLength(0); for (int i=0; i<pattern.length(); ) { char c = pattern.charAt(i++); if (c == QUOTE) { c = pattern.charAt(i++); switch (c) { case CURRENCY_SIGN: if (i<pattern.length() && pattern.charAt(i) == CURRENCY_SIGN) { ++i; buffer.append(symbols.getInternationalCurrencySymbol()); } else { buffer.append(symbols.getCurrencySymbol()); } continue; case PATTERN_PERCENT: c = symbols.getPercent(); break; case PATTERN_PER_MILLE: c = symbols.getPerMill(); break; case PATTERN_MINUS: c = symbols.getMinusSign(); break; } } buffer.append(c); } return buffer.toString(); }
[ "private", "String", "expandAffix", "(", "String", "pattern", ",", "StringBuffer", "buffer", ")", "{", "buffer", ".", "setLength", "(", "0", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pattern", ".", "length", "(", ")", ";", ")", "{...
Expand an affix pattern into an affix string. All characters in the pattern are literal unless prefixed by QUOTE. The following characters after QUOTE are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE, PATTERN_MINUS, and CURRENCY_SIGN. If CURRENCY_SIGN is doubled (QUOTE + CURRENCY_SIGN + CURRENCY_SIGN), it is interpreted as an ISO 4217 currency code. Any other character after a QUOTE represents itself. QUOTE must be followed by another character; QUOTE may not occur by itself at the end of the pattern. @param pattern the non-null, possibly empty pattern @param buffer a scratch StringBuffer; its contents will be lost @return the expanded equivalent of pattern
[ "Expand", "an", "affix", "pattern", "into", "an", "affix", "string", ".", "All", "characters", "in", "the", "pattern", "are", "literal", "unless", "prefixed", "by", "QUOTE", ".", "The", "following", "characters", "after", "QUOTE", "are", "recognized", ":", "...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/text/DecimalFormat.java#L2817-L2847
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java
ApiOvhDedicatednasha.serviceName_partition_partitionName_options_POST
public OvhTask serviceName_partition_partitionName_options_POST(String serviceName, String partitionName, OvhAtimeEnum atime, OvhRecordSizeEnum recordsize, OvhSyncEnum sync) throws IOException { String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/options"; StringBuilder sb = path(qPath, serviceName, partitionName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "atime", atime); addBody(o, "recordsize", recordsize); addBody(o, "sync", sync); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_partition_partitionName_options_POST(String serviceName, String partitionName, OvhAtimeEnum atime, OvhRecordSizeEnum recordsize, OvhSyncEnum sync) throws IOException { String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/options"; StringBuilder sb = path(qPath, serviceName, partitionName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "atime", atime); addBody(o, "recordsize", recordsize); addBody(o, "sync", sync); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_partition_partitionName_options_POST", "(", "String", "serviceName", ",", "String", "partitionName", ",", "OvhAtimeEnum", "atime", ",", "OvhRecordSizeEnum", "recordsize", ",", "OvhSyncEnum", "sync", ")", "throws", "IOException", "{", "Str...
Setup options REST: POST /dedicated/nasha/{serviceName}/partition/{partitionName}/options @param sync [required] sync setting @param recordsize [required] ZFS recordsize @param atime [required] atime setting @param serviceName [required] The internal name of your storage @param partitionName [required] the given name of partition
[ "Setup", "options" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java#L128-L137
apache/incubator-druid
server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java
AuthorizationUtils.filterAuthorizedResources
public static <ResType> Iterable<ResType> filterAuthorizedResources( final AuthenticationResult authenticationResult, final Iterable<ResType> resources, final Function<? super ResType, Iterable<ResourceAction>> resourceActionGenerator, final AuthorizerMapper authorizerMapper ) { final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } final Map<ResourceAction, Access> resultCache = new HashMap<>(); final Iterable<ResType> filteredResources = Iterables.filter( resources, resource -> { final Iterable<ResourceAction> resourceActions = resourceActionGenerator.apply(resource); if (resourceActions == null) { return false; } for (ResourceAction resourceAction : resourceActions) { Access access = resultCache.computeIfAbsent( resourceAction, ra -> authorizer.authorize( authenticationResult, ra.getResource(), ra.getAction() ) ); if (!access.isAllowed()) { return false; } } return true; } ); return filteredResources; }
java
public static <ResType> Iterable<ResType> filterAuthorizedResources( final AuthenticationResult authenticationResult, final Iterable<ResType> resources, final Function<? super ResType, Iterable<ResourceAction>> resourceActionGenerator, final AuthorizerMapper authorizerMapper ) { final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } final Map<ResourceAction, Access> resultCache = new HashMap<>(); final Iterable<ResType> filteredResources = Iterables.filter( resources, resource -> { final Iterable<ResourceAction> resourceActions = resourceActionGenerator.apply(resource); if (resourceActions == null) { return false; } for (ResourceAction resourceAction : resourceActions) { Access access = resultCache.computeIfAbsent( resourceAction, ra -> authorizer.authorize( authenticationResult, ra.getResource(), ra.getAction() ) ); if (!access.isAllowed()) { return false; } } return true; } ); return filteredResources; }
[ "public", "static", "<", "ResType", ">", "Iterable", "<", "ResType", ">", "filterAuthorizedResources", "(", "final", "AuthenticationResult", "authenticationResult", ",", "final", "Iterable", "<", "ResType", ">", "resources", ",", "final", "Function", "<", "?", "su...
Filter a collection of resources by applying the resourceActionGenerator to each resource, return an iterable containing the filtered resources. The resourceActionGenerator returns an Iterable<ResourceAction> for each resource. If every resource-action in the iterable is authorized, the resource will be added to the filtered resources. If there is an authorization failure for one of the resource-actions, the resource will not be added to the returned filtered resources.. If the resourceActionGenerator returns null for a resource, that resource will not be added to the filtered resources. @param authenticationResult Authentication result representing identity of requester @param resources resources to be processed into resource-actions @param resourceActionGenerator Function that creates an iterable of resource-actions from a resource @param authorizerMapper authorizer mapper @return Iterable containing resources that were authorized
[ "Filter", "a", "collection", "of", "resources", "by", "applying", "the", "resourceActionGenerator", "to", "each", "resource", "return", "an", "iterable", "containing", "the", "filtered", "resources", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/server/src/main/java/org/apache/druid/server/security/AuthorizationUtils.java#L254-L292
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/geo/GeoInterface.java
GeoInterface.setContext
public void setContext(String photoId, int context) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_CONTEXT); parameters.put("photo_id", photoId); parameters.put("context", "" + context); // Note: This method requires an HTTP POST request. Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); // This method has no specific response - It returns an empty sucess response // if it completes without error. if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void setContext(String photoId, int context) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_CONTEXT); parameters.put("photo_id", photoId); parameters.put("context", "" + context); // Note: This method requires an HTTP POST request. Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); // This method has no specific response - It returns an empty sucess response // if it completes without error. if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "setContext", "(", "String", "photoId", ",", "int", "context", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "para...
Indicate the state of a photo's geotagginess beyond latitude and longitude. <p> Note : photos passed to this method must already be geotagged (using the {@link GeoInterface#setLocation(String, GeoData)} method). @param photoId Photo id (required). @param context Context is a numeric value representing the photo's geotagginess beyond latitude and longitude. For example, you may wish to indicate that a photo was taken "indoors" (1) or "outdoors" (2). @throws FlickrException
[ "Indicate", "the", "state", "of", "a", "photo", "s", "geotagginess", "beyond", "latitude", "and", "longitude", ".", "<p", ">" ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/geo/GeoInterface.java#L339-L353
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java
SeaGlassTextFieldUI.paintSearchButton
protected void paintSearchButton(Graphics g, JTextComponent c, Region region) { Rectangle bounds; if (region == SeaGlassRegion.SEARCH_FIELD_FIND_BUTTON) { bounds = getFindButtonBounds(); } else { bounds = getCancelButtonBounds(); } SeaGlassContext subcontext = getContext(c, region); SeaGlassLookAndFeel.updateSubregion(subcontext, g, bounds); SeaGlassSynthPainterImpl painter = (SeaGlassSynthPainterImpl) subcontext.getPainter(); painter.paintSearchButtonForeground(subcontext, g, bounds.x, bounds.y, bounds.width, bounds.height); subcontext.dispose(); }
java
protected void paintSearchButton(Graphics g, JTextComponent c, Region region) { Rectangle bounds; if (region == SeaGlassRegion.SEARCH_FIELD_FIND_BUTTON) { bounds = getFindButtonBounds(); } else { bounds = getCancelButtonBounds(); } SeaGlassContext subcontext = getContext(c, region); SeaGlassLookAndFeel.updateSubregion(subcontext, g, bounds); SeaGlassSynthPainterImpl painter = (SeaGlassSynthPainterImpl) subcontext.getPainter(); painter.paintSearchButtonForeground(subcontext, g, bounds.x, bounds.y, bounds.width, bounds.height); subcontext.dispose(); }
[ "protected", "void", "paintSearchButton", "(", "Graphics", "g", ",", "JTextComponent", "c", ",", "Region", "region", ")", "{", "Rectangle", "bounds", ";", "if", "(", "region", "==", "SeaGlassRegion", ".", "SEARCH_FIELD_FIND_BUTTON", ")", "{", "bounds", "=", "g...
DOCUMENT ME! @param g DOCUMENT ME! @param c DOCUMENT ME! @param region DOCUMENT ME!
[ "DOCUMENT", "ME!" ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassTextFieldUI.java#L527-L545
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/XmlStringBuilder.java
XmlStringBuilder.appendOptionalUrlAttribute
public void appendOptionalUrlAttribute(final String name, final String value) { if (value != null) { appendUrlAttribute(name, value); } }
java
public void appendOptionalUrlAttribute(final String name, final String value) { if (value != null) { appendUrlAttribute(name, value); } }
[ "public", "void", "appendOptionalUrlAttribute", "(", "final", "String", "name", ",", "final", "String", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "appendUrlAttribute", "(", "name", ",", "value", ")", ";", "}", "}" ]
<p> If the value is not null, add an xml attribute name+value pair to the end of this XmlStringBuilder <p> Eg. name="value" </p> @param name the name of the attribute to be added. @param value the value of the attribute.
[ "<p", ">", "If", "the", "value", "is", "not", "null", "add", "an", "xml", "attribute", "name", "+", "value", "pair", "to", "the", "end", "of", "this", "XmlStringBuilder", "<p", ">", "Eg", ".", "name", "=", "value", "<", "/", "p", ">" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/XmlStringBuilder.java#L169-L173
samskivert/samskivert
src/main/java/com/samskivert/util/CountHashMap.java
CountHashMap.incrementCount
public int incrementCount (K key, int amount) { int[] val = get(key); if (val == null) { put(key, val = new int[1]); } val[0] += amount; return val[0]; /* Alternate implementation, less hashing on the first increment but more garbage created * every other time. (this whole method would be more optimal if this class were * rewritten) * int[] newVal = new int[] { amount }; int[] oldVal = put(key, newVal); if (oldVal != null) { newVal[0] += oldVal[0]; return oldVal[0]; } return 0; */ }
java
public int incrementCount (K key, int amount) { int[] val = get(key); if (val == null) { put(key, val = new int[1]); } val[0] += amount; return val[0]; /* Alternate implementation, less hashing on the first increment but more garbage created * every other time. (this whole method would be more optimal if this class were * rewritten) * int[] newVal = new int[] { amount }; int[] oldVal = put(key, newVal); if (oldVal != null) { newVal[0] += oldVal[0]; return oldVal[0]; } return 0; */ }
[ "public", "int", "incrementCount", "(", "K", "key", ",", "int", "amount", ")", "{", "int", "[", "]", "val", "=", "get", "(", "key", ")", ";", "if", "(", "val", "==", "null", ")", "{", "put", "(", "key", ",", "val", "=", "new", "int", "[", "1"...
Increment the value associated with the specified key, return the new value.
[ "Increment", "the", "value", "associated", "with", "the", "specified", "key", "return", "the", "new", "value", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/CountHashMap.java#L42-L63
selenide/selenide
src/main/java/com/codeborne/selenide/Condition.java
Condition.textCaseSensitive
public static Condition textCaseSensitive(final String text) { return new Condition("textCaseSensitive") { @Override public boolean apply(Driver driver, WebElement element) { return Html.text.containsCaseSensitive(element.getText(), text); } @Override public String toString() { return name + " '" + text + '\''; } }; }
java
public static Condition textCaseSensitive(final String text) { return new Condition("textCaseSensitive") { @Override public boolean apply(Driver driver, WebElement element) { return Html.text.containsCaseSensitive(element.getText(), text); } @Override public String toString() { return name + " '" + text + '\''; } }; }
[ "public", "static", "Condition", "textCaseSensitive", "(", "final", "String", "text", ")", "{", "return", "new", "Condition", "(", "\"textCaseSensitive\"", ")", "{", "@", "Override", "public", "boolean", "apply", "(", "Driver", "driver", ",", "WebElement", "elem...
<p>Sample: <code>$("h1").shouldHave(textCaseSensitive("Hello\s*John"))</code></p> <p>NB! Ignores multiple whitespaces between words</p> @param text expected text of HTML element
[ "<p", ">", "Sample", ":", "<code", ">", "$", "(", "h1", ")", ".", "shouldHave", "(", "textCaseSensitive", "(", "Hello", "\\", "s", "*", "John", "))", "<", "/", "code", ">", "<", "/", "p", ">" ]
train
https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L298-L310
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeRegex.java
UnicodeRegex.appendLines
public static List<String> appendLines(List<String> result, InputStream inputStream, String encoding) throws UnsupportedEncodingException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, encoding == null ? "UTF-8" : encoding)); while (true) { String line = in.readLine(); if (line == null) break; result.add(line); } return result; }
java
public static List<String> appendLines(List<String> result, InputStream inputStream, String encoding) throws UnsupportedEncodingException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, encoding == null ? "UTF-8" : encoding)); while (true) { String line = in.readLine(); if (line == null) break; result.add(line); } return result; }
[ "public", "static", "List", "<", "String", ">", "appendLines", "(", "List", "<", "String", ">", "result", ",", "InputStream", "inputStream", ",", "String", "encoding", ")", "throws", "UnsupportedEncodingException", ",", "IOException", "{", "BufferedReader", "in", ...
Utility for loading lines from a UTF8 file. @param result The result of the appended lines. @param inputStream The input stream. @param encoding if null, then UTF-8 @return filled list @throws IOException If there were problems opening the input stream for reading.
[ "Utility", "for", "loading", "lines", "from", "a", "UTF8", "file", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeRegex.java#L296-L305
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java
Schema.removeVertexLabel
void removeVertexLabel(VertexLabel vertexLabel, boolean preserveData) { getTopology().lock(); String fn = this.name + "." + VERTEX_PREFIX + vertexLabel.getName(); if (!uncommittedRemovedVertexLabels.contains(fn)) { uncommittedRemovedVertexLabels.add(fn); TopologyManager.removeVertexLabel(this.sqlgGraph, vertexLabel); for (EdgeRole er : vertexLabel.getOutEdgeRoles().values()) { er.remove(preserveData); } for (EdgeRole er : vertexLabel.getInEdgeRoles().values()) { er.remove(preserveData); } if (!preserveData) { vertexLabel.delete(); } getTopology().fire(vertexLabel, "", TopologyChangeAction.DELETE); } }
java
void removeVertexLabel(VertexLabel vertexLabel, boolean preserveData) { getTopology().lock(); String fn = this.name + "." + VERTEX_PREFIX + vertexLabel.getName(); if (!uncommittedRemovedVertexLabels.contains(fn)) { uncommittedRemovedVertexLabels.add(fn); TopologyManager.removeVertexLabel(this.sqlgGraph, vertexLabel); for (EdgeRole er : vertexLabel.getOutEdgeRoles().values()) { er.remove(preserveData); } for (EdgeRole er : vertexLabel.getInEdgeRoles().values()) { er.remove(preserveData); } if (!preserveData) { vertexLabel.delete(); } getTopology().fire(vertexLabel, "", TopologyChangeAction.DELETE); } }
[ "void", "removeVertexLabel", "(", "VertexLabel", "vertexLabel", ",", "boolean", "preserveData", ")", "{", "getTopology", "(", ")", ".", "lock", "(", ")", ";", "String", "fn", "=", "this", ".", "name", "+", "\".\"", "+", "VERTEX_PREFIX", "+", "vertexLabel", ...
remove a given vertex label @param vertexLabel the vertex label @param preserveData should we keep the SQL data
[ "remove", "a", "given", "vertex", "label" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Schema.java#L1784-L1802
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java
FlowLoaderUtils.addEmailPropsToFlow
public static void addEmailPropsToFlow(final Flow flow, final Props prop) { final List<String> successEmailList = prop.getStringList(CommonJobProperties.SUCCESS_EMAILS, Collections.EMPTY_LIST); final Set<String> successEmail = new HashSet<>(); for (final String email : successEmailList) { successEmail.add(email.toLowerCase()); } final List<String> failureEmailList = prop.getStringList(CommonJobProperties.FAILURE_EMAILS, Collections.EMPTY_LIST); final Set<String> failureEmail = new HashSet<>(); for (final String email : failureEmailList) { failureEmail.add(email.toLowerCase()); } final List<String> notifyEmailList = prop.getStringList(CommonJobProperties.NOTIFY_EMAILS, Collections.EMPTY_LIST); for (String email : notifyEmailList) { email = email.toLowerCase(); successEmail.add(email); failureEmail.add(email); } flow.addFailureEmails(failureEmail); flow.addSuccessEmails(successEmail); }
java
public static void addEmailPropsToFlow(final Flow flow, final Props prop) { final List<String> successEmailList = prop.getStringList(CommonJobProperties.SUCCESS_EMAILS, Collections.EMPTY_LIST); final Set<String> successEmail = new HashSet<>(); for (final String email : successEmailList) { successEmail.add(email.toLowerCase()); } final List<String> failureEmailList = prop.getStringList(CommonJobProperties.FAILURE_EMAILS, Collections.EMPTY_LIST); final Set<String> failureEmail = new HashSet<>(); for (final String email : failureEmailList) { failureEmail.add(email.toLowerCase()); } final List<String> notifyEmailList = prop.getStringList(CommonJobProperties.NOTIFY_EMAILS, Collections.EMPTY_LIST); for (String email : notifyEmailList) { email = email.toLowerCase(); successEmail.add(email); failureEmail.add(email); } flow.addFailureEmails(failureEmail); flow.addSuccessEmails(successEmail); }
[ "public", "static", "void", "addEmailPropsToFlow", "(", "final", "Flow", "flow", ",", "final", "Props", "prop", ")", "{", "final", "List", "<", "String", ">", "successEmailList", "=", "prop", ".", "getStringList", "(", "CommonJobProperties", ".", "SUCCESS_EMAILS...
Adds email properties to a flow. @param flow the flow @param prop the prop
[ "Adds", "email", "properties", "to", "a", "flow", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/FlowLoaderUtils.java#L198-L226
junit-team/junit4
src/main/java/org/junit/runner/manipulation/Ordering.java
Ordering.definedBy
public static Ordering definedBy( Class<? extends Ordering.Factory> factoryClass, Description annotatedTestClass) throws InvalidOrderingException { if (factoryClass == null) { throw new NullPointerException("factoryClass cannot be null"); } if (annotatedTestClass == null) { throw new NullPointerException("annotatedTestClass cannot be null"); } Ordering.Factory factory; try { Constructor<? extends Ordering.Factory> constructor = factoryClass.getConstructor(); factory = constructor.newInstance(); } catch (NoSuchMethodException e) { throw new InvalidOrderingException(String.format( CONSTRUCTOR_ERROR_FORMAT, getClassName(factoryClass), factoryClass.getSimpleName())); } catch (Exception e) { throw new InvalidOrderingException( "Could not create ordering for " + annotatedTestClass, e); } return definedBy(factory, annotatedTestClass); }
java
public static Ordering definedBy( Class<? extends Ordering.Factory> factoryClass, Description annotatedTestClass) throws InvalidOrderingException { if (factoryClass == null) { throw new NullPointerException("factoryClass cannot be null"); } if (annotatedTestClass == null) { throw new NullPointerException("annotatedTestClass cannot be null"); } Ordering.Factory factory; try { Constructor<? extends Ordering.Factory> constructor = factoryClass.getConstructor(); factory = constructor.newInstance(); } catch (NoSuchMethodException e) { throw new InvalidOrderingException(String.format( CONSTRUCTOR_ERROR_FORMAT, getClassName(factoryClass), factoryClass.getSimpleName())); } catch (Exception e) { throw new InvalidOrderingException( "Could not create ordering for " + annotatedTestClass, e); } return definedBy(factory, annotatedTestClass); }
[ "public", "static", "Ordering", "definedBy", "(", "Class", "<", "?", "extends", "Ordering", ".", "Factory", ">", "factoryClass", ",", "Description", "annotatedTestClass", ")", "throws", "InvalidOrderingException", "{", "if", "(", "factoryClass", "==", "null", ")",...
Creates an {@link Ordering} from the given factory class. The class must have a public no-arg constructor. @param factoryClass class to use to create the ordering @param annotatedTestClass test class that is annotated with {@link OrderWith}. @throws InvalidOrderingException if the instance could not be created
[ "Creates", "an", "{", "@link", "Ordering", "}", "from", "the", "given", "factory", "class", ".", "The", "class", "must", "have", "a", "public", "no", "-", "arg", "constructor", "." ]
train
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/manipulation/Ordering.java#L55-L79
j256/simplejmx
src/main/java/com/j256/simplejmx/client/JmxClient.java
JmxClient.invokeOperation
public Object invokeOperation(ObjectName name, String operName, String... paramStrings) throws Exception { String[] paramTypes = lookupParamTypes(name, operName, paramStrings); Object[] paramObjs; if (paramStrings.length == 0) { paramObjs = null; } else { paramObjs = new Object[paramStrings.length]; for (int i = 0; i < paramStrings.length; i++) { paramObjs[i] = ClientUtils.stringToParam(paramStrings[i], paramTypes[i]); } } return invokeOperation(name, operName, paramTypes, paramObjs); }
java
public Object invokeOperation(ObjectName name, String operName, String... paramStrings) throws Exception { String[] paramTypes = lookupParamTypes(name, operName, paramStrings); Object[] paramObjs; if (paramStrings.length == 0) { paramObjs = null; } else { paramObjs = new Object[paramStrings.length]; for (int i = 0; i < paramStrings.length; i++) { paramObjs[i] = ClientUtils.stringToParam(paramStrings[i], paramTypes[i]); } } return invokeOperation(name, operName, paramTypes, paramObjs); }
[ "public", "Object", "invokeOperation", "(", "ObjectName", "name", ",", "String", "operName", ",", "String", "...", "paramStrings", ")", "throws", "Exception", "{", "String", "[", "]", "paramTypes", "=", "lookupParamTypes", "(", "name", ",", "operName", ",", "p...
Invoke a JMX method as an array of parameter strings. @return The value returned by the method or null if none.
[ "Invoke", "a", "JMX", "method", "as", "an", "array", "of", "parameter", "strings", "." ]
train
https://github.com/j256/simplejmx/blob/1a04f52512dfa0a711ba0cc7023c604dbc82a352/src/main/java/com/j256/simplejmx/client/JmxClient.java#L421-L433
jlinn/quartz-redis-jobstore
src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java
AbstractRedisStorage.isBlockedJob
protected boolean isBlockedJob(String jobHashKey, T jedis) { JobKey jobKey = redisSchema.jobKey(jobHashKey); return jedis.sismember(redisSchema.blockedJobsSet(), jobHashKey) && isActiveInstance(jedis.get(redisSchema.jobBlockedKey(jobKey)), jedis); }
java
protected boolean isBlockedJob(String jobHashKey, T jedis) { JobKey jobKey = redisSchema.jobKey(jobHashKey); return jedis.sismember(redisSchema.blockedJobsSet(), jobHashKey) && isActiveInstance(jedis.get(redisSchema.jobBlockedKey(jobKey)), jedis); }
[ "protected", "boolean", "isBlockedJob", "(", "String", "jobHashKey", ",", "T", "jedis", ")", "{", "JobKey", "jobKey", "=", "redisSchema", ".", "jobKey", "(", "jobHashKey", ")", ";", "return", "jedis", ".", "sismember", "(", "redisSchema", ".", "blockedJobsSet"...
Determine if the given job is blocked by an active instance @param jobHashKey the job in question @param jedis a thread-safe Redis connection @return true if the given job is blocked by an active instance
[ "Determine", "if", "the", "given", "job", "is", "blocked", "by", "an", "active", "instance" ]
train
https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L768-L772
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.doubleFunction
public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function) { return doubleFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function) { return doubleFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "R", ">", "DoubleFunction", "<", "R", ">", "doubleFunction", "(", "CheckedDoubleFunction", "<", "R", ">", "function", ")", "{", "return", "doubleFunction", "(", "function", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedDoubleFunction} in a {@link DoubleFunction}. <p> Example: <code><pre> DoubleStream.of(1.0, 2.0, 3.0).mapToObj(Unchecked.doubleFunction(d -> { if (d &lt; 0.0) throw new Exception("Only positive numbers allowed"); return "" + d; }); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedDoubleFunction", "}", "in", "a", "{", "@link", "DoubleFunction", "}", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "DoubleStream", ".", "of", "(", "1", ".", "0", "2", ".", "0", "3", ".", "0", ")", ...
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1333-L1335
BoltsFramework/Bolts-Android
bolts-tasks/src/main/java/bolts/Task.java
Task.continueWith
public <TContinuationResult> Task<TContinuationResult> continueWith( Continuation<TResult, TContinuationResult> continuation) { return continueWith(continuation, IMMEDIATE_EXECUTOR, null); }
java
public <TContinuationResult> Task<TContinuationResult> continueWith( Continuation<TResult, TContinuationResult> continuation) { return continueWith(continuation, IMMEDIATE_EXECUTOR, null); }
[ "public", "<", "TContinuationResult", ">", "Task", "<", "TContinuationResult", ">", "continueWith", "(", "Continuation", "<", "TResult", ",", "TContinuationResult", ">", "continuation", ")", "{", "return", "continueWith", "(", "continuation", ",", "IMMEDIATE_EXECUTOR"...
Adds a synchronous continuation to this task, returning a new task that completes after the continuation has finished running.
[ "Adds", "a", "synchronous", "continuation", "to", "this", "task", "returning", "a", "new", "task", "that", "completes", "after", "the", "continuation", "has", "finished", "running", "." ]
train
https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L667-L670
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandStream.java
AdminCommandStream.executeHelp
public static void executeHelp(String[] args, PrintStream stream) throws Exception { String subCmd = (args.length > 0) ? args[0] : ""; if(subCmd.equals("fetch-entries")) { SubCommandStreamFetchEntries.printHelp(stream); } else if(subCmd.equals("fetch-keys")) { SubCommandStreamFetchKeys.printHelp(stream); } else if(subCmd.equals("mirror")) { SubCommandStreamMirror.printHelp(stream); } else if(subCmd.equals("update-entries")) { SubCommandStreamUpdateEntries.printHelp(stream); } else { printHelp(stream); } }
java
public static void executeHelp(String[] args, PrintStream stream) throws Exception { String subCmd = (args.length > 0) ? args[0] : ""; if(subCmd.equals("fetch-entries")) { SubCommandStreamFetchEntries.printHelp(stream); } else if(subCmd.equals("fetch-keys")) { SubCommandStreamFetchKeys.printHelp(stream); } else if(subCmd.equals("mirror")) { SubCommandStreamMirror.printHelp(stream); } else if(subCmd.equals("update-entries")) { SubCommandStreamUpdateEntries.printHelp(stream); } else { printHelp(stream); } }
[ "public", "static", "void", "executeHelp", "(", "String", "[", "]", "args", ",", "PrintStream", "stream", ")", "throws", "Exception", "{", "String", "subCmd", "=", "(", "args", ".", "length", ">", "0", ")", "?", "args", "[", "0", "]", ":", "\"\"", ";...
Parses command-line input and prints help menu. @throws Exception
[ "Parses", "command", "-", "line", "input", "and", "prints", "help", "menu", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandStream.java#L121-L134