repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java
SegmentedBucketLocker.lockBucketsRead
void lockBucketsRead(long i1, long i2) { """ Locks segments corresponding to bucket indexes in specific order to prevent deadlocks """ int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always lock segments in same order to avoid deadlocks if (bucket1LockIdx < bucket2LockIdx) { lockAry[bucket1LockIdx].readLock(); lockAry[bucket2LockIdx].readLock(); } else if (bucket1LockIdx > bucket2LockIdx) { lockAry[bucket2LockIdx].readLock(); lockAry[bucket1LockIdx].readLock(); } // if we get here both indexes are on same segment so only lock once!!! else { lockAry[bucket1LockIdx].readLock(); } }
java
void lockBucketsRead(long i1, long i2) { int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always lock segments in same order to avoid deadlocks if (bucket1LockIdx < bucket2LockIdx) { lockAry[bucket1LockIdx].readLock(); lockAry[bucket2LockIdx].readLock(); } else if (bucket1LockIdx > bucket2LockIdx) { lockAry[bucket2LockIdx].readLock(); lockAry[bucket1LockIdx].readLock(); } // if we get here both indexes are on same segment so only lock once!!! else { lockAry[bucket1LockIdx].readLock(); } }
[ "void", "lockBucketsRead", "(", "long", "i1", ",", "long", "i2", ")", "{", "int", "bucket1LockIdx", "=", "getBucketLock", "(", "i1", ")", ";", "int", "bucket2LockIdx", "=", "getBucketLock", "(", "i2", ")", ";", "// always lock segments in same order to avoid deadlocks\r", "if", "(", "bucket1LockIdx", "<", "bucket2LockIdx", ")", "{", "lockAry", "[", "bucket1LockIdx", "]", ".", "readLock", "(", ")", ";", "lockAry", "[", "bucket2LockIdx", "]", ".", "readLock", "(", ")", ";", "}", "else", "if", "(", "bucket1LockIdx", ">", "bucket2LockIdx", ")", "{", "lockAry", "[", "bucket2LockIdx", "]", ".", "readLock", "(", ")", ";", "lockAry", "[", "bucket1LockIdx", "]", ".", "readLock", "(", ")", ";", "}", "// if we get here both indexes are on same segment so only lock once!!!\r", "else", "{", "lockAry", "[", "bucket1LockIdx", "]", ".", "readLock", "(", ")", ";", "}", "}" ]
Locks segments corresponding to bucket indexes in specific order to prevent deadlocks
[ "Locks", "segments", "corresponding", "to", "bucket", "indexes", "in", "specific", "order", "to", "prevent", "deadlocks" ]
train
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java#L83-L98
sniggle/simple-pgp
simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java
BasePGPCommon.retrieveSecretKey
protected PGPSecretKey retrieveSecretKey(PGPSecretKeyRingCollection secretKeyRingCollection, KeyFilter<PGPSecretKey> keyFilter) throws PGPException { """ retrieve the appropriate secret key from the secret key ring collection based on the key filter @param secretKeyRingCollection the PGP secret key ring collection @param keyFilter the key filter to apply @return the secret key or null if none matches the filter @throws PGPException """ LOGGER.trace("retrieveSecretKey(PGPSecretKeyRingCollection, KeyFilter<PGPSecretKey>)"); LOGGER.trace("Secret KeyRing Collection: {}, Key Filter: {}", secretKeyRingCollection == null ? "not set" : "set", keyFilter == null ? "not set" : "set"); PGPSecretKey result = null; Iterator<PGPSecretKeyRing> secretKeyRingIterator = secretKeyRingCollection.getKeyRings(); PGPSecretKeyRing secretKeyRing = null; LOGGER.debug("Iterating secret key ring"); while( result == null && secretKeyRingIterator.hasNext() ) { secretKeyRing = secretKeyRingIterator.next(); Iterator<PGPSecretKey> secretKeyIterator = secretKeyRing.getSecretKeys(); LOGGER.debug("Iterating secret keys in key ring"); while( secretKeyIterator.hasNext() ) { PGPSecretKey secretKey = secretKeyIterator.next(); LOGGER.info("Found secret key: {}", secretKey.getKeyID()); LOGGER.debug("Checking secret key with filter"); if (keyFilter.accept(secretKey)) { LOGGER.info("Key {} selected from secret key ring"); result = secretKey; } } } return result; }
java
protected PGPSecretKey retrieveSecretKey(PGPSecretKeyRingCollection secretKeyRingCollection, KeyFilter<PGPSecretKey> keyFilter) throws PGPException { LOGGER.trace("retrieveSecretKey(PGPSecretKeyRingCollection, KeyFilter<PGPSecretKey>)"); LOGGER.trace("Secret KeyRing Collection: {}, Key Filter: {}", secretKeyRingCollection == null ? "not set" : "set", keyFilter == null ? "not set" : "set"); PGPSecretKey result = null; Iterator<PGPSecretKeyRing> secretKeyRingIterator = secretKeyRingCollection.getKeyRings(); PGPSecretKeyRing secretKeyRing = null; LOGGER.debug("Iterating secret key ring"); while( result == null && secretKeyRingIterator.hasNext() ) { secretKeyRing = secretKeyRingIterator.next(); Iterator<PGPSecretKey> secretKeyIterator = secretKeyRing.getSecretKeys(); LOGGER.debug("Iterating secret keys in key ring"); while( secretKeyIterator.hasNext() ) { PGPSecretKey secretKey = secretKeyIterator.next(); LOGGER.info("Found secret key: {}", secretKey.getKeyID()); LOGGER.debug("Checking secret key with filter"); if (keyFilter.accept(secretKey)) { LOGGER.info("Key {} selected from secret key ring"); result = secretKey; } } } return result; }
[ "protected", "PGPSecretKey", "retrieveSecretKey", "(", "PGPSecretKeyRingCollection", "secretKeyRingCollection", ",", "KeyFilter", "<", "PGPSecretKey", ">", "keyFilter", ")", "throws", "PGPException", "{", "LOGGER", ".", "trace", "(", "\"retrieveSecretKey(PGPSecretKeyRingCollection, KeyFilter<PGPSecretKey>)\"", ")", ";", "LOGGER", ".", "trace", "(", "\"Secret KeyRing Collection: {}, Key Filter: {}\"", ",", "secretKeyRingCollection", "==", "null", "?", "\"not set\"", ":", "\"set\"", ",", "keyFilter", "==", "null", "?", "\"not set\"", ":", "\"set\"", ")", ";", "PGPSecretKey", "result", "=", "null", ";", "Iterator", "<", "PGPSecretKeyRing", ">", "secretKeyRingIterator", "=", "secretKeyRingCollection", ".", "getKeyRings", "(", ")", ";", "PGPSecretKeyRing", "secretKeyRing", "=", "null", ";", "LOGGER", ".", "debug", "(", "\"Iterating secret key ring\"", ")", ";", "while", "(", "result", "==", "null", "&&", "secretKeyRingIterator", ".", "hasNext", "(", ")", ")", "{", "secretKeyRing", "=", "secretKeyRingIterator", ".", "next", "(", ")", ";", "Iterator", "<", "PGPSecretKey", ">", "secretKeyIterator", "=", "secretKeyRing", ".", "getSecretKeys", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"Iterating secret keys in key ring\"", ")", ";", "while", "(", "secretKeyIterator", ".", "hasNext", "(", ")", ")", "{", "PGPSecretKey", "secretKey", "=", "secretKeyIterator", ".", "next", "(", ")", ";", "LOGGER", ".", "info", "(", "\"Found secret key: {}\"", ",", "secretKey", ".", "getKeyID", "(", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Checking secret key with filter\"", ")", ";", "if", "(", "keyFilter", ".", "accept", "(", "secretKey", ")", ")", "{", "LOGGER", ".", "info", "(", "\"Key {} selected from secret key ring\"", ")", ";", "result", "=", "secretKey", ";", "}", "}", "}", "return", "result", ";", "}" ]
retrieve the appropriate secret key from the secret key ring collection based on the key filter @param secretKeyRingCollection the PGP secret key ring collection @param keyFilter the key filter to apply @return the secret key or null if none matches the filter @throws PGPException
[ "retrieve", "the", "appropriate", "secret", "key", "from", "the", "secret", "key", "ring", "collection", "based", "on", "the", "key", "filter" ]
train
https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java#L79-L101
apache/incubator-shardingsphere
sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/common/MemoryQueryResultRow.java
MemoryQueryResultRow.setCell
public void setCell(final int columnIndex, final Object value) { """ Set data for cell. @param columnIndex column index @param value data for cell """ Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.length + 1); data[columnIndex - 1] = value; }
java
public void setCell(final int columnIndex, final Object value) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.length + 1); data[columnIndex - 1] = value; }
[ "public", "void", "setCell", "(", "final", "int", "columnIndex", ",", "final", "Object", "value", ")", "{", "Preconditions", ".", "checkArgument", "(", "columnIndex", ">", "0", "&&", "columnIndex", "<", "data", ".", "length", "+", "1", ")", ";", "data", "[", "columnIndex", "-", "1", "]", "=", "value", ";", "}" ]
Set data for cell. @param columnIndex column index @param value data for cell
[ "Set", "data", "for", "cell", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/common/MemoryQueryResultRow.java#L64-L67
ops4j/org.ops4j.pax.web
pax-web-resources/pax-web-resources-jsf/src/main/java/org/ops4j/pax/web/resources/jsf/internal/ResourceHandlerUtils.java
ResourceHandlerUtils.pipeBytes
public static int pipeBytes(InputStream in, OutputStream out, byte[] buffer) throws IOException { """ Reads the specified input stream into the provided byte array storage and writes it to the output stream. """ int count = 0; int length; while ((length = (in.read(buffer))) >= 0) { out.write(buffer, 0, length); count += length; } return count; }
java
public static int pipeBytes(InputStream in, OutputStream out, byte[] buffer) throws IOException { int count = 0; int length; while ((length = (in.read(buffer))) >= 0) { out.write(buffer, 0, length); count += length; } return count; }
[ "public", "static", "int", "pipeBytes", "(", "InputStream", "in", ",", "OutputStream", "out", ",", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "int", "count", "=", "0", ";", "int", "length", ";", "while", "(", "(", "length", "=", "(", "in", ".", "read", "(", "buffer", ")", ")", ")", ">=", "0", ")", "{", "out", ".", "write", "(", "buffer", ",", "0", ",", "length", ")", ";", "count", "+=", "length", ";", "}", "return", "count", ";", "}" ]
Reads the specified input stream into the provided byte array storage and writes it to the output stream.
[ "Reads", "the", "specified", "input", "stream", "into", "the", "provided", "byte", "array", "storage", "and", "writes", "it", "to", "the", "output", "stream", "." ]
train
https://github.com/ops4j/org.ops4j.pax.web/blob/9ecf3676c1d316be0d43ea7fcfdc8f0defffc2a2/pax-web-resources/pax-web-resources-jsf/src/main/java/org/ops4j/pax/web/resources/jsf/internal/ResourceHandlerUtils.java#L203-L212
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java
CategoryGraph.matchesFilter
private boolean matchesFilter(Category cat, List<String> filterList) throws WikiTitleParsingException { """ Checks whether the category title matches the filter (a filter matches a string, if the string starts with the filter expression). @param cat A category. @param filterList A list of filter strings. @return True, if the category title starts with or is equal to a string in the filter list. False, otherwise. @throws WikiTitleParsingException Thrown if errors occurred. """ String categoryTitle = cat.getTitle().getPlainTitle(); for (String filter : filterList) { if (categoryTitle.startsWith(filter)) { logger.info(categoryTitle + " starts with " + filter + " => removing"); return true; } } return false; }
java
private boolean matchesFilter(Category cat, List<String> filterList) throws WikiTitleParsingException { String categoryTitle = cat.getTitle().getPlainTitle(); for (String filter : filterList) { if (categoryTitle.startsWith(filter)) { logger.info(categoryTitle + " starts with " + filter + " => removing"); return true; } } return false; }
[ "private", "boolean", "matchesFilter", "(", "Category", "cat", ",", "List", "<", "String", ">", "filterList", ")", "throws", "WikiTitleParsingException", "{", "String", "categoryTitle", "=", "cat", ".", "getTitle", "(", ")", ".", "getPlainTitle", "(", ")", ";", "for", "(", "String", "filter", ":", "filterList", ")", "{", "if", "(", "categoryTitle", ".", "startsWith", "(", "filter", ")", ")", "{", "logger", ".", "info", "(", "categoryTitle", "+", "\" starts with \"", "+", "filter", "+", "\" => removing\"", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the category title matches the filter (a filter matches a string, if the string starts with the filter expression). @param cat A category. @param filterList A list of filter strings. @return True, if the category title starts with or is equal to a string in the filter list. False, otherwise. @throws WikiTitleParsingException Thrown if errors occurred.
[ "Checks", "whether", "the", "category", "title", "matches", "the", "filter", "(", "a", "filter", "matches", "a", "string", "if", "the", "string", "starts", "with", "the", "filter", "expression", ")", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/CategoryGraph.java#L378-L387
joniles/mpxj
src/main/java/net/sf/mpxj/ProjectProperties.java
ProjectProperties.setBaselineDate
public void setBaselineDate(int baselineNumber, Date value) { """ Set a baseline value. @param baselineNumber baseline index (1-10) @param value baseline value """ set(selectField(ProjectFieldLists.BASELINE_DATES, baselineNumber), value); }
java
public void setBaselineDate(int baselineNumber, Date value) { set(selectField(ProjectFieldLists.BASELINE_DATES, baselineNumber), value); }
[ "public", "void", "setBaselineDate", "(", "int", "baselineNumber", ",", "Date", "value", ")", "{", "set", "(", "selectField", "(", "ProjectFieldLists", ".", "BASELINE_DATES", ",", "baselineNumber", ")", ",", "value", ")", ";", "}" ]
Set a baseline value. @param baselineNumber baseline index (1-10) @param value baseline value
[ "Set", "a", "baseline", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectProperties.java#L2193-L2196
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/release/ReleaseAction.java
ReleaseAction.doApi
@SuppressWarnings( { """ This method is used to initiate a release staging process using the Artifactory Release Staging API. """"UnusedDeclaration"}) protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { try { log.log(Level.INFO, "Initiating Artifactory Release Staging using API"); // Enforce release permissions project.checkPermission(ArtifactoryPlugin.RELEASE); // In case a staging user plugin is configured, the init() method invoke it: init(); // Read the values provided by the staging user plugin and assign them to data members in this class. // Those values can be overriden by URL arguments sent with the API: readStagingPluginValues(); // Read values from the request and override the staging plugin values: overrideStagingPluginParams(req); // Schedule the release build: Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule( project, 0, new Action[]{this, new CauseAction(new Cause.UserIdCause())} ); if (item == null) { log.log(Level.SEVERE, "Failed to schedule a release build following a Release API invocation"); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); } else { String url = req.getContextPath() + '/' + item.getUrl(); JSONObject json = new JSONObject(); json.element("queueItem", item.getId()); json.element("releaseVersion", getReleaseVersion()); json.element("nextVersion", getNextVersion()); json.element("releaseBranch", getReleaseBranch()); // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it) resp.getOutputStream().print(json.toString()); resp.sendRedirect(201, url); } } catch (Exception e) { log.log(Level.SEVERE, "Artifactory Release Staging API invocation failed: " + e.getMessage(), e); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); resp.getWriter().write(mapper.writeValueAsString(errorResponse)); } }
java
@SuppressWarnings({"UnusedDeclaration"}) protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { try { log.log(Level.INFO, "Initiating Artifactory Release Staging using API"); // Enforce release permissions project.checkPermission(ArtifactoryPlugin.RELEASE); // In case a staging user plugin is configured, the init() method invoke it: init(); // Read the values provided by the staging user plugin and assign them to data members in this class. // Those values can be overriden by URL arguments sent with the API: readStagingPluginValues(); // Read values from the request and override the staging plugin values: overrideStagingPluginParams(req); // Schedule the release build: Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule( project, 0, new Action[]{this, new CauseAction(new Cause.UserIdCause())} ); if (item == null) { log.log(Level.SEVERE, "Failed to schedule a release build following a Release API invocation"); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); } else { String url = req.getContextPath() + '/' + item.getUrl(); JSONObject json = new JSONObject(); json.element("queueItem", item.getId()); json.element("releaseVersion", getReleaseVersion()); json.element("nextVersion", getNextVersion()); json.element("releaseBranch", getReleaseBranch()); // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it) resp.getOutputStream().print(json.toString()); resp.sendRedirect(201, url); } } catch (Exception e) { log.log(Level.SEVERE, "Artifactory Release Staging API invocation failed: " + e.getMessage(), e); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); resp.getWriter().write(mapper.writeValueAsString(errorResponse)); } }
[ "@", "SuppressWarnings", "(", "{", "\"UnusedDeclaration\"", "}", ")", "protected", "void", "doApi", "(", "StaplerRequest", "req", ",", "StaplerResponse", "resp", ")", "throws", "IOException", ",", "ServletException", "{", "try", "{", "log", ".", "log", "(", "Level", ".", "INFO", ",", "\"Initiating Artifactory Release Staging using API\"", ")", ";", "// Enforce release permissions", "project", ".", "checkPermission", "(", "ArtifactoryPlugin", ".", "RELEASE", ")", ";", "// In case a staging user plugin is configured, the init() method invoke it:", "init", "(", ")", ";", "// Read the values provided by the staging user plugin and assign them to data members in this class.", "// Those values can be overriden by URL arguments sent with the API:", "readStagingPluginValues", "(", ")", ";", "// Read values from the request and override the staging plugin values:", "overrideStagingPluginParams", "(", "req", ")", ";", "// Schedule the release build:", "Queue", ".", "WaitingItem", "item", "=", "Jenkins", ".", "getInstance", "(", ")", ".", "getQueue", "(", ")", ".", "schedule", "(", "project", ",", "0", ",", "new", "Action", "[", "]", "{", "this", ",", "new", "CauseAction", "(", "new", "Cause", ".", "UserIdCause", "(", ")", ")", "}", ")", ";", "if", "(", "item", "==", "null", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Failed to schedule a release build following a Release API invocation\"", ")", ";", "resp", ".", "setStatus", "(", "StaplerResponse", ".", "SC_INTERNAL_SERVER_ERROR", ")", ";", "}", "else", "{", "String", "url", "=", "req", ".", "getContextPath", "(", ")", "+", "'", "'", "+", "item", ".", "getUrl", "(", ")", ";", "JSONObject", "json", "=", "new", "JSONObject", "(", ")", ";", "json", ".", "element", "(", "\"queueItem\"", ",", "item", ".", "getId", "(", ")", ")", ";", "json", ".", "element", "(", "\"releaseVersion\"", ",", "getReleaseVersion", "(", ")", ")", ";", "json", ".", "element", "(", "\"nextVersion\"", ",", "getNextVersion", "(", ")", ")", ";", "json", ".", "element", "(", "\"releaseBranch\"", ",", "getReleaseBranch", "(", ")", ")", ";", "// Must use getOutputStream as sendRedirect uses getOutputStream (and closes it)", "resp", ".", "getOutputStream", "(", ")", ".", "print", "(", "json", ".", "toString", "(", ")", ")", ";", "resp", ".", "sendRedirect", "(", "201", ",", "url", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Artifactory Release Staging API invocation failed: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "resp", ".", "setStatus", "(", "StaplerResponse", ".", "SC_INTERNAL_SERVER_ERROR", ")", ";", "ErrorResponse", "errorResponse", "=", "new", "ErrorResponse", "(", "StaplerResponse", ".", "SC_INTERNAL_SERVER_ERROR", ",", "e", ".", "getMessage", "(", ")", ")", ";", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "mapper", ".", "enable", "(", "SerializationFeature", ".", "INDENT_OUTPUT", ")", ";", "resp", ".", "getWriter", "(", ")", ".", "write", "(", "mapper", ".", "writeValueAsString", "(", "errorResponse", ")", ")", ";", "}", "}" ]
This method is used to initiate a release staging process using the Artifactory Release Staging API.
[ "This", "method", "is", "used", "to", "initiate", "a", "release", "staging", "process", "using", "the", "Artifactory", "Release", "Staging", "API", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/release/ReleaseAction.java#L273-L313
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java
StringSupport.replaceFirst
public static void replaceFirst(StringBuffer haystack, String needle, String newNeedle) { """ replaces the first occurance of needle in haystack with newNeedle @param haystack input string @param needle string to replace @param newNeedle replacement """ int idx = haystack.indexOf(needle); if (idx != -1) { haystack.replace(idx, idx + needle.length(), newNeedle); } }
java
public static void replaceFirst(StringBuffer haystack, String needle, String newNeedle) { int idx = haystack.indexOf(needle); if (idx != -1) { haystack.replace(idx, idx + needle.length(), newNeedle); } }
[ "public", "static", "void", "replaceFirst", "(", "StringBuffer", "haystack", ",", "String", "needle", ",", "String", "newNeedle", ")", "{", "int", "idx", "=", "haystack", ".", "indexOf", "(", "needle", ")", ";", "if", "(", "idx", "!=", "-", "1", ")", "{", "haystack", ".", "replace", "(", "idx", ",", "idx", "+", "needle", ".", "length", "(", ")", ",", "newNeedle", ")", ";", "}", "}" ]
replaces the first occurance of needle in haystack with newNeedle @param haystack input string @param needle string to replace @param newNeedle replacement
[ "replaces", "the", "first", "occurance", "of", "needle", "in", "haystack", "with", "newNeedle" ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java#L61-L66
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/AbstractAzkabanServlet.java
AbstractAzkabanServlet.setWarnMessageInCookie
protected void setWarnMessageInCookie(final HttpServletResponse response, final String errorMsg) { """ Sets a warning message in azkaban.warn.message in the cookie. This will be used by the web client javascript to somehow display the message """ final Cookie cookie = new Cookie(AZKABAN_WARN_MESSAGE, errorMsg); cookie.setPath("/"); response.addCookie(cookie); }
java
protected void setWarnMessageInCookie(final HttpServletResponse response, final String errorMsg) { final Cookie cookie = new Cookie(AZKABAN_WARN_MESSAGE, errorMsg); cookie.setPath("/"); response.addCookie(cookie); }
[ "protected", "void", "setWarnMessageInCookie", "(", "final", "HttpServletResponse", "response", ",", "final", "String", "errorMsg", ")", "{", "final", "Cookie", "cookie", "=", "new", "Cookie", "(", "AZKABAN_WARN_MESSAGE", ",", "errorMsg", ")", ";", "cookie", ".", "setPath", "(", "\"/\"", ")", ";", "response", ".", "addCookie", "(", "cookie", ")", ";", "}" ]
Sets a warning message in azkaban.warn.message in the cookie. This will be used by the web client javascript to somehow display the message
[ "Sets", "a", "warning", "message", "in", "azkaban", ".", "warn", ".", "message", "in", "the", "cookie", ".", "This", "will", "be", "used", "by", "the", "web", "client", "javascript", "to", "somehow", "display", "the", "message" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/webapp/servlet/AbstractAzkabanServlet.java#L208-L213
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.prechomp
public static String prechomp(String str, String sep) { """ <p>Remove the first value of a supplied String, and everything before it from a String.</p> @param str the String to chomp from, must not be null @param sep the String to chomp, must not be null @return String without chomped beginning @throws NullPointerException if str or sep is <code>null</code> @deprecated Use {@link #substringAfter(String,String)} instead. Method will be removed in Commons Lang 3.0. """ int idx = str.indexOf(sep); if (idx == -1) { return str; } return str.substring(idx + sep.length()); }
java
public static String prechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx == -1) { return str; } return str.substring(idx + sep.length()); }
[ "public", "static", "String", "prechomp", "(", "String", "str", ",", "String", "sep", ")", "{", "int", "idx", "=", "str", ".", "indexOf", "(", "sep", ")", ";", "if", "(", "idx", "==", "-", "1", ")", "{", "return", "str", ";", "}", "return", "str", ".", "substring", "(", "idx", "+", "sep", ".", "length", "(", ")", ")", ";", "}" ]
<p>Remove the first value of a supplied String, and everything before it from a String.</p> @param str the String to chomp from, must not be null @param sep the String to chomp, must not be null @return String without chomped beginning @throws NullPointerException if str or sep is <code>null</code> @deprecated Use {@link #substringAfter(String,String)} instead. Method will be removed in Commons Lang 3.0.
[ "<p", ">", "Remove", "the", "first", "value", "of", "a", "supplied", "String", "and", "everything", "before", "it", "from", "a", "String", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L4070-L4076
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/formats/html/AbstractProfileIndexWriter.java
AbstractProfileIndexWriter.addProfilePackagesIndex
protected void addProfilePackagesIndex(Content body, String profileName) { """ Adds the frame or non-frame profile packages index to the documentation tree. @param body the document tree to which the index will be added @param profileName the name of the profile being documented """ addProfilePackagesIndexContents(profiles, "doclet.Profile_Summary", configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Profile_Summary"), configuration.getText("doclet.profiles")), body, profileName); }
java
protected void addProfilePackagesIndex(Content body, String profileName) { addProfilePackagesIndexContents(profiles, "doclet.Profile_Summary", configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Profile_Summary"), configuration.getText("doclet.profiles")), body, profileName); }
[ "protected", "void", "addProfilePackagesIndex", "(", "Content", "body", ",", "String", "profileName", ")", "{", "addProfilePackagesIndexContents", "(", "profiles", ",", "\"doclet.Profile_Summary\"", ",", "configuration", ".", "getText", "(", "\"doclet.Member_Table_Summary\"", ",", "configuration", ".", "getText", "(", "\"doclet.Profile_Summary\"", ")", ",", "configuration", ".", "getText", "(", "\"doclet.profiles\"", ")", ")", ",", "body", ",", "profileName", ")", ";", "}" ]
Adds the frame or non-frame profile packages index to the documentation tree. @param body the document tree to which the index will be added @param profileName the name of the profile being documented
[ "Adds", "the", "frame", "or", "non", "-", "frame", "profile", "packages", "index", "to", "the", "documentation", "tree", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/AbstractProfileIndexWriter.java#L178-L183
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteSharedProjectGroupLink
public void deleteSharedProjectGroupLink(int groupId, int projectId) throws IOException { """ Delete a shared project link within a group. @param groupId The group id number. @param projectId The project id number. @throws IOException on gitlab api call error """ String tailUrl = GitlabProject.URL + "/" + projectId + "/share/" + groupId; retrieve().method(DELETE).to(tailUrl, Void.class); }
java
public void deleteSharedProjectGroupLink(int groupId, int projectId) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + "/share/" + groupId; retrieve().method(DELETE).to(tailUrl, Void.class); }
[ "public", "void", "deleteSharedProjectGroupLink", "(", "int", "groupId", ",", "int", "projectId", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", "+", "projectId", "+", "\"/share/\"", "+", "groupId", ";", "retrieve", "(", ")", ".", "method", "(", "DELETE", ")", ".", "to", "(", "tailUrl", ",", "Void", ".", "class", ")", ";", "}" ]
Delete a shared project link within a group. @param groupId The group id number. @param projectId The project id number. @throws IOException on gitlab api call error
[ "Delete", "a", "shared", "project", "link", "within", "a", "group", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3915-L3918
cdapio/tephra
tephra-core/src/main/java/co/cask/tephra/persist/TransactionEditCodecs.java
TransactionEditCodecs.encode
public static void encode(TransactionEdit src, DataOutput out) throws IOException { """ Serializes the given {@code TransactionEdit} instance with the latest available codec. This will first write out the version of the codec used to serialize the instance so that the correct codec can be used when calling {@link #decode(TransactionEdit, DataInput)}. @param src the transaction edit to serialize @param out the output stream to contain the data @throws IOException if an error occurs while serializing to the output stream """ TransactionEditCodec latestCodec = CODECS.get(CODECS.firstKey()); out.writeByte(latestCodec.getVersion()); latestCodec.encode(src, out); }
java
public static void encode(TransactionEdit src, DataOutput out) throws IOException { TransactionEditCodec latestCodec = CODECS.get(CODECS.firstKey()); out.writeByte(latestCodec.getVersion()); latestCodec.encode(src, out); }
[ "public", "static", "void", "encode", "(", "TransactionEdit", "src", ",", "DataOutput", "out", ")", "throws", "IOException", "{", "TransactionEditCodec", "latestCodec", "=", "CODECS", ".", "get", "(", "CODECS", ".", "firstKey", "(", ")", ")", ";", "out", ".", "writeByte", "(", "latestCodec", ".", "getVersion", "(", ")", ")", ";", "latestCodec", ".", "encode", "(", "src", ",", "out", ")", ";", "}" ]
Serializes the given {@code TransactionEdit} instance with the latest available codec. This will first write out the version of the codec used to serialize the instance so that the correct codec can be used when calling {@link #decode(TransactionEdit, DataInput)}. @param src the transaction edit to serialize @param out the output stream to contain the data @throws IOException if an error occurs while serializing to the output stream
[ "Serializes", "the", "given", "{", "@code", "TransactionEdit", "}", "instance", "with", "the", "latest", "available", "codec", ".", "This", "will", "first", "write", "out", "the", "version", "of", "the", "codec", "used", "to", "serialize", "the", "instance", "so", "that", "the", "correct", "codec", "can", "be", "used", "when", "calling", "{", "@link", "#decode", "(", "TransactionEdit", "DataInput", ")", "}", "." ]
train
https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/persist/TransactionEditCodecs.java#L79-L83
lucee/Lucee
core/src/main/java/lucee/transformer/interpreter/op/OpBool.java
OpBool.toExprBoolean
public static ExprBoolean toExprBoolean(Expression left, Expression right, int operation) { """ Create a String expression from a Expression @param left @param right @return String expression @throws TemplateException """ if (left instanceof Literal && right instanceof Literal) { Boolean l = ((Literal) left).getBoolean(null); Boolean r = ((Literal) right).getBoolean(null); if (l != null && r != null) { switch (operation) { case Factory.OP_BOOL_AND: return left.getFactory().createLitBoolean(l.booleanValue() && r.booleanValue(), left.getStart(), right.getEnd()); case Factory.OP_BOOL_OR: return left.getFactory().createLitBoolean(l.booleanValue() || r.booleanValue(), left.getStart(), right.getEnd()); case Factory.OP_BOOL_XOR: return left.getFactory().createLitBoolean(l.booleanValue() ^ r.booleanValue(), left.getStart(), right.getEnd()); } } } return new OpBool(left, right, operation); }
java
public static ExprBoolean toExprBoolean(Expression left, Expression right, int operation) { if (left instanceof Literal && right instanceof Literal) { Boolean l = ((Literal) left).getBoolean(null); Boolean r = ((Literal) right).getBoolean(null); if (l != null && r != null) { switch (operation) { case Factory.OP_BOOL_AND: return left.getFactory().createLitBoolean(l.booleanValue() && r.booleanValue(), left.getStart(), right.getEnd()); case Factory.OP_BOOL_OR: return left.getFactory().createLitBoolean(l.booleanValue() || r.booleanValue(), left.getStart(), right.getEnd()); case Factory.OP_BOOL_XOR: return left.getFactory().createLitBoolean(l.booleanValue() ^ r.booleanValue(), left.getStart(), right.getEnd()); } } } return new OpBool(left, right, operation); }
[ "public", "static", "ExprBoolean", "toExprBoolean", "(", "Expression", "left", ",", "Expression", "right", ",", "int", "operation", ")", "{", "if", "(", "left", "instanceof", "Literal", "&&", "right", "instanceof", "Literal", ")", "{", "Boolean", "l", "=", "(", "(", "Literal", ")", "left", ")", ".", "getBoolean", "(", "null", ")", ";", "Boolean", "r", "=", "(", "(", "Literal", ")", "right", ")", ".", "getBoolean", "(", "null", ")", ";", "if", "(", "l", "!=", "null", "&&", "r", "!=", "null", ")", "{", "switch", "(", "operation", ")", "{", "case", "Factory", ".", "OP_BOOL_AND", ":", "return", "left", ".", "getFactory", "(", ")", ".", "createLitBoolean", "(", "l", ".", "booleanValue", "(", ")", "&&", "r", ".", "booleanValue", "(", ")", ",", "left", ".", "getStart", "(", ")", ",", "right", ".", "getEnd", "(", ")", ")", ";", "case", "Factory", ".", "OP_BOOL_OR", ":", "return", "left", ".", "getFactory", "(", ")", ".", "createLitBoolean", "(", "l", ".", "booleanValue", "(", ")", "||", "r", ".", "booleanValue", "(", ")", ",", "left", ".", "getStart", "(", ")", ",", "right", ".", "getEnd", "(", ")", ")", ";", "case", "Factory", ".", "OP_BOOL_XOR", ":", "return", "left", ".", "getFactory", "(", ")", ".", "createLitBoolean", "(", "l", ".", "booleanValue", "(", ")", "^", "r", ".", "booleanValue", "(", ")", ",", "left", ".", "getStart", "(", ")", ",", "right", ".", "getEnd", "(", ")", ")", ";", "}", "}", "}", "return", "new", "OpBool", "(", "left", ",", "right", ",", "operation", ")", ";", "}" ]
Create a String expression from a Expression @param left @param right @return String expression @throws TemplateException
[ "Create", "a", "String", "expression", "from", "a", "Expression" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/interpreter/op/OpBool.java#L74-L91
astrapi69/jaulp-wicket
jaulp-wicket-behaviors/src/main/java/de/alpharogroup/wicket/behaviors/JavascriptAppenderBehavior.java
JavascriptAppenderBehavior.of
public static JavascriptAppenderBehavior of(final String id, final CharSequence javascript, final JavascriptBindEvent bindEvent) { """ Factory method to create a new {@link JavascriptAppenderBehavior} object from the given parameters. @param id the id @param javascript the javascript @param bindEvent the bind event @return the new {@link JavascriptAppenderBehavior} object """ return new JavascriptAppenderBehavior(id, javascript, bindEvent); }
java
public static JavascriptAppenderBehavior of(final String id, final CharSequence javascript, final JavascriptBindEvent bindEvent) { return new JavascriptAppenderBehavior(id, javascript, bindEvent); }
[ "public", "static", "JavascriptAppenderBehavior", "of", "(", "final", "String", "id", ",", "final", "CharSequence", "javascript", ",", "final", "JavascriptBindEvent", "bindEvent", ")", "{", "return", "new", "JavascriptAppenderBehavior", "(", "id", ",", "javascript", ",", "bindEvent", ")", ";", "}" ]
Factory method to create a new {@link JavascriptAppenderBehavior} object from the given parameters. @param id the id @param javascript the javascript @param bindEvent the bind event @return the new {@link JavascriptAppenderBehavior} object
[ "Factory", "method", "to", "create", "a", "new", "{", "@link", "JavascriptAppenderBehavior", "}", "object", "from", "the", "given", "parameters", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-behaviors/src/main/java/de/alpharogroup/wicket/behaviors/JavascriptAppenderBehavior.java#L98-L102
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/chess/ChessboardCornerClusterToGrid.java
ChessboardCornerClusterToGrid.convert
public boolean convert( ChessboardCornerGraph cluster , GridInfo info ) { """ Puts cluster nodes into grid order and computes the number of rows and columns. If the cluster is not a complete grid this function will fail and return false @param cluster (Input) cluster. Edge order will be modified. @param info (Output) Contains ordered nodes and the grid's size. @return true if successful or false if it failed """ // default to an invalid value to ensure a failure doesn't go unnoticed. info.reset(); // Get the edges in a consistent order if( !orderEdges(cluster) ) return false; // Now we need to order the nodes into a proper grid which follows right hand rule if( !orderNodes(cluster.corners,info) ) return false; // select a valid corner to be (0,0). If there are multiple options select the one which is int corner = selectCorner(info); if( corner == -1 ) { if( verbose != null) verbose.println("Failed to find valid corner."); return false; } // rotate the grid until the select corner is at (0,0) for (int i = 0; i < corner; i++) { rotateCCW(info); } return true; }
java
public boolean convert( ChessboardCornerGraph cluster , GridInfo info ) { // default to an invalid value to ensure a failure doesn't go unnoticed. info.reset(); // Get the edges in a consistent order if( !orderEdges(cluster) ) return false; // Now we need to order the nodes into a proper grid which follows right hand rule if( !orderNodes(cluster.corners,info) ) return false; // select a valid corner to be (0,0). If there are multiple options select the one which is int corner = selectCorner(info); if( corner == -1 ) { if( verbose != null) verbose.println("Failed to find valid corner."); return false; } // rotate the grid until the select corner is at (0,0) for (int i = 0; i < corner; i++) { rotateCCW(info); } return true; }
[ "public", "boolean", "convert", "(", "ChessboardCornerGraph", "cluster", ",", "GridInfo", "info", ")", "{", "// default to an invalid value to ensure a failure doesn't go unnoticed.", "info", ".", "reset", "(", ")", ";", "// Get the edges in a consistent order", "if", "(", "!", "orderEdges", "(", "cluster", ")", ")", "return", "false", ";", "// Now we need to order the nodes into a proper grid which follows right hand rule", "if", "(", "!", "orderNodes", "(", "cluster", ".", "corners", ",", "info", ")", ")", "return", "false", ";", "// select a valid corner to be (0,0). If there are multiple options select the one which is", "int", "corner", "=", "selectCorner", "(", "info", ")", ";", "if", "(", "corner", "==", "-", "1", ")", "{", "if", "(", "verbose", "!=", "null", ")", "verbose", ".", "println", "(", "\"Failed to find valid corner.\"", ")", ";", "return", "false", ";", "}", "// rotate the grid until the select corner is at (0,0)", "for", "(", "int", "i", "=", "0", ";", "i", "<", "corner", ";", "i", "++", ")", "{", "rotateCCW", "(", "info", ")", ";", "}", "return", "true", ";", "}" ]
Puts cluster nodes into grid order and computes the number of rows and columns. If the cluster is not a complete grid this function will fail and return false @param cluster (Input) cluster. Edge order will be modified. @param info (Output) Contains ordered nodes and the grid's size. @return true if successful or false if it failed
[ "Puts", "cluster", "nodes", "into", "grid", "order", "and", "computes", "the", "number", "of", "rows", "and", "columns", ".", "If", "the", "cluster", "is", "not", "a", "complete", "grid", "this", "function", "will", "fail", "and", "return", "false" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/chess/ChessboardCornerClusterToGrid.java#L79-L103
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/Client.java
Client.openApplication
public static ApplicationSession openApplication(String appName, String host, int port, SSLTransportParameters sslParams, Credentials credentials) { """ Create an {@link ApplicationSession} for the given application name on the Doradus server, creating a new connection the given REST API host, port, and TLS/SSL parameters. This static method allows an application session to be created without creating a Client object and then calling {@link #openApplication(String)}. If the given sslParams is null, an unsecured (HTTP) connectio is opened. Otherwise, a TLS/SSL connection is created using the given credentials. An exception is thrown if the given application is unknown or cannot be accessed or if a connection cannot be established. If successful, the session object will be specific to the type of application opened, and it will have its own REST session to the Doradus server. @param appName Name of an application to open. @param host REST API host name or IP address. @param port REST API port number. @param sslParams {@link SSLTransportParameters} object containing TLS/SSL parameters to use, or null to open an HTTP connection. @param credentials {@link Credentials} to use for all requests with the new application session. Can be null to use an unauthenticated session. @return {@link ApplicationSession} through which the application can be accessed. @see com.dell.doradus.client.OLAPSession @see com.dell.doradus.client.SpiderSession """ Utils.require(!Utils.isEmpty(appName), "appName"); Utils.require(!Utils.isEmpty(host), "host"); try (Client client = new Client(host, port, sslParams)) { client.setCredentials(credentials); ApplicationDefinition appDef = client.getAppDef(appName); Utils.require(appDef != null, "Unknown application: %s", appName); RESTClient restClient = new RESTClient(client.m_restClient); return openApplication(appDef, restClient); } }
java
public static ApplicationSession openApplication(String appName, String host, int port, SSLTransportParameters sslParams, Credentials credentials) { Utils.require(!Utils.isEmpty(appName), "appName"); Utils.require(!Utils.isEmpty(host), "host"); try (Client client = new Client(host, port, sslParams)) { client.setCredentials(credentials); ApplicationDefinition appDef = client.getAppDef(appName); Utils.require(appDef != null, "Unknown application: %s", appName); RESTClient restClient = new RESTClient(client.m_restClient); return openApplication(appDef, restClient); } }
[ "public", "static", "ApplicationSession", "openApplication", "(", "String", "appName", ",", "String", "host", ",", "int", "port", ",", "SSLTransportParameters", "sslParams", ",", "Credentials", "credentials", ")", "{", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "appName", ")", ",", "\"appName\"", ")", ";", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "host", ")", ",", "\"host\"", ")", ";", "try", "(", "Client", "client", "=", "new", "Client", "(", "host", ",", "port", ",", "sslParams", ")", ")", "{", "client", ".", "setCredentials", "(", "credentials", ")", ";", "ApplicationDefinition", "appDef", "=", "client", ".", "getAppDef", "(", "appName", ")", ";", "Utils", ".", "require", "(", "appDef", "!=", "null", ",", "\"Unknown application: %s\"", ",", "appName", ")", ";", "RESTClient", "restClient", "=", "new", "RESTClient", "(", "client", ".", "m_restClient", ")", ";", "return", "openApplication", "(", "appDef", ",", "restClient", ")", ";", "}", "}" ]
Create an {@link ApplicationSession} for the given application name on the Doradus server, creating a new connection the given REST API host, port, and TLS/SSL parameters. This static method allows an application session to be created without creating a Client object and then calling {@link #openApplication(String)}. If the given sslParams is null, an unsecured (HTTP) connectio is opened. Otherwise, a TLS/SSL connection is created using the given credentials. An exception is thrown if the given application is unknown or cannot be accessed or if a connection cannot be established. If successful, the session object will be specific to the type of application opened, and it will have its own REST session to the Doradus server. @param appName Name of an application to open. @param host REST API host name or IP address. @param port REST API port number. @param sslParams {@link SSLTransportParameters} object containing TLS/SSL parameters to use, or null to open an HTTP connection. @param credentials {@link Credentials} to use for all requests with the new application session. Can be null to use an unauthenticated session. @return {@link ApplicationSession} through which the application can be accessed. @see com.dell.doradus.client.OLAPSession @see com.dell.doradus.client.SpiderSession
[ "Create", "an", "{", "@link", "ApplicationSession", "}", "for", "the", "given", "application", "name", "on", "the", "Doradus", "server", "creating", "a", "new", "connection", "the", "given", "REST", "API", "host", "port", "and", "TLS", "/", "SSL", "parameters", ".", "This", "static", "method", "allows", "an", "application", "session", "to", "be", "created", "without", "creating", "a", "Client", "object", "and", "then", "calling", "{", "@link", "#openApplication", "(", "String", ")", "}", ".", "If", "the", "given", "sslParams", "is", "null", "an", "unsecured", "(", "HTTP", ")", "connectio", "is", "opened", ".", "Otherwise", "a", "TLS", "/", "SSL", "connection", "is", "created", "using", "the", "given", "credentials", ".", "An", "exception", "is", "thrown", "if", "the", "given", "application", "is", "unknown", "or", "cannot", "be", "accessed", "or", "if", "a", "connection", "cannot", "be", "established", ".", "If", "successful", "the", "session", "object", "will", "be", "specific", "to", "the", "type", "of", "application", "opened", "and", "it", "will", "have", "its", "own", "REST", "session", "to", "the", "Doradus", "server", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/Client.java#L223-L236
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java
ReflectUtil.hasField
public static boolean hasField(Class<?> beanClass, String name) throws SecurityException { """ 查找指定类中是否包含指定名称对应的字段,包括所有字段(包括非public字段),也包括父类和Object类的字段 @param beanClass 被查找字段的类,不能为null @param name 字段名 @return 是否包含字段 @throws SecurityException 安全异常 @since 4.1.21 """ return null != getField(beanClass, name); }
java
public static boolean hasField(Class<?> beanClass, String name) throws SecurityException { return null != getField(beanClass, name); }
[ "public", "static", "boolean", "hasField", "(", "Class", "<", "?", ">", "beanClass", ",", "String", "name", ")", "throws", "SecurityException", "{", "return", "null", "!=", "getField", "(", "beanClass", ",", "name", ")", ";", "}" ]
查找指定类中是否包含指定名称对应的字段,包括所有字段(包括非public字段),也包括父类和Object类的字段 @param beanClass 被查找字段的类,不能为null @param name 字段名 @return 是否包含字段 @throws SecurityException 安全异常 @since 4.1.21
[ "查找指定类中是否包含指定名称对应的字段,包括所有字段(包括非public字段),也包括父类和Object类的字段" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java#L103-L105
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/operators/Operator.java
Operator.createUnionCascade
public static <T> Operator<T> createUnionCascade(Operator<T>... operators) { """ Takes a list of operators and creates a cascade of unions of this inputs, if needed. If not needed (there was only one operator in the list), then that operator is returned. @param operators The operators. @return The single operator or a cascade of unions of the operators. """ return createUnionCascade(null, operators); }
java
public static <T> Operator<T> createUnionCascade(Operator<T>... operators) { return createUnionCascade(null, operators); }
[ "public", "static", "<", "T", ">", "Operator", "<", "T", ">", "createUnionCascade", "(", "Operator", "<", "T", ">", "...", "operators", ")", "{", "return", "createUnionCascade", "(", "null", ",", "operators", ")", ";", "}" ]
Takes a list of operators and creates a cascade of unions of this inputs, if needed. If not needed (there was only one operator in the list), then that operator is returned. @param operators The operators. @return The single operator or a cascade of unions of the operators.
[ "Takes", "a", "list", "of", "operators", "and", "creates", "a", "cascade", "of", "unions", "of", "this", "inputs", "if", "needed", ".", "If", "not", "needed", "(", "there", "was", "only", "one", "operator", "in", "the", "list", ")", "then", "that", "operator", "is", "returned", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/operators/Operator.java#L259-L261
skjolber/3d-bin-container-packing
src/main/java/com/github/skjolberg/packing/Packager.java
Packager.pack
public Container pack(List<BoxItem> boxes, List<Container> containers, long deadline, AtomicBoolean interrupt) { """ Return a container which holds all the boxes in the argument @param boxes list of boxes to fit in a container @param containers list of containers @param deadline the system time in milliseconds at which the search should be aborted @param interrupt When true, the computation is interrupted as soon as possible. @return index of container if match, -1 if not """ return pack(boxes, containers, () -> deadlineReached(deadline) || interrupt.get()); }
java
public Container pack(List<BoxItem> boxes, List<Container> containers, long deadline, AtomicBoolean interrupt) { return pack(boxes, containers, () -> deadlineReached(deadline) || interrupt.get()); }
[ "public", "Container", "pack", "(", "List", "<", "BoxItem", ">", "boxes", ",", "List", "<", "Container", ">", "containers", ",", "long", "deadline", ",", "AtomicBoolean", "interrupt", ")", "{", "return", "pack", "(", "boxes", ",", "containers", ",", "(", ")", "->", "deadlineReached", "(", "deadline", ")", "||", "interrupt", ".", "get", "(", ")", ")", ";", "}" ]
Return a container which holds all the boxes in the argument @param boxes list of boxes to fit in a container @param containers list of containers @param deadline the system time in milliseconds at which the search should be aborted @param interrupt When true, the computation is interrupted as soon as possible. @return index of container if match, -1 if not
[ "Return", "a", "container", "which", "holds", "all", "the", "boxes", "in", "the", "argument" ]
train
https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Packager.java#L126-L128
liyiorg/weixin-popular
src/main/java/weixin/popular/api/PayMchAPI.java
PayMchAPI.toolsAuthcodetoopenid
public static AuthcodetoopenidResult toolsAuthcodetoopenid(Authcodetoopenid authcodetoopenid,String key) { """ 刷卡支付 授权码查询OPENID接口 @param authcodetoopenid authcodetoopenid @param key key @return AuthcodetoopenidResult """ Map<String,String> map = MapUtil.objectToMap(authcodetoopenid); String sign = SignatureUtil.generateSign(map,authcodetoopenid.getSign_type(),key); authcodetoopenid.setSign(sign); String shorturlXML = XMLConverUtil.convertToXML(authcodetoopenid); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/tools/authcodetoopenid") .setEntity(new StringEntity(shorturlXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeXmlResult(httpUriRequest,AuthcodetoopenidResult.class,authcodetoopenid.getSign_type(),key); }
java
public static AuthcodetoopenidResult toolsAuthcodetoopenid(Authcodetoopenid authcodetoopenid,String key){ Map<String,String> map = MapUtil.objectToMap(authcodetoopenid); String sign = SignatureUtil.generateSign(map,authcodetoopenid.getSign_type(),key); authcodetoopenid.setSign(sign); String shorturlXML = XMLConverUtil.convertToXML(authcodetoopenid); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/tools/authcodetoopenid") .setEntity(new StringEntity(shorturlXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeXmlResult(httpUriRequest,AuthcodetoopenidResult.class,authcodetoopenid.getSign_type(),key); }
[ "public", "static", "AuthcodetoopenidResult", "toolsAuthcodetoopenid", "(", "Authcodetoopenid", "authcodetoopenid", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "MapUtil", ".", "objectToMap", "(", "authcodetoopenid", ")", ";", "String", "sign", "=", "SignatureUtil", ".", "generateSign", "(", "map", ",", "authcodetoopenid", ".", "getSign_type", "(", ")", ",", "key", ")", ";", "authcodetoopenid", ".", "setSign", "(", "sign", ")", ";", "String", "shorturlXML", "=", "XMLConverUtil", ".", "convertToXML", "(", "authcodetoopenid", ")", ";", "HttpUriRequest", "httpUriRequest", "=", "RequestBuilder", ".", "post", "(", ")", ".", "setHeader", "(", "xmlHeader", ")", ".", "setUri", "(", "baseURI", "(", ")", "+", "\"/tools/authcodetoopenid\"", ")", ".", "setEntity", "(", "new", "StringEntity", "(", "shorturlXML", ",", "Charset", ".", "forName", "(", "\"utf-8\"", ")", ")", ")", ".", "build", "(", ")", ";", "return", "LocalHttpClient", ".", "executeXmlResult", "(", "httpUriRequest", ",", "AuthcodetoopenidResult", ".", "class", ",", "authcodetoopenid", ".", "getSign_type", "(", ")", ",", "key", ")", ";", "}" ]
刷卡支付 授权码查询OPENID接口 @param authcodetoopenid authcodetoopenid @param key key @return AuthcodetoopenidResult
[ "刷卡支付", "授权码查询OPENID接口" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L393-L404
mariosotil/river-framework
river-core/src/main/java/org/riverframework/core/AbstractDocument.java
AbstractDocument.numericEquals
protected static boolean numericEquals(Field vector1, Field vector2) { """ Compares two vectors and determines if they are numeric equals, independent of its type. @param vector1 the first vector @param vector2 the second vector @return true if the vectors are numeric equals """ if (vector1.size() != vector2.size()) return false; if (vector1.isEmpty()) return true; Iterator<Object> it1 = vector1.iterator(); Iterator<Object> it2 = vector2.iterator(); while (it1.hasNext()) { Object obj1 = it1.next(); Object obj2 = it2.next(); if (!(obj1 instanceof Number && obj2 instanceof Number)) return false; if (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue()) return false; } return true; }
java
protected static boolean numericEquals(Field vector1, Field vector2) { if (vector1.size() != vector2.size()) return false; if (vector1.isEmpty()) return true; Iterator<Object> it1 = vector1.iterator(); Iterator<Object> it2 = vector2.iterator(); while (it1.hasNext()) { Object obj1 = it1.next(); Object obj2 = it2.next(); if (!(obj1 instanceof Number && obj2 instanceof Number)) return false; if (((Number) obj1).doubleValue() != ((Number) obj2).doubleValue()) return false; } return true; }
[ "protected", "static", "boolean", "numericEquals", "(", "Field", "vector1", ",", "Field", "vector2", ")", "{", "if", "(", "vector1", ".", "size", "(", ")", "!=", "vector2", ".", "size", "(", ")", ")", "return", "false", ";", "if", "(", "vector1", ".", "isEmpty", "(", ")", ")", "return", "true", ";", "Iterator", "<", "Object", ">", "it1", "=", "vector1", ".", "iterator", "(", ")", ";", "Iterator", "<", "Object", ">", "it2", "=", "vector2", ".", "iterator", "(", ")", ";", "while", "(", "it1", ".", "hasNext", "(", ")", ")", "{", "Object", "obj1", "=", "it1", ".", "next", "(", ")", ";", "Object", "obj2", "=", "it2", ".", "next", "(", ")", ";", "if", "(", "!", "(", "obj1", "instanceof", "Number", "&&", "obj2", "instanceof", "Number", ")", ")", "return", "false", ";", "if", "(", "(", "(", "Number", ")", "obj1", ")", ".", "doubleValue", "(", ")", "!=", "(", "(", "Number", ")", "obj2", ")", ".", "doubleValue", "(", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Compares two vectors and determines if they are numeric equals, independent of its type. @param vector1 the first vector @param vector2 the second vector @return true if the vectors are numeric equals
[ "Compares", "two", "vectors", "and", "determines", "if", "they", "are", "numeric", "equals", "independent", "of", "its", "type", "." ]
train
https://github.com/mariosotil/river-framework/blob/e8c3ae3b0a956ec9cb4e14a81376ba8e8370b44e/river-core/src/main/java/org/riverframework/core/AbstractDocument.java#L107-L128
wigforss/Ka-Commons-Reflection
src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java
AnnotationUtils.getAnnotation
public static <T extends Annotation> T getAnnotation( Class<?> target, Class<T> annotationClass) { """ Returns the annotation of the annotationClass of the clazz or any of it super classes. @param clazz The class to inspect. @param annotationClass Class of the annotation to return @return The annotation of annnotationClass if found else null. """ Class<?> clazz = target; T annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } while((clazz = clazz.getSuperclass()) != null) { annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } } return null; }
java
public static <T extends Annotation> T getAnnotation( Class<?> target, Class<T> annotationClass) { Class<?> clazz = target; T annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } while((clazz = clazz.getSuperclass()) != null) { annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } } return null; }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "Class", "<", "?", ">", "target", ",", "Class", "<", "T", ">", "annotationClass", ")", "{", "Class", "<", "?", ">", "clazz", "=", "target", ";", "T", "annotation", "=", "clazz", ".", "getAnnotation", "(", "annotationClass", ")", ";", "if", "(", "annotation", "!=", "null", ")", "{", "return", "annotation", ";", "}", "while", "(", "(", "clazz", "=", "clazz", ".", "getSuperclass", "(", ")", ")", "!=", "null", ")", "{", "annotation", "=", "clazz", ".", "getAnnotation", "(", "annotationClass", ")", ";", "if", "(", "annotation", "!=", "null", ")", "{", "return", "annotation", ";", "}", "}", "return", "null", ";", "}" ]
Returns the annotation of the annotationClass of the clazz or any of it super classes. @param clazz The class to inspect. @param annotationClass Class of the annotation to return @return The annotation of annnotationClass if found else null.
[ "Returns", "the", "annotation", "of", "the", "annotationClass", "of", "the", "clazz", "or", "any", "of", "it", "super", "classes", "." ]
train
https://github.com/wigforss/Ka-Commons-Reflection/blob/a80f7a164cd800089e4f4dd948ca6f0e7badcf33/src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java#L67-L80
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java
Character.codePointCount
public static int codePointCount(char[] a, int offset, int count) { """ Returns the number of Unicode code points in a subarray of the {@code char} array argument. The {@code offset} argument is the index of the first {@code char} of the subarray and the {@code count} argument specifies the length of the subarray in {@code char}s. Unpaired surrogates within the subarray count as one code point each. @param a the {@code char} array @param offset the index of the first {@code char} in the given {@code char} array @param count the length of the subarray in {@code char}s @return the number of Unicode code points in the specified subarray @exception NullPointerException if {@code a} is null. @exception IndexOutOfBoundsException if {@code offset} or {@code count} is negative, or if {@code offset + count} is larger than the length of the given array. @since 1.5 """ if (count > a.length - offset || offset < 0 || count < 0) { throw new IndexOutOfBoundsException(); } return codePointCountImpl(a, offset, count); }
java
public static int codePointCount(char[] a, int offset, int count) { if (count > a.length - offset || offset < 0 || count < 0) { throw new IndexOutOfBoundsException(); } return codePointCountImpl(a, offset, count); }
[ "public", "static", "int", "codePointCount", "(", "char", "[", "]", "a", ",", "int", "offset", ",", "int", "count", ")", "{", "if", "(", "count", ">", "a", ".", "length", "-", "offset", "||", "offset", "<", "0", "||", "count", "<", "0", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "return", "codePointCountImpl", "(", "a", ",", "offset", ",", "count", ")", ";", "}" ]
Returns the number of Unicode code points in a subarray of the {@code char} array argument. The {@code offset} argument is the index of the first {@code char} of the subarray and the {@code count} argument specifies the length of the subarray in {@code char}s. Unpaired surrogates within the subarray count as one code point each. @param a the {@code char} array @param offset the index of the first {@code char} in the given {@code char} array @param count the length of the subarray in {@code char}s @return the number of Unicode code points in the specified subarray @exception NullPointerException if {@code a} is null. @exception IndexOutOfBoundsException if {@code offset} or {@code count} is negative, or if {@code offset + count} is larger than the length of the given array. @since 1.5
[ "Returns", "the", "number", "of", "Unicode", "code", "points", "in", "a", "subarray", "of", "the", "{", "@code", "char", "}", "array", "argument", ".", "The", "{", "@code", "offset", "}", "argument", "is", "the", "index", "of", "the", "first", "{", "@code", "char", "}", "of", "the", "subarray", "and", "the", "{", "@code", "count", "}", "argument", "specifies", "the", "length", "of", "the", "subarray", "in", "{", "@code", "char", "}", "s", ".", "Unpaired", "surrogates", "within", "the", "subarray", "count", "as", "one", "code", "point", "each", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java#L5301-L5306
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/AbstractMethod.java
AbstractMethod.processWrapper
protected <T> WrapperGenericList<T> processWrapper(TypeReference typeRef, URL url, String errorMessageSuffix) throws MovieDbException { """ Process the wrapper list and return the whole wrapper @param <T> Type of list to process @param typeRef @param url URL of the page (Error output only) @param errorMessageSuffix Error message to output (Error output only) @return @throws MovieDbException """ String webpage = httpTools.getRequest(url); try { // Due to type erasure, this doesn't work // TypeReference<WrapperGenericList<T>> typeRef = new TypeReference<WrapperGenericList<T>>() {}; return MAPPER.readValue(webpage, typeRef); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get " + errorMessageSuffix, url, ex); } }
java
protected <T> WrapperGenericList<T> processWrapper(TypeReference typeRef, URL url, String errorMessageSuffix) throws MovieDbException { String webpage = httpTools.getRequest(url); try { // Due to type erasure, this doesn't work // TypeReference<WrapperGenericList<T>> typeRef = new TypeReference<WrapperGenericList<T>>() {}; return MAPPER.readValue(webpage, typeRef); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get " + errorMessageSuffix, url, ex); } }
[ "protected", "<", "T", ">", "WrapperGenericList", "<", "T", ">", "processWrapper", "(", "TypeReference", "typeRef", ",", "URL", "url", ",", "String", "errorMessageSuffix", ")", "throws", "MovieDbException", "{", "String", "webpage", "=", "httpTools", ".", "getRequest", "(", "url", ")", ";", "try", "{", "// Due to type erasure, this doesn't work", "// TypeReference<WrapperGenericList<T>> typeRef = new TypeReference<WrapperGenericList<T>>() {};", "return", "MAPPER", ".", "readValue", "(", "webpage", ",", "typeRef", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "MAPPING_FAILED", ",", "\"Failed to get \"", "+", "errorMessageSuffix", ",", "url", ",", "ex", ")", ";", "}", "}" ]
Process the wrapper list and return the whole wrapper @param <T> Type of list to process @param typeRef @param url URL of the page (Error output only) @param errorMessageSuffix Error message to output (Error output only) @return @throws MovieDbException
[ "Process", "the", "wrapper", "list", "and", "return", "the", "whole", "wrapper" ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/AbstractMethod.java#L160-L169
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java
JDBCResultSet.updateObject
public void updateObject(int columnIndex, Object x) throws SQLException { """ <!-- start generic documentation --> Updates the designated column with an <code>Object</code> value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database. <!-- end generic documentation --> <!-- start release-specific documentation --> <div class="ReleaseSpecificDocumentation"> <h3>HSQLDB-Specific Information:</h3> <p> HSQLDB supports this feature. <p> </div> <!-- end release-specific documentation --> @param columnIndex the first column is 1, the second is 2, ... @param x the new column value @exception SQLException if a database access error occurs, the result set concurrency is <code>CONCUR_READ_ONLY</code> or this method is called on a closed result set @exception SQLFeatureNotSupportedException if the JDBC driver does not support this method @since JDK 1.2 (JDK 1.1.x developers: read the overview for JDBCResultSet) """ startUpdate(columnIndex); preparedStatement.setParameter(columnIndex, x); }
java
public void updateObject(int columnIndex, Object x) throws SQLException { startUpdate(columnIndex); preparedStatement.setParameter(columnIndex, x); }
[ "public", "void", "updateObject", "(", "int", "columnIndex", ",", "Object", "x", ")", "throws", "SQLException", "{", "startUpdate", "(", "columnIndex", ")", ";", "preparedStatement", ".", "setParameter", "(", "columnIndex", ",", "x", ")", ";", "}" ]
<!-- start generic documentation --> Updates the designated column with an <code>Object</code> value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the <code>updateRow</code> or <code>insertRow</code> methods are called to update the database. <!-- end generic documentation --> <!-- start release-specific documentation --> <div class="ReleaseSpecificDocumentation"> <h3>HSQLDB-Specific Information:</h3> <p> HSQLDB supports this feature. <p> </div> <!-- end release-specific documentation --> @param columnIndex the first column is 1, the second is 2, ... @param x the new column value @exception SQLException if a database access error occurs, the result set concurrency is <code>CONCUR_READ_ONLY</code> or this method is called on a closed result set @exception SQLFeatureNotSupportedException if the JDBC driver does not support this method @since JDK 1.2 (JDK 1.1.x developers: read the overview for JDBCResultSet)
[ "<!", "--", "start", "generic", "documentation", "--", ">", "Updates", "the", "designated", "column", "with", "an", "<code", ">", "Object<", "/", "code", ">", "value", ".", "The", "updater", "methods", "are", "used", "to", "update", "column", "values", "in", "the", "current", "row", "or", "the", "insert", "row", ".", "The", "updater", "methods", "do", "not", "update", "the", "underlying", "database", ";", "instead", "the", "<code", ">", "updateRow<", "/", "code", ">", "or", "<code", ">", "insertRow<", "/", "code", ">", "methods", "are", "called", "to", "update", "the", "database", ".", "<!", "--", "end", "generic", "documentation", "--", ">" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L3232-L3235
codecentric/zucchini
zucchini-web/src/main/java/de/codecentric/zucchini/web/results/AbstractWebResult.java
AbstractWebResult.injectVariables
@SuppressWarnings("WeakerAccess") protected final void injectVariables(Map<String, String> variables, By element) { """ This method can be used to inject variables into {@link org.openqa.selenium.By} instances that implement {@link de.codecentric.zucchini.bdd.dsl.VariablesAware}. If the element does not implement {@link de.codecentric.zucchini.bdd.dsl.VariablesAware}, then no injection will occur. @param variables The variables that will be injected. @param element The element. """ if (element instanceof VariablesAware) { ((VariablesAware) element).setVariables(variables); } }
java
@SuppressWarnings("WeakerAccess") protected final void injectVariables(Map<String, String> variables, By element) { if (element instanceof VariablesAware) { ((VariablesAware) element).setVariables(variables); } }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "protected", "final", "void", "injectVariables", "(", "Map", "<", "String", ",", "String", ">", "variables", ",", "By", "element", ")", "{", "if", "(", "element", "instanceof", "VariablesAware", ")", "{", "(", "(", "VariablesAware", ")", "element", ")", ".", "setVariables", "(", "variables", ")", ";", "}", "}" ]
This method can be used to inject variables into {@link org.openqa.selenium.By} instances that implement {@link de.codecentric.zucchini.bdd.dsl.VariablesAware}. If the element does not implement {@link de.codecentric.zucchini.bdd.dsl.VariablesAware}, then no injection will occur. @param variables The variables that will be injected. @param element The element.
[ "This", "method", "can", "be", "used", "to", "inject", "variables", "into", "{", "@link", "org", ".", "openqa", ".", "selenium", ".", "By", "}", "instances", "that", "implement", "{", "@link", "de", ".", "codecentric", ".", "zucchini", ".", "bdd", ".", "dsl", ".", "VariablesAware", "}", "." ]
train
https://github.com/codecentric/zucchini/blob/61541cd8ce666ef21ad943486a7c0eb53310ed5a/zucchini-web/src/main/java/de/codecentric/zucchini/web/results/AbstractWebResult.java#L60-L65
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ActivityConstraint.java
ActivityConstraint.satisfies
@Override public boolean satisfies(Match match, int... ind) { """ Checks if the PhysicalEntity controls anything. @param match current match to validate @param ind mapped index @return true if it controls anything """ PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); return pe.getControllerOf().isEmpty() == active; }
java
@Override public boolean satisfies(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); return pe.getControllerOf().isEmpty() == active; }
[ "@", "Override", "public", "boolean", "satisfies", "(", "Match", "match", ",", "int", "...", "ind", ")", "{", "PhysicalEntity", "pe", "=", "(", "PhysicalEntity", ")", "match", ".", "get", "(", "ind", "[", "0", "]", ")", ";", "return", "pe", ".", "getControllerOf", "(", ")", ".", "isEmpty", "(", ")", "==", "active", ";", "}" ]
Checks if the PhysicalEntity controls anything. @param match current match to validate @param ind mapped index @return true if it controls anything
[ "Checks", "if", "the", "PhysicalEntity", "controls", "anything", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ActivityConstraint.java#L34-L40
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/crdt/pncounter/PNCounterImpl.java
PNCounterImpl.getAndAdd
public CRDTTimestampedLong getAndAdd(long delta, VectorClock observedTimestamps) { """ Adds the given value to the current value. <p> The method can throw a {@link ConsistencyLostException} when the state of this CRDT is not causally related to the observed timestamps. This means that it cannot provide the session guarantees of RYW (read your writes) and monotonic read. @param delta the value to add @param observedTimestamps the vector clock last observed by the client of this counter @return the current counter value with the current counter vector clock @throws ConsistencyLostException if this replica cannot provide the session guarantees """ checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); if (delta < 0) { return getAndSubtract(-delta, observedTimestamps); } return getAndUpdate(delta, observedTimestamps, true); } finally { stateWriteLock.unlock(); } }
java
public CRDTTimestampedLong getAndAdd(long delta, VectorClock observedTimestamps) { checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); if (delta < 0) { return getAndSubtract(-delta, observedTimestamps); } return getAndUpdate(delta, observedTimestamps, true); } finally { stateWriteLock.unlock(); } }
[ "public", "CRDTTimestampedLong", "getAndAdd", "(", "long", "delta", ",", "VectorClock", "observedTimestamps", ")", "{", "checkSessionConsistency", "(", "observedTimestamps", ")", ";", "stateWriteLock", ".", "lock", "(", ")", ";", "try", "{", "checkNotMigrated", "(", ")", ";", "if", "(", "delta", "<", "0", ")", "{", "return", "getAndSubtract", "(", "-", "delta", ",", "observedTimestamps", ")", ";", "}", "return", "getAndUpdate", "(", "delta", ",", "observedTimestamps", ",", "true", ")", ";", "}", "finally", "{", "stateWriteLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Adds the given value to the current value. <p> The method can throw a {@link ConsistencyLostException} when the state of this CRDT is not causally related to the observed timestamps. This means that it cannot provide the session guarantees of RYW (read your writes) and monotonic read. @param delta the value to add @param observedTimestamps the vector clock last observed by the client of this counter @return the current counter value with the current counter vector clock @throws ConsistencyLostException if this replica cannot provide the session guarantees
[ "Adds", "the", "given", "value", "to", "the", "current", "value", ".", "<p", ">", "The", "method", "can", "throw", "a", "{", "@link", "ConsistencyLostException", "}", "when", "the", "state", "of", "this", "CRDT", "is", "not", "causally", "related", "to", "the", "observed", "timestamps", ".", "This", "means", "that", "it", "cannot", "provide", "the", "session", "guarantees", "of", "RYW", "(", "read", "your", "writes", ")", "and", "monotonic", "read", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/crdt/pncounter/PNCounterImpl.java#L110-L122
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/nodetype/NodeTypeImpl.java
NodeTypeImpl.checkValueConstraints
private boolean checkValueConstraints(int requiredType, String[] constraints, Value value) { """ Check value constrains. @param requiredType int @param constraints - string constrains. @param value - value to check. @return result of check. """ ValueConstraintsMatcher constrMatcher = new ValueConstraintsMatcher(constraints, locationFactory, dataManager, nodeTypeDataManager); try { return constrMatcher.match(((BaseValue)value).getInternalData(), requiredType); } catch (RepositoryException e1) { return false; } }
java
private boolean checkValueConstraints(int requiredType, String[] constraints, Value value) { ValueConstraintsMatcher constrMatcher = new ValueConstraintsMatcher(constraints, locationFactory, dataManager, nodeTypeDataManager); try { return constrMatcher.match(((BaseValue)value).getInternalData(), requiredType); } catch (RepositoryException e1) { return false; } }
[ "private", "boolean", "checkValueConstraints", "(", "int", "requiredType", ",", "String", "[", "]", "constraints", ",", "Value", "value", ")", "{", "ValueConstraintsMatcher", "constrMatcher", "=", "new", "ValueConstraintsMatcher", "(", "constraints", ",", "locationFactory", ",", "dataManager", ",", "nodeTypeDataManager", ")", ";", "try", "{", "return", "constrMatcher", ".", "match", "(", "(", "(", "BaseValue", ")", "value", ")", ".", "getInternalData", "(", ")", ",", "requiredType", ")", ";", "}", "catch", "(", "RepositoryException", "e1", ")", "{", "return", "false", ";", "}", "}" ]
Check value constrains. @param requiredType int @param constraints - string constrains. @param value - value to check. @return result of check.
[ "Check", "value", "constrains", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/nodetype/NodeTypeImpl.java#L723-L736
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/EventManager.java
EventManager.addListener
public void addListener(InstallEventListener listener, String notificationType) { """ Adds an install event listener to the listenersMap with a specified notification type @param listener InstallEventListener to add @param notificationType Notification type of listener """ if (listener == null || notificationType == null) return; if (notificationType.isEmpty()) return; if (listenersMap == null) { listenersMap = new HashMap<String, Collection<InstallEventListener>>(); } Collection<InstallEventListener> listeners = listenersMap.get(notificationType); if (listeners == null) { listeners = new ArrayList<InstallEventListener>(1); listenersMap.put(notificationType, listeners); } listeners.add(listener); }
java
public void addListener(InstallEventListener listener, String notificationType) { if (listener == null || notificationType == null) return; if (notificationType.isEmpty()) return; if (listenersMap == null) { listenersMap = new HashMap<String, Collection<InstallEventListener>>(); } Collection<InstallEventListener> listeners = listenersMap.get(notificationType); if (listeners == null) { listeners = new ArrayList<InstallEventListener>(1); listenersMap.put(notificationType, listeners); } listeners.add(listener); }
[ "public", "void", "addListener", "(", "InstallEventListener", "listener", ",", "String", "notificationType", ")", "{", "if", "(", "listener", "==", "null", "||", "notificationType", "==", "null", ")", "return", ";", "if", "(", "notificationType", ".", "isEmpty", "(", ")", ")", "return", ";", "if", "(", "listenersMap", "==", "null", ")", "{", "listenersMap", "=", "new", "HashMap", "<", "String", ",", "Collection", "<", "InstallEventListener", ">", ">", "(", ")", ";", "}", "Collection", "<", "InstallEventListener", ">", "listeners", "=", "listenersMap", ".", "get", "(", "notificationType", ")", ";", "if", "(", "listeners", "==", "null", ")", "{", "listeners", "=", "new", "ArrayList", "<", "InstallEventListener", ">", "(", "1", ")", ";", "listenersMap", ".", "put", "(", "notificationType", ",", "listeners", ")", ";", "}", "listeners", ".", "add", "(", "listener", ")", ";", "}" ]
Adds an install event listener to the listenersMap with a specified notification type @param listener InstallEventListener to add @param notificationType Notification type of listener
[ "Adds", "an", "install", "event", "listener", "to", "the", "listenersMap", "with", "a", "specified", "notification", "type" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/EventManager.java#L35-L49
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/DefaultStatisticsReportLabellingStrategy.java
DefaultStatisticsReportLabellingStrategy.getColumnDescriptions
@Override public List<ColumnDescription> getColumnDescriptions( TitleAndCount[] items, boolean showAll, BaseReportForm form) { """ Create column descriptions for the portlet report. The column descriptions are essentially the opposite of the title description changes. Those items that have size > 1 (more than one value selected in the report criteria) are displayed in the column description. If all items have only 1 value selected, the first item will be the column description. @param items ordered array of items in the report. NOTE: item ordering must be the same as with getReportTitleAugmentation @param showAll true to include all item descriptions in the column headings. Useful if report is being written to CSV, XML, HTML, etc. for importing into another tool @param form statistics report form @return List of column descriptions for the report """ String description = null; int multipleValues = 0; for (TitleAndCount item : items) { if (item.getCriteriaValuesSelected() > 1 || showAll) { multipleValues++; description = description == null ? item.getCriteriaItem() : description + displaySeparator + item.getCriteriaItem(); } } // If all items have 1 value selected or if there is only 1 item, make the // first item the column descriptor. if (multipleValues == 0 || items.length == 1) { description = items[0].getCriteriaItem(); } final List<ColumnDescription> columnDescriptions = new ArrayList<ColumnDescription>(); columnDescriptions.add(new ColumnDescription(description, ValueType.NUMBER, description)); return columnDescriptions; }
java
@Override public List<ColumnDescription> getColumnDescriptions( TitleAndCount[] items, boolean showAll, BaseReportForm form) { String description = null; int multipleValues = 0; for (TitleAndCount item : items) { if (item.getCriteriaValuesSelected() > 1 || showAll) { multipleValues++; description = description == null ? item.getCriteriaItem() : description + displaySeparator + item.getCriteriaItem(); } } // If all items have 1 value selected or if there is only 1 item, make the // first item the column descriptor. if (multipleValues == 0 || items.length == 1) { description = items[0].getCriteriaItem(); } final List<ColumnDescription> columnDescriptions = new ArrayList<ColumnDescription>(); columnDescriptions.add(new ColumnDescription(description, ValueType.NUMBER, description)); return columnDescriptions; }
[ "@", "Override", "public", "List", "<", "ColumnDescription", ">", "getColumnDescriptions", "(", "TitleAndCount", "[", "]", "items", ",", "boolean", "showAll", ",", "BaseReportForm", "form", ")", "{", "String", "description", "=", "null", ";", "int", "multipleValues", "=", "0", ";", "for", "(", "TitleAndCount", "item", ":", "items", ")", "{", "if", "(", "item", ".", "getCriteriaValuesSelected", "(", ")", ">", "1", "||", "showAll", ")", "{", "multipleValues", "++", ";", "description", "=", "description", "==", "null", "?", "item", ".", "getCriteriaItem", "(", ")", ":", "description", "+", "displaySeparator", "+", "item", ".", "getCriteriaItem", "(", ")", ";", "}", "}", "// If all items have 1 value selected or if there is only 1 item, make the", "// first item the column descriptor.", "if", "(", "multipleValues", "==", "0", "||", "items", ".", "length", "==", "1", ")", "{", "description", "=", "items", "[", "0", "]", ".", "getCriteriaItem", "(", ")", ";", "}", "final", "List", "<", "ColumnDescription", ">", "columnDescriptions", "=", "new", "ArrayList", "<", "ColumnDescription", ">", "(", ")", ";", "columnDescriptions", ".", "add", "(", "new", "ColumnDescription", "(", "description", ",", "ValueType", ".", "NUMBER", ",", "description", ")", ")", ";", "return", "columnDescriptions", ";", "}" ]
Create column descriptions for the portlet report. The column descriptions are essentially the opposite of the title description changes. Those items that have size > 1 (more than one value selected in the report criteria) are displayed in the column description. If all items have only 1 value selected, the first item will be the column description. @param items ordered array of items in the report. NOTE: item ordering must be the same as with getReportTitleAugmentation @param showAll true to include all item descriptions in the column headings. Useful if report is being written to CSV, XML, HTML, etc. for importing into another tool @param form statistics report form @return List of column descriptions for the report
[ "Create", "column", "descriptions", "for", "the", "portlet", "report", ".", "The", "column", "descriptions", "are", "essentially", "the", "opposite", "of", "the", "title", "description", "changes", ".", "Those", "items", "that", "have", "size", ">", "1", "(", "more", "than", "one", "value", "selected", "in", "the", "report", "criteria", ")", "are", "displayed", "in", "the", "column", "description", ".", "If", "all", "items", "have", "only", "1", "value", "selected", "the", "first", "item", "will", "be", "the", "column", "description", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/statistics/DefaultStatisticsReportLabellingStrategy.java#L88-L111
michael-rapp/AndroidMaterialDialog
library/src/main/java/de/mrapp/android/dialog/view/DialogRootView.java
DialogRootView.applyDialogPaddingBottom
private void applyDialogPaddingBottom(@NonNull final Area area, @NonNull final View view) { """ Applies the dialog's bottom padding to the view of a specific area. @param area The area, the view, the padding should be applied to, corresponds to, as an instance of the class {@link Area}. The area may not be null @param view The view, the padding should be applied to, as an instance of the class {@link View}. The view may not be null """ if (area != Area.HEADER && area != Area.BUTTON_BAR) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), dialogPadding[3]); } }
java
private void applyDialogPaddingBottom(@NonNull final Area area, @NonNull final View view) { if (area != Area.HEADER && area != Area.BUTTON_BAR) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), dialogPadding[3]); } }
[ "private", "void", "applyDialogPaddingBottom", "(", "@", "NonNull", "final", "Area", "area", ",", "@", "NonNull", "final", "View", "view", ")", "{", "if", "(", "area", "!=", "Area", ".", "HEADER", "&&", "area", "!=", "Area", ".", "BUTTON_BAR", ")", "{", "view", ".", "setPadding", "(", "view", ".", "getPaddingLeft", "(", ")", ",", "view", ".", "getPaddingTop", "(", ")", ",", "view", ".", "getPaddingRight", "(", ")", ",", "dialogPadding", "[", "3", "]", ")", ";", "}", "}" ]
Applies the dialog's bottom padding to the view of a specific area. @param area The area, the view, the padding should be applied to, corresponds to, as an instance of the class {@link Area}. The area may not be null @param view The view, the padding should be applied to, as an instance of the class {@link View}. The view may not be null
[ "Applies", "the", "dialog", "s", "bottom", "padding", "to", "the", "view", "of", "a", "specific", "area", "." ]
train
https://github.com/michael-rapp/AndroidMaterialDialog/blob/8990eed72ee5f5a9720836ee708f71ac0d43053b/library/src/main/java/de/mrapp/android/dialog/view/DialogRootView.java#L720-L725
casbin/jcasbin
src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java
BuiltInFunctions.generateGFunction
public static AviatorFunction generateGFunction(String name, RoleManager rm) { """ generateGFunction is the factory method of the g(_, _) function. @param name the name of the g(_, _) function, can be "g", "g2", .. @param rm the role manager used by the function. @return the function. """ return new AbstractFunction() { public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) { String name1 = FunctionUtils.getStringValue(arg1, env); String name2 = FunctionUtils.getStringValue(arg2, env); if (rm == null) { return AviatorBoolean.valueOf(name1.equals(name2)); } else { boolean res = rm.hasLink(name1, name2); return AviatorBoolean.valueOf(res); } } public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) { String name1 = FunctionUtils.getStringValue(arg1, env); String name2 = FunctionUtils.getStringValue(arg2, env); if (rm == null) { return AviatorBoolean.valueOf(name1.equals(name2)); } else { String domain = FunctionUtils.getStringValue(arg3, env); boolean res = rm.hasLink(name1, name2, domain); return AviatorBoolean.valueOf(res); } } public String getName() { return name; } }; }
java
public static AviatorFunction generateGFunction(String name, RoleManager rm) { return new AbstractFunction() { public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) { String name1 = FunctionUtils.getStringValue(arg1, env); String name2 = FunctionUtils.getStringValue(arg2, env); if (rm == null) { return AviatorBoolean.valueOf(name1.equals(name2)); } else { boolean res = rm.hasLink(name1, name2); return AviatorBoolean.valueOf(res); } } public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) { String name1 = FunctionUtils.getStringValue(arg1, env); String name2 = FunctionUtils.getStringValue(arg2, env); if (rm == null) { return AviatorBoolean.valueOf(name1.equals(name2)); } else { String domain = FunctionUtils.getStringValue(arg3, env); boolean res = rm.hasLink(name1, name2, domain); return AviatorBoolean.valueOf(res); } } public String getName() { return name; } }; }
[ "public", "static", "AviatorFunction", "generateGFunction", "(", "String", "name", ",", "RoleManager", "rm", ")", "{", "return", "new", "AbstractFunction", "(", ")", "{", "public", "AviatorObject", "call", "(", "Map", "<", "String", ",", "Object", ">", "env", ",", "AviatorObject", "arg1", ",", "AviatorObject", "arg2", ")", "{", "String", "name1", "=", "FunctionUtils", ".", "getStringValue", "(", "arg1", ",", "env", ")", ";", "String", "name2", "=", "FunctionUtils", ".", "getStringValue", "(", "arg2", ",", "env", ")", ";", "if", "(", "rm", "==", "null", ")", "{", "return", "AviatorBoolean", ".", "valueOf", "(", "name1", ".", "equals", "(", "name2", ")", ")", ";", "}", "else", "{", "boolean", "res", "=", "rm", ".", "hasLink", "(", "name1", ",", "name2", ")", ";", "return", "AviatorBoolean", ".", "valueOf", "(", "res", ")", ";", "}", "}", "public", "AviatorObject", "call", "(", "Map", "<", "String", ",", "Object", ">", "env", ",", "AviatorObject", "arg1", ",", "AviatorObject", "arg2", ",", "AviatorObject", "arg3", ")", "{", "String", "name1", "=", "FunctionUtils", ".", "getStringValue", "(", "arg1", ",", "env", ")", ";", "String", "name2", "=", "FunctionUtils", ".", "getStringValue", "(", "arg2", ",", "env", ")", ";", "if", "(", "rm", "==", "null", ")", "{", "return", "AviatorBoolean", ".", "valueOf", "(", "name1", ".", "equals", "(", "name2", ")", ")", ";", "}", "else", "{", "String", "domain", "=", "FunctionUtils", ".", "getStringValue", "(", "arg3", ",", "env", ")", ";", "boolean", "res", "=", "rm", ".", "hasLink", "(", "name1", ",", "name2", ",", "domain", ")", ";", "return", "AviatorBoolean", ".", "valueOf", "(", "res", ")", ";", "}", "}", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "}", ";", "}" ]
generateGFunction is the factory method of the g(_, _) function. @param name the name of the g(_, _) function, can be "g", "g2", .. @param rm the role manager used by the function. @return the function.
[ "generateGFunction", "is", "the", "factory", "method", "of", "the", "g", "(", "_", "_", ")", "function", "." ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java#L159-L190
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java
SftpClient.get
public SftpFileAttributes get(String path, FileTransferProgress progress) throws FileNotFoundException, SftpStatusException, SshException, TransferCancelledException { """ <p> Download the remote file to the local computer. </p> @param path the path to the remote file @param progress @return the downloaded file's attributes @throws FileNotFoundException @throws SftpStatusException @throws SshException @throws TransferCancelledException """ return get(path, progress, false); }
java
public SftpFileAttributes get(String path, FileTransferProgress progress) throws FileNotFoundException, SftpStatusException, SshException, TransferCancelledException { return get(path, progress, false); }
[ "public", "SftpFileAttributes", "get", "(", "String", "path", ",", "FileTransferProgress", "progress", ")", "throws", "FileNotFoundException", ",", "SftpStatusException", ",", "SshException", ",", "TransferCancelledException", "{", "return", "get", "(", "path", ",", "progress", ",", "false", ")", ";", "}" ]
<p> Download the remote file to the local computer. </p> @param path the path to the remote file @param progress @return the downloaded file's attributes @throws FileNotFoundException @throws SftpStatusException @throws SshException @throws TransferCancelledException
[ "<p", ">", "Download", "the", "remote", "file", "to", "the", "local", "computer", ".", "<", "/", "p", ">" ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L800-L804
monitorjbl/excel-streaming-reader
src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java
StreamingSheetReader.setFormatString
void setFormatString(StartElement startElement, StreamingCell cell) { """ Read the numeric format string out of the styles table for this cell. Stores the result in the Cell. @param startElement @param cell """ Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if(cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if(stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if(style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if(formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
java
void setFormatString(StartElement startElement, StreamingCell cell) { Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if(cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if(stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if(style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if(formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
[ "void", "setFormatString", "(", "StartElement", "startElement", ",", "StreamingCell", "cell", ")", "{", "Attribute", "cellStyle", "=", "startElement", ".", "getAttributeByName", "(", "new", "QName", "(", "\"s\"", ")", ")", ";", "String", "cellStyleString", "=", "(", "cellStyle", "!=", "null", ")", "?", "cellStyle", ".", "getValue", "(", ")", ":", "null", ";", "XSSFCellStyle", "style", "=", "null", ";", "if", "(", "cellStyleString", "!=", "null", ")", "{", "style", "=", "stylesTable", ".", "getStyleAt", "(", "Integer", ".", "parseInt", "(", "cellStyleString", ")", ")", ";", "}", "else", "if", "(", "stylesTable", ".", "getNumCellStyles", "(", ")", ">", "0", ")", "{", "style", "=", "stylesTable", ".", "getStyleAt", "(", "0", ")", ";", "}", "if", "(", "style", "!=", "null", ")", "{", "cell", ".", "setNumericFormatIndex", "(", "style", ".", "getDataFormat", "(", ")", ")", ";", "String", "formatString", "=", "style", ".", "getDataFormatString", "(", ")", ";", "if", "(", "formatString", "!=", "null", ")", "{", "cell", ".", "setNumericFormat", "(", "formatString", ")", ";", "}", "else", "{", "cell", ".", "setNumericFormat", "(", "BuiltinFormats", ".", "getBuiltinFormat", "(", "cell", ".", "getNumericFormatIndex", "(", ")", ")", ")", ";", "}", "}", "else", "{", "cell", ".", "setNumericFormatIndex", "(", "null", ")", ";", "cell", ".", "setNumericFormat", "(", "null", ")", ";", "}", "}" ]
Read the numeric format string out of the styles table for this cell. Stores the result in the Cell. @param startElement @param cell
[ "Read", "the", "numeric", "format", "string", "out", "of", "the", "styles", "table", "for", "this", "cell", ".", "Stores", "the", "result", "in", "the", "Cell", "." ]
train
https://github.com/monitorjbl/excel-streaming-reader/blob/4e95c9aaaecf33685a09f8c267af3a578ba5e070/src/main/java/com/monitorjbl/xlsx/impl/StreamingSheetReader.java#L265-L289
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/symmetric/RC4.java
RC4.decrypt
public String decrypt(byte[] message, Charset charset) throws CryptoException { """ 解密 @param message 消息 @param charset 编码 @return 明文 @throws CryptoException key长度小于5或者大于255抛出此异常 """ return StrUtil.str(crypt(message), charset); }
java
public String decrypt(byte[] message, Charset charset) throws CryptoException { return StrUtil.str(crypt(message), charset); }
[ "public", "String", "decrypt", "(", "byte", "[", "]", "message", ",", "Charset", "charset", ")", "throws", "CryptoException", "{", "return", "StrUtil", ".", "str", "(", "crypt", "(", "message", ")", ",", "charset", ")", ";", "}" ]
解密 @param message 消息 @param charset 编码 @return 明文 @throws CryptoException key长度小于5或者大于255抛出此异常
[ "解密" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/symmetric/RC4.java#L72-L74
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.findImmediateMemberType
Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { """ Find a type declared in a scope (not inherited). Return null if none is found. @param env The current environment. @param site The original type from where the selection takes place. @param name The type's name. @param c The class to search for the member type. This is always a superclass or implemented interface of site's class. """ Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { return isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); } e = e.next(); } return typeNotFound; }
java
Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { return isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); } e = e.next(); } return typeNotFound; }
[ "Symbol", "findImmediateMemberType", "(", "Env", "<", "AttrContext", ">", "env", ",", "Type", "site", ",", "Name", "name", ",", "TypeSymbol", "c", ")", "{", "Scope", ".", "Entry", "e", "=", "c", ".", "members", "(", ")", ".", "lookup", "(", "name", ")", ";", "while", "(", "e", ".", "scope", "!=", "null", ")", "{", "if", "(", "e", ".", "sym", ".", "kind", "==", "TYP", ")", "{", "return", "isAccessible", "(", "env", ",", "site", ",", "e", ".", "sym", ")", "?", "e", ".", "sym", ":", "new", "AccessError", "(", "env", ",", "site", ",", "e", ".", "sym", ")", ";", "}", "e", "=", "e", ".", "next", "(", ")", ";", "}", "return", "typeNotFound", ";", "}" ]
Find a type declared in a scope (not inherited). Return null if none is found. @param env The current environment. @param site The original type from where the selection takes place. @param name The type's name. @param c The class to search for the member type. This is always a superclass or implemented interface of site's class.
[ "Find", "a", "type", "declared", "in", "a", "scope", "(", "not", "inherited", ")", ".", "Return", "null", "if", "none", "is", "found", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/comp/Resolve.java#L1928-L1942
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/URIUtils.java
URIUtils.getParameters
public static Multimap<String, String> getParameters(final String rawQuery) { """ Parse the URI and get all the parameters in map form. Query name -&gt; List of Query values. @param rawQuery query portion of the uri to analyze. """ Multimap<String, String> result = HashMultimap.create(); if (rawQuery == null) { return result; } StringTokenizer tokens = new StringTokenizer(rawQuery, "&"); while (tokens.hasMoreTokens()) { String pair = tokens.nextToken(); int pos = pair.indexOf('='); String key; String value; if (pos == -1) { key = pair; value = ""; } else { try { key = URLDecoder.decode(pair.substring(0, pos), "UTF-8"); value = URLDecoder.decode(pair.substring(pos + 1), "UTF-8"); } catch (UnsupportedEncodingException e) { throw ExceptionUtils.getRuntimeException(e); } } result.put(key, value); } return result; }
java
public static Multimap<String, String> getParameters(final String rawQuery) { Multimap<String, String> result = HashMultimap.create(); if (rawQuery == null) { return result; } StringTokenizer tokens = new StringTokenizer(rawQuery, "&"); while (tokens.hasMoreTokens()) { String pair = tokens.nextToken(); int pos = pair.indexOf('='); String key; String value; if (pos == -1) { key = pair; value = ""; } else { try { key = URLDecoder.decode(pair.substring(0, pos), "UTF-8"); value = URLDecoder.decode(pair.substring(pos + 1), "UTF-8"); } catch (UnsupportedEncodingException e) { throw ExceptionUtils.getRuntimeException(e); } } result.put(key, value); } return result; }
[ "public", "static", "Multimap", "<", "String", ",", "String", ">", "getParameters", "(", "final", "String", "rawQuery", ")", "{", "Multimap", "<", "String", ",", "String", ">", "result", "=", "HashMultimap", ".", "create", "(", ")", ";", "if", "(", "rawQuery", "==", "null", ")", "{", "return", "result", ";", "}", "StringTokenizer", "tokens", "=", "new", "StringTokenizer", "(", "rawQuery", ",", "\"&\"", ")", ";", "while", "(", "tokens", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "pair", "=", "tokens", ".", "nextToken", "(", ")", ";", "int", "pos", "=", "pair", ".", "indexOf", "(", "'", "'", ")", ";", "String", "key", ";", "String", "value", ";", "if", "(", "pos", "==", "-", "1", ")", "{", "key", "=", "pair", ";", "value", "=", "\"\"", ";", "}", "else", "{", "try", "{", "key", "=", "URLDecoder", ".", "decode", "(", "pair", ".", "substring", "(", "0", ",", "pos", ")", ",", "\"UTF-8\"", ")", ";", "value", "=", "URLDecoder", ".", "decode", "(", "pair", ".", "substring", "(", "pos", "+", "1", ")", ",", "\"UTF-8\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "ExceptionUtils", ".", "getRuntimeException", "(", "e", ")", ";", "}", "}", "result", ".", "put", "(", "key", ",", "value", ")", ";", "}", "return", "result", ";", "}" ]
Parse the URI and get all the parameters in map form. Query name -&gt; List of Query values. @param rawQuery query portion of the uri to analyze.
[ "Parse", "the", "URI", "and", "get", "all", "the", "parameters", "in", "map", "form", ".", "Query", "name", "-", "&gt", ";", "List", "of", "Query", "values", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/URIUtils.java#L44-L72
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java
SparkUtils.listPaths
public static JavaRDD<String> listPaths(JavaSparkContext sc, String path, boolean recursive) throws IOException { """ List of the files in the given directory (path), as a {@code JavaRDD<String>} @param sc Spark context @param path Path to list files in @param recursive Whether to walk the directory tree recursively (i.e., include subdirectories) @return Paths in the directory @throws IOException If error occurs getting directory contents """ //NativeImageLoader.ALLOWED_FORMATS return listPaths(sc, path, recursive, (Set<String>)null); }
java
public static JavaRDD<String> listPaths(JavaSparkContext sc, String path, boolean recursive) throws IOException { //NativeImageLoader.ALLOWED_FORMATS return listPaths(sc, path, recursive, (Set<String>)null); }
[ "public", "static", "JavaRDD", "<", "String", ">", "listPaths", "(", "JavaSparkContext", "sc", ",", "String", "path", ",", "boolean", "recursive", ")", "throws", "IOException", "{", "//NativeImageLoader.ALLOWED_FORMATS", "return", "listPaths", "(", "sc", ",", "path", ",", "recursive", ",", "(", "Set", "<", "String", ">", ")", "null", ")", ";", "}" ]
List of the files in the given directory (path), as a {@code JavaRDD<String>} @param sc Spark context @param path Path to list files in @param recursive Whether to walk the directory tree recursively (i.e., include subdirectories) @return Paths in the directory @throws IOException If error occurs getting directory contents
[ "List", "of", "the", "files", "in", "the", "given", "directory", "(", "path", ")", "as", "a", "{", "@code", "JavaRDD<String", ">", "}" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L540-L543
qiniu/java-sdk
src/main/java/com/qiniu/storage/BucketManager.java
BucketManager.asynFetch
public Response asynFetch(String url, String bucket, String key) throws QiniuException { """ 异步第三方资源抓取 从指定 URL 抓取资源,并将该资源存储到指定空间中。每次只抓取一个文件,抓取时可以指定保存空间名和最终资源名。 主要对于大文件进行抓取 https://developer.qiniu.com/kodo/api/4097/asynch-fetch @param url 待抓取的文件链接,支持设置多个,以';'分隔 @param bucket 文件抓取后保存的空间 @param key 文件抓取后保存的文件名 @return Response @throws QiniuException """ String requesturl = configuration.apiHost(auth.accessKey, bucket) + "/sisyphus/fetch"; StringMap stringMap = new StringMap().put("url", url).put("bucket", bucket).putNotNull("key", key); byte[] bodyByte = Json.encode(stringMap).getBytes(Constants.UTF_8); return client.post(requesturl, bodyByte, auth.authorizationV2(requesturl, "POST", bodyByte, "application/json"), Client.JsonMime); }
java
public Response asynFetch(String url, String bucket, String key) throws QiniuException { String requesturl = configuration.apiHost(auth.accessKey, bucket) + "/sisyphus/fetch"; StringMap stringMap = new StringMap().put("url", url).put("bucket", bucket).putNotNull("key", key); byte[] bodyByte = Json.encode(stringMap).getBytes(Constants.UTF_8); return client.post(requesturl, bodyByte, auth.authorizationV2(requesturl, "POST", bodyByte, "application/json"), Client.JsonMime); }
[ "public", "Response", "asynFetch", "(", "String", "url", ",", "String", "bucket", ",", "String", "key", ")", "throws", "QiniuException", "{", "String", "requesturl", "=", "configuration", ".", "apiHost", "(", "auth", ".", "accessKey", ",", "bucket", ")", "+", "\"/sisyphus/fetch\"", ";", "StringMap", "stringMap", "=", "new", "StringMap", "(", ")", ".", "put", "(", "\"url\"", ",", "url", ")", ".", "put", "(", "\"bucket\"", ",", "bucket", ")", ".", "putNotNull", "(", "\"key\"", ",", "key", ")", ";", "byte", "[", "]", "bodyByte", "=", "Json", ".", "encode", "(", "stringMap", ")", ".", "getBytes", "(", "Constants", ".", "UTF_8", ")", ";", "return", "client", ".", "post", "(", "requesturl", ",", "bodyByte", ",", "auth", ".", "authorizationV2", "(", "requesturl", ",", "\"POST\"", ",", "bodyByte", ",", "\"application/json\"", ")", ",", "Client", ".", "JsonMime", ")", ";", "}" ]
异步第三方资源抓取 从指定 URL 抓取资源,并将该资源存储到指定空间中。每次只抓取一个文件,抓取时可以指定保存空间名和最终资源名。 主要对于大文件进行抓取 https://developer.qiniu.com/kodo/api/4097/asynch-fetch @param url 待抓取的文件链接,支持设置多个,以';'分隔 @param bucket 文件抓取后保存的空间 @param key 文件抓取后保存的文件名 @return Response @throws QiniuException
[ "异步第三方资源抓取", "从指定", "URL", "抓取资源,并将该资源存储到指定空间中。每次只抓取一个文件,抓取时可以指定保存空间名和最终资源名。", "主要对于大文件进行抓取", "https", ":", "//", "developer", ".", "qiniu", ".", "com", "/", "kodo", "/", "api", "/", "4097", "/", "asynch", "-", "fetch" ]
train
https://github.com/qiniu/java-sdk/blob/6c05f3fb718403a496c725b048e9241f80171499/src/main/java/com/qiniu/storage/BucketManager.java#L473-L479
shrinkwrap/shrinkwrap
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/path/PathUtil.java
PathUtil.composeAbsoluteContext
public static String composeAbsoluteContext(final String base, final String context) { """ Composes an absolute context from a given base and actual context relative to the base, returning the result. ie. base of "base" and context of "context" will result in form "/base/context". """ // Precondition checks assertSpecified(base); assertSpecified(context); // Compose final String relative = PathUtil.adjustToAbsoluteDirectoryContext(base); final String reformedContext = PathUtil.optionallyRemovePrecedingSlash(context); final String actual = relative + reformedContext; // Return return actual; }
java
public static String composeAbsoluteContext(final String base, final String context) { // Precondition checks assertSpecified(base); assertSpecified(context); // Compose final String relative = PathUtil.adjustToAbsoluteDirectoryContext(base); final String reformedContext = PathUtil.optionallyRemovePrecedingSlash(context); final String actual = relative + reformedContext; // Return return actual; }
[ "public", "static", "String", "composeAbsoluteContext", "(", "final", "String", "base", ",", "final", "String", "context", ")", "{", "// Precondition checks", "assertSpecified", "(", "base", ")", ";", "assertSpecified", "(", "context", ")", ";", "// Compose", "final", "String", "relative", "=", "PathUtil", ".", "adjustToAbsoluteDirectoryContext", "(", "base", ")", ";", "final", "String", "reformedContext", "=", "PathUtil", ".", "optionallyRemovePrecedingSlash", "(", "context", ")", ";", "final", "String", "actual", "=", "relative", "+", "reformedContext", ";", "// Return", "return", "actual", ";", "}" ]
Composes an absolute context from a given base and actual context relative to the base, returning the result. ie. base of "base" and context of "context" will result in form "/base/context".
[ "Composes", "an", "absolute", "context", "from", "a", "given", "base", "and", "actual", "context", "relative", "to", "the", "base", "returning", "the", "result", ".", "ie", ".", "base", "of", "base", "and", "context", "of", "context", "will", "result", "in", "form", "/", "base", "/", "context", "." ]
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/path/PathUtil.java#L61-L73
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/resource/BatchLinkingService.java
BatchLinkingService.resolveBatched
public EObject resolveBatched(EObject context, EReference reference, String uriFragment) { """ @param context the current instance that owns the referenced proxy. @param reference the {@link EReference} that has the proxy value. @param uriFragment the lazy linking fragment. @return the resolved object for the given context or <code>null</code> if it couldn't be resolved """ return resolveBatched(context, reference, uriFragment, CancelIndicator.NullImpl); }
java
public EObject resolveBatched(EObject context, EReference reference, String uriFragment) { return resolveBatched(context, reference, uriFragment, CancelIndicator.NullImpl); }
[ "public", "EObject", "resolveBatched", "(", "EObject", "context", ",", "EReference", "reference", ",", "String", "uriFragment", ")", "{", "return", "resolveBatched", "(", "context", ",", "reference", ",", "uriFragment", ",", "CancelIndicator", ".", "NullImpl", ")", ";", "}" ]
@param context the current instance that owns the referenced proxy. @param reference the {@link EReference} that has the proxy value. @param uriFragment the lazy linking fragment. @return the resolved object for the given context or <code>null</code> if it couldn't be resolved
[ "@param", "context", "the", "current", "instance", "that", "owns", "the", "referenced", "proxy", ".", "@param", "reference", "the", "{", "@link", "EReference", "}", "that", "has", "the", "proxy", "value", ".", "@param", "uriFragment", "the", "lazy", "linking", "fragment", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/resource/BatchLinkingService.java#L40-L42
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.getTimestamp
@Override public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { """ Retrieves the value of the designated JDBC TIMESTAMP parameter as a java.sql.Timestamp object, using the given Calendar object to construct the Timestamp object. """ checkClosed(); throw SQLError.noSupport(); }
java
@Override public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "Timestamp", "getTimestamp", "(", "int", "parameterIndex", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Retrieves the value of the designated JDBC TIMESTAMP parameter as a java.sql.Timestamp object, using the given Calendar object to construct the Timestamp object.
[ "Retrieves", "the", "value", "of", "the", "designated", "JDBC", "TIMESTAMP", "parameter", "as", "a", "java", ".", "sql", ".", "Timestamp", "object", "using", "the", "given", "Calendar", "object", "to", "construct", "the", "Timestamp", "object", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L479-L484
indeedeng/proctor
proctor-store-git/src/main/java/com/indeed/proctor/store/GitProctorUtils.java
GitProctorUtils.resolveSvnMigratedRevision
public static String resolveSvnMigratedRevision(final Revision revision, final String branch) { """ Helper method to retrieve a canonical revision for git commits migrated from SVN. Migrated commits are detected by the presence of 'git-svn-id' in the commit message. @param revision the commit/revision to inspect @param branch the name of the branch it came from @return the original SVN revision if it was a migrated commit from the branch specified, otherwise the git revision """ if (revision == null) { return null; } final Pattern pattern = Pattern.compile("^git-svn-id: .*" + branch + "@([0-9]+) ", Pattern.MULTILINE); final Matcher matcher = pattern.matcher(revision.getMessage()); if (matcher.find()) { return matcher.group(1); } else { return revision.getRevision(); } }
java
public static String resolveSvnMigratedRevision(final Revision revision, final String branch) { if (revision == null) { return null; } final Pattern pattern = Pattern.compile("^git-svn-id: .*" + branch + "@([0-9]+) ", Pattern.MULTILINE); final Matcher matcher = pattern.matcher(revision.getMessage()); if (matcher.find()) { return matcher.group(1); } else { return revision.getRevision(); } }
[ "public", "static", "String", "resolveSvnMigratedRevision", "(", "final", "Revision", "revision", ",", "final", "String", "branch", ")", "{", "if", "(", "revision", "==", "null", ")", "{", "return", "null", ";", "}", "final", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "\"^git-svn-id: .*\"", "+", "branch", "+", "\"@([0-9]+) \"", ",", "Pattern", ".", "MULTILINE", ")", ";", "final", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "revision", ".", "getMessage", "(", ")", ")", ";", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "return", "matcher", ".", "group", "(", "1", ")", ";", "}", "else", "{", "return", "revision", ".", "getRevision", "(", ")", ";", "}", "}" ]
Helper method to retrieve a canonical revision for git commits migrated from SVN. Migrated commits are detected by the presence of 'git-svn-id' in the commit message. @param revision the commit/revision to inspect @param branch the name of the branch it came from @return the original SVN revision if it was a migrated commit from the branch specified, otherwise the git revision
[ "Helper", "method", "to", "retrieve", "a", "canonical", "revision", "for", "git", "commits", "migrated", "from", "SVN", ".", "Migrated", "commits", "are", "detected", "by", "the", "presence", "of", "git", "-", "svn", "-", "id", "in", "the", "commit", "message", "." ]
train
https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-git/src/main/java/com/indeed/proctor/store/GitProctorUtils.java#L26-L37
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/component/UIViewRoot.java
UIViewRoot.createUniqueId
public String createUniqueId(FacesContext context, String seed) { """ <p>Generate an identifier for a component. The identifier will be prefixed with UNIQUE_ID_PREFIX, and will be unique within this UIViewRoot. Optionally, a unique seed value can be supplied by component creators which should be included in the generated unique id.</p> @param context FacesContext @param seed an optional seed value - e.g. based on the position of the component in the VDL-template @return a unique-id in this component-container """ if (seed != null) { return UIViewRoot.UNIQUE_ID_PREFIX + seed; } else { Integer i = (Integer) getStateHelper().get(PropertyKeys.lastId); int lastId = ((i != null) ? i : 0); getStateHelper().put(PropertyKeys.lastId, ++lastId); return UIViewRoot.UNIQUE_ID_PREFIX + lastId; } }
java
public String createUniqueId(FacesContext context, String seed) { if (seed != null) { return UIViewRoot.UNIQUE_ID_PREFIX + seed; } else { Integer i = (Integer) getStateHelper().get(PropertyKeys.lastId); int lastId = ((i != null) ? i : 0); getStateHelper().put(PropertyKeys.lastId, ++lastId); return UIViewRoot.UNIQUE_ID_PREFIX + lastId; } }
[ "public", "String", "createUniqueId", "(", "FacesContext", "context", ",", "String", "seed", ")", "{", "if", "(", "seed", "!=", "null", ")", "{", "return", "UIViewRoot", ".", "UNIQUE_ID_PREFIX", "+", "seed", ";", "}", "else", "{", "Integer", "i", "=", "(", "Integer", ")", "getStateHelper", "(", ")", ".", "get", "(", "PropertyKeys", ".", "lastId", ")", ";", "int", "lastId", "=", "(", "(", "i", "!=", "null", ")", "?", "i", ":", "0", ")", ";", "getStateHelper", "(", ")", ".", "put", "(", "PropertyKeys", ".", "lastId", ",", "++", "lastId", ")", ";", "return", "UIViewRoot", ".", "UNIQUE_ID_PREFIX", "+", "lastId", ";", "}", "}" ]
<p>Generate an identifier for a component. The identifier will be prefixed with UNIQUE_ID_PREFIX, and will be unique within this UIViewRoot. Optionally, a unique seed value can be supplied by component creators which should be included in the generated unique id.</p> @param context FacesContext @param seed an optional seed value - e.g. based on the position of the component in the VDL-template @return a unique-id in this component-container
[ "<p", ">", "Generate", "an", "identifier", "for", "a", "component", ".", "The", "identifier", "will", "be", "prefixed", "with", "UNIQUE_ID_PREFIX", "and", "will", "be", "unique", "within", "this", "UIViewRoot", ".", "Optionally", "a", "unique", "seed", "value", "can", "be", "supplied", "by", "component", "creators", "which", "should", "be", "included", "in", "the", "generated", "unique", "id", ".", "<", "/", "p", ">" ]
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/UIViewRoot.java#L1327-L1336
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/StochasticMultinomialLogisticRegression.java
StochasticMultinomialLogisticRegression.setAlpha
public void setAlpha(double alpha) { """ Sets the extra parameter alpha. This is used for some priors that take an extra parameter. This is {@link Prior#CAUCHY} and {@link Prior#ELASTIC}. If these two priors are not in use, the value is ignored. @param alpha the extra parameter value to use. Must be positive """ if(alpha < 0 || Double.isNaN(alpha) || Double.isInfinite(alpha)) throw new IllegalArgumentException("Extra parameter must be non negative, not " + alpha); this.alpha = alpha; }
java
public void setAlpha(double alpha) { if(alpha < 0 || Double.isNaN(alpha) || Double.isInfinite(alpha)) throw new IllegalArgumentException("Extra parameter must be non negative, not " + alpha); this.alpha = alpha; }
[ "public", "void", "setAlpha", "(", "double", "alpha", ")", "{", "if", "(", "alpha", "<", "0", "||", "Double", ".", "isNaN", "(", "alpha", ")", "||", "Double", ".", "isInfinite", "(", "alpha", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Extra parameter must be non negative, not \"", "+", "alpha", ")", ";", "this", ".", "alpha", "=", "alpha", ";", "}" ]
Sets the extra parameter alpha. This is used for some priors that take an extra parameter. This is {@link Prior#CAUCHY} and {@link Prior#ELASTIC}. If these two priors are not in use, the value is ignored. @param alpha the extra parameter value to use. Must be positive
[ "Sets", "the", "extra", "parameter", "alpha", ".", "This", "is", "used", "for", "some", "priors", "that", "take", "an", "extra", "parameter", ".", "This", "is", "{", "@link", "Prior#CAUCHY", "}", "and", "{", "@link", "Prior#ELASTIC", "}", ".", "If", "these", "two", "priors", "are", "not", "in", "use", "the", "value", "is", "ignored", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/StochasticMultinomialLogisticRegression.java#L315-L320
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/media/MediaClient.java
MediaClient.listThumbnailJobs
public ListThumbnailJobsResponse listThumbnailJobs(ListThumbnailJobsRequest request) { """ List thumbnail jobs for a given pipeline. @param request The request object containing all options for creating new water mark. @return List of thumbnail jobs. """ checkStringNotEmpty(request.getPipeline(), "The parameter pipelineName should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, THUMBNAIL); internalRequest.addParameter("pipelineName", request.getPipeline()); return invokeHttpClient(internalRequest, ListThumbnailJobsResponse.class); }
java
public ListThumbnailJobsResponse listThumbnailJobs(ListThumbnailJobsRequest request) { checkStringNotEmpty(request.getPipeline(), "The parameter pipelineName should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, THUMBNAIL); internalRequest.addParameter("pipelineName", request.getPipeline()); return invokeHttpClient(internalRequest, ListThumbnailJobsResponse.class); }
[ "public", "ListThumbnailJobsResponse", "listThumbnailJobs", "(", "ListThumbnailJobsRequest", "request", ")", "{", "checkStringNotEmpty", "(", "request", ".", "getPipeline", "(", ")", ",", "\"The parameter pipelineName should NOT be null or empty string.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "GET", ",", "request", ",", "THUMBNAIL", ")", ";", "internalRequest", ".", "addParameter", "(", "\"pipelineName\"", ",", "request", ".", "getPipeline", "(", ")", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "ListThumbnailJobsResponse", ".", "class", ")", ";", "}" ]
List thumbnail jobs for a given pipeline. @param request The request object containing all options for creating new water mark. @return List of thumbnail jobs.
[ "List", "thumbnail", "jobs", "for", "a", "given", "pipeline", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L1315-L1320
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/ChronoLocalDateTimeImpl.java
ChronoLocalDateTimeImpl.ensureValid
static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) { """ Casts the {@code Temporal} to {@code ChronoLocalDateTime} ensuring it bas the specified chronology. @param chrono the chronology to check for, not null @param temporal a date-time to cast, not null @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl or the chronology is not equal this Chronology """ @SuppressWarnings("unchecked") ChronoLocalDateTimeImpl<R> other = (ChronoLocalDateTimeImpl<R>) temporal; if (chrono.equals(other.getChronology()) == false) { throw new ClassCastException("Chronology mismatch, required: " + chrono.getId() + ", actual: " + other.getChronology().getId()); } return other; }
java
static <R extends ChronoLocalDate> ChronoLocalDateTimeImpl<R> ensureValid(Chronology chrono, Temporal temporal) { @SuppressWarnings("unchecked") ChronoLocalDateTimeImpl<R> other = (ChronoLocalDateTimeImpl<R>) temporal; if (chrono.equals(other.getChronology()) == false) { throw new ClassCastException("Chronology mismatch, required: " + chrono.getId() + ", actual: " + other.getChronology().getId()); } return other; }
[ "static", "<", "R", "extends", "ChronoLocalDate", ">", "ChronoLocalDateTimeImpl", "<", "R", ">", "ensureValid", "(", "Chronology", "chrono", ",", "Temporal", "temporal", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ChronoLocalDateTimeImpl", "<", "R", ">", "other", "=", "(", "ChronoLocalDateTimeImpl", "<", "R", ">", ")", "temporal", ";", "if", "(", "chrono", ".", "equals", "(", "other", ".", "getChronology", "(", ")", ")", "==", "false", ")", "{", "throw", "new", "ClassCastException", "(", "\"Chronology mismatch, required: \"", "+", "chrono", ".", "getId", "(", ")", "+", "\", actual: \"", "+", "other", ".", "getChronology", "(", ")", ".", "getId", "(", ")", ")", ";", "}", "return", "other", ";", "}" ]
Casts the {@code Temporal} to {@code ChronoLocalDateTime} ensuring it bas the specified chronology. @param chrono the chronology to check for, not null @param temporal a date-time to cast, not null @return the date-time checked and cast to {@code ChronoLocalDateTime}, not null @throws ClassCastException if the date-time cannot be cast to ChronoLocalDateTimeImpl or the chronology is not equal this Chronology
[ "Casts", "the", "{", "@code", "Temporal", "}", "to", "{", "@code", "ChronoLocalDateTime", "}", "ensuring", "it", "bas", "the", "specified", "chronology", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/ChronoLocalDateTimeImpl.java#L186-L194
Ordinastie/MalisisCore
src/main/java/net/malisis/core/inventory/message/UpdateInventorySlotsMessage.java
UpdateInventorySlotsMessage.process
@Override public void process(Packet message, MessageContext ctx) { """ Handles the received {@link Packet} on the client.<br> Updates the slots in the client {@link MalisisInventory} @param message the message @param ctx the ctx """ EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer(); Container c = player.openContainer; if (message.windowId != c.windowId || !(c instanceof MalisisInventoryContainer)) return; MalisisInventoryContainer container = (MalisisInventoryContainer) c; if (message.inventoryId == PICKEDITEM) { container.setPickedItemStack(message.slots.get(-1)); return; } MalisisInventory inventory = container.getInventory(message.inventoryId); if (inventory == null) return; for (Entry<Integer, ItemStack> entry : message.slots.entrySet()) { Integer slotNumber = entry.getKey(); ItemStack itemStack = entry.getValue(); inventory.setItemStack(slotNumber, itemStack); } }
java
@Override public void process(Packet message, MessageContext ctx) { EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer(); Container c = player.openContainer; if (message.windowId != c.windowId || !(c instanceof MalisisInventoryContainer)) return; MalisisInventoryContainer container = (MalisisInventoryContainer) c; if (message.inventoryId == PICKEDITEM) { container.setPickedItemStack(message.slots.get(-1)); return; } MalisisInventory inventory = container.getInventory(message.inventoryId); if (inventory == null) return; for (Entry<Integer, ItemStack> entry : message.slots.entrySet()) { Integer slotNumber = entry.getKey(); ItemStack itemStack = entry.getValue(); inventory.setItemStack(slotNumber, itemStack); } }
[ "@", "Override", "public", "void", "process", "(", "Packet", "message", ",", "MessageContext", "ctx", ")", "{", "EntityPlayerSP", "player", "=", "(", "EntityPlayerSP", ")", "Utils", ".", "getClientPlayer", "(", ")", ";", "Container", "c", "=", "player", ".", "openContainer", ";", "if", "(", "message", ".", "windowId", "!=", "c", ".", "windowId", "||", "!", "(", "c", "instanceof", "MalisisInventoryContainer", ")", ")", "return", ";", "MalisisInventoryContainer", "container", "=", "(", "MalisisInventoryContainer", ")", "c", ";", "if", "(", "message", ".", "inventoryId", "==", "PICKEDITEM", ")", "{", "container", ".", "setPickedItemStack", "(", "message", ".", "slots", ".", "get", "(", "-", "1", ")", ")", ";", "return", ";", "}", "MalisisInventory", "inventory", "=", "container", ".", "getInventory", "(", "message", ".", "inventoryId", ")", ";", "if", "(", "inventory", "==", "null", ")", "return", ";", "for", "(", "Entry", "<", "Integer", ",", "ItemStack", ">", "entry", ":", "message", ".", "slots", ".", "entrySet", "(", ")", ")", "{", "Integer", "slotNumber", "=", "entry", ".", "getKey", "(", ")", ";", "ItemStack", "itemStack", "=", "entry", ".", "getValue", "(", ")", ";", "inventory", ".", "setItemStack", "(", "slotNumber", ",", "itemStack", ")", ";", "}", "}" ]
Handles the received {@link Packet} on the client.<br> Updates the slots in the client {@link MalisisInventory} @param message the message @param ctx the ctx
[ "Handles", "the", "received", "{", "@link", "Packet", "}", "on", "the", "client", ".", "<br", ">", "Updates", "the", "slots", "in", "the", "client", "{", "@link", "MalisisInventory", "}" ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/inventory/message/UpdateInventorySlotsMessage.java#L71-L97
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getSummonerSpell
public Future<SummonerSpell> getSummonerSpell(int id, SpellData data, String version, String locale) { """ <p> Retrieve a specific summoner spell </p> This method does not count towards the rate limit and is not affected by the throttle @param id The id of the spell @param data Additional information to retrieve @param version Data dragon version for returned data @param locale Locale code for returned data @return The spell @see <a href=https://developer.riotgames.com/api/methods#!/649/2167>Official API documentation</a> """ return new DummyFuture<>(handler.getSummonerSpell(id, data, version, locale)); }
java
public Future<SummonerSpell> getSummonerSpell(int id, SpellData data, String version, String locale) { return new DummyFuture<>(handler.getSummonerSpell(id, data, version, locale)); }
[ "public", "Future", "<", "SummonerSpell", ">", "getSummonerSpell", "(", "int", "id", ",", "SpellData", "data", ",", "String", "version", ",", "String", "locale", ")", "{", "return", "new", "DummyFuture", "<>", "(", "handler", ".", "getSummonerSpell", "(", "id", ",", "data", ",", "version", ",", "locale", ")", ")", ";", "}" ]
<p> Retrieve a specific summoner spell </p> This method does not count towards the rate limit and is not affected by the throttle @param id The id of the spell @param data Additional information to retrieve @param version Data dragon version for returned data @param locale Locale code for returned data @return The spell @see <a href=https://developer.riotgames.com/api/methods#!/649/2167>Official API documentation</a>
[ "<p", ">", "Retrieve", "a", "specific", "summoner", "spell", "<", "/", "p", ">", "This", "method", "does", "not", "count", "towards", "the", "rate", "limit", "and", "is", "not", "affected", "by", "the", "throttle" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L825-L827
jbundle/jbundle
thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java
BaseApplet.popHistory
public String popHistory(int quanityToPop, boolean bPopFromBrowser) { """ Pop this command off the history stack. @param quanityToPop The number of commands to pop off the stack @param bPopFromBrowser Pop them off the browser stack also? NOTE: The params are different from the next call. """ String strHistory = null; for (int i = 0; i < quanityToPop; i++) { strHistory = null; if (m_vHistory != null) if (m_vHistory.size() > 0) strHistory = (String)m_vHistory.remove(m_vHistory.size() - 1); } if (bPopFromBrowser) this.popBrowserHistory(quanityToPop, strHistory != null, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen return strHistory; }
java
public String popHistory(int quanityToPop, boolean bPopFromBrowser) { String strHistory = null; for (int i = 0; i < quanityToPop; i++) { strHistory = null; if (m_vHistory != null) if (m_vHistory.size() > 0) strHistory = (String)m_vHistory.remove(m_vHistory.size() - 1); } if (bPopFromBrowser) this.popBrowserHistory(quanityToPop, strHistory != null, this.getStatusText(Constants.INFORMATION)); // Let browser know about the new screen return strHistory; }
[ "public", "String", "popHistory", "(", "int", "quanityToPop", ",", "boolean", "bPopFromBrowser", ")", "{", "String", "strHistory", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "quanityToPop", ";", "i", "++", ")", "{", "strHistory", "=", "null", ";", "if", "(", "m_vHistory", "!=", "null", ")", "if", "(", "m_vHistory", ".", "size", "(", ")", ">", "0", ")", "strHistory", "=", "(", "String", ")", "m_vHistory", ".", "remove", "(", "m_vHistory", ".", "size", "(", ")", "-", "1", ")", ";", "}", "if", "(", "bPopFromBrowser", ")", "this", ".", "popBrowserHistory", "(", "quanityToPop", ",", "strHistory", "!=", "null", ",", "this", ".", "getStatusText", "(", "Constants", ".", "INFORMATION", ")", ")", ";", "// Let browser know about the new screen", "return", "strHistory", ";", "}" ]
Pop this command off the history stack. @param quanityToPop The number of commands to pop off the stack @param bPopFromBrowser Pop them off the browser stack also? NOTE: The params are different from the next call.
[ "Pop", "this", "command", "off", "the", "history", "stack", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L1261-L1273
apptik/jus
examples-android/src/main/java/io/apptik/comm/jus/examples/nav/JToggle.java
JToggle.onDrawerSlide
@Override public void onDrawerSlide(View drawerView, float slideOffset) { """ {@link DrawerLayout.DrawerListener} callback method. If you do not use your JToggle instance directly as your DrawerLayout's listener, you should call through to this method from your own listener object. @param drawerView The child view that was moved @param slideOffset The new offset of this drawer within its range, from 0-1 """ mSlider.setPosition(Math.min(1f, Math.max(0, slideOffset))); }
java
@Override public void onDrawerSlide(View drawerView, float slideOffset) { mSlider.setPosition(Math.min(1f, Math.max(0, slideOffset))); }
[ "@", "Override", "public", "void", "onDrawerSlide", "(", "View", "drawerView", ",", "float", "slideOffset", ")", "{", "mSlider", ".", "setPosition", "(", "Math", ".", "min", "(", "1f", ",", "Math", ".", "max", "(", "0", ",", "slideOffset", ")", ")", ")", ";", "}" ]
{@link DrawerLayout.DrawerListener} callback method. If you do not use your JToggle instance directly as your DrawerLayout's listener, you should call through to this method from your own listener object. @param drawerView The child view that was moved @param slideOffset The new offset of this drawer within its range, from 0-1
[ "{", "@link", "DrawerLayout", ".", "DrawerListener", "}", "callback", "method", ".", "If", "you", "do", "not", "use", "your", "JToggle", "instance", "directly", "as", "your", "DrawerLayout", "s", "listener", "you", "should", "call", "through", "to", "this", "method", "from", "your", "own", "listener", "object", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/examples-android/src/main/java/io/apptik/comm/jus/examples/nav/JToggle.java#L377-L380
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/MultiLongWatermark.java
MultiLongWatermark.calculatePercentCompletion
@Override public short calculatePercentCompletion(Watermark lowWatermark, Watermark highWatermark) { """ Given a low watermark (starting point) and a high watermark (target), returns the percentage of events pulled. @return a percentage value between 0 and 100. """ Preconditions.checkArgument( lowWatermark instanceof MultiLongWatermark && highWatermark instanceof MultiLongWatermark, String.format("Arguments of %s.%s must be of type %s", MultiLongWatermark.class.getSimpleName(), Thread.currentThread().getStackTrace()[1].getMethodName(), MultiLongWatermark.class.getSimpleName())); long pulled = ((MultiLongWatermark) lowWatermark).getGap(this); long all = ((MultiLongWatermark) lowWatermark).getGap((MultiLongWatermark) highWatermark); Preconditions.checkState(all > 0); long percent = Math.min(100, LongMath.divide(pulled * 100, all, RoundingMode.HALF_UP)); return (short) percent; }
java
@Override public short calculatePercentCompletion(Watermark lowWatermark, Watermark highWatermark) { Preconditions.checkArgument( lowWatermark instanceof MultiLongWatermark && highWatermark instanceof MultiLongWatermark, String.format("Arguments of %s.%s must be of type %s", MultiLongWatermark.class.getSimpleName(), Thread.currentThread().getStackTrace()[1].getMethodName(), MultiLongWatermark.class.getSimpleName())); long pulled = ((MultiLongWatermark) lowWatermark).getGap(this); long all = ((MultiLongWatermark) lowWatermark).getGap((MultiLongWatermark) highWatermark); Preconditions.checkState(all > 0); long percent = Math.min(100, LongMath.divide(pulled * 100, all, RoundingMode.HALF_UP)); return (short) percent; }
[ "@", "Override", "public", "short", "calculatePercentCompletion", "(", "Watermark", "lowWatermark", ",", "Watermark", "highWatermark", ")", "{", "Preconditions", ".", "checkArgument", "(", "lowWatermark", "instanceof", "MultiLongWatermark", "&&", "highWatermark", "instanceof", "MultiLongWatermark", ",", "String", ".", "format", "(", "\"Arguments of %s.%s must be of type %s\"", ",", "MultiLongWatermark", ".", "class", ".", "getSimpleName", "(", ")", ",", "Thread", ".", "currentThread", "(", ")", ".", "getStackTrace", "(", ")", "[", "1", "]", ".", "getMethodName", "(", ")", ",", "MultiLongWatermark", ".", "class", ".", "getSimpleName", "(", ")", ")", ")", ";", "long", "pulled", "=", "(", "(", "MultiLongWatermark", ")", "lowWatermark", ")", ".", "getGap", "(", "this", ")", ";", "long", "all", "=", "(", "(", "MultiLongWatermark", ")", "lowWatermark", ")", ".", "getGap", "(", "(", "MultiLongWatermark", ")", "highWatermark", ")", ";", "Preconditions", ".", "checkState", "(", "all", ">", "0", ")", ";", "long", "percent", "=", "Math", ".", "min", "(", "100", ",", "LongMath", ".", "divide", "(", "pulled", "*", "100", ",", "all", ",", "RoundingMode", ".", "HALF_UP", ")", ")", ";", "return", "(", "short", ")", "percent", ";", "}" ]
Given a low watermark (starting point) and a high watermark (target), returns the percentage of events pulled. @return a percentage value between 0 and 100.
[ "Given", "a", "low", "watermark", "(", "starting", "point", ")", "and", "a", "high", "watermark", "(", "target", ")", "returns", "the", "percentage", "of", "events", "pulled", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/MultiLongWatermark.java#L77-L89
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java
SourceToHTMLConverter.convertRoot
public static void convertRoot(ConfigurationImpl configuration, RootDoc rd, DocPath outputdir) { """ Convert the Classes in the given RootDoc to an HTML. @param configuration the configuration. @param rd the RootDoc to convert. @param outputdir the name of the directory to output to. """ new SourceToHTMLConverter(configuration, rd, outputdir).generate(); }
java
public static void convertRoot(ConfigurationImpl configuration, RootDoc rd, DocPath outputdir) { new SourceToHTMLConverter(configuration, rd, outputdir).generate(); }
[ "public", "static", "void", "convertRoot", "(", "ConfigurationImpl", "configuration", ",", "RootDoc", "rd", ",", "DocPath", "outputdir", ")", "{", "new", "SourceToHTMLConverter", "(", "configuration", ",", "rd", ",", "outputdir", ")", ".", "generate", "(", ")", ";", "}" ]
Convert the Classes in the given RootDoc to an HTML. @param configuration the configuration. @param rd the RootDoc to convert. @param outputdir the name of the directory to output to.
[ "Convert", "the", "Classes", "in", "the", "given", "RootDoc", "to", "an", "HTML", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java#L93-L96
mabe02/lanterna
src/main/java/com/googlecode/lanterna/terminal/swing/AWTTerminalFontConfiguration.java
AWTTerminalFontConfiguration.getFontSize
private static int getFontSize() { """ Here we check the screen resolution on the primary monitor and make a guess at if it's high-DPI or not """ if (Toolkit.getDefaultToolkit().getScreenResolution() >= 110) { // Rely on DPI if it is a high value. return Toolkit.getDefaultToolkit().getScreenResolution() / 7 + 1; } else { // Otherwise try to guess it from the monitor size: // If the width is wider than Full HD (1080p, or 1920x1080), then assume it's high-DPI. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if (ge.getMaximumWindowBounds().getWidth() > 4096) { return 56; } else if (ge.getMaximumWindowBounds().getWidth() > 2048) { return 28; } else { return 14; } } }
java
private static int getFontSize() { if (Toolkit.getDefaultToolkit().getScreenResolution() >= 110) { // Rely on DPI if it is a high value. return Toolkit.getDefaultToolkit().getScreenResolution() / 7 + 1; } else { // Otherwise try to guess it from the monitor size: // If the width is wider than Full HD (1080p, or 1920x1080), then assume it's high-DPI. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if (ge.getMaximumWindowBounds().getWidth() > 4096) { return 56; } else if (ge.getMaximumWindowBounds().getWidth() > 2048) { return 28; } else { return 14; } } }
[ "private", "static", "int", "getFontSize", "(", ")", "{", "if", "(", "Toolkit", ".", "getDefaultToolkit", "(", ")", ".", "getScreenResolution", "(", ")", ">=", "110", ")", "{", "// Rely on DPI if it is a high value.", "return", "Toolkit", ".", "getDefaultToolkit", "(", ")", ".", "getScreenResolution", "(", ")", "/", "7", "+", "1", ";", "}", "else", "{", "// Otherwise try to guess it from the monitor size:", "// If the width is wider than Full HD (1080p, or 1920x1080), then assume it's high-DPI.", "GraphicsEnvironment", "ge", "=", "GraphicsEnvironment", ".", "getLocalGraphicsEnvironment", "(", ")", ";", "if", "(", "ge", ".", "getMaximumWindowBounds", "(", ")", ".", "getWidth", "(", ")", ">", "4096", ")", "{", "return", "56", ";", "}", "else", "if", "(", "ge", ".", "getMaximumWindowBounds", "(", ")", ".", "getWidth", "(", ")", ">", "2048", ")", "{", "return", "28", ";", "}", "else", "{", "return", "14", ";", "}", "}", "}" ]
Here we check the screen resolution on the primary monitor and make a guess at if it's high-DPI or not
[ "Here", "we", "check", "the", "screen", "resolution", "on", "the", "primary", "monitor", "and", "make", "a", "guess", "at", "if", "it", "s", "high", "-", "DPI", "or", "not" ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/terminal/swing/AWTTerminalFontConfiguration.java#L111-L127
Chorus-bdd/Chorus
interpreter/chorus-interpreter/src/main/java/org/chorusbdd/chorus/interpreter/startup/InterpreterBuilder.java
InterpreterBuilder.buildAndConfigure
public ChorusInterpreter buildAndConfigure(ConfigProperties config, SubsystemManager subsystemManager) { """ Run the interpreter, collating results into the executionToken """ ChorusInterpreter chorusInterpreter = new ChorusInterpreter(listenerSupport); chorusInterpreter.setHandlerClassBasePackages(config.getValues(ChorusConfigProperty.HANDLER_PACKAGES)); chorusInterpreter.setScenarioTimeoutMillis(Integer.valueOf(config.getValue(ChorusConfigProperty.SCENARIO_TIMEOUT)) * 1000); chorusInterpreter.setDryRun(config.isTrue(ChorusConfigProperty.DRY_RUN)); chorusInterpreter.setSubsystemManager(subsystemManager); StepCatalogue stepCatalogue = createStepCatalogue(config); chorusInterpreter.setStepCatalogue(stepCatalogue); return chorusInterpreter; }
java
public ChorusInterpreter buildAndConfigure(ConfigProperties config, SubsystemManager subsystemManager) { ChorusInterpreter chorusInterpreter = new ChorusInterpreter(listenerSupport); chorusInterpreter.setHandlerClassBasePackages(config.getValues(ChorusConfigProperty.HANDLER_PACKAGES)); chorusInterpreter.setScenarioTimeoutMillis(Integer.valueOf(config.getValue(ChorusConfigProperty.SCENARIO_TIMEOUT)) * 1000); chorusInterpreter.setDryRun(config.isTrue(ChorusConfigProperty.DRY_RUN)); chorusInterpreter.setSubsystemManager(subsystemManager); StepCatalogue stepCatalogue = createStepCatalogue(config); chorusInterpreter.setStepCatalogue(stepCatalogue); return chorusInterpreter; }
[ "public", "ChorusInterpreter", "buildAndConfigure", "(", "ConfigProperties", "config", ",", "SubsystemManager", "subsystemManager", ")", "{", "ChorusInterpreter", "chorusInterpreter", "=", "new", "ChorusInterpreter", "(", "listenerSupport", ")", ";", "chorusInterpreter", ".", "setHandlerClassBasePackages", "(", "config", ".", "getValues", "(", "ChorusConfigProperty", ".", "HANDLER_PACKAGES", ")", ")", ";", "chorusInterpreter", ".", "setScenarioTimeoutMillis", "(", "Integer", ".", "valueOf", "(", "config", ".", "getValue", "(", "ChorusConfigProperty", ".", "SCENARIO_TIMEOUT", ")", ")", "*", "1000", ")", ";", "chorusInterpreter", ".", "setDryRun", "(", "config", ".", "isTrue", "(", "ChorusConfigProperty", ".", "DRY_RUN", ")", ")", ";", "chorusInterpreter", ".", "setSubsystemManager", "(", "subsystemManager", ")", ";", "StepCatalogue", "stepCatalogue", "=", "createStepCatalogue", "(", "config", ")", ";", "chorusInterpreter", ".", "setStepCatalogue", "(", "stepCatalogue", ")", ";", "return", "chorusInterpreter", ";", "}" ]
Run the interpreter, collating results into the executionToken
[ "Run", "the", "interpreter", "collating", "results", "into", "the", "executionToken" ]
train
https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/interpreter/chorus-interpreter/src/main/java/org/chorusbdd/chorus/interpreter/startup/InterpreterBuilder.java#L56-L66
GII/broccoli
broccoli-owls/src/main/java/com/hi3project/broccoli/bsdf/impl/owls/serviceBuilder/OWLSServiceBuilder.java
OWLSServiceBuilder.buildOWLSServiceFrom
public OWLSAtomicService buildOWLSServiceFrom(URI serviceURI, List<URI> modelURIs) throws ModelException { """ Builds an OWLSAtomicService @param serviceURI the URI that identifies the service @param modelURIs a List of URIs for ontologies that may be used by the service to be loaded @return @throws ModelException """ if (isFile(serviceURI)) { return buildOWLSServiceFromLocalOrRemoteURI(serviceURI, modelURIs); } else { Service service = OWLSStore.persistentModelAsOWLKB().getService(serviceURI); if (null == service) { throw new OWLTranslationException("Not found as a local file, nor a valid Service found in data store", null); } return buildOWLSServiceFrom(service); } }
java
public OWLSAtomicService buildOWLSServiceFrom(URI serviceURI, List<URI> modelURIs) throws ModelException { if (isFile(serviceURI)) { return buildOWLSServiceFromLocalOrRemoteURI(serviceURI, modelURIs); } else { Service service = OWLSStore.persistentModelAsOWLKB().getService(serviceURI); if (null == service) { throw new OWLTranslationException("Not found as a local file, nor a valid Service found in data store", null); } return buildOWLSServiceFrom(service); } }
[ "public", "OWLSAtomicService", "buildOWLSServiceFrom", "(", "URI", "serviceURI", ",", "List", "<", "URI", ">", "modelURIs", ")", "throws", "ModelException", "{", "if", "(", "isFile", "(", "serviceURI", ")", ")", "{", "return", "buildOWLSServiceFromLocalOrRemoteURI", "(", "serviceURI", ",", "modelURIs", ")", ";", "}", "else", "{", "Service", "service", "=", "OWLSStore", ".", "persistentModelAsOWLKB", "(", ")", ".", "getService", "(", "serviceURI", ")", ";", "if", "(", "null", "==", "service", ")", "{", "throw", "new", "OWLTranslationException", "(", "\"Not found as a local file, nor a valid Service found in data store\"", ",", "null", ")", ";", "}", "return", "buildOWLSServiceFrom", "(", "service", ")", ";", "}", "}" ]
Builds an OWLSAtomicService @param serviceURI the URI that identifies the service @param modelURIs a List of URIs for ontologies that may be used by the service to be loaded @return @throws ModelException
[ "Builds", "an", "OWLSAtomicService" ]
train
https://github.com/GII/broccoli/blob/a3033a90322cbcee4dc0f1719143b84b822bc4ba/broccoli-owls/src/main/java/com/hi3project/broccoli/bsdf/impl/owls/serviceBuilder/OWLSServiceBuilder.java#L76-L90
alkacon/opencms-core
src-modules/org/opencms/workplace/explorer/CmsNewResourceXmlPage.java
CmsNewResourceXmlPage.getTemplates
public static TreeMap<String, String> getTemplates(CmsObject cms, String currWpPath) throws CmsException { """ Returns a sorted Map of all available templates of the OpenCms modules.<p> @param cms the current cms object @param currWpPath the current path in the OpenCms workplace @return a sorted map with the template title as key and absolute path to the template as value @throws CmsException if reading a folder or file fails """ return getElements(cms, CmsWorkplace.VFS_DIR_TEMPLATES, currWpPath, true); }
java
public static TreeMap<String, String> getTemplates(CmsObject cms, String currWpPath) throws CmsException { return getElements(cms, CmsWorkplace.VFS_DIR_TEMPLATES, currWpPath, true); }
[ "public", "static", "TreeMap", "<", "String", ",", "String", ">", "getTemplates", "(", "CmsObject", "cms", ",", "String", "currWpPath", ")", "throws", "CmsException", "{", "return", "getElements", "(", "cms", ",", "CmsWorkplace", ".", "VFS_DIR_TEMPLATES", ",", "currWpPath", ",", "true", ")", ";", "}" ]
Returns a sorted Map of all available templates of the OpenCms modules.<p> @param cms the current cms object @param currWpPath the current path in the OpenCms workplace @return a sorted map with the template title as key and absolute path to the template as value @throws CmsException if reading a folder or file fails
[ "Returns", "a", "sorted", "Map", "of", "all", "available", "templates", "of", "the", "OpenCms", "modules", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/explorer/CmsNewResourceXmlPage.java#L113-L116
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.generateNewVarName
public String generateNewVarName(String baseName, int argIndex) { """ Generate a new variable name based on the uniqueness of the base name and arg index<br> For example, if baseName = "X" will return:<br> "X" if "X" does not already exist, or "X:argIndex" if argIndex > 0<br> "X_1" if "X" already exists, or "X_1:argIndex" if argIndex > 0<br> "X_2" if "X" and "X_1" already exists, or "X_2:argIndex" if argIndex > 0<br> And so on, until an unused name is found @param baseName the base name to use (use function.opName() where function is a {@link DifferentialFunction} @param argIndex the arg index @return the new generated name """ if (!variables.containsKey(baseName) && argIndex == 0) { return baseName; } //need to find a new name int count = 0; String name = baseName + (count == 0 ? "" : "_" + count) + (argIndex > 0 ? ":" + argIndex : ""); while (getVariable(name) != null) { name = baseName + "_" + (++count) + (argIndex > 0 ? ":" + argIndex : ""); } if (getVariable(name) != null) { throw new ND4JIllegalStateException("Converged on already generated variable!"); } return name; }
java
public String generateNewVarName(String baseName, int argIndex) { if (!variables.containsKey(baseName) && argIndex == 0) { return baseName; } //need to find a new name int count = 0; String name = baseName + (count == 0 ? "" : "_" + count) + (argIndex > 0 ? ":" + argIndex : ""); while (getVariable(name) != null) { name = baseName + "_" + (++count) + (argIndex > 0 ? ":" + argIndex : ""); } if (getVariable(name) != null) { throw new ND4JIllegalStateException("Converged on already generated variable!"); } return name; }
[ "public", "String", "generateNewVarName", "(", "String", "baseName", ",", "int", "argIndex", ")", "{", "if", "(", "!", "variables", ".", "containsKey", "(", "baseName", ")", "&&", "argIndex", "==", "0", ")", "{", "return", "baseName", ";", "}", "//need to find a new name", "int", "count", "=", "0", ";", "String", "name", "=", "baseName", "+", "(", "count", "==", "0", "?", "\"\"", ":", "\"_\"", "+", "count", ")", "+", "(", "argIndex", ">", "0", "?", "\":\"", "+", "argIndex", ":", "\"\"", ")", ";", "while", "(", "getVariable", "(", "name", ")", "!=", "null", ")", "{", "name", "=", "baseName", "+", "\"_\"", "+", "(", "++", "count", ")", "+", "(", "argIndex", ">", "0", "?", "\":\"", "+", "argIndex", ":", "\"\"", ")", ";", "}", "if", "(", "getVariable", "(", "name", ")", "!=", "null", ")", "{", "throw", "new", "ND4JIllegalStateException", "(", "\"Converged on already generated variable!\"", ")", ";", "}", "return", "name", ";", "}" ]
Generate a new variable name based on the uniqueness of the base name and arg index<br> For example, if baseName = "X" will return:<br> "X" if "X" does not already exist, or "X:argIndex" if argIndex > 0<br> "X_1" if "X" already exists, or "X_1:argIndex" if argIndex > 0<br> "X_2" if "X" and "X_1" already exists, or "X_2:argIndex" if argIndex > 0<br> And so on, until an unused name is found @param baseName the base name to use (use function.opName() where function is a {@link DifferentialFunction} @param argIndex the arg index @return the new generated name
[ "Generate", "a", "new", "variable", "name", "based", "on", "the", "uniqueness", "of", "the", "base", "name", "and", "arg", "index<br", ">", "For", "example", "if", "baseName", "=", "X", "will", "return", ":", "<br", ">", "X", "if", "X", "does", "not", "already", "exist", "or", "X", ":", "argIndex", "if", "argIndex", ">", "0<br", ">", "X_1", "if", "X", "already", "exists", "or", "X_1", ":", "argIndex", "if", "argIndex", ">", "0<br", ">", "X_2", "if", "X", "and", "X_1", "already", "exists", "or", "X_2", ":", "argIndex", "if", "argIndex", ">", "0<br", ">", "And", "so", "on", "until", "an", "unused", "name", "is", "found" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L2863-L2879
52inc/android-52Kit
library/src/main/java/com/ftinc/kit/util/Utils.java
Utils.parseDouble
public static double parseDouble(String val, double defValue) { """ Parse a double from a String in a safe manner @param val the string to parse @param defValue the default value to return in parsing fails @return the parsed double, or default value """ if(TextUtils.isEmpty(val)) return defValue; try{ return Double.parseDouble(val); }catch(NumberFormatException e){ return defValue; } }
java
public static double parseDouble(String val, double defValue){ if(TextUtils.isEmpty(val)) return defValue; try{ return Double.parseDouble(val); }catch(NumberFormatException e){ return defValue; } }
[ "public", "static", "double", "parseDouble", "(", "String", "val", ",", "double", "defValue", ")", "{", "if", "(", "TextUtils", ".", "isEmpty", "(", "val", ")", ")", "return", "defValue", ";", "try", "{", "return", "Double", ".", "parseDouble", "(", "val", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "return", "defValue", ";", "}", "}" ]
Parse a double from a String in a safe manner @param val the string to parse @param defValue the default value to return in parsing fails @return the parsed double, or default value
[ "Parse", "a", "double", "from", "a", "String", "in", "a", "safe", "manner" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/Utils.java#L294-L301
diffplug/durian
src/com/diffplug/common/base/FieldsAndGetters.java
FieldsAndGetters.dumpAll
public static void dumpAll(String name, Object obj, StringPrinter printer) { """ Dumps all fields and getters of {@code obj} to {@code printer}. @see #dumpIf """ dumpIf(name, obj, Predicates.alwaysTrue(), Predicates.alwaysTrue(), printer); }
java
public static void dumpAll(String name, Object obj, StringPrinter printer) { dumpIf(name, obj, Predicates.alwaysTrue(), Predicates.alwaysTrue(), printer); }
[ "public", "static", "void", "dumpAll", "(", "String", "name", ",", "Object", "obj", ",", "StringPrinter", "printer", ")", "{", "dumpIf", "(", "name", ",", "obj", ",", "Predicates", ".", "alwaysTrue", "(", ")", ",", "Predicates", ".", "alwaysTrue", "(", ")", ",", "printer", ")", ";", "}" ]
Dumps all fields and getters of {@code obj} to {@code printer}. @see #dumpIf
[ "Dumps", "all", "fields", "and", "getters", "of", "{" ]
train
https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L185-L187
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java
DefaultSystemUnderDevelopment.getFixture
public Fixture getFixture( String name, String... params ) throws Throwable { """ Creates a new instance of a fixture class using a set of parameters. @param name the name of the class to instantiate @param params the parameters (constructor arguments) @return a new instance of the fixtureClass with fields populated using Constructor @throws Exception if any. @throws java.lang.Throwable if any. """ Type<?> type = loadType( name ); Object target = type.newInstanceUsingCoercion( params ); return new DefaultFixture( target ); }
java
public Fixture getFixture( String name, String... params ) throws Throwable { Type<?> type = loadType( name ); Object target = type.newInstanceUsingCoercion( params ); return new DefaultFixture( target ); }
[ "public", "Fixture", "getFixture", "(", "String", "name", ",", "String", "...", "params", ")", "throws", "Throwable", "{", "Type", "<", "?", ">", "type", "=", "loadType", "(", "name", ")", ";", "Object", "target", "=", "type", ".", "newInstanceUsingCoercion", "(", "params", ")", ";", "return", "new", "DefaultFixture", "(", "target", ")", ";", "}" ]
Creates a new instance of a fixture class using a set of parameters. @param name the name of the class to instantiate @param params the parameters (constructor arguments) @return a new instance of the fixtureClass with fields populated using Constructor @throws Exception if any. @throws java.lang.Throwable if any.
[ "Creates", "a", "new", "instance", "of", "a", "fixture", "class", "using", "a", "set", "of", "parameters", "." ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java#L77-L82
lessthanoptimal/BoofCV
examples/src/main/java/boofcv/examples/recognition/ExampleColorHistogramLookup.java
ExampleColorHistogramLookup.histogramGray
public static List<double[]> histogramGray( List<File> images ) { """ Computes a histogram from the gray scale intensity image alone. Probably the least effective at looking up similar images. """ List<double[]> points = new ArrayList<>(); GrayU8 gray = new GrayU8(1,1); for( File f : images ) { BufferedImage buffered = UtilImageIO.loadImage(f.getPath()); if( buffered == null ) throw new RuntimeException("Can't load image!"); gray.reshape(buffered.getWidth(), buffered.getHeight()); ConvertBufferedImage.convertFrom(buffered, gray, true); TupleDesc_F64 imageHist = new TupleDesc_F64(150); HistogramFeatureOps.histogram(gray, 255, imageHist); UtilFeature.normalizeL2(imageHist); // normalize so that image size doesn't matter points.add(imageHist.value); } return points; }
java
public static List<double[]> histogramGray( List<File> images ) { List<double[]> points = new ArrayList<>(); GrayU8 gray = new GrayU8(1,1); for( File f : images ) { BufferedImage buffered = UtilImageIO.loadImage(f.getPath()); if( buffered == null ) throw new RuntimeException("Can't load image!"); gray.reshape(buffered.getWidth(), buffered.getHeight()); ConvertBufferedImage.convertFrom(buffered, gray, true); TupleDesc_F64 imageHist = new TupleDesc_F64(150); HistogramFeatureOps.histogram(gray, 255, imageHist); UtilFeature.normalizeL2(imageHist); // normalize so that image size doesn't matter points.add(imageHist.value); } return points; }
[ "public", "static", "List", "<", "double", "[", "]", ">", "histogramGray", "(", "List", "<", "File", ">", "images", ")", "{", "List", "<", "double", "[", "]", ">", "points", "=", "new", "ArrayList", "<>", "(", ")", ";", "GrayU8", "gray", "=", "new", "GrayU8", "(", "1", ",", "1", ")", ";", "for", "(", "File", "f", ":", "images", ")", "{", "BufferedImage", "buffered", "=", "UtilImageIO", ".", "loadImage", "(", "f", ".", "getPath", "(", ")", ")", ";", "if", "(", "buffered", "==", "null", ")", "throw", "new", "RuntimeException", "(", "\"Can't load image!\"", ")", ";", "gray", ".", "reshape", "(", "buffered", ".", "getWidth", "(", ")", ",", "buffered", ".", "getHeight", "(", ")", ")", ";", "ConvertBufferedImage", ".", "convertFrom", "(", "buffered", ",", "gray", ",", "true", ")", ";", "TupleDesc_F64", "imageHist", "=", "new", "TupleDesc_F64", "(", "150", ")", ";", "HistogramFeatureOps", ".", "histogram", "(", "gray", ",", "255", ",", "imageHist", ")", ";", "UtilFeature", ".", "normalizeL2", "(", "imageHist", ")", ";", "// normalize so that image size doesn't matter", "points", ".", "add", "(", "imageHist", ".", "value", ")", ";", "}", "return", "points", ";", "}" ]
Computes a histogram from the gray scale intensity image alone. Probably the least effective at looking up similar images.
[ "Computes", "a", "histogram", "from", "the", "gray", "scale", "intensity", "image", "alone", ".", "Probably", "the", "least", "effective", "at", "looking", "up", "similar", "images", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/recognition/ExampleColorHistogramLookup.java#L180-L200
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/LossLayer.java
LossLayer.computeScore
@Override public double computeScore(double fullNetRegTerm, boolean training, LayerWorkspaceMgr workspaceMgr) { """ Compute score after labels and input have been set. @param fullNetRegTerm Regularization score term for the entire network @param training whether score should be calculated at train or test time (this affects things like application of dropout, etc) @return score (loss function) """ if (input == null || labels == null) throw new IllegalStateException("Cannot calculate score without input and labels " + layerId()); this.fullNetworkRegularizationScore = fullNetRegTerm; INDArray preOut = input; ILossFunction lossFunction = layerConf().getLossFn(); //double score = lossFunction.computeScore(getLabels2d(), preOut, layerConf().getActivationFunction(), maskArray, false); double score = lossFunction.computeScore(getLabels2d(), preOut, layerConf().getActivationFn(), maskArray, false); score /= getInputMiniBatchSize(); score += fullNetworkRegularizationScore; this.score = score; return score; }
java
@Override public double computeScore(double fullNetRegTerm, boolean training, LayerWorkspaceMgr workspaceMgr) { if (input == null || labels == null) throw new IllegalStateException("Cannot calculate score without input and labels " + layerId()); this.fullNetworkRegularizationScore = fullNetRegTerm; INDArray preOut = input; ILossFunction lossFunction = layerConf().getLossFn(); //double score = lossFunction.computeScore(getLabels2d(), preOut, layerConf().getActivationFunction(), maskArray, false); double score = lossFunction.computeScore(getLabels2d(), preOut, layerConf().getActivationFn(), maskArray, false); score /= getInputMiniBatchSize(); score += fullNetworkRegularizationScore; this.score = score; return score; }
[ "@", "Override", "public", "double", "computeScore", "(", "double", "fullNetRegTerm", ",", "boolean", "training", ",", "LayerWorkspaceMgr", "workspaceMgr", ")", "{", "if", "(", "input", "==", "null", "||", "labels", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot calculate score without input and labels \"", "+", "layerId", "(", ")", ")", ";", "this", ".", "fullNetworkRegularizationScore", "=", "fullNetRegTerm", ";", "INDArray", "preOut", "=", "input", ";", "ILossFunction", "lossFunction", "=", "layerConf", "(", ")", ".", "getLossFn", "(", ")", ";", "//double score = lossFunction.computeScore(getLabels2d(), preOut, layerConf().getActivationFunction(), maskArray, false);", "double", "score", "=", "lossFunction", ".", "computeScore", "(", "getLabels2d", "(", ")", ",", "preOut", ",", "layerConf", "(", ")", ".", "getActivationFn", "(", ")", ",", "maskArray", ",", "false", ")", ";", "score", "/=", "getInputMiniBatchSize", "(", ")", ";", "score", "+=", "fullNetworkRegularizationScore", ";", "this", ".", "score", "=", "score", ";", "return", "score", ";", "}" ]
Compute score after labels and input have been set. @param fullNetRegTerm Regularization score term for the entire network @param training whether score should be calculated at train or test time (this affects things like application of dropout, etc) @return score (loss function)
[ "Compute", "score", "after", "labels", "and", "input", "have", "been", "set", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/LossLayer.java#L69-L86
svanoort/rest-compress
rest-compress-lib/src/main/java/com/restcompress/provider/LZFEncodingInterceptor.java
LZFEncodingInterceptor.write
public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException { """ Grab the outgoing message, if encoding is set to LZF, then wrap the OutputStream in an LZF OutputStream before sending it on its merry way, compressing all the time. Note: strips out the content-length header because the compression changes that unpredictably @param context @throws IOException @throws WebApplicationException """ Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if (encoding != null && encoding.toString().equalsIgnoreCase("lzf")) { OutputStream old = context.getOutputStream(); // constructor writes to underlying OS causing headers to be written. CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream(old, null); // Any content length set will be obsolete context.getHeaders().remove("Content-Length"); context.setOutputStream(lzfOutputStream); try { context.proceed(); } finally { if (lzfOutputStream.getLzf() != null) lzfOutputStream.getLzf().flush(); context.setOutputStream(old); } return; } else { context.proceed(); } }
java
public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException { Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING); if (encoding != null && encoding.toString().equalsIgnoreCase("lzf")) { OutputStream old = context.getOutputStream(); // constructor writes to underlying OS causing headers to be written. CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream(old, null); // Any content length set will be obsolete context.getHeaders().remove("Content-Length"); context.setOutputStream(lzfOutputStream); try { context.proceed(); } finally { if (lzfOutputStream.getLzf() != null) lzfOutputStream.getLzf().flush(); context.setOutputStream(old); } return; } else { context.proceed(); } }
[ "public", "void", "write", "(", "MessageBodyWriterContext", "context", ")", "throws", "IOException", ",", "WebApplicationException", "{", "Object", "encoding", "=", "context", ".", "getHeaders", "(", ")", ".", "getFirst", "(", "HttpHeaders", ".", "CONTENT_ENCODING", ")", ";", "if", "(", "encoding", "!=", "null", "&&", "encoding", ".", "toString", "(", ")", ".", "equalsIgnoreCase", "(", "\"lzf\"", ")", ")", "{", "OutputStream", "old", "=", "context", ".", "getOutputStream", "(", ")", ";", "// constructor writes to underlying OS causing headers to be written.", "CommittedLZFOutputStream", "lzfOutputStream", "=", "new", "CommittedLZFOutputStream", "(", "old", ",", "null", ")", ";", "// Any content length set will be obsolete", "context", ".", "getHeaders", "(", ")", ".", "remove", "(", "\"Content-Length\"", ")", ";", "context", ".", "setOutputStream", "(", "lzfOutputStream", ")", ";", "try", "{", "context", ".", "proceed", "(", ")", ";", "}", "finally", "{", "if", "(", "lzfOutputStream", ".", "getLzf", "(", ")", "!=", "null", ")", "lzfOutputStream", ".", "getLzf", "(", ")", ".", "flush", "(", ")", ";", "context", ".", "setOutputStream", "(", "old", ")", ";", "}", "return", ";", "}", "else", "{", "context", ".", "proceed", "(", ")", ";", "}", "}" ]
Grab the outgoing message, if encoding is set to LZF, then wrap the OutputStream in an LZF OutputStream before sending it on its merry way, compressing all the time. Note: strips out the content-length header because the compression changes that unpredictably @param context @throws IOException @throws WebApplicationException
[ "Grab", "the", "outgoing", "message", "if", "encoding", "is", "set", "to", "LZF", "then", "wrap", "the", "OutputStream", "in", "an", "LZF", "OutputStream", "before", "sending", "it", "on", "its", "merry", "way", "compressing", "all", "the", "time", "." ]
train
https://github.com/svanoort/rest-compress/blob/4e34fcbe0d1b510962a93509a78b6a8ade234606/rest-compress-lib/src/main/java/com/restcompress/provider/LZFEncodingInterceptor.java#L65-L87
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressSection.java
IPAddressSection.isPrefixSubnet
protected static boolean isPrefixSubnet(IPAddressSegment sectionSegments[], Integer networkPrefixLength, IPAddressNetwork<?, ?, ?, ?, ?> network, boolean fullRangeOnly) { """ /* Starting from the first host bit according to the prefix, if the section is a sequence of zeros in both low and high values, followed by a sequence where low values are zero and high values are 1, then the section is a subnet prefix. Note that this includes sections where hosts are all zeros, or sections where hosts are full range of values, so the sequence of zeros can be empty and the sequence of where low values are zero and high values are 1 can be empty as well. However, if they are both empty, then this returns false, there must be at least one bit in the sequence. """ int segmentCount = sectionSegments.length; if(segmentCount == 0) { return false; } IPAddressSegment seg = sectionSegments[0]; return ParsedAddressGrouping.isPrefixSubnet( (segmentIndex) -> sectionSegments[segmentIndex].getSegmentValue(), (segmentIndex) -> sectionSegments[segmentIndex].getUpperSegmentValue(), segmentCount, seg.getByteCount(), seg.getBitCount(), seg.getMaxSegmentValue(), networkPrefixLength, network.getPrefixConfiguration(), fullRangeOnly); }
java
protected static boolean isPrefixSubnet(IPAddressSegment sectionSegments[], Integer networkPrefixLength, IPAddressNetwork<?, ?, ?, ?, ?> network, boolean fullRangeOnly) { int segmentCount = sectionSegments.length; if(segmentCount == 0) { return false; } IPAddressSegment seg = sectionSegments[0]; return ParsedAddressGrouping.isPrefixSubnet( (segmentIndex) -> sectionSegments[segmentIndex].getSegmentValue(), (segmentIndex) -> sectionSegments[segmentIndex].getUpperSegmentValue(), segmentCount, seg.getByteCount(), seg.getBitCount(), seg.getMaxSegmentValue(), networkPrefixLength, network.getPrefixConfiguration(), fullRangeOnly); }
[ "protected", "static", "boolean", "isPrefixSubnet", "(", "IPAddressSegment", "sectionSegments", "[", "]", ",", "Integer", "networkPrefixLength", ",", "IPAddressNetwork", "<", "?", ",", "?", ",", "?", ",", "?", ",", "?", ">", "network", ",", "boolean", "fullRangeOnly", ")", "{", "int", "segmentCount", "=", "sectionSegments", ".", "length", ";", "if", "(", "segmentCount", "==", "0", ")", "{", "return", "false", ";", "}", "IPAddressSegment", "seg", "=", "sectionSegments", "[", "0", "]", ";", "return", "ParsedAddressGrouping", ".", "isPrefixSubnet", "(", "(", "segmentIndex", ")", "-", ">", "sectionSegments", "[", "segmentIndex", "]", ".", "getSegmentValue", "(", ")", ",", "(", "segmentIndex", ")", "-", ">", "sectionSegments", "[", "segmentIndex", "]", ".", "getUpperSegmentValue", "(", ")", ",", "segmentCount", ",", "seg", ".", "getByteCount", "(", ")", ",", "seg", ".", "getBitCount", "(", ")", ",", "seg", ".", "getMaxSegmentValue", "(", ")", ",", "networkPrefixLength", ",", "network", ".", "getPrefixConfiguration", "(", ")", ",", "fullRangeOnly", ")", ";", "}" ]
/* Starting from the first host bit according to the prefix, if the section is a sequence of zeros in both low and high values, followed by a sequence where low values are zero and high values are 1, then the section is a subnet prefix. Note that this includes sections where hosts are all zeros, or sections where hosts are full range of values, so the sequence of zeros can be empty and the sequence of where low values are zero and high values are 1 can be empty as well. However, if they are both empty, then this returns false, there must be at least one bit in the sequence.
[ "/", "*", "Starting", "from", "the", "first", "host", "bit", "according", "to", "the", "prefix", "if", "the", "section", "is", "a", "sequence", "of", "zeros", "in", "both", "low", "and", "high", "values", "followed", "by", "a", "sequence", "where", "low", "values", "are", "zero", "and", "high", "values", "are", "1", "then", "the", "section", "is", "a", "subnet", "prefix", "." ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressSection.java#L239-L255
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/LatLongUtils.java
LatLongUtils.destinationPoint
public static LatLong destinationPoint(LatLong start, double distance, float bearing) { """ Returns the destination point from this point having travelled the given distance on the given initial bearing (bearing normally varies around path followed). @param start the start point @param distance the distance travelled, in same units as earth radius (default: meters) @param bearing the initial bearing in degrees from north @return the destination point @see <a href="http://www.movable-type.co.uk/scripts/latlon.js">latlon.js</a> """ double theta = Math.toRadians(bearing); double delta = distance / EQUATORIAL_RADIUS; // angular distance in radians double phi1 = Math.toRadians(start.latitude); double lambda1 = Math.toRadians(start.longitude); double phi2 = Math.asin(Math.sin(phi1) * Math.cos(delta) + Math.cos(phi1) * Math.sin(delta) * Math.cos(theta)); double lambda2 = lambda1 + Math.atan2(Math.sin(theta) * Math.sin(delta) * Math.cos(phi1), Math.cos(delta) - Math.sin(phi1) * Math.sin(phi2)); return new LatLong(Math.toDegrees(phi2), Math.toDegrees(lambda2)); }
java
public static LatLong destinationPoint(LatLong start, double distance, float bearing) { double theta = Math.toRadians(bearing); double delta = distance / EQUATORIAL_RADIUS; // angular distance in radians double phi1 = Math.toRadians(start.latitude); double lambda1 = Math.toRadians(start.longitude); double phi2 = Math.asin(Math.sin(phi1) * Math.cos(delta) + Math.cos(phi1) * Math.sin(delta) * Math.cos(theta)); double lambda2 = lambda1 + Math.atan2(Math.sin(theta) * Math.sin(delta) * Math.cos(phi1), Math.cos(delta) - Math.sin(phi1) * Math.sin(phi2)); return new LatLong(Math.toDegrees(phi2), Math.toDegrees(lambda2)); }
[ "public", "static", "LatLong", "destinationPoint", "(", "LatLong", "start", ",", "double", "distance", ",", "float", "bearing", ")", "{", "double", "theta", "=", "Math", ".", "toRadians", "(", "bearing", ")", ";", "double", "delta", "=", "distance", "/", "EQUATORIAL_RADIUS", ";", "// angular distance in radians", "double", "phi1", "=", "Math", ".", "toRadians", "(", "start", ".", "latitude", ")", ";", "double", "lambda1", "=", "Math", ".", "toRadians", "(", "start", ".", "longitude", ")", ";", "double", "phi2", "=", "Math", ".", "asin", "(", "Math", ".", "sin", "(", "phi1", ")", "*", "Math", ".", "cos", "(", "delta", ")", "+", "Math", ".", "cos", "(", "phi1", ")", "*", "Math", ".", "sin", "(", "delta", ")", "*", "Math", ".", "cos", "(", "theta", ")", ")", ";", "double", "lambda2", "=", "lambda1", "+", "Math", ".", "atan2", "(", "Math", ".", "sin", "(", "theta", ")", "*", "Math", ".", "sin", "(", "delta", ")", "*", "Math", ".", "cos", "(", "phi1", ")", ",", "Math", ".", "cos", "(", "delta", ")", "-", "Math", ".", "sin", "(", "phi1", ")", "*", "Math", ".", "sin", "(", "phi2", ")", ")", ";", "return", "new", "LatLong", "(", "Math", ".", "toDegrees", "(", "phi2", ")", ",", "Math", ".", "toDegrees", "(", "lambda2", ")", ")", ";", "}" ]
Returns the destination point from this point having travelled the given distance on the given initial bearing (bearing normally varies around path followed). @param start the start point @param distance the distance travelled, in same units as earth radius (default: meters) @param bearing the initial bearing in degrees from north @return the destination point @see <a href="http://www.movable-type.co.uk/scripts/latlon.js">latlon.js</a>
[ "Returns", "the", "destination", "point", "from", "this", "point", "having", "travelled", "the", "given", "distance", "on", "the", "given", "initial", "bearing", "(", "bearing", "normally", "varies", "around", "path", "followed", ")", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/LatLongUtils.java#L135-L148
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java
Collections.anyAndEveryIn
public static SatisfiesBuilder anyAndEveryIn(String variable, Expression expression) { """ Create an ANY AND EVERY comprehension with a first IN range. ANY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a collection, object, or objects. It uses the IN and WITHIN operators to range through the collection. EVERY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a collection, object, or objects. It uses the IN and WITHIN operators to range through the collection. """ return new SatisfiesBuilder(x("ANY AND EVERY"), variable, expression, true); }
java
public static SatisfiesBuilder anyAndEveryIn(String variable, Expression expression) { return new SatisfiesBuilder(x("ANY AND EVERY"), variable, expression, true); }
[ "public", "static", "SatisfiesBuilder", "anyAndEveryIn", "(", "String", "variable", ",", "Expression", "expression", ")", "{", "return", "new", "SatisfiesBuilder", "(", "x", "(", "\"ANY AND EVERY\"", ")", ",", "variable", ",", "expression", ",", "true", ")", ";", "}" ]
Create an ANY AND EVERY comprehension with a first IN range. ANY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a collection, object, or objects. It uses the IN and WITHIN operators to range through the collection. EVERY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a collection, object, or objects. It uses the IN and WITHIN operators to range through the collection.
[ "Create", "an", "ANY", "AND", "EVERY", "comprehension", "with", "a", "first", "IN", "range", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java#L170-L172
jhipster/jhipster
jhipster-framework/src/main/java/io/github/jhipster/web/util/PaginationUtil.java
PaginationUtil.generatePaginationHttpHeaders
public static <T> HttpHeaders generatePaginationHttpHeaders(UriComponentsBuilder uriBuilder, Page<T> page) { """ Generate pagination headers for a Spring Data {@link Page} object. @param uriBuilder The URI builder. @param page The page. @param <T> The type of object. @return http header. """ HttpHeaders headers = new HttpHeaders(); headers.add(HEADER_X_TOTAL_COUNT, Long.toString(page.getTotalElements())); int pageNumber = page.getNumber(); int pageSize = page.getSize(); StringBuilder link = new StringBuilder(); if (pageNumber < page.getTotalPages() - 1) { link.append(prepareLink(uriBuilder, pageNumber + 1, pageSize, "next")) .append(","); } if (pageNumber > 0) { link.append(prepareLink(uriBuilder, pageNumber - 1, pageSize, "prev")) .append(","); } link.append(prepareLink(uriBuilder, page.getTotalPages() - 1, pageSize, "last")) .append(",") .append(prepareLink(uriBuilder, 0, pageSize, "first")); headers.add(HttpHeaders.LINK, link.toString()); return headers; }
java
public static <T> HttpHeaders generatePaginationHttpHeaders(UriComponentsBuilder uriBuilder, Page<T> page) { HttpHeaders headers = new HttpHeaders(); headers.add(HEADER_X_TOTAL_COUNT, Long.toString(page.getTotalElements())); int pageNumber = page.getNumber(); int pageSize = page.getSize(); StringBuilder link = new StringBuilder(); if (pageNumber < page.getTotalPages() - 1) { link.append(prepareLink(uriBuilder, pageNumber + 1, pageSize, "next")) .append(","); } if (pageNumber > 0) { link.append(prepareLink(uriBuilder, pageNumber - 1, pageSize, "prev")) .append(","); } link.append(prepareLink(uriBuilder, page.getTotalPages() - 1, pageSize, "last")) .append(",") .append(prepareLink(uriBuilder, 0, pageSize, "first")); headers.add(HttpHeaders.LINK, link.toString()); return headers; }
[ "public", "static", "<", "T", ">", "HttpHeaders", "generatePaginationHttpHeaders", "(", "UriComponentsBuilder", "uriBuilder", ",", "Page", "<", "T", ">", "page", ")", "{", "HttpHeaders", "headers", "=", "new", "HttpHeaders", "(", ")", ";", "headers", ".", "add", "(", "HEADER_X_TOTAL_COUNT", ",", "Long", ".", "toString", "(", "page", ".", "getTotalElements", "(", ")", ")", ")", ";", "int", "pageNumber", "=", "page", ".", "getNumber", "(", ")", ";", "int", "pageSize", "=", "page", ".", "getSize", "(", ")", ";", "StringBuilder", "link", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "pageNumber", "<", "page", ".", "getTotalPages", "(", ")", "-", "1", ")", "{", "link", ".", "append", "(", "prepareLink", "(", "uriBuilder", ",", "pageNumber", "+", "1", ",", "pageSize", ",", "\"next\"", ")", ")", ".", "append", "(", "\",\"", ")", ";", "}", "if", "(", "pageNumber", ">", "0", ")", "{", "link", ".", "append", "(", "prepareLink", "(", "uriBuilder", ",", "pageNumber", "-", "1", ",", "pageSize", ",", "\"prev\"", ")", ")", ".", "append", "(", "\",\"", ")", ";", "}", "link", ".", "append", "(", "prepareLink", "(", "uriBuilder", ",", "page", ".", "getTotalPages", "(", ")", "-", "1", ",", "pageSize", ",", "\"last\"", ")", ")", ".", "append", "(", "\",\"", ")", ".", "append", "(", "prepareLink", "(", "uriBuilder", ",", "0", ",", "pageSize", ",", "\"first\"", ")", ")", ";", "headers", ".", "add", "(", "HttpHeaders", ".", "LINK", ",", "link", ".", "toString", "(", ")", ")", ";", "return", "headers", ";", "}" ]
Generate pagination headers for a Spring Data {@link Page} object. @param uriBuilder The URI builder. @param page The page. @param <T> The type of object. @return http header.
[ "Generate", "pagination", "headers", "for", "a", "Spring", "Data", "{", "@link", "Page", "}", "object", "." ]
train
https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/web/util/PaginationUtil.java#L50-L69
jacobtabak/Fragment-Switcher
sample/src/main/java/me/tabak/fragmentswitcher/sample/DrawerActivity.java
DrawerActivity.initializeList
private void initializeList() { """ Initializes the list that controls which fragment will be shown. """ mListView = (ListView) findViewById(R.id.drawer_list); mListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { mFragmentSwitcher.setCurrentItem(position); mDrawerLayout.closeDrawer(Gravity.START); } }); }
java
private void initializeList() { mListView = (ListView) findViewById(R.id.drawer_list); mListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { mFragmentSwitcher.setCurrentItem(position); mDrawerLayout.closeDrawer(Gravity.START); } }); }
[ "private", "void", "initializeList", "(", ")", "{", "mListView", "=", "(", "ListView", ")", "findViewById", "(", "R", ".", "id", ".", "drawer_list", ")", ";", "mListAdapter", "=", "new", "ArrayAdapter", "<", "String", ">", "(", "this", ",", "android", ".", "R", ".", "layout", ".", "simple_list_item_1", ")", ";", "mListView", ".", "setAdapter", "(", "mListAdapter", ")", ";", "mListView", ".", "setOnItemClickListener", "(", "new", "AdapterView", ".", "OnItemClickListener", "(", ")", "{", "@", "Override", "public", "void", "onItemClick", "(", "AdapterView", "<", "?", ">", "adapterView", ",", "View", "view", ",", "int", "position", ",", "long", "id", ")", "{", "mFragmentSwitcher", ".", "setCurrentItem", "(", "position", ")", ";", "mDrawerLayout", ".", "closeDrawer", "(", "Gravity", ".", "START", ")", ";", "}", "}", ")", ";", "}" ]
Initializes the list that controls which fragment will be shown.
[ "Initializes", "the", "list", "that", "controls", "which", "fragment", "will", "be", "shown", "." ]
train
https://github.com/jacobtabak/Fragment-Switcher/blob/9d4cd33d68057ebfb8c5910cd49c65fb6bdfdbed/sample/src/main/java/me/tabak/fragmentswitcher/sample/DrawerActivity.java#L79-L90
m-m-m/util
pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java
PojoDescriptorBuilderImpl.registerAccessor
protected boolean registerAccessor(PojoDescriptorImpl<?> descriptor, PojoPropertyAccessor accessor) { """ This method registers the given {@code accessor} for the given {@code descriptor}. @param descriptor is the {@link net.sf.mmm.util.pojo.descriptor.api.PojoDescriptor}. @param accessor is the {@link PojoPropertyAccessor} to register. @return {@code true} if the given {@code accessor} has been registered or {@code false} if it has been ignored (it is a duplicate). """ PojoPropertyDescriptorImpl propertyDescriptor = descriptor.getOrCreatePropertyDescriptor(accessor.getName()); boolean added = false; PojoPropertyAccessor existing = propertyDescriptor.getAccessor(accessor.getMode()); if (existing == null) { propertyDescriptor.putAccessor(accessor); added = true; } else { // Workaround for JVM-Bug with overridden methods if (existing.getReturnType().isAssignableFrom(accessor.getReturnType())) { AccessibleObject accessorAccessible = accessor.getAccessibleObject(); if (accessorAccessible instanceof Method) { propertyDescriptor.putAccessor(accessor); added = true; } } // this will also happen for private fields with the same name and is // then a regular log message... if (added) { logDuplicateAccessor(accessor, existing); } else { logDuplicateAccessor(existing, accessor); } } return added; }
java
protected boolean registerAccessor(PojoDescriptorImpl<?> descriptor, PojoPropertyAccessor accessor) { PojoPropertyDescriptorImpl propertyDescriptor = descriptor.getOrCreatePropertyDescriptor(accessor.getName()); boolean added = false; PojoPropertyAccessor existing = propertyDescriptor.getAccessor(accessor.getMode()); if (existing == null) { propertyDescriptor.putAccessor(accessor); added = true; } else { // Workaround for JVM-Bug with overridden methods if (existing.getReturnType().isAssignableFrom(accessor.getReturnType())) { AccessibleObject accessorAccessible = accessor.getAccessibleObject(); if (accessorAccessible instanceof Method) { propertyDescriptor.putAccessor(accessor); added = true; } } // this will also happen for private fields with the same name and is // then a regular log message... if (added) { logDuplicateAccessor(accessor, existing); } else { logDuplicateAccessor(existing, accessor); } } return added; }
[ "protected", "boolean", "registerAccessor", "(", "PojoDescriptorImpl", "<", "?", ">", "descriptor", ",", "PojoPropertyAccessor", "accessor", ")", "{", "PojoPropertyDescriptorImpl", "propertyDescriptor", "=", "descriptor", ".", "getOrCreatePropertyDescriptor", "(", "accessor", ".", "getName", "(", ")", ")", ";", "boolean", "added", "=", "false", ";", "PojoPropertyAccessor", "existing", "=", "propertyDescriptor", ".", "getAccessor", "(", "accessor", ".", "getMode", "(", ")", ")", ";", "if", "(", "existing", "==", "null", ")", "{", "propertyDescriptor", ".", "putAccessor", "(", "accessor", ")", ";", "added", "=", "true", ";", "}", "else", "{", "// Workaround for JVM-Bug with overridden methods", "if", "(", "existing", ".", "getReturnType", "(", ")", ".", "isAssignableFrom", "(", "accessor", ".", "getReturnType", "(", ")", ")", ")", "{", "AccessibleObject", "accessorAccessible", "=", "accessor", ".", "getAccessibleObject", "(", ")", ";", "if", "(", "accessorAccessible", "instanceof", "Method", ")", "{", "propertyDescriptor", ".", "putAccessor", "(", "accessor", ")", ";", "added", "=", "true", ";", "}", "}", "// this will also happen for private fields with the same name and is", "// then a regular log message...", "if", "(", "added", ")", "{", "logDuplicateAccessor", "(", "accessor", ",", "existing", ")", ";", "}", "else", "{", "logDuplicateAccessor", "(", "existing", ",", "accessor", ")", ";", "}", "}", "return", "added", ";", "}" ]
This method registers the given {@code accessor} for the given {@code descriptor}. @param descriptor is the {@link net.sf.mmm.util.pojo.descriptor.api.PojoDescriptor}. @param accessor is the {@link PojoPropertyAccessor} to register. @return {@code true} if the given {@code accessor} has been registered or {@code false} if it has been ignored (it is a duplicate).
[ "This", "method", "registers", "the", "given", "{", "@code", "accessor", "}", "for", "the", "given", "{", "@code", "descriptor", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java#L185-L211
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java
ST_Split.splitPolygonWithLine
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { """ Splits a Polygon using a LineString. @param polygon @param lineString @return """ Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } return null; }
java
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } return null; }
[ "private", "static", "Geometry", "splitPolygonWithLine", "(", "Polygon", "polygon", ",", "LineString", "lineString", ")", "throws", "SQLException", "{", "Collection", "<", "Polygon", ">", "pols", "=", "polygonWithLineSplitter", "(", "polygon", ",", "lineString", ")", ";", "if", "(", "pols", "!=", "null", ")", "{", "return", "FACTORY", ".", "buildGeometry", "(", "polygonWithLineSplitter", "(", "polygon", ",", "lineString", ")", ")", ";", "}", "return", "null", ";", "}" ]
Splits a Polygon using a LineString. @param polygon @param lineString @return
[ "Splits", "a", "Polygon", "using", "a", "LineString", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java#L254-L260
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/BusHandler.java
BusHandler.updateSendAllowed
public void updateSendAllowed(boolean oldSendAllowed, boolean newSendAllowed) { """ Update sendAllowed setting for this bus and any targetting Handlers. @param foreignBusDefinition """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateSendAllowed", new Object[] {Boolean.valueOf(oldSendAllowed), Boolean.valueOf(newSendAllowed)}); if(oldSendAllowed && !newSendAllowed) setForeignBusSendAllowed(false); else if(!oldSendAllowed && newSendAllowed) setForeignBusSendAllowed(true); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateSendAllowed"); }
java
public void updateSendAllowed(boolean oldSendAllowed, boolean newSendAllowed) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateSendAllowed", new Object[] {Boolean.valueOf(oldSendAllowed), Boolean.valueOf(newSendAllowed)}); if(oldSendAllowed && !newSendAllowed) setForeignBusSendAllowed(false); else if(!oldSendAllowed && newSendAllowed) setForeignBusSendAllowed(true); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateSendAllowed"); }
[ "public", "void", "updateSendAllowed", "(", "boolean", "oldSendAllowed", ",", "boolean", "newSendAllowed", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"updateSendAllowed\"", ",", "new", "Object", "[", "]", "{", "Boolean", ".", "valueOf", "(", "oldSendAllowed", ")", ",", "Boolean", ".", "valueOf", "(", "newSendAllowed", ")", "}", ")", ";", "if", "(", "oldSendAllowed", "&&", "!", "newSendAllowed", ")", "setForeignBusSendAllowed", "(", "false", ")", ";", "else", "if", "(", "!", "oldSendAllowed", "&&", "newSendAllowed", ")", "setForeignBusSendAllowed", "(", "true", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"updateSendAllowed\"", ")", ";", "}" ]
Update sendAllowed setting for this bus and any targetting Handlers. @param foreignBusDefinition
[ "Update", "sendAllowed", "setting", "for", "this", "bus", "and", "any", "targetting", "Handlers", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/BusHandler.java#L240-L255
scaleset/scaleset-geo
src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java
GoogleMapsTileMath.pixelsToMeters
public Coordinate pixelsToMeters(double px, double py, int zoomLevel) { """ Converts pixel coordinates in given zoom level of pyramid to EPSG:3857 @param px the X pixel coordinate @param py the Y pixel coordinate @param zoomLevel the zoom level @return The coordinate transformed to EPSG:3857 """ double res = resolution(zoomLevel); double mx = px * res - originShift; double my = -py * res + originShift; return new Coordinate(mx, my); }
java
public Coordinate pixelsToMeters(double px, double py, int zoomLevel) { double res = resolution(zoomLevel); double mx = px * res - originShift; double my = -py * res + originShift; return new Coordinate(mx, my); }
[ "public", "Coordinate", "pixelsToMeters", "(", "double", "px", ",", "double", "py", ",", "int", "zoomLevel", ")", "{", "double", "res", "=", "resolution", "(", "zoomLevel", ")", ";", "double", "mx", "=", "px", "*", "res", "-", "originShift", ";", "double", "my", "=", "-", "py", "*", "res", "+", "originShift", ";", "return", "new", "Coordinate", "(", "mx", ",", "my", ")", ";", "}" ]
Converts pixel coordinates in given zoom level of pyramid to EPSG:3857 @param px the X pixel coordinate @param py the Y pixel coordinate @param zoomLevel the zoom level @return The coordinate transformed to EPSG:3857
[ "Converts", "pixel", "coordinates", "in", "given", "zoom", "level", "of", "pyramid", "to", "EPSG", ":", "3857" ]
train
https://github.com/scaleset/scaleset-geo/blob/5cff2349668037dc287928a6c1a1f67c76d96b02/src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java#L249-L255
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java
SARLOperationHelper._hasSideEffects
protected Boolean _hasSideEffects(XVariableDeclaration expression, ISideEffectContext context) { """ Test if the given expression has side effects. @param expression the expression. @param context the list of context expressions. @return {@code true} if the expression has side effects. """ if (hasSideEffects(expression.getRight(), context)) { return true; } context.declareVariable(expression.getIdentifier(), expression.getRight()); return false; }
java
protected Boolean _hasSideEffects(XVariableDeclaration expression, ISideEffectContext context) { if (hasSideEffects(expression.getRight(), context)) { return true; } context.declareVariable(expression.getIdentifier(), expression.getRight()); return false; }
[ "protected", "Boolean", "_hasSideEffects", "(", "XVariableDeclaration", "expression", ",", "ISideEffectContext", "context", ")", "{", "if", "(", "hasSideEffects", "(", "expression", ".", "getRight", "(", ")", ",", "context", ")", ")", "{", "return", "true", ";", "}", "context", ".", "declareVariable", "(", "expression", ".", "getIdentifier", "(", ")", ",", "expression", ".", "getRight", "(", ")", ")", ";", "return", "false", ";", "}" ]
Test if the given expression has side effects. @param expression the expression. @param context the list of context expressions. @return {@code true} if the expression has side effects.
[ "Test", "if", "the", "given", "expression", "has", "side", "effects", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java#L388-L394
depsypher/pngtastic
src/main/java/com/googlecode/pngtastic/core/processing/Base64.java
Base64.encodeToFile
public static void encodeToFile(byte[] dataToEncode, String filename) throws IOException { """ Convenience method for encoding data to a file. <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it.</p> @param dataToEncode byte array of data to encode in base64 form @param filename Filename for saving encoded data @throws IOException if there is an error @throws NullPointerException if dataToEncode is null @since 2.1 """ if (dataToEncode == null) { throw new NullPointerException("Data to encode was null."); } Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); } catch (IOException e) { throw e; // Catch and throw to execute finally{} block } finally { try { if (bos != null) { bos.close(); } } catch (Exception e) { } } }
java
public static void encodeToFile(byte[] dataToEncode, String filename) throws IOException { if (dataToEncode == null) { throw new NullPointerException("Data to encode was null."); } Base64.OutputStream bos = null; try { bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE); bos.write(dataToEncode); } catch (IOException e) { throw e; // Catch and throw to execute finally{} block } finally { try { if (bos != null) { bos.close(); } } catch (Exception e) { } } }
[ "public", "static", "void", "encodeToFile", "(", "byte", "[", "]", "dataToEncode", ",", "String", "filename", ")", "throws", "IOException", "{", "if", "(", "dataToEncode", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Data to encode was null.\"", ")", ";", "}", "Base64", ".", "OutputStream", "bos", "=", "null", ";", "try", "{", "bos", "=", "new", "Base64", ".", "OutputStream", "(", "new", "java", ".", "io", ".", "FileOutputStream", "(", "filename", ")", ",", "Base64", ".", "ENCODE", ")", ";", "bos", ".", "write", "(", "dataToEncode", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "e", ";", "// Catch and throw to execute finally{} block", "}", "finally", "{", "try", "{", "if", "(", "bos", "!=", "null", ")", "{", "bos", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}" ]
Convenience method for encoding data to a file. <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it.</p> @param dataToEncode byte array of data to encode in base64 form @param filename Filename for saving encoded data @throws IOException if there is an error @throws NullPointerException if dataToEncode is null @since 2.1
[ "Convenience", "method", "for", "encoding", "data", "to", "a", "file", "." ]
train
https://github.com/depsypher/pngtastic/blob/13fd2a63dd8b2febd7041273889a1bba4f2a6a07/src/main/java/com/googlecode/pngtastic/core/processing/Base64.java#L1288-L1307
lets-blade/blade
src/main/java/com/blade/server/netty/StaticFileHandler.java
StaticFileHandler.setContentTypeHeader
private static void setContentTypeHeader(HttpResponse response, File file) { """ Sets the content type header for the HTTP Response @param response HTTP response @param file file to extract content type """ String contentType = StringKit.mimeType(file.getName()); if (null == contentType) { contentType = URLConnection.guessContentTypeFromName(file.getName()); } response.headers().set(HttpConst.CONTENT_TYPE, contentType); }
java
private static void setContentTypeHeader(HttpResponse response, File file) { String contentType = StringKit.mimeType(file.getName()); if (null == contentType) { contentType = URLConnection.guessContentTypeFromName(file.getName()); } response.headers().set(HttpConst.CONTENT_TYPE, contentType); }
[ "private", "static", "void", "setContentTypeHeader", "(", "HttpResponse", "response", ",", "File", "file", ")", "{", "String", "contentType", "=", "StringKit", ".", "mimeType", "(", "file", ".", "getName", "(", ")", ")", ";", "if", "(", "null", "==", "contentType", ")", "{", "contentType", "=", "URLConnection", ".", "guessContentTypeFromName", "(", "file", ".", "getName", "(", ")", ")", ";", "}", "response", ".", "headers", "(", ")", ".", "set", "(", "HttpConst", ".", "CONTENT_TYPE", ",", "contentType", ")", ";", "}" ]
Sets the content type header for the HTTP Response @param response HTTP response @param file file to extract content type
[ "Sets", "the", "content", "type", "header", "for", "the", "HTTP", "Response" ]
train
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/server/netty/StaticFileHandler.java#L519-L525
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpRequestMessageImpl.java
HttpRequestMessageImpl.parseAuthority
private void parseAuthority(byte[] data, int start) { """ Parse the authority information out that followed a "//" marker. Once that data is saved, then it starts the parse for the remaining info in the URL. If any format errors are encountered, then an exception is thrown. @param data @param start @throws IllegalArgumentException """ // authority is [userinfo@] host [:port] "/URI" if (start >= data.length) { // nothing after the "//" which is invalid throw new IllegalArgumentException("Invalid authority: " + GenericUtils.getEnglishString(data)); } int i = start; int host_start = start; int slash_start = data.length; for (; i < data.length; i++) { // find either a "@" or "/" if ('@' == data[i]) { // Note: we're just cutting off the userinfo section for now host_start = i + 1; } else if ('/' == data[i]) { slash_start = i; break; } } parseURLHost(data, host_start, slash_start); parseURI(data, slash_start); }
java
private void parseAuthority(byte[] data, int start) { // authority is [userinfo@] host [:port] "/URI" if (start >= data.length) { // nothing after the "//" which is invalid throw new IllegalArgumentException("Invalid authority: " + GenericUtils.getEnglishString(data)); } int i = start; int host_start = start; int slash_start = data.length; for (; i < data.length; i++) { // find either a "@" or "/" if ('@' == data[i]) { // Note: we're just cutting off the userinfo section for now host_start = i + 1; } else if ('/' == data[i]) { slash_start = i; break; } } parseURLHost(data, host_start, slash_start); parseURI(data, slash_start); }
[ "private", "void", "parseAuthority", "(", "byte", "[", "]", "data", ",", "int", "start", ")", "{", "// authority is [userinfo@] host [:port] \"/URI\"", "if", "(", "start", ">=", "data", ".", "length", ")", "{", "// nothing after the \"//\" which is invalid", "throw", "new", "IllegalArgumentException", "(", "\"Invalid authority: \"", "+", "GenericUtils", ".", "getEnglishString", "(", "data", ")", ")", ";", "}", "int", "i", "=", "start", ";", "int", "host_start", "=", "start", ";", "int", "slash_start", "=", "data", ".", "length", ";", "for", "(", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "// find either a \"@\" or \"/\"", "if", "(", "'", "'", "==", "data", "[", "i", "]", ")", "{", "// Note: we're just cutting off the userinfo section for now", "host_start", "=", "i", "+", "1", ";", "}", "else", "if", "(", "'", "'", "==", "data", "[", "i", "]", ")", "{", "slash_start", "=", "i", ";", "break", ";", "}", "}", "parseURLHost", "(", "data", ",", "host_start", ",", "slash_start", ")", ";", "parseURI", "(", "data", ",", "slash_start", ")", ";", "}" ]
Parse the authority information out that followed a "//" marker. Once that data is saved, then it starts the parse for the remaining info in the URL. If any format errors are encountered, then an exception is thrown. @param data @param start @throws IllegalArgumentException
[ "Parse", "the", "authority", "information", "out", "that", "followed", "a", "//", "marker", ".", "Once", "that", "data", "is", "saved", "then", "it", "starts", "the", "parse", "for", "the", "remaining", "info", "in", "the", "URL", ".", "If", "any", "format", "errors", "are", "encountered", "then", "an", "exception", "is", "thrown", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpRequestMessageImpl.java#L1199-L1220
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockMasterClient.java
BlockMasterClient.commitBlockInUfs
public void commitBlockInUfs(final long blockId, final long length) throws IOException { """ Commits a block in Ufs. @param blockId the block id being committed @param length the length of the block being committed """ retryRPC((RpcCallable<Void>) () -> { CommitBlockInUfsPRequest request = CommitBlockInUfsPRequest.newBuilder().setBlockId(blockId).setLength(length).build(); mClient.commitBlockInUfs(request); return null; }); }
java
public void commitBlockInUfs(final long blockId, final long length) throws IOException { retryRPC((RpcCallable<Void>) () -> { CommitBlockInUfsPRequest request = CommitBlockInUfsPRequest.newBuilder().setBlockId(blockId).setLength(length).build(); mClient.commitBlockInUfs(request); return null; }); }
[ "public", "void", "commitBlockInUfs", "(", "final", "long", "blockId", ",", "final", "long", "length", ")", "throws", "IOException", "{", "retryRPC", "(", "(", "RpcCallable", "<", "Void", ">", ")", "(", ")", "->", "{", "CommitBlockInUfsPRequest", "request", "=", "CommitBlockInUfsPRequest", ".", "newBuilder", "(", ")", ".", "setBlockId", "(", "blockId", ")", ".", "setLength", "(", "length", ")", ".", "build", "(", ")", ";", "mClient", ".", "commitBlockInUfs", "(", "request", ")", ";", "return", "null", ";", "}", ")", ";", "}" ]
Commits a block in Ufs. @param blockId the block id being committed @param length the length of the block being committed
[ "Commits", "a", "block", "in", "Ufs", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockMasterClient.java#L104-L112
jglobus/JGlobus
gridftp/src/main/java/org/globus/ftp/GridFTPClient.java
GridFTPClient.changeModificationTime
public void changeModificationTime(int year, int month, int day, int hour, int min, int sec, String file) throws IOException, ServerException { """ Change the modification time of a file. @param year Modifcation year @param month Modification month (1-12) @param day Modification day (1-31) @param hour Modification hour (0-23) @param min Modification minutes (0-59) @param sec Modification seconds (0-59) @param file file whose modification time should be changed @throws IOException @throws ServerException if an error occurred. """ DecimalFormat df2 = new DecimalFormat("00"); DecimalFormat df4 = new DecimalFormat("0000"); String arguments = df4.format(year) + df2.format(month) + df2.format(day) + df2.format(hour) + df2.format(min) + df2.format(sec) + " " + file; Command cmd = new Command("SITE UTIME", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } }
java
public void changeModificationTime(int year, int month, int day, int hour, int min, int sec, String file) throws IOException, ServerException { DecimalFormat df2 = new DecimalFormat("00"); DecimalFormat df4 = new DecimalFormat("0000"); String arguments = df4.format(year) + df2.format(month) + df2.format(day) + df2.format(hour) + df2.format(min) + df2.format(sec) + " " + file; Command cmd = new Command("SITE UTIME", arguments); try { controlChannel.execute(cmd); }catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException(urce); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } }
[ "public", "void", "changeModificationTime", "(", "int", "year", ",", "int", "month", ",", "int", "day", ",", "int", "hour", ",", "int", "min", ",", "int", "sec", ",", "String", "file", ")", "throws", "IOException", ",", "ServerException", "{", "DecimalFormat", "df2", "=", "new", "DecimalFormat", "(", "\"00\"", ")", ";", "DecimalFormat", "df4", "=", "new", "DecimalFormat", "(", "\"0000\"", ")", ";", "String", "arguments", "=", "df4", ".", "format", "(", "year", ")", "+", "df2", ".", "format", "(", "month", ")", "+", "df2", ".", "format", "(", "day", ")", "+", "df2", ".", "format", "(", "hour", ")", "+", "df2", ".", "format", "(", "min", ")", "+", "df2", ".", "format", "(", "sec", ")", "+", "\" \"", "+", "file", ";", "Command", "cmd", "=", "new", "Command", "(", "\"SITE UTIME\"", ",", "arguments", ")", ";", "try", "{", "controlChannel", ".", "execute", "(", "cmd", ")", ";", "}", "catch", "(", "UnexpectedReplyCodeException", "urce", ")", "{", "throw", "ServerException", ".", "embedUnexpectedReplyCodeException", "(", "urce", ")", ";", "}", "catch", "(", "FTPReplyParseException", "rpe", ")", "{", "throw", "ServerException", ".", "embedFTPReplyParseException", "(", "rpe", ")", ";", "}", "}" ]
Change the modification time of a file. @param year Modifcation year @param month Modification month (1-12) @param day Modification day (1-31) @param hour Modification hour (0-23) @param min Modification minutes (0-59) @param sec Modification seconds (0-59) @param file file whose modification time should be changed @throws IOException @throws ServerException if an error occurred.
[ "Change", "the", "modification", "time", "of", "a", "file", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/GridFTPClient.java#L1111-L1127
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java
AvroUtils.decorateRecordSchema
public static Schema decorateRecordSchema(Schema inputSchema, @Nonnull List<Field> fieldList) { """ Decorate the {@link Schema} for a record with additional {@link Field}s. @param inputSchema: must be a {@link Record} schema. @return the decorated Schema. Fields are appended to the inputSchema. """ Preconditions.checkState(inputSchema.getType().equals(Type.RECORD)); List<Field> outputFields = deepCopySchemaFields(inputSchema); List<Field> newOutputFields = Stream.concat(outputFields.stream(), fieldList.stream()).collect(Collectors.toList()); Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(), inputSchema.getNamespace(), inputSchema.isError()); outputSchema.setFields(newOutputFields); copyProperties(inputSchema, outputSchema); return outputSchema; }
java
public static Schema decorateRecordSchema(Schema inputSchema, @Nonnull List<Field> fieldList) { Preconditions.checkState(inputSchema.getType().equals(Type.RECORD)); List<Field> outputFields = deepCopySchemaFields(inputSchema); List<Field> newOutputFields = Stream.concat(outputFields.stream(), fieldList.stream()).collect(Collectors.toList()); Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(), inputSchema.getNamespace(), inputSchema.isError()); outputSchema.setFields(newOutputFields); copyProperties(inputSchema, outputSchema); return outputSchema; }
[ "public", "static", "Schema", "decorateRecordSchema", "(", "Schema", "inputSchema", ",", "@", "Nonnull", "List", "<", "Field", ">", "fieldList", ")", "{", "Preconditions", ".", "checkState", "(", "inputSchema", ".", "getType", "(", ")", ".", "equals", "(", "Type", ".", "RECORD", ")", ")", ";", "List", "<", "Field", ">", "outputFields", "=", "deepCopySchemaFields", "(", "inputSchema", ")", ";", "List", "<", "Field", ">", "newOutputFields", "=", "Stream", ".", "concat", "(", "outputFields", ".", "stream", "(", ")", ",", "fieldList", ".", "stream", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "Schema", "outputSchema", "=", "Schema", ".", "createRecord", "(", "inputSchema", ".", "getName", "(", ")", ",", "inputSchema", ".", "getDoc", "(", ")", ",", "inputSchema", ".", "getNamespace", "(", ")", ",", "inputSchema", ".", "isError", "(", ")", ")", ";", "outputSchema", ".", "setFields", "(", "newOutputFields", ")", ";", "copyProperties", "(", "inputSchema", ",", "outputSchema", ")", ";", "return", "outputSchema", ";", "}" ]
Decorate the {@link Schema} for a record with additional {@link Field}s. @param inputSchema: must be a {@link Record} schema. @return the decorated Schema. Fields are appended to the inputSchema.
[ "Decorate", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java#L852-L862
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/converters/Converters.java
Converters.toDBObject
public void toDBObject(final Object containingObject, final MappedField mf, final DBObject dbObj, final MapperOptions opts) { """ Converts an entity to a DBObject @param containingObject The object to convert @param mf the MappedField to extract @param dbObj the DBObject to populate @param opts the options to apply """ final Object fieldValue = mf.getFieldValue(containingObject); final TypeConverter enc = getEncoder(fieldValue, mf); final Object encoded = enc.encode(fieldValue, mf); if (encoded != null || opts.isStoreNulls()) { dbObj.put(mf.getNameToStore(), encoded); } }
java
public void toDBObject(final Object containingObject, final MappedField mf, final DBObject dbObj, final MapperOptions opts) { final Object fieldValue = mf.getFieldValue(containingObject); final TypeConverter enc = getEncoder(fieldValue, mf); final Object encoded = enc.encode(fieldValue, mf); if (encoded != null || opts.isStoreNulls()) { dbObj.put(mf.getNameToStore(), encoded); } }
[ "public", "void", "toDBObject", "(", "final", "Object", "containingObject", ",", "final", "MappedField", "mf", ",", "final", "DBObject", "dbObj", ",", "final", "MapperOptions", "opts", ")", "{", "final", "Object", "fieldValue", "=", "mf", ".", "getFieldValue", "(", "containingObject", ")", ";", "final", "TypeConverter", "enc", "=", "getEncoder", "(", "fieldValue", ",", "mf", ")", ";", "final", "Object", "encoded", "=", "enc", ".", "encode", "(", "fieldValue", ",", "mf", ")", ";", "if", "(", "encoded", "!=", "null", "||", "opts", ".", "isStoreNulls", "(", ")", ")", "{", "dbObj", ".", "put", "(", "mf", ".", "getNameToStore", "(", ")", ",", "encoded", ")", ";", "}", "}" ]
Converts an entity to a DBObject @param containingObject The object to convert @param mf the MappedField to extract @param dbObj the DBObject to populate @param opts the options to apply
[ "Converts", "an", "entity", "to", "a", "DBObject" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/converters/Converters.java#L239-L247
facebookarchive/hadoop-20
src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderUtil.java
ServerLogReaderUtil.shouldSkipOp
static boolean shouldSkipOp(long currentTransactionId, FSEditLogOp op) { """ We would skip the transaction if its id is less than or equal to current transaction id. """ if (currentTransactionId == -1 || op.getTransactionId() > currentTransactionId) { return false; } return true; }
java
static boolean shouldSkipOp(long currentTransactionId, FSEditLogOp op) { if (currentTransactionId == -1 || op.getTransactionId() > currentTransactionId) { return false; } return true; }
[ "static", "boolean", "shouldSkipOp", "(", "long", "currentTransactionId", ",", "FSEditLogOp", "op", ")", "{", "if", "(", "currentTransactionId", "==", "-", "1", "||", "op", ".", "getTransactionId", "(", ")", ">", "currentTransactionId", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
We would skip the transaction if its id is less than or equal to current transaction id.
[ "We", "would", "skip", "the", "transaction", "if", "its", "id", "is", "less", "than", "or", "equal", "to", "current", "transaction", "id", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderUtil.java#L70-L77
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/index/SecondaryIndexManager.java
SecondaryIndexManager.maybeBuildSecondaryIndexes
public void maybeBuildSecondaryIndexes(Collection<SSTableReader> sstables, Set<String> idxNames) { """ Does a full, blocking rebuild of the indexes specified by columns from the sstables. Does nothing if columns is empty. Caller must acquire and release references to the sstables used here. @param sstables the data to build from @param idxNames the list of columns to index, ordered by comparator """ if (idxNames.isEmpty()) return; logger.info(String.format("Submitting index build of %s for data in %s", idxNames, StringUtils.join(sstables, ", "))); SecondaryIndexBuilder builder = new SecondaryIndexBuilder(baseCfs, idxNames, new ReducingKeyIterator(sstables)); Future<?> future = CompactionManager.instance.submitIndexBuild(builder); FBUtilities.waitOnFuture(future); flushIndexesBlocking(); logger.info("Index build of {} complete", idxNames); }
java
public void maybeBuildSecondaryIndexes(Collection<SSTableReader> sstables, Set<String> idxNames) { if (idxNames.isEmpty()) return; logger.info(String.format("Submitting index build of %s for data in %s", idxNames, StringUtils.join(sstables, ", "))); SecondaryIndexBuilder builder = new SecondaryIndexBuilder(baseCfs, idxNames, new ReducingKeyIterator(sstables)); Future<?> future = CompactionManager.instance.submitIndexBuild(builder); FBUtilities.waitOnFuture(future); flushIndexesBlocking(); logger.info("Index build of {} complete", idxNames); }
[ "public", "void", "maybeBuildSecondaryIndexes", "(", "Collection", "<", "SSTableReader", ">", "sstables", ",", "Set", "<", "String", ">", "idxNames", ")", "{", "if", "(", "idxNames", ".", "isEmpty", "(", ")", ")", "return", ";", "logger", ".", "info", "(", "String", ".", "format", "(", "\"Submitting index build of %s for data in %s\"", ",", "idxNames", ",", "StringUtils", ".", "join", "(", "sstables", ",", "\", \"", ")", ")", ")", ";", "SecondaryIndexBuilder", "builder", "=", "new", "SecondaryIndexBuilder", "(", "baseCfs", ",", "idxNames", ",", "new", "ReducingKeyIterator", "(", "sstables", ")", ")", ";", "Future", "<", "?", ">", "future", "=", "CompactionManager", ".", "instance", ".", "submitIndexBuild", "(", "builder", ")", ";", "FBUtilities", ".", "waitOnFuture", "(", "future", ")", ";", "flushIndexesBlocking", "(", ")", ";", "logger", ".", "info", "(", "\"Index build of {} complete\"", ",", "idxNames", ")", ";", "}" ]
Does a full, blocking rebuild of the indexes specified by columns from the sstables. Does nothing if columns is empty. Caller must acquire and release references to the sstables used here. @param sstables the data to build from @param idxNames the list of columns to index, ordered by comparator
[ "Does", "a", "full", "blocking", "rebuild", "of", "the", "indexes", "specified", "by", "columns", "from", "the", "sstables", ".", "Does", "nothing", "if", "columns", "is", "empty", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/index/SecondaryIndexManager.java#L157-L172
fcrepo4/fcrepo4
fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/utils/ContentDigest.java
ContentDigest.asURI
public static URI asURI(final String algorithm, final String value) { """ Convert a MessageDigest algorithm and checksum value to a URN @param algorithm the message digest algorithm @param value the checksum value @return URI """ try { final String scheme = DIGEST_ALGORITHM.getScheme(algorithm); return new URI(scheme, value, null); } catch (final URISyntaxException unlikelyException) { LOGGER.warn("Exception creating checksum URI: {}", unlikelyException); throw new RepositoryRuntimeException(unlikelyException); } }
java
public static URI asURI(final String algorithm, final String value) { try { final String scheme = DIGEST_ALGORITHM.getScheme(algorithm); return new URI(scheme, value, null); } catch (final URISyntaxException unlikelyException) { LOGGER.warn("Exception creating checksum URI: {}", unlikelyException); throw new RepositoryRuntimeException(unlikelyException); } }
[ "public", "static", "URI", "asURI", "(", "final", "String", "algorithm", ",", "final", "String", "value", ")", "{", "try", "{", "final", "String", "scheme", "=", "DIGEST_ALGORITHM", ".", "getScheme", "(", "algorithm", ")", ";", "return", "new", "URI", "(", "scheme", ",", "value", ",", "null", ")", ";", "}", "catch", "(", "final", "URISyntaxException", "unlikelyException", ")", "{", "LOGGER", ".", "warn", "(", "\"Exception creating checksum URI: {}\"", ",", "unlikelyException", ")", ";", "throw", "new", "RepositoryRuntimeException", "(", "unlikelyException", ")", ";", "}", "}" ]
Convert a MessageDigest algorithm and checksum value to a URN @param algorithm the message digest algorithm @param value the checksum value @return URI
[ "Convert", "a", "MessageDigest", "algorithm", "and", "checksum", "value", "to", "a", "URN" ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/utils/ContentDigest.java#L97-L107
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photosets/PhotosetsInterface.java
PhotosetsInterface.editMeta
public void editMeta(String photosetId, String title, String description) throws FlickrException { """ Modify the meta-data for a photoset. @param photosetId The photoset ID @param title A new title @param description A new description (can be null) @throws FlickrException """ Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_META); parameters.put("photoset_id", photosetId); parameters.put("title", title); if (description != null) { parameters.put("description", description); } Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void editMeta(String photosetId, String title, String description) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_EDIT_META); parameters.put("photoset_id", photosetId); parameters.put("title", title); if (description != null) { parameters.put("description", description); } Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "editMeta", "(", "String", "photosetId", ",", "String", "title", ",", "String", "description", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_EDIT_META", ")", ";", "parameters", ".", "put", "(", "\"photoset_id\"", ",", "photosetId", ")", ";", "parameters", ".", "put", "(", "\"title\"", ",", "title", ")", ";", "if", "(", "description", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"description\"", ",", "description", ")", ";", "}", "Response", "response", "=", "transportAPI", ".", "post", "(", "transportAPI", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Modify the meta-data for a photoset. @param photosetId The photoset ID @param title A new title @param description A new description (can be null) @throws FlickrException
[ "Modify", "the", "meta", "-", "data", "for", "a", "photoset", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photosets/PhotosetsInterface.java#L162-L176
alkacon/opencms-core
src/org/opencms/search/CmsSearchManager.java
CmsSearchManager.getDocumentFactory
public I_CmsDocumentFactory getDocumentFactory(CmsResource resource) { """ Returns a lucene document factory for given resource.<p> The type of the document factory is selected by the type of the resource and the MIME type of the resource content, according to the configuration in <code>opencms-search.xml</code>.<p> @param resource a cms resource @return a lucene document factory or null """ // first get the MIME type of the resource String mimeType = OpenCms.getResourceManager().getMimeType(resource.getRootPath(), null, "unknown"); String resourceType = null; try { resourceType = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getTypeName(); } catch (CmsLoaderException e) { // ignore, unknown resource type, resource can not be indexed LOG.info(e.getLocalizedMessage(), e); } return getDocumentFactory(resourceType, mimeType); }
java
public I_CmsDocumentFactory getDocumentFactory(CmsResource resource) { // first get the MIME type of the resource String mimeType = OpenCms.getResourceManager().getMimeType(resource.getRootPath(), null, "unknown"); String resourceType = null; try { resourceType = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getTypeName(); } catch (CmsLoaderException e) { // ignore, unknown resource type, resource can not be indexed LOG.info(e.getLocalizedMessage(), e); } return getDocumentFactory(resourceType, mimeType); }
[ "public", "I_CmsDocumentFactory", "getDocumentFactory", "(", "CmsResource", "resource", ")", "{", "// first get the MIME type of the resource", "String", "mimeType", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getMimeType", "(", "resource", ".", "getRootPath", "(", ")", ",", "null", ",", "\"unknown\"", ")", ";", "String", "resourceType", "=", "null", ";", "try", "{", "resourceType", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "resource", ".", "getTypeId", "(", ")", ")", ".", "getTypeName", "(", ")", ";", "}", "catch", "(", "CmsLoaderException", "e", ")", "{", "// ignore, unknown resource type, resource can not be indexed", "LOG", ".", "info", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "return", "getDocumentFactory", "(", "resourceType", ",", "mimeType", ")", ";", "}" ]
Returns a lucene document factory for given resource.<p> The type of the document factory is selected by the type of the resource and the MIME type of the resource content, according to the configuration in <code>opencms-search.xml</code>.<p> @param resource a cms resource @return a lucene document factory or null
[ "Returns", "a", "lucene", "document", "factory", "for", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchManager.java#L1116-L1128
sagiegurari/fax4j
src/main/java/org/fax4j/util/IOHelper.java
IOHelper.getFileFromPathList
public static File getFileFromPathList(String fileNameWithNoPath,String[] pathList) { """ This function returns the file object of the first location in which the requested file is found. @param fileNameWithNoPath The file name (with no directory path) @param pathList The path list @return The file object if found, else null will be returned """ File foundFile=null; if(pathList!=null) { //get amount int amount=pathList.length; String directoryPath=null; File file=null; for(int index=0;index<amount;index++) { //get next element directoryPath=pathList[index]; //get file file=new File(directoryPath,fileNameWithNoPath); if((file.exists())&&(file.isFile())) { foundFile=file; break; } } } return foundFile; }
java
public static File getFileFromPathList(String fileNameWithNoPath,String[] pathList) { File foundFile=null; if(pathList!=null) { //get amount int amount=pathList.length; String directoryPath=null; File file=null; for(int index=0;index<amount;index++) { //get next element directoryPath=pathList[index]; //get file file=new File(directoryPath,fileNameWithNoPath); if((file.exists())&&(file.isFile())) { foundFile=file; break; } } } return foundFile; }
[ "public", "static", "File", "getFileFromPathList", "(", "String", "fileNameWithNoPath", ",", "String", "[", "]", "pathList", ")", "{", "File", "foundFile", "=", "null", ";", "if", "(", "pathList", "!=", "null", ")", "{", "//get amount", "int", "amount", "=", "pathList", ".", "length", ";", "String", "directoryPath", "=", "null", ";", "File", "file", "=", "null", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "amount", ";", "index", "++", ")", "{", "//get next element", "directoryPath", "=", "pathList", "[", "index", "]", ";", "//get file", "file", "=", "new", "File", "(", "directoryPath", ",", "fileNameWithNoPath", ")", ";", "if", "(", "(", "file", ".", "exists", "(", ")", ")", "&&", "(", "file", ".", "isFile", "(", ")", ")", ")", "{", "foundFile", "=", "file", ";", "break", ";", "}", "}", "}", "return", "foundFile", ";", "}" ]
This function returns the file object of the first location in which the requested file is found. @param fileNameWithNoPath The file name (with no directory path) @param pathList The path list @return The file object if found, else null will be returned
[ "This", "function", "returns", "the", "file", "object", "of", "the", "first", "location", "in", "which", "the", "requested", "file", "is", "found", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/IOHelper.java#L491-L518
wildfly/wildfly-core
protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java
AbstractMessageHandler.safeWriteErrorResponse
protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) { """ Safe write error response. @param channel the channel @param header the request header @param error the exception """ if(header.getType() == ManagementProtocol.TYPE_REQUEST) { try { writeErrorResponse(channel, (ManagementRequestHeader) header, error); } catch(IOException ioe) { ProtocolLogger.ROOT_LOGGER.tracef(ioe, "failed to write error response for %s on channel: %s", header, channel); } } }
java
protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) { if(header.getType() == ManagementProtocol.TYPE_REQUEST) { try { writeErrorResponse(channel, (ManagementRequestHeader) header, error); } catch(IOException ioe) { ProtocolLogger.ROOT_LOGGER.tracef(ioe, "failed to write error response for %s on channel: %s", header, channel); } } }
[ "protected", "static", "void", "safeWriteErrorResponse", "(", "final", "Channel", "channel", ",", "final", "ManagementProtocolHeader", "header", ",", "final", "Throwable", "error", ")", "{", "if", "(", "header", ".", "getType", "(", ")", "==", "ManagementProtocol", ".", "TYPE_REQUEST", ")", "{", "try", "{", "writeErrorResponse", "(", "channel", ",", "(", "ManagementRequestHeader", ")", "header", ",", "error", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "ProtocolLogger", ".", "ROOT_LOGGER", ".", "tracef", "(", "ioe", ",", "\"failed to write error response for %s on channel: %s\"", ",", "header", ",", "channel", ")", ";", "}", "}", "}" ]
Safe write error response. @param channel the channel @param header the request header @param error the exception
[ "Safe", "write", "error", "response", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/protocol/src/main/java/org/jboss/as/protocol/mgmt/AbstractMessageHandler.java#L489-L497
gfk-ba/senbot
SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/ElementService.java
ElementService.viewShouldNotShowElement
public void viewShouldNotShowElement(String viewName, String elementName) throws IllegalAccessException, InterruptedException { """ The referenced view should not show the element identified by elementName @param viewName @param elementName @throws IllegalAccessException @throws InterruptedException """ boolean pass = false; long startOfLookup = System.currentTimeMillis(); int timeoutInMillies = getSeleniumManager().getTimeout() * 1000; while (!pass) { WebElement found = getElementFromReferencedView(viewName, elementName); try { pass = !found.isDisplayed(); } catch (NoSuchElementException e) { pass = true; } if (!pass) { Thread.sleep(100); } if (System.currentTimeMillis() - startOfLookup > timeoutInMillies) { String foundLocator = getElementLocatorFromReferencedView(viewName, elementName); fail("The element \"" + foundLocator + "\" referenced by \"" + elementName + "\" on view/page \"" + viewName + "\" is still found where it is not expected after " + getSeleniumManager().getTimeout() + " seconds."); break; } } }
java
public void viewShouldNotShowElement(String viewName, String elementName) throws IllegalAccessException, InterruptedException { boolean pass = false; long startOfLookup = System.currentTimeMillis(); int timeoutInMillies = getSeleniumManager().getTimeout() * 1000; while (!pass) { WebElement found = getElementFromReferencedView(viewName, elementName); try { pass = !found.isDisplayed(); } catch (NoSuchElementException e) { pass = true; } if (!pass) { Thread.sleep(100); } if (System.currentTimeMillis() - startOfLookup > timeoutInMillies) { String foundLocator = getElementLocatorFromReferencedView(viewName, elementName); fail("The element \"" + foundLocator + "\" referenced by \"" + elementName + "\" on view/page \"" + viewName + "\" is still found where it is not expected after " + getSeleniumManager().getTimeout() + " seconds."); break; } } }
[ "public", "void", "viewShouldNotShowElement", "(", "String", "viewName", ",", "String", "elementName", ")", "throws", "IllegalAccessException", ",", "InterruptedException", "{", "boolean", "pass", "=", "false", ";", "long", "startOfLookup", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "int", "timeoutInMillies", "=", "getSeleniumManager", "(", ")", ".", "getTimeout", "(", ")", "*", "1000", ";", "while", "(", "!", "pass", ")", "{", "WebElement", "found", "=", "getElementFromReferencedView", "(", "viewName", ",", "elementName", ")", ";", "try", "{", "pass", "=", "!", "found", ".", "isDisplayed", "(", ")", ";", "}", "catch", "(", "NoSuchElementException", "e", ")", "{", "pass", "=", "true", ";", "}", "if", "(", "!", "pass", ")", "{", "Thread", ".", "sleep", "(", "100", ")", ";", "}", "if", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startOfLookup", ">", "timeoutInMillies", ")", "{", "String", "foundLocator", "=", "getElementLocatorFromReferencedView", "(", "viewName", ",", "elementName", ")", ";", "fail", "(", "\"The element \\\"\"", "+", "foundLocator", "+", "\"\\\" referenced by \\\"\"", "+", "elementName", "+", "\"\\\" on view/page \\\"\"", "+", "viewName", "+", "\"\\\" is still found where it is not expected after \"", "+", "getSeleniumManager", "(", ")", ".", "getTimeout", "(", ")", "+", "\" seconds.\"", ")", ";", "break", ";", "}", "}", "}" ]
The referenced view should not show the element identified by elementName @param viewName @param elementName @throws IllegalAccessException @throws InterruptedException
[ "The", "referenced", "view", "should", "not", "show", "the", "element", "identified", "by", "elementName" ]
train
https://github.com/gfk-ba/senbot/blob/e9a152aa67be48b1bb13a4691655caf6d873b553/SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/ElementService.java#L488-L514
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_vrack_vrack_GET
public OvhDedicatedCloud serviceName_vrack_vrack_GET(String serviceName, String vrack) throws IOException { """ Get this object properties REST: GET /dedicatedCloud/{serviceName}/vrack/{vrack} @param serviceName [required] Domain of the service @param vrack [required] vrack name """ String qPath = "/dedicatedCloud/{serviceName}/vrack/{vrack}"; StringBuilder sb = path(qPath, serviceName, vrack); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDedicatedCloud.class); }
java
public OvhDedicatedCloud serviceName_vrack_vrack_GET(String serviceName, String vrack) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/vrack/{vrack}"; StringBuilder sb = path(qPath, serviceName, vrack); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDedicatedCloud.class); }
[ "public", "OvhDedicatedCloud", "serviceName_vrack_vrack_GET", "(", "String", "serviceName", ",", "String", "vrack", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/{serviceName}/vrack/{vrack}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "vrack", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhDedicatedCloud", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /dedicatedCloud/{serviceName}/vrack/{vrack} @param serviceName [required] Domain of the service @param vrack [required] vrack name
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1256-L1261
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.executeConnectionAsync
public static RequestAsyncTask executeConnectionAsync(Handler callbackHandler, HttpURLConnection connection, RequestBatch requests) { """ Asynchronously executes requests that have already been serialized into an HttpURLConnection. No validation is done that the contents of the connection actually reflect the serialized requests, so it is the caller's responsibility to ensure that it will correctly generate the desired responses. This function will return immediately, and the requests will be processed on a separate thread. In order to process results of a request, or determine whether a request succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method) <p/> This should only be called from the UI thread. @param callbackHandler a Handler that will be used to post calls to the callback for each request; if null, a Handler will be instantiated on the calling thread @param connection the HttpURLConnection that the requests were serialized into @param requests the requests represented by the HttpURLConnection @return a RequestAsyncTask that is executing the request """ Validate.notNull(connection, "connection"); RequestAsyncTask asyncTask = new RequestAsyncTask(connection, requests); requests.setCallbackHandler(callbackHandler); asyncTask.executeOnSettingsExecutor(); return asyncTask; }
java
public static RequestAsyncTask executeConnectionAsync(Handler callbackHandler, HttpURLConnection connection, RequestBatch requests) { Validate.notNull(connection, "connection"); RequestAsyncTask asyncTask = new RequestAsyncTask(connection, requests); requests.setCallbackHandler(callbackHandler); asyncTask.executeOnSettingsExecutor(); return asyncTask; }
[ "public", "static", "RequestAsyncTask", "executeConnectionAsync", "(", "Handler", "callbackHandler", ",", "HttpURLConnection", "connection", ",", "RequestBatch", "requests", ")", "{", "Validate", ".", "notNull", "(", "connection", ",", "\"connection\"", ")", ";", "RequestAsyncTask", "asyncTask", "=", "new", "RequestAsyncTask", "(", "connection", ",", "requests", ")", ";", "requests", ".", "setCallbackHandler", "(", "callbackHandler", ")", ";", "asyncTask", ".", "executeOnSettingsExecutor", "(", ")", ";", "return", "asyncTask", ";", "}" ]
Asynchronously executes requests that have already been serialized into an HttpURLConnection. No validation is done that the contents of the connection actually reflect the serialized requests, so it is the caller's responsibility to ensure that it will correctly generate the desired responses. This function will return immediately, and the requests will be processed on a separate thread. In order to process results of a request, or determine whether a request succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method) <p/> This should only be called from the UI thread. @param callbackHandler a Handler that will be used to post calls to the callback for each request; if null, a Handler will be instantiated on the calling thread @param connection the HttpURLConnection that the requests were serialized into @param requests the requests represented by the HttpURLConnection @return a RequestAsyncTask that is executing the request
[ "Asynchronously", "executes", "requests", "that", "have", "already", "been", "serialized", "into", "an", "HttpURLConnection", ".", "No", "validation", "is", "done", "that", "the", "contents", "of", "the", "connection", "actually", "reflect", "the", "serialized", "requests", "so", "it", "is", "the", "caller", "s", "responsibility", "to", "ensure", "that", "it", "will", "correctly", "generate", "the", "desired", "responses", ".", "This", "function", "will", "return", "immediately", "and", "the", "requests", "will", "be", "processed", "on", "a", "separate", "thread", ".", "In", "order", "to", "process", "results", "of", "a", "request", "or", "determine", "whether", "a", "request", "succeeded", "or", "failed", "a", "callback", "must", "be", "specified", "(", "see", "the", "{", "@link", "#setCallback", "(", "Callback", ")", "setCallback", "}", "method", ")", "<p", "/", ">", "This", "should", "only", "be", "called", "from", "the", "UI", "thread", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1619-L1627
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/constraint/RelatedControl.java
RelatedControl.generate
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { """ According to the relation between PhysicalEntity and the Conversion, checks of the Control is relevant. If relevant it is retrieved. @param match current pattern match @param ind mapped indices @return related controls """ PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); Conversion conv = (Conversion) match.get(ind[1]); if (!((peType == RelType.INPUT && getConvParticipants(conv, RelType.INPUT).contains(pe)) || (peType == RelType.OUTPUT && getConvParticipants(conv, RelType.OUTPUT).contains(pe)))) throw new IllegalArgumentException("peType = " + peType + ", and related participant set does not contain this PE. Conv dir = " + getDirection(conv) + " conv.id=" + conv.getUri() + " pe.id=" +pe.getUri()); boolean rightContains = conv.getRight().contains(pe); boolean leftContains = conv.getLeft().contains(pe); assert rightContains || leftContains : "PE is not a participant."; Set<BioPAXElement> result = new HashSet<BioPAXElement>(); ConversionDirectionType avoidDir = (leftContains && rightContains) ? null : peType == RelType.OUTPUT ? (leftContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT) : (rightContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT); for (Object o : controlledOf.getValueFromBean(conv)) { Control ctrl = (Control) o; ConversionDirectionType dir = getDirection(conv, ctrl); if (avoidDir != null && dir == avoidDir) continue; // don't collect this if the pe is ubique in the context of this control if (blacklist != null && blacklist.isUbique(pe, conv, dir, peType)) continue; result.add(ctrl); } return result; }
java
@Override public Collection<BioPAXElement> generate(Match match, int... ind) { PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]); Conversion conv = (Conversion) match.get(ind[1]); if (!((peType == RelType.INPUT && getConvParticipants(conv, RelType.INPUT).contains(pe)) || (peType == RelType.OUTPUT && getConvParticipants(conv, RelType.OUTPUT).contains(pe)))) throw new IllegalArgumentException("peType = " + peType + ", and related participant set does not contain this PE. Conv dir = " + getDirection(conv) + " conv.id=" + conv.getUri() + " pe.id=" +pe.getUri()); boolean rightContains = conv.getRight().contains(pe); boolean leftContains = conv.getLeft().contains(pe); assert rightContains || leftContains : "PE is not a participant."; Set<BioPAXElement> result = new HashSet<BioPAXElement>(); ConversionDirectionType avoidDir = (leftContains && rightContains) ? null : peType == RelType.OUTPUT ? (leftContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT) : (rightContains ? ConversionDirectionType.LEFT_TO_RIGHT : ConversionDirectionType.RIGHT_TO_LEFT); for (Object o : controlledOf.getValueFromBean(conv)) { Control ctrl = (Control) o; ConversionDirectionType dir = getDirection(conv, ctrl); if (avoidDir != null && dir == avoidDir) continue; // don't collect this if the pe is ubique in the context of this control if (blacklist != null && blacklist.isUbique(pe, conv, dir, peType)) continue; result.add(ctrl); } return result; }
[ "@", "Override", "public", "Collection", "<", "BioPAXElement", ">", "generate", "(", "Match", "match", ",", "int", "...", "ind", ")", "{", "PhysicalEntity", "pe", "=", "(", "PhysicalEntity", ")", "match", ".", "get", "(", "ind", "[", "0", "]", ")", ";", "Conversion", "conv", "=", "(", "Conversion", ")", "match", ".", "get", "(", "ind", "[", "1", "]", ")", ";", "if", "(", "!", "(", "(", "peType", "==", "RelType", ".", "INPUT", "&&", "getConvParticipants", "(", "conv", ",", "RelType", ".", "INPUT", ")", ".", "contains", "(", "pe", ")", ")", "||", "(", "peType", "==", "RelType", ".", "OUTPUT", "&&", "getConvParticipants", "(", "conv", ",", "RelType", ".", "OUTPUT", ")", ".", "contains", "(", "pe", ")", ")", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"peType = \"", "+", "peType", "+", "\", and related participant set does not contain this PE. Conv dir = \"", "+", "getDirection", "(", "conv", ")", "+", "\" conv.id=\"", "+", "conv", ".", "getUri", "(", ")", "+", "\" pe.id=\"", "+", "pe", ".", "getUri", "(", ")", ")", ";", "boolean", "rightContains", "=", "conv", ".", "getRight", "(", ")", ".", "contains", "(", "pe", ")", ";", "boolean", "leftContains", "=", "conv", ".", "getLeft", "(", ")", ".", "contains", "(", "pe", ")", ";", "assert", "rightContains", "||", "leftContains", ":", "\"PE is not a participant.\"", ";", "Set", "<", "BioPAXElement", ">", "result", "=", "new", "HashSet", "<", "BioPAXElement", ">", "(", ")", ";", "ConversionDirectionType", "avoidDir", "=", "(", "leftContains", "&&", "rightContains", ")", "?", "null", ":", "peType", "==", "RelType", ".", "OUTPUT", "?", "(", "leftContains", "?", "ConversionDirectionType", ".", "LEFT_TO_RIGHT", ":", "ConversionDirectionType", ".", "RIGHT_TO_LEFT", ")", ":", "(", "rightContains", "?", "ConversionDirectionType", ".", "LEFT_TO_RIGHT", ":", "ConversionDirectionType", ".", "RIGHT_TO_LEFT", ")", ";", "for", "(", "Object", "o", ":", "controlledOf", ".", "getValueFromBean", "(", "conv", ")", ")", "{", "Control", "ctrl", "=", "(", "Control", ")", "o", ";", "ConversionDirectionType", "dir", "=", "getDirection", "(", "conv", ",", "ctrl", ")", ";", "if", "(", "avoidDir", "!=", "null", "&&", "dir", "==", "avoidDir", ")", "continue", ";", "// don't collect this if the pe is ubique in the context of this control", "if", "(", "blacklist", "!=", "null", "&&", "blacklist", ".", "isUbique", "(", "pe", ",", "conv", ",", "dir", ",", "peType", ")", ")", "continue", ";", "result", ".", "add", "(", "ctrl", ")", ";", "}", "return", "result", ";", "}" ]
According to the relation between PhysicalEntity and the Conversion, checks of the Control is relevant. If relevant it is retrieved. @param match current pattern match @param ind mapped indices @return related controls
[ "According", "to", "the", "relation", "between", "PhysicalEntity", "and", "the", "Conversion", "checks", "of", "the", "Control", "is", "relevant", ".", "If", "relevant", "it", "is", "retrieved", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/RelatedControl.java#L74-L110
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.getAt
@SuppressWarnings("unchecked") public static List<Long> getAt(long[] array, Collection indices) { """ Support the subscript operator with a collection for a long array @param array a long array @param indices a collection of indices for the items to retrieve @return list of the longs at the given indices @since 1.0 """ return primitiveArrayGet(array, indices); }
java
@SuppressWarnings("unchecked") public static List<Long> getAt(long[] array, Collection indices) { return primitiveArrayGet(array, indices); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "List", "<", "Long", ">", "getAt", "(", "long", "[", "]", "array", ",", "Collection", "indices", ")", "{", "return", "primitiveArrayGet", "(", "array", ",", "indices", ")", ";", "}" ]
Support the subscript operator with a collection for a long array @param array a long array @param indices a collection of indices for the items to retrieve @return list of the longs at the given indices @since 1.0
[ "Support", "the", "subscript", "operator", "with", "a", "collection", "for", "a", "long", "array" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13990-L13993
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.lifecycleQueryChaincodeDefinition
public Collection<LifecycleQueryChaincodeDefinitionProposalResponse> lifecycleQueryChaincodeDefinition( QueryLifecycleQueryChaincodeDefinitionRequest queryLifecycleQueryChaincodeDefinitionRequest, Collection<Peer> peers) throws InvalidArgumentException, ProposalException { """ lifecycleQueryChaincodeDefinition get definition of chaincode. @param queryLifecycleQueryChaincodeDefinitionRequest The request see {@link QueryLifecycleQueryChaincodeDefinitionRequest} @param peers The peers to send the request to. @return A {@link LifecycleQueryChaincodeDefinitionProposalResponse} @throws InvalidArgumentException @throws ProposalException """ if (null == queryLifecycleQueryChaincodeDefinitionRequest) { throw new InvalidArgumentException("The queryLifecycleQueryChaincodeDefinitionRequest parameter can not be null."); } checkChannelState(); checkPeers(peers); try { logger.trace(format("LifecycleQueryChaincodeDefinition channel: %s, chaincode name: %s", name, queryLifecycleQueryChaincodeDefinitionRequest.getChaincodeName())); TransactionContext context = getTransactionContext(queryLifecycleQueryChaincodeDefinitionRequest); LifecycleQueryChaincodeDefinitionBuilder lifecycleQueryChaincodeDefinitionBuilder = LifecycleQueryChaincodeDefinitionBuilder.newBuilder(); lifecycleQueryChaincodeDefinitionBuilder.context(context).setChaincodeName(queryLifecycleQueryChaincodeDefinitionRequest.getChaincodeName()); SignedProposal qProposal = getSignedProposal(context, lifecycleQueryChaincodeDefinitionBuilder.build()); return sendProposalToPeers(peers, qProposal, context, LifecycleQueryChaincodeDefinitionProposalResponse.class); } catch (ProposalException e) { throw e; } catch (Exception e) { throw new ProposalException(format("Query for peer %s channels failed. " + e.getMessage(), name), e); } }
java
public Collection<LifecycleQueryChaincodeDefinitionProposalResponse> lifecycleQueryChaincodeDefinition( QueryLifecycleQueryChaincodeDefinitionRequest queryLifecycleQueryChaincodeDefinitionRequest, Collection<Peer> peers) throws InvalidArgumentException, ProposalException { if (null == queryLifecycleQueryChaincodeDefinitionRequest) { throw new InvalidArgumentException("The queryLifecycleQueryChaincodeDefinitionRequest parameter can not be null."); } checkChannelState(); checkPeers(peers); try { logger.trace(format("LifecycleQueryChaincodeDefinition channel: %s, chaincode name: %s", name, queryLifecycleQueryChaincodeDefinitionRequest.getChaincodeName())); TransactionContext context = getTransactionContext(queryLifecycleQueryChaincodeDefinitionRequest); LifecycleQueryChaincodeDefinitionBuilder lifecycleQueryChaincodeDefinitionBuilder = LifecycleQueryChaincodeDefinitionBuilder.newBuilder(); lifecycleQueryChaincodeDefinitionBuilder.context(context).setChaincodeName(queryLifecycleQueryChaincodeDefinitionRequest.getChaincodeName()); SignedProposal qProposal = getSignedProposal(context, lifecycleQueryChaincodeDefinitionBuilder.build()); return sendProposalToPeers(peers, qProposal, context, LifecycleQueryChaincodeDefinitionProposalResponse.class); } catch (ProposalException e) { throw e; } catch (Exception e) { throw new ProposalException(format("Query for peer %s channels failed. " + e.getMessage(), name), e); } }
[ "public", "Collection", "<", "LifecycleQueryChaincodeDefinitionProposalResponse", ">", "lifecycleQueryChaincodeDefinition", "(", "QueryLifecycleQueryChaincodeDefinitionRequest", "queryLifecycleQueryChaincodeDefinitionRequest", ",", "Collection", "<", "Peer", ">", "peers", ")", "throws", "InvalidArgumentException", ",", "ProposalException", "{", "if", "(", "null", "==", "queryLifecycleQueryChaincodeDefinitionRequest", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"The queryLifecycleQueryChaincodeDefinitionRequest parameter can not be null.\"", ")", ";", "}", "checkChannelState", "(", ")", ";", "checkPeers", "(", "peers", ")", ";", "try", "{", "logger", ".", "trace", "(", "format", "(", "\"LifecycleQueryChaincodeDefinition channel: %s, chaincode name: %s\"", ",", "name", ",", "queryLifecycleQueryChaincodeDefinitionRequest", ".", "getChaincodeName", "(", ")", ")", ")", ";", "TransactionContext", "context", "=", "getTransactionContext", "(", "queryLifecycleQueryChaincodeDefinitionRequest", ")", ";", "LifecycleQueryChaincodeDefinitionBuilder", "lifecycleQueryChaincodeDefinitionBuilder", "=", "LifecycleQueryChaincodeDefinitionBuilder", ".", "newBuilder", "(", ")", ";", "lifecycleQueryChaincodeDefinitionBuilder", ".", "context", "(", "context", ")", ".", "setChaincodeName", "(", "queryLifecycleQueryChaincodeDefinitionRequest", ".", "getChaincodeName", "(", ")", ")", ";", "SignedProposal", "qProposal", "=", "getSignedProposal", "(", "context", ",", "lifecycleQueryChaincodeDefinitionBuilder", ".", "build", "(", ")", ")", ";", "return", "sendProposalToPeers", "(", "peers", ",", "qProposal", ",", "context", ",", "LifecycleQueryChaincodeDefinitionProposalResponse", ".", "class", ")", ";", "}", "catch", "(", "ProposalException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ProposalException", "(", "format", "(", "\"Query for peer %s channels failed. \"", "+", "e", ".", "getMessage", "(", ")", ",", "name", ")", ",", "e", ")", ";", "}", "}" ]
lifecycleQueryChaincodeDefinition get definition of chaincode. @param queryLifecycleQueryChaincodeDefinitionRequest The request see {@link QueryLifecycleQueryChaincodeDefinitionRequest} @param peers The peers to send the request to. @return A {@link LifecycleQueryChaincodeDefinitionProposalResponse} @throws InvalidArgumentException @throws ProposalException
[ "lifecycleQueryChaincodeDefinition", "get", "definition", "of", "chaincode", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L3828-L3855
Azure/azure-sdk-for-java
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java
ResourcesInner.beginCreateOrUpdate
public GenericResourceInner beginCreateOrUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) { """ Creates a resource. @param resourceGroupName The name of the resource group for the resource. The name is case insensitive. @param resourceProviderNamespace The namespace of the resource provider. @param parentResourcePath The parent resource identity. @param resourceType The resource type of the resource to create. @param resourceName The name of the resource to create. @param apiVersion The API version to use for the operation. @param parameters Parameters for creating or updating the resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the GenericResourceInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body(); }
java
public GenericResourceInner beginCreateOrUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body(); }
[ "public", "GenericResourceInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "resourceProviderNamespace", ",", "String", "parentResourcePath", ",", "String", "resourceType", ",", "String", "resourceName", ",", "String", "apiVersion", ",", "GenericResourceInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceProviderNamespace", ",", "parentResourcePath", ",", "resourceType", ",", "resourceName", ",", "apiVersion", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a resource. @param resourceGroupName The name of the resource group for the resource. The name is case insensitive. @param resourceProviderNamespace The namespace of the resource provider. @param parentResourcePath The parent resource identity. @param resourceType The resource type of the resource to create. @param resourceName The name of the resource to create. @param apiVersion The API version to use for the operation. @param parameters Parameters for creating or updating the resource. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the GenericResourceInner object if successful.
[ "Creates", "a", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L1396-L1398
GoogleCloudPlatform/app-gradle-plugin
src/main/java/com/google/cloud/tools/gradle/appengine/core/DeployTargetResolver.java
DeployTargetResolver.getProject
public String getProject(String configString) { """ Process user configuration of "projectId". If set to GCLOUD_CONFIG then read from gcloud's global state. If set but not a keyword then just return the set value. """ if (configString == null || configString.trim().isEmpty() || configString.equals(APPENGINE_CONFIG)) { throw new GradleException(PROJECT_ERROR); } if (configString.equals(GCLOUD_CONFIG)) { try { String gcloudProject = cloudSdkOperations.getGcloud().getConfig().getProject(); if (gcloudProject == null || gcloudProject.trim().isEmpty()) { throw new GradleException("Project was not found in gcloud config"); } return gcloudProject; } catch (IOException | CloudSdkOutOfDateException | ProcessHandlerException | CloudSdkNotFoundException | CloudSdkVersionFileException ex) { throw new GradleException("Failed to read project from gcloud config", ex); } } return configString; }
java
public String getProject(String configString) { if (configString == null || configString.trim().isEmpty() || configString.equals(APPENGINE_CONFIG)) { throw new GradleException(PROJECT_ERROR); } if (configString.equals(GCLOUD_CONFIG)) { try { String gcloudProject = cloudSdkOperations.getGcloud().getConfig().getProject(); if (gcloudProject == null || gcloudProject.trim().isEmpty()) { throw new GradleException("Project was not found in gcloud config"); } return gcloudProject; } catch (IOException | CloudSdkOutOfDateException | ProcessHandlerException | CloudSdkNotFoundException | CloudSdkVersionFileException ex) { throw new GradleException("Failed to read project from gcloud config", ex); } } return configString; }
[ "public", "String", "getProject", "(", "String", "configString", ")", "{", "if", "(", "configString", "==", "null", "||", "configString", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", "||", "configString", ".", "equals", "(", "APPENGINE_CONFIG", ")", ")", "{", "throw", "new", "GradleException", "(", "PROJECT_ERROR", ")", ";", "}", "if", "(", "configString", ".", "equals", "(", "GCLOUD_CONFIG", ")", ")", "{", "try", "{", "String", "gcloudProject", "=", "cloudSdkOperations", ".", "getGcloud", "(", ")", ".", "getConfig", "(", ")", ".", "getProject", "(", ")", ";", "if", "(", "gcloudProject", "==", "null", "||", "gcloudProject", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "GradleException", "(", "\"Project was not found in gcloud config\"", ")", ";", "}", "return", "gcloudProject", ";", "}", "catch", "(", "IOException", "|", "CloudSdkOutOfDateException", "|", "ProcessHandlerException", "|", "CloudSdkNotFoundException", "|", "CloudSdkVersionFileException", "ex", ")", "{", "throw", "new", "GradleException", "(", "\"Failed to read project from gcloud config\"", ",", "ex", ")", ";", "}", "}", "return", "configString", ";", "}" ]
Process user configuration of "projectId". If set to GCLOUD_CONFIG then read from gcloud's global state. If set but not a keyword then just return the set value.
[ "Process", "user", "configuration", "of", "projectId", ".", "If", "set", "to", "GCLOUD_CONFIG", "then", "read", "from", "gcloud", "s", "global", "state", ".", "If", "set", "but", "not", "a", "keyword", "then", "just", "return", "the", "set", "value", "." ]
train
https://github.com/GoogleCloudPlatform/app-gradle-plugin/blob/86d44fe0668e28f55eee9e002d5e19f0041efa3c/src/main/java/com/google/cloud/tools/gradle/appengine/core/DeployTargetResolver.java#L61-L83
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.switchToCoaching
public ApiSuccessResponse switchToCoaching(String id, MonitoringScopeData monitoringScopeData) throws ApiException { """ Switch to coach Switch to the coach monitoring mode. When coaching is enabled and the agent receives a call, the supervisor is brought into the call. Only the agent can hear the supervisor. @param id The connection ID of the call being monitored. (required) @param monitoringScopeData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = switchToCoachingWithHttpInfo(id, monitoringScopeData); return resp.getData(); }
java
public ApiSuccessResponse switchToCoaching(String id, MonitoringScopeData monitoringScopeData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = switchToCoachingWithHttpInfo(id, monitoringScopeData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "switchToCoaching", "(", "String", "id", ",", "MonitoringScopeData", "monitoringScopeData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "switchToCoachingWithHttpInfo", "(", "id", ",", "monitoringScopeData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Switch to coach Switch to the coach monitoring mode. When coaching is enabled and the agent receives a call, the supervisor is brought into the call. Only the agent can hear the supervisor. @param id The connection ID of the call being monitored. (required) @param monitoringScopeData (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Switch", "to", "coach", "Switch", "to", "the", "coach", "monitoring", "mode", ".", "When", "coaching", "is", "enabled", "and", "the", "agent", "receives", "a", "call", "the", "supervisor", "is", "brought", "into", "the", "call", ".", "Only", "the", "agent", "can", "hear", "the", "supervisor", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L5099-L5102
CenturyLinkCloud/mdw
mdw-workflow/assets/com/centurylink/mdw/routing/RoutingServiceMonitor.java
RoutingServiceMonitor.getRoutingStrategyDestination
protected URL getRoutingStrategyDestination(Object request, Map<String,String> headers) { """ Returns an instance of the first applicable routing strategy found based on priority of each strategy, or null if none return a URL. """ for (RequestRoutingStrategy routingStrategy : MdwServiceRegistry.getInstance().getRequestRoutingStrategies()) { URL destination = routingStrategy.getDestination(request, headers); if (destination != null) { // Only return a destination if it is not itself (identical call) - Avoid infinite loop // int queryIdx = destination.toString().indexOf("?"); URL origRequestUrl = null; try { origRequestUrl = new URL(headers.get(Listener.METAINFO_REQUEST_URL)); } catch (MalformedURLException e) { logger.severeException("Malformed original RequestURL", e); } String origHost = origRequestUrl.getHost().indexOf(".") > 0 ? origRequestUrl.getHost().substring(0, origRequestUrl.getHost().indexOf(".")) : origRequestUrl.getHost(); int origPort = origRequestUrl.getPort() == 80 || origRequestUrl.getPort() == 443 ? -1 : origRequestUrl.getPort(); String origQuery = headers.get(Listener.METAINFO_REQUEST_QUERY_STRING) == null ? "" : headers.get(Listener.METAINFO_REQUEST_QUERY_STRING); String newHost = destination.getHost().indexOf(".") > 0 ? destination.getHost().substring(0, destination.getHost().indexOf(".")) : destination.getHost(); int newPort = destination.getPort() == 80 || destination.getPort() == 443 ? -1 : destination.getPort(); String newQuery = destination.getQuery() == null ? "" : destination.getQuery(); if (!newHost.equalsIgnoreCase(origHost) || !(newPort == origPort) || !newQuery.equalsIgnoreCase(origQuery) || !origRequestUrl.getPath().equals(destination.getPath())) return destination; } } return null; }
java
protected URL getRoutingStrategyDestination(Object request, Map<String,String> headers) { for (RequestRoutingStrategy routingStrategy : MdwServiceRegistry.getInstance().getRequestRoutingStrategies()) { URL destination = routingStrategy.getDestination(request, headers); if (destination != null) { // Only return a destination if it is not itself (identical call) - Avoid infinite loop // int queryIdx = destination.toString().indexOf("?"); URL origRequestUrl = null; try { origRequestUrl = new URL(headers.get(Listener.METAINFO_REQUEST_URL)); } catch (MalformedURLException e) { logger.severeException("Malformed original RequestURL", e); } String origHost = origRequestUrl.getHost().indexOf(".") > 0 ? origRequestUrl.getHost().substring(0, origRequestUrl.getHost().indexOf(".")) : origRequestUrl.getHost(); int origPort = origRequestUrl.getPort() == 80 || origRequestUrl.getPort() == 443 ? -1 : origRequestUrl.getPort(); String origQuery = headers.get(Listener.METAINFO_REQUEST_QUERY_STRING) == null ? "" : headers.get(Listener.METAINFO_REQUEST_QUERY_STRING); String newHost = destination.getHost().indexOf(".") > 0 ? destination.getHost().substring(0, destination.getHost().indexOf(".")) : destination.getHost(); int newPort = destination.getPort() == 80 || destination.getPort() == 443 ? -1 : destination.getPort(); String newQuery = destination.getQuery() == null ? "" : destination.getQuery(); if (!newHost.equalsIgnoreCase(origHost) || !(newPort == origPort) || !newQuery.equalsIgnoreCase(origQuery) || !origRequestUrl.getPath().equals(destination.getPath())) return destination; } } return null; }
[ "protected", "URL", "getRoutingStrategyDestination", "(", "Object", "request", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "for", "(", "RequestRoutingStrategy", "routingStrategy", ":", "MdwServiceRegistry", ".", "getInstance", "(", ")", ".", "getRequestRoutingStrategies", "(", ")", ")", "{", "URL", "destination", "=", "routingStrategy", ".", "getDestination", "(", "request", ",", "headers", ")", ";", "if", "(", "destination", "!=", "null", ")", "{", "// Only return a destination if it is not itself (identical call) - Avoid infinite loop", "// int queryIdx = destination.toString().indexOf(\"?\");", "URL", "origRequestUrl", "=", "null", ";", "try", "{", "origRequestUrl", "=", "new", "URL", "(", "headers", ".", "get", "(", "Listener", ".", "METAINFO_REQUEST_URL", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "logger", ".", "severeException", "(", "\"Malformed original RequestURL\"", ",", "e", ")", ";", "}", "String", "origHost", "=", "origRequestUrl", ".", "getHost", "(", ")", ".", "indexOf", "(", "\".\"", ")", ">", "0", "?", "origRequestUrl", ".", "getHost", "(", ")", ".", "substring", "(", "0", ",", "origRequestUrl", ".", "getHost", "(", ")", ".", "indexOf", "(", "\".\"", ")", ")", ":", "origRequestUrl", ".", "getHost", "(", ")", ";", "int", "origPort", "=", "origRequestUrl", ".", "getPort", "(", ")", "==", "80", "||", "origRequestUrl", ".", "getPort", "(", ")", "==", "443", "?", "-", "1", ":", "origRequestUrl", ".", "getPort", "(", ")", ";", "String", "origQuery", "=", "headers", ".", "get", "(", "Listener", ".", "METAINFO_REQUEST_QUERY_STRING", ")", "==", "null", "?", "\"\"", ":", "headers", ".", "get", "(", "Listener", ".", "METAINFO_REQUEST_QUERY_STRING", ")", ";", "String", "newHost", "=", "destination", ".", "getHost", "(", ")", ".", "indexOf", "(", "\".\"", ")", ">", "0", "?", "destination", ".", "getHost", "(", ")", ".", "substring", "(", "0", ",", "destination", ".", "getHost", "(", ")", ".", "indexOf", "(", "\".\"", ")", ")", ":", "destination", ".", "getHost", "(", ")", ";", "int", "newPort", "=", "destination", ".", "getPort", "(", ")", "==", "80", "||", "destination", ".", "getPort", "(", ")", "==", "443", "?", "-", "1", ":", "destination", ".", "getPort", "(", ")", ";", "String", "newQuery", "=", "destination", ".", "getQuery", "(", ")", "==", "null", "?", "\"\"", ":", "destination", ".", "getQuery", "(", ")", ";", "if", "(", "!", "newHost", ".", "equalsIgnoreCase", "(", "origHost", ")", "||", "!", "(", "newPort", "==", "origPort", ")", "||", "!", "newQuery", ".", "equalsIgnoreCase", "(", "origQuery", ")", "||", "!", "origRequestUrl", ".", "getPath", "(", ")", ".", "equals", "(", "destination", ".", "getPath", "(", ")", ")", ")", "return", "destination", ";", "}", "}", "return", "null", ";", "}" ]
Returns an instance of the first applicable routing strategy found based on priority of each strategy, or null if none return a URL.
[ "Returns", "an", "instance", "of", "the", "first", "applicable", "routing", "strategy", "found", "based", "on", "priority", "of", "each", "strategy", "or", "null", "if", "none", "return", "a", "URL", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/routing/RoutingServiceMonitor.java#L138-L163