repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
twilio/twilio-java
src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java
AvailablePhoneNumberCountryReader.pageForRequest
private Page<AvailablePhoneNumberCountry> pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException("AvailablePhoneNumberCountry read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Page.fromJson( "countries", response.getContent(), AvailablePhoneNumberCountry.class, client.getObjectMapper() ); }
java
private Page<AvailablePhoneNumberCountry> pageForRequest(final TwilioRestClient client, final Request request) { Response response = client.request(request); if (response == null) { throw new ApiConnectionException("AvailablePhoneNumberCountry read failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Page.fromJson( "countries", response.getContent(), AvailablePhoneNumberCountry.class, client.getObjectMapper() ); }
[ "private", "Page", "<", "AvailablePhoneNumberCountry", ">", "pageForRequest", "(", "final", "TwilioRestClient", "client", ",", "final", "Request", "request", ")", "{", "Response", "response", "=", "client", ".", "request", "(", "request", ")", ";", "if", "(", ...
Generate a Page of AvailablePhoneNumberCountry Resources for a given request. @param client TwilioRestClient with which to make the request @param request Request to generate a page for @return Page for the Request
[ "Generate", "a", "Page", "of", "AvailablePhoneNumberCountry", "Resources", "for", "a", "given", "request", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java#L139-L165
threerings/narya
tools/src/main/java/com/threerings/presents/tools/ImportSet.java
ImportSet.toGroups
public List<List<String>> toGroups () { List<String> list = Lists.newArrayList(_imports); Collections.sort(list, new Comparator<String>() { public int compare (String class1, String class2) { return ComparisonChain.start() .compare(findImportGroup(class1), findImportGroup(class2)) .compare(class1, class2) .result(); } }); List<List<String>> result = Lists.newArrayList(); List<String> current = null; int lastGroup = -2; for (String imp : list) { int group = findImportGroup(imp); if (group != lastGroup) { if (current == null || !current.isEmpty()) { result.add(current = Lists.<String>newArrayList()); } lastGroup = group; } current.add(imp); } return result; }
java
public List<List<String>> toGroups () { List<String> list = Lists.newArrayList(_imports); Collections.sort(list, new Comparator<String>() { public int compare (String class1, String class2) { return ComparisonChain.start() .compare(findImportGroup(class1), findImportGroup(class2)) .compare(class1, class2) .result(); } }); List<List<String>> result = Lists.newArrayList(); List<String> current = null; int lastGroup = -2; for (String imp : list) { int group = findImportGroup(imp); if (group != lastGroup) { if (current == null || !current.isEmpty()) { result.add(current = Lists.<String>newArrayList()); } lastGroup = group; } current.add(imp); } return result; }
[ "public", "List", "<", "List", "<", "String", ">", ">", "toGroups", "(", ")", "{", "List", "<", "String", ">", "list", "=", "Lists", ".", "newArrayList", "(", "_imports", ")", ";", "Collections", ".", "sort", "(", "list", ",", "new", "Comparator", "<...
Converts the set of imports to groups of class names, according to conventional package ordering and spacing. Within each group, sorting is alphabetical.
[ "Converts", "the", "set", "of", "imports", "to", "groups", "of", "class", "names", "according", "to", "conventional", "package", "ordering", "and", "spacing", ".", "Within", "each", "group", "sorting", "is", "alphabetical", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/ImportSet.java#L341-L366
lucee/Lucee
core/src/main/java/lucee/transformer/util/SourceCode.java
SourceCode.forwardIfCurrent
public boolean forwardIfCurrent(short before, String val, short after) { int start = pos; // space before if (before == AT_LEAST_ONE_SPACE) { if (!removeSpace()) return false; } else removeSpace(); // value if (!forwardIfCurrent(val)) { setPos(start); return false; } // space after if (after == AT_LEAST_ONE_SPACE) { if (!removeSpace()) { setPos(start); return false; } } else removeSpace(); return true; }
java
public boolean forwardIfCurrent(short before, String val, short after) { int start = pos; // space before if (before == AT_LEAST_ONE_SPACE) { if (!removeSpace()) return false; } else removeSpace(); // value if (!forwardIfCurrent(val)) { setPos(start); return false; } // space after if (after == AT_LEAST_ONE_SPACE) { if (!removeSpace()) { setPos(start); return false; } } else removeSpace(); return true; }
[ "public", "boolean", "forwardIfCurrent", "(", "short", "before", ",", "String", "val", ",", "short", "after", ")", "{", "int", "start", "=", "pos", ";", "// space before", "if", "(", "before", "==", "AT_LEAST_ONE_SPACE", ")", "{", "if", "(", "!", "removeSp...
Gibt zurueck ob ein Wert folgt und vor und hinterher Leerzeichen folgen. @param before Definition der Leerzeichen vorher. @param val Gefolgter Wert der erartet wird. @param after Definition der Leerzeichen nach dem Wert. @return Gibt zurueck ob der Zeiger vorwaerts geschoben wurde oder nicht.
[ "Gibt", "zurueck", "ob", "ein", "Wert", "folgt", "und", "vor", "und", "hinterher", "Leerzeichen", "folgen", "." ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/util/SourceCode.java#L367-L390
js-lib-com/commons
src/main/java/js/util/Classes.java
Classes.invoke
private static Object invoke(Object object, Method method, Object... arguments) throws Exception { Throwable cause = null; try { method.setAccessible(true); return method.invoke(object instanceof Class<?> ? null : object, arguments); } catch(IllegalAccessException e) { throw new BugError(e); } catch(InvocationTargetException e) { cause = e.getCause(); if(cause instanceof Exception) { throw (Exception)cause; } if(cause instanceof AssertionError) { throw (AssertionError)cause; } } throw new BugError("Method |%s| invocation fails: %s", method, cause); }
java
private static Object invoke(Object object, Method method, Object... arguments) throws Exception { Throwable cause = null; try { method.setAccessible(true); return method.invoke(object instanceof Class<?> ? null : object, arguments); } catch(IllegalAccessException e) { throw new BugError(e); } catch(InvocationTargetException e) { cause = e.getCause(); if(cause instanceof Exception) { throw (Exception)cause; } if(cause instanceof AssertionError) { throw (AssertionError)cause; } } throw new BugError("Method |%s| invocation fails: %s", method, cause); }
[ "private", "static", "Object", "invoke", "(", "Object", "object", ",", "Method", "method", ",", "Object", "...", "arguments", ")", "throws", "Exception", "{", "Throwable", "cause", "=", "null", ";", "try", "{", "method", ".", "setAccessible", "(", "true", ...
Do the actual reflexive method invocation. @param object object instance, @param method reflexive method, @param arguments variable number of arguments. @return value returned by method execution. @throws Exception if invocation fail for whatever reason including method internals.
[ "Do", "the", "actual", "reflexive", "method", "invocation", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L478-L498
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/BufferUtils.java
BufferUtils.equalIncreasingByteBuffer
public static boolean equalIncreasingByteBuffer(int start, int len, ByteBuffer buf) { if (buf == null) { return false; } buf.rewind(); if (buf.remaining() != len) { return false; } for (int k = 0; k < len; k++) { if (buf.get() != (byte) (start + k)) { return false; } } return true; }
java
public static boolean equalIncreasingByteBuffer(int start, int len, ByteBuffer buf) { if (buf == null) { return false; } buf.rewind(); if (buf.remaining() != len) { return false; } for (int k = 0; k < len; k++) { if (buf.get() != (byte) (start + k)) { return false; } } return true; }
[ "public", "static", "boolean", "equalIncreasingByteBuffer", "(", "int", "start", ",", "int", "len", ",", "ByteBuffer", "buf", ")", "{", "if", "(", "buf", "==", "null", ")", "{", "return", "false", ";", "}", "buf", ".", "rewind", "(", ")", ";", "if", ...
Checks if the given {@link ByteBuffer} starts with an increasing sequence of bytes starting at the given value of length equal to or greater than the given length. @param start the starting value to use @param len the target length of the sequence @param buf the ByteBuffer to check @return true if the ByteBuffer has a prefix of length {@code len} that is an increasing sequence of bytes starting at {@code start}
[ "Checks", "if", "the", "given", "{", "@link", "ByteBuffer", "}", "starts", "with", "an", "increasing", "sequence", "of", "bytes", "starting", "at", "the", "given", "value", "of", "length", "equal", "to", "or", "greater", "than", "the", "given", "length", "...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/BufferUtils.java#L251-L265
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryFileApi.java
RepositoryFileApi.getRawFile
public File getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath, File directory) throws GitLabApiException { InputStream in = getRawFile(projectIdOrPath, commitOrBranchName, filepath); try { if (directory == null) { directory = new File(System.getProperty("java.io.tmpdir")); } String filename = new File(filepath).getName(); File file = new File(directory, filename); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } finally { try { in.close(); } catch (IOException ignore) { } } }
java
public File getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath, File directory) throws GitLabApiException { InputStream in = getRawFile(projectIdOrPath, commitOrBranchName, filepath); try { if (directory == null) { directory = new File(System.getProperty("java.io.tmpdir")); } String filename = new File(filepath).getName(); File file = new File(directory, filename); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } finally { try { in.close(); } catch (IOException ignore) { } } }
[ "public", "File", "getRawFile", "(", "Object", "projectIdOrPath", ",", "String", "commitOrBranchName", ",", "String", "filepath", ",", "File", "directory", ")", "throws", "GitLabApiException", "{", "InputStream", "in", "=", "getRawFile", "(", "projectIdOrPath", ",",...
Get the raw file for the file by commit sha and path. Thye file will be saved to the specified directory. If the file already exists in the directory it will be overwritten. V3: <pre><code>GitLab Endpoint: GET /projects/:id/repository/blobs/:sha</code></pre> V4: <pre><code>GitLab Endpoint: GET /projects/:id/repository/files/:filepath</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param commitOrBranchName the commit or branch name to get the file for @param filepath the path of the file to get @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" @return a File instance pointing to the download of the specified file @throws GitLabApiException if any exception occurs
[ "Get", "the", "raw", "file", "for", "the", "file", "by", "commit", "sha", "and", "path", ".", "Thye", "file", "will", "be", "saved", "to", "the", "specified", "directory", ".", "If", "the", "file", "already", "exists", "in", "the", "directory", "it", "...
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryFileApi.java#L374-L398
alkacon/opencms-core
src/org/opencms/ui/dialogs/permissions/CmsPermissionBean.java
CmsPermissionBean.getPrincipalNameFromACE
public static String getPrincipalNameFromACE(CmsObject cms, CmsAccessControlEntry entry) { if (entry.isAllOthers()) { return CmsAccessControlEntry.PRINCIPAL_ALL_OTHERS_NAME; } if (entry.isOverwriteAll()) { return CmsAccessControlEntry.PRINCIPAL_OVERWRITE_ALL_NAME; } CmsRole role = CmsRole.valueOfId(entry.getPrincipal()); if (role != null) { return role.getRoleName(); } else { try { return CmsPrincipal.readPrincipal(cms, entry.getPrincipal()).getName(); } catch (CmsException e) { // } } return ""; }
java
public static String getPrincipalNameFromACE(CmsObject cms, CmsAccessControlEntry entry) { if (entry.isAllOthers()) { return CmsAccessControlEntry.PRINCIPAL_ALL_OTHERS_NAME; } if (entry.isOverwriteAll()) { return CmsAccessControlEntry.PRINCIPAL_OVERWRITE_ALL_NAME; } CmsRole role = CmsRole.valueOfId(entry.getPrincipal()); if (role != null) { return role.getRoleName(); } else { try { return CmsPrincipal.readPrincipal(cms, entry.getPrincipal()).getName(); } catch (CmsException e) { // } } return ""; }
[ "public", "static", "String", "getPrincipalNameFromACE", "(", "CmsObject", "cms", ",", "CmsAccessControlEntry", "entry", ")", "{", "if", "(", "entry", ".", "isAllOthers", "(", ")", ")", "{", "return", "CmsAccessControlEntry", ".", "PRINCIPAL_ALL_OTHERS_NAME", ";", ...
Get name of principal from ACE.<p> @param cms CmsObject @param entry ACE @return principal name
[ "Get", "name", "of", "principal", "from", "ACE", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/permissions/CmsPermissionBean.java#L137-L156
abel533/Mapper
core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java
SqlHelper.getIfCacheNotNull
public static String getIfCacheNotNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); }
java
public static String getIfCacheNotNull(EntityColumn column, String contents) { StringBuilder sql = new StringBuilder(); sql.append("<if test=\"").append(column.getProperty()).append("_cache != null\">"); sql.append(contents); sql.append("</if>"); return sql.toString(); }
[ "public", "static", "String", "getIfCacheNotNull", "(", "EntityColumn", "column", ",", "String", "contents", ")", "{", "StringBuilder", "sql", "=", "new", "StringBuilder", "(", ")", ";", "sql", ".", "append", "(", "\"<if test=\\\"\"", ")", ".", "append", "(", ...
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> @param column @return
[ "<bind", "name", "=", "pattern", "value", "=", "%", "+", "_parameter", ".", "getTitle", "()", "+", "%", "/", ">" ]
train
https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java#L135-L141
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobsInner.java
JobsInner.createOrUpdate
public JobInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, JobInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, parameters).toBlocking().single().body(); }
java
public JobInner createOrUpdate(String resourceGroupName, String serverName, String jobAgentName, String jobName, JobInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, parameters).toBlocking().single().body(); }
[ "public", "JobInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "jobAgentName", ",", "String", "jobName", ",", "JobInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceG...
Creates or updates a job. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent. @param jobName The name of the job to get. @param parameters The requested job state. @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 JobInner object if successful.
[ "Creates", "or", "updates", "a", "job", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobsInner.java#L330-L332
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/ServerRedirectService.java
ServerRedirectService.setSourceUrl
public void setSourceUrl(String newUrl, int id) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_SERVERS + " SET " + Constants.SERVER_REDIRECT_SRC_URL + " = ?" + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, newUrl); statement.setInt(2, id); statement.executeUpdate(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
public void setSourceUrl(String newUrl, int id) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_SERVERS + " SET " + Constants.SERVER_REDIRECT_SRC_URL + " = ?" + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, newUrl); statement.setInt(2, id); statement.executeUpdate(); statement.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
[ "public", "void", "setSourceUrl", "(", "String", "newUrl", ",", "int", "id", ")", "{", "PreparedStatement", "statement", "=", "null", ";", "try", "(", "Connection", "sqlConnection", "=", "sqlService", ".", "getConnection", "(", ")", ")", "{", "statement", "=...
Set source url for a server @param newUrl new URL @param id Server ID
[ "Set", "source", "url", "for", "a", "server" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/ServerRedirectService.java#L476-L499
passwordmaker/java-passwordmaker-lib
src/main/java/org/daveware/passwordmaker/AccountPatternMatcher.java
AccountPatternMatcher.globMatch
private static boolean globMatch(String glob, String text) { GlobMatch m = new GlobMatch(); return m.match(text, glob); }
java
private static boolean globMatch(String glob, String text) { GlobMatch m = new GlobMatch(); return m.match(text, glob); }
[ "private", "static", "boolean", "globMatch", "(", "String", "glob", ",", "String", "text", ")", "{", "GlobMatch", "m", "=", "new", "GlobMatch", "(", ")", ";", "return", "m", ".", "match", "(", "text", ",", "glob", ")", ";", "}" ]
Performs a glob match against a string. <p/> Taken from: http://stackoverflow.com/questions/1247772/is-there-an-equivalent-of-java-util-regex-for-glob-type-patterns @param glob The glob pattern to match with. @param text The text to match against. @return true if it matches, else false.
[ "Performs", "a", "glob", "match", "against", "a", "string", ".", "<p", "/", ">", "Taken", "from", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "1247772", "/", "is", "-", "there", "-", "an", "-", "equivalent", "-", "of",...
train
https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/AccountPatternMatcher.java#L68-L72
Azure/azure-sdk-for-java
datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.createOrUpdateFirewallRuleAsync
public Observable<FirewallRuleInner> createOrUpdateFirewallRuleAsync(String resourceGroupName, String accountName, String name, FirewallRuleInner parameters) { return createOrUpdateFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, name, parameters).map(new Func1<ServiceResponse<FirewallRuleInner>, FirewallRuleInner>() { @Override public FirewallRuleInner call(ServiceResponse<FirewallRuleInner> response) { return response.body(); } }); }
java
public Observable<FirewallRuleInner> createOrUpdateFirewallRuleAsync(String resourceGroupName, String accountName, String name, FirewallRuleInner parameters) { return createOrUpdateFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, name, parameters).map(new Func1<ServiceResponse<FirewallRuleInner>, FirewallRuleInner>() { @Override public FirewallRuleInner call(ServiceResponse<FirewallRuleInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "FirewallRuleInner", ">", "createOrUpdateFirewallRuleAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "name", ",", "FirewallRuleInner", "parameters", ")", "{", "return", "createOrUpdateFirewallRuleWithServ...
Creates or updates the specified firewall rule. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Store account. @param accountName The name of the Data Lake Store account to which to add the firewall rule. @param name The name of the firewall rule to create or update. @param parameters Parameters supplied to create the create firewall rule. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the FirewallRuleInner object
[ "Creates", "or", "updates", "the", "specified", "firewall", "rule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java#L489-L496
phax/ph-oton
ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload/FineUploaderBasic.java
FineUploaderBasic.addCustomHeader
@Nonnull public FineUploaderBasic addCustomHeader (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue) { ValueEnforcer.notEmpty (sKey, "Key"); ValueEnforcer.notNull (sValue, "Value"); m_aRequestCustomHeaders.put (sKey, sValue); return this; }
java
@Nonnull public FineUploaderBasic addCustomHeader (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue) { ValueEnforcer.notEmpty (sKey, "Key"); ValueEnforcer.notNull (sValue, "Value"); m_aRequestCustomHeaders.put (sKey, sValue); return this; }
[ "@", "Nonnull", "public", "FineUploaderBasic", "addCustomHeader", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sKey", ",", "@", "Nonnull", "final", "String", "sValue", ")", "{", "ValueEnforcer", ".", "notEmpty", "(", "sKey", ",", "\"Key\"", ")", ...
Additional headers sent along with the XHR POST request. Note that is option is only relevant to the ajax/XHR uploader. @param sKey Custom header name @param sValue Custom header value @return this
[ "Additional", "headers", "sent", "along", "with", "the", "XHR", "POST", "request", ".", "Note", "that", "is", "option", "is", "only", "relevant", "to", "the", "ajax", "/", "XHR", "uploader", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload/FineUploaderBasic.java#L280-L288
PawelAdamski/HttpClientMock
src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java
HttpClientVerifyBuilder.withHeader
public HttpClientVerifyBuilder withHeader(String header, Matcher<String> matcher) { ruleBuilder.addCondition(new HeaderCondition(header, matcher)); return this; }
java
public HttpClientVerifyBuilder withHeader(String header, Matcher<String> matcher) { ruleBuilder.addCondition(new HeaderCondition(header, matcher)); return this; }
[ "public", "HttpClientVerifyBuilder", "withHeader", "(", "String", "header", ",", "Matcher", "<", "String", ">", "matcher", ")", "{", "ruleBuilder", ".", "addCondition", "(", "new", "HeaderCondition", "(", "header", ",", "matcher", ")", ")", ";", "return", "thi...
Adds header condition. Header must be equal to provided value. @param header header name @param matcher header value matcher @return verification builder
[ "Adds", "header", "condition", ".", "Header", "must", "be", "equal", "to", "provided", "value", "." ]
train
https://github.com/PawelAdamski/HttpClientMock/blob/0205498434bbc0c78c187a51181cac9b266a28fb/src/main/java/com/github/paweladamski/httpclientmock/HttpClientVerifyBuilder.java#L40-L43
lestard/assertj-javafx
src/main/java/eu/lestard/assertj/javafx/api/ReadOnlyFloatPropertyAssert.java
ReadOnlyFloatPropertyAssert.hasValue
public ReadOnlyFloatPropertyAssert hasValue(Double expectedValue, Offset offset){ new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset); return this; }
java
public ReadOnlyFloatPropertyAssert hasValue(Double expectedValue, Offset offset){ new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset); return this; }
[ "public", "ReadOnlyFloatPropertyAssert", "hasValue", "(", "Double", "expectedValue", ",", "Offset", "offset", ")", "{", "new", "ObservableNumberValueAssertions", "(", "actual", ")", ".", "hasValue", "(", "expectedValue", ",", "offset", ")", ";", "return", "this", ...
Verifies that the actual observable number has a value that is close to the given one by less then the given offset. @param expectedValue the given value to compare the actual observables value to. @param offset the given positive offset. @return {@code this} assertion object. @throws java.lang.NullPointerException if the given offset is <code>null</code>. @throws java.lang.AssertionError if the actual observables value is not equal to the expected one.
[ "Verifies", "that", "the", "actual", "observable", "number", "has", "a", "value", "that", "is", "close", "to", "the", "given", "one", "by", "less", "then", "the", "given", "offset", "." ]
train
https://github.com/lestard/assertj-javafx/blob/f6b4d22e542a5501c7c1c2fae8700b0f69b956c1/src/main/java/eu/lestard/assertj/javafx/api/ReadOnlyFloatPropertyAssert.java#L45-L49
teatrove/teatrove
teaservlet/src/main/java/org/teatrove/teaservlet/stats/Histogram.java
Histogram.find
public int find(double x) { if (x < xMinRangeLimit) return Integer.MIN_VALUE; else if (x >= xMaxRangeLimit) return Integer.MAX_VALUE; return findSmaller(ranges, x); }
java
public int find(double x) { if (x < xMinRangeLimit) return Integer.MIN_VALUE; else if (x >= xMaxRangeLimit) return Integer.MAX_VALUE; return findSmaller(ranges, x); }
[ "public", "int", "find", "(", "double", "x", ")", "{", "if", "(", "x", "<", "xMinRangeLimit", ")", "return", "Integer", ".", "MIN_VALUE", ";", "else", "if", "(", "x", ">=", "xMaxRangeLimit", ")", "return", "Integer", ".", "MAX_VALUE", ";", "return", "f...
Returns the index of the bin containing the specified coordinate. @param x the coordinate data value @return the index of the bin containing the coordinate value.
[ "Returns", "the", "index", "of", "the", "bin", "containing", "the", "specified", "coordinate", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaservlet/src/main/java/org/teatrove/teaservlet/stats/Histogram.java#L320-L324
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ArrayHashCode.java
ArrayHashCode.rewriteArrayArgument
private static String rewriteArrayArgument(ExpressionTree arg, VisitorState state) { Types types = state.getTypes(); Type argType = ASTHelpers.getType(arg); Preconditions.checkState(types.isArray(argType), "arg must be of array type"); if (types.isArray(types.elemtype(argType))) { return "Arrays.deepHashCode(" + state.getSourceForNode(arg) + ")"; } else { return "Arrays.hashCode(" + state.getSourceForNode(arg) + ")"; } }
java
private static String rewriteArrayArgument(ExpressionTree arg, VisitorState state) { Types types = state.getTypes(); Type argType = ASTHelpers.getType(arg); Preconditions.checkState(types.isArray(argType), "arg must be of array type"); if (types.isArray(types.elemtype(argType))) { return "Arrays.deepHashCode(" + state.getSourceForNode(arg) + ")"; } else { return "Arrays.hashCode(" + state.getSourceForNode(arg) + ")"; } }
[ "private", "static", "String", "rewriteArrayArgument", "(", "ExpressionTree", "arg", ",", "VisitorState", "state", ")", "{", "Types", "types", "=", "state", ".", "getTypes", "(", ")", ";", "Type", "argType", "=", "ASTHelpers", ".", "getType", "(", "arg", ")"...
Given an {@link ExpressionTree} that represents an argument of array type, rewrites it to wrap it in a call to either {@link java.util.Arrays#hashCode} if it is single dimensional, or {@link java.util.Arrays#deepHashCode} if it is multidimensional.
[ "Given", "an", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ArrayHashCode.java#L141-L150
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.readSiblings
public List<CmsResource> readSiblings(String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource resource = readResource(resourcename, filter); return readSiblings(resource, filter); }
java
public List<CmsResource> readSiblings(String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource resource = readResource(resourcename, filter); return readSiblings(resource, filter); }
[ "public", "List", "<", "CmsResource", ">", "readSiblings", "(", "String", "resourcename", ",", "CmsResourceFilter", "filter", ")", "throws", "CmsException", "{", "CmsResource", "resource", "=", "readResource", "(", "resourcename", ",", "filter", ")", ";", "return"...
Returns a list of all siblings of the specified resource, the specified resource being always part of the result set.<p> @param resourcename the name of the specified resource @param filter a resource filter @return a list of <code>{@link CmsResource}</code>s that are siblings to the specified resource, including the specified resource itself. @throws CmsException if something goes wrong
[ "Returns", "a", "list", "of", "all", "siblings", "of", "the", "specified", "resource", "the", "specified", "resource", "being", "always", "part", "of", "the", "result", "set", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L3435-L3439
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/NDArrayMath.java
NDArrayMath.mapIndexOntoTensor
public static int mapIndexOntoTensor(int index, INDArray arr, int... rank) { int ret = index * ArrayUtil.prod(ArrayUtil.removeIndex(arr.shape(), rank)); return ret; }
java
public static int mapIndexOntoTensor(int index, INDArray arr, int... rank) { int ret = index * ArrayUtil.prod(ArrayUtil.removeIndex(arr.shape(), rank)); return ret; }
[ "public", "static", "int", "mapIndexOntoTensor", "(", "int", "index", ",", "INDArray", "arr", ",", "int", "...", "rank", ")", "{", "int", "ret", "=", "index", "*", "ArrayUtil", ".", "prod", "(", "ArrayUtil", ".", "removeIndex", "(", "arr", ".", "shape", ...
This maps an index of a vector on to a vector in the matrix that can be used for indexing in to a tensor @param index the index to map @param arr the array to use for indexing @param rank the dimensions to compute a slice for @return the mapped index
[ "This", "maps", "an", "index", "of", "a", "vector", "on", "to", "a", "vector", "in", "the", "matrix", "that", "can", "be", "used", "for", "indexing", "in", "to", "a", "tensor" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/NDArrayMath.java#L185-L188
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/SliderArea.java
SliderArea.drawStartRectangle
public void drawStartRectangle(Double width) { GraphicsContext vectorContext = mapWidget.getVectorContext(); vectorContext.drawRectangle(group, MAP_AREA, applyMargins(new Bbox(0, 0, width, getHeight())), // IE9 does not draw an empty shapestyle (new ShapeStyle()), but it does draw one with opacity = 0... new ShapeStyle("#FF0000", 0, "#FF0000", 0, 1)); // new ShapeStyle("#FF0000", 0.1f, "#FF0000", 0.5f, 1)); vectorContext.setCursor(group, MAP_AREA, Cursor.POINTER.getValue()); }
java
public void drawStartRectangle(Double width) { GraphicsContext vectorContext = mapWidget.getVectorContext(); vectorContext.drawRectangle(group, MAP_AREA, applyMargins(new Bbox(0, 0, width, getHeight())), // IE9 does not draw an empty shapestyle (new ShapeStyle()), but it does draw one with opacity = 0... new ShapeStyle("#FF0000", 0, "#FF0000", 0, 1)); // new ShapeStyle("#FF0000", 0.1f, "#FF0000", 0.5f, 1)); vectorContext.setCursor(group, MAP_AREA, Cursor.POINTER.getValue()); }
[ "public", "void", "drawStartRectangle", "(", "Double", "width", ")", "{", "GraphicsContext", "vectorContext", "=", "mapWidget", ".", "getVectorContext", "(", ")", ";", "vectorContext", ".", "drawRectangle", "(", "group", ",", "MAP_AREA", ",", "applyMargins", "(", ...
Provides a rectangle over the area over which the user can slide. An onDown event redraws this rectangle into one that covers the map with {@link SliderArea#drawMapRectangle()}.
[ "Provides", "a", "rectangle", "over", "the", "area", "over", "which", "the", "user", "can", "slide", ".", "An", "onDown", "event", "redraws", "this", "rectangle", "into", "one", "that", "covers", "the", "map", "with", "{" ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/SliderArea.java#L72-L80
aicer/hibiscus-http-client
src/main/java/org/aicer/hibiscus/http/workers/HttpWorkerAbstract.java
HttpWorkerAbstract.getWorkerStrategy
public static HttpWorkerAbstract getWorkerStrategy(final String requestMethod, final HttpClient client) { if (requestMethod.equals(HEAD)) { return new HttpWorkerHead(client); } else if (requestMethod.equals(GET)) { return new HttpWorkerGet(client); } else if (requestMethod.equals(POST)) { return new HttpWorkerPost(client); } else if (requestMethod.equals(PUT)) { return new HttpWorkerPut(client); } else if (requestMethod.equals(DELETE)) { return new HttpWorkerDelete(client); } return new HttpWorkerGet(client); }
java
public static HttpWorkerAbstract getWorkerStrategy(final String requestMethod, final HttpClient client) { if (requestMethod.equals(HEAD)) { return new HttpWorkerHead(client); } else if (requestMethod.equals(GET)) { return new HttpWorkerGet(client); } else if (requestMethod.equals(POST)) { return new HttpWorkerPost(client); } else if (requestMethod.equals(PUT)) { return new HttpWorkerPut(client); } else if (requestMethod.equals(DELETE)) { return new HttpWorkerDelete(client); } return new HttpWorkerGet(client); }
[ "public", "static", "HttpWorkerAbstract", "getWorkerStrategy", "(", "final", "String", "requestMethod", ",", "final", "HttpClient", "client", ")", "{", "if", "(", "requestMethod", ".", "equals", "(", "HEAD", ")", ")", "{", "return", "new", "HttpWorkerHead", "(",...
Returns an instance of a HTTP Worker based on the request method @param requestMethod One of GET, PUT, POST, DELETE, HEAD @param client @return
[ "Returns", "an", "instance", "of", "a", "HTTP", "Worker", "based", "on", "the", "request", "method" ]
train
https://github.com/aicer/hibiscus-http-client/blob/a037e3cf8d4bb862d38a55a090778736a48d67cc/src/main/java/org/aicer/hibiscus/http/workers/HttpWorkerAbstract.java#L205-L220
landawn/AbacusUtil
src/com/landawn/abacus/util/ShortList.java
ShortList.anyMatch
public <E extends Exception> boolean anyMatch(Try.ShortPredicate<E> filter) throws E { return anyMatch(0, size(), filter); }
java
public <E extends Exception> boolean anyMatch(Try.ShortPredicate<E> filter) throws E { return anyMatch(0, size(), filter); }
[ "public", "<", "E", "extends", "Exception", ">", "boolean", "anyMatch", "(", "Try", ".", "ShortPredicate", "<", "E", ">", "filter", ")", "throws", "E", "{", "return", "anyMatch", "(", "0", ",", "size", "(", ")", ",", "filter", ")", ";", "}" ]
Returns whether any elements of this List match the provided predicate. @param filter @return
[ "Returns", "whether", "any", "elements", "of", "this", "List", "match", "the", "provided", "predicate", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/ShortList.java#L945-L947
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java
ResolvableType.forMethodReturnType
public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) { Assert.notNull(method, "Method must not be null"); MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, -1); methodParameter.setContainingClass(implementationClass); return forMethodParameter(methodParameter); }
java
public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) { Assert.notNull(method, "Method must not be null"); MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, -1); methodParameter.setContainingClass(implementationClass); return forMethodParameter(methodParameter); }
[ "public", "static", "ResolvableType", "forMethodReturnType", "(", "Method", "method", ",", "Class", "<", "?", ">", "implementationClass", ")", "{", "Assert", ".", "notNull", "(", "method", ",", "\"Method must not be null\"", ")", ";", "MethodParameter", "methodParam...
Return a {@link ResolvableType} for the specified {@link Method} return type. Use this variant when the class that declares the method includes generic parameter variables that are satisfied by the implementation class. @param method the source for the method return type @param implementationClass the implementation class @return a {@link ResolvableType} for the specified method return @see #forMethodReturnType(Method)
[ "Return", "a", "{" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java#L1043-L1048
jmxtrans/jmxtrans
jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java
KeyUtils.getKeyString
public static String getKeyString(Server server, Query query, Result result, List<String> typeNames, String rootPrefix) { StringBuilder sb = new StringBuilder(); addRootPrefix(rootPrefix, sb); addAlias(server, sb); addSeparator(sb); addMBeanIdentifier(query, result, sb); addSeparator(sb); addTypeName(query, result, typeNames, sb); addKeyString(query, result, sb); return sb.toString(); }
java
public static String getKeyString(Server server, Query query, Result result, List<String> typeNames, String rootPrefix) { StringBuilder sb = new StringBuilder(); addRootPrefix(rootPrefix, sb); addAlias(server, sb); addSeparator(sb); addMBeanIdentifier(query, result, sb); addSeparator(sb); addTypeName(query, result, typeNames, sb); addKeyString(query, result, sb); return sb.toString(); }
[ "public", "static", "String", "getKeyString", "(", "Server", "server", ",", "Query", "query", ",", "Result", "result", ",", "List", "<", "String", ">", "typeNames", ",", "String", "rootPrefix", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(...
Gets the key string. @param server @param query the query @param result the result @param typeNames the type names @param rootPrefix the root prefix @return the key string
[ "Gets", "the", "key", "string", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L46-L56
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java
WaveformFinder.requestPreviewInternal
private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) { // First check if we are using cached data for this slot MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference)); if (cache != null) { return cache.getWaveformPreview(null, trackReference); } // Then see if any registered metadata providers can offer it for us. final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(trackReference.getSlotReference()); if (sourceDetails != null) { final WaveformPreview provided = MetadataFinder.getInstance().allMetadataProviders.getWaveformPreview(sourceDetails, trackReference); if (provided != null) { return provided; } } // At this point, unless we are allowed to actively request the data, we are done. We can always actively // request tracks from rekordbox. if (MetadataFinder.getInstance().isPassive() && failIfPassive && trackReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) { return null; } // We have to actually request the preview using the dbserver protocol. ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() { @Override public WaveformPreview useClient(Client client) throws Exception { return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client); } }; try { return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, "requesting waveform preview"); } catch (Exception e) { logger.error("Problem requesting waveform preview, returning null", e); } return null; }
java
private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) { // First check if we are using cached data for this slot MetadataCache cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference)); if (cache != null) { return cache.getWaveformPreview(null, trackReference); } // Then see if any registered metadata providers can offer it for us. final MediaDetails sourceDetails = MetadataFinder.getInstance().getMediaDetailsFor(trackReference.getSlotReference()); if (sourceDetails != null) { final WaveformPreview provided = MetadataFinder.getInstance().allMetadataProviders.getWaveformPreview(sourceDetails, trackReference); if (provided != null) { return provided; } } // At this point, unless we are allowed to actively request the data, we are done. We can always actively // request tracks from rekordbox. if (MetadataFinder.getInstance().isPassive() && failIfPassive && trackReference.slot != CdjStatus.TrackSourceSlot.COLLECTION) { return null; } // We have to actually request the preview using the dbserver protocol. ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() { @Override public WaveformPreview useClient(Client client) throws Exception { return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client); } }; try { return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, "requesting waveform preview"); } catch (Exception e) { logger.error("Problem requesting waveform preview, returning null", e); } return null; }
[ "private", "WaveformPreview", "requestPreviewInternal", "(", "final", "DataReference", "trackReference", ",", "final", "boolean", "failIfPassive", ")", "{", "// First check if we are using cached data for this slot", "MetadataCache", "cache", "=", "MetadataFinder", ".", "getIns...
Ask the specified player for the waveform preview in the specified slot with the specified rekordbox ID, using cached media instead if it is available, and possibly giving up if we are in passive mode. @param trackReference uniquely identifies the desired waveform preview @param failIfPassive will prevent the request from taking place if we are in passive mode, so that automatic waveform updates will use available caches only @return the waveform preview found, if any
[ "Ask", "the", "specified", "player", "for", "the", "waveform", "preview", "in", "the", "specified", "slot", "with", "the", "specified", "rekordbox", "ID", "using", "cached", "media", "instead", "if", "it", "is", "available", "and", "possibly", "giving", "up", ...
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java#L410-L447
h2oai/h2o-3
h2o-core/src/main/java/jsr166y/Phaser.java
Phaser.awaitAdvanceInterruptibly
public int awaitAdvanceInterruptibly(int phase) throws InterruptedException { final Phaser root = this.root; long s = (root == this) ? state : reconcileState(); int p = (int)(s >>> PHASE_SHIFT); if (phase < 0) return phase; if (p == phase) { QNode node = new QNode(this, phase, true, false, 0L); p = root.internalAwaitAdvance(phase, node); if (node.wasInterrupted) throw new InterruptedException(); } return p; }
java
public int awaitAdvanceInterruptibly(int phase) throws InterruptedException { final Phaser root = this.root; long s = (root == this) ? state : reconcileState(); int p = (int)(s >>> PHASE_SHIFT); if (phase < 0) return phase; if (p == phase) { QNode node = new QNode(this, phase, true, false, 0L); p = root.internalAwaitAdvance(phase, node); if (node.wasInterrupted) throw new InterruptedException(); } return p; }
[ "public", "int", "awaitAdvanceInterruptibly", "(", "int", "phase", ")", "throws", "InterruptedException", "{", "final", "Phaser", "root", "=", "this", ".", "root", ";", "long", "s", "=", "(", "root", "==", "this", ")", "?", "state", ":", "reconcileState", ...
Awaits the phase of this phaser to advance from the given phase value, throwing {@code InterruptedException} if interrupted while waiting, or returning immediately if the current phase is not equal to the given phase value or this phaser is terminated. @param phase an arrival phase number, or negative value if terminated; this argument is normally the value returned by a previous call to {@code arrive} or {@code arriveAndDeregister}. @return the next arrival phase number, or the argument if it is negative, or the (negative) {@linkplain #getPhase() current phase} if terminated @throws InterruptedException if thread interrupted while waiting
[ "Awaits", "the", "phase", "of", "this", "phaser", "to", "advance", "from", "the", "given", "phase", "value", "throwing", "{", "@code", "InterruptedException", "}", "if", "interrupted", "while", "waiting", "or", "returning", "immediately", "if", "the", "current",...
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/jsr166y/Phaser.java#L720-L734
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java
Configurer.getDoubleDefault
public final double getDoubleDefault(double defaultValue, String attribute, String... path) { try { return Double.parseDouble(getNodeStringDefault(String.valueOf(defaultValue), attribute, path)); } catch (final NumberFormatException exception) { throw new LionEngineException(exception, media); } }
java
public final double getDoubleDefault(double defaultValue, String attribute, String... path) { try { return Double.parseDouble(getNodeStringDefault(String.valueOf(defaultValue), attribute, path)); } catch (final NumberFormatException exception) { throw new LionEngineException(exception, media); } }
[ "public", "final", "double", "getDoubleDefault", "(", "double", "defaultValue", ",", "String", "attribute", ",", "String", "...", "path", ")", "{", "try", "{", "return", "Double", ".", "parseDouble", "(", "getNodeStringDefault", "(", "String", ".", "valueOf", ...
Get a double in the xml tree. @param defaultValue Value used if node does not exist. @param attribute The attribute to get as double. @param path The node path (child list) @return The double value. @throws LionEngineException If unable to read node.
[ "Get", "a", "double", "in", "the", "xml", "tree", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java#L274-L284
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/KeyManagerActor.java
KeyManagerActor.onPublicKeysGroupRemoved
private void onPublicKeysGroupRemoved(int uid, int keyGroupId) { UserKeys userKeys = getCachedUserKeys(uid); if (userKeys == null) { return; } UserKeys updatedUserKeys = userKeys.removeUserKeyGroup(keyGroupId); cacheUserKeys(updatedUserKeys); context().getEncryption().getEncryptedChatManager(uid) .send(new EncryptedPeerActor.KeyGroupUpdated(userKeys)); }
java
private void onPublicKeysGroupRemoved(int uid, int keyGroupId) { UserKeys userKeys = getCachedUserKeys(uid); if (userKeys == null) { return; } UserKeys updatedUserKeys = userKeys.removeUserKeyGroup(keyGroupId); cacheUserKeys(updatedUserKeys); context().getEncryption().getEncryptedChatManager(uid) .send(new EncryptedPeerActor.KeyGroupUpdated(userKeys)); }
[ "private", "void", "onPublicKeysGroupRemoved", "(", "int", "uid", ",", "int", "keyGroupId", ")", "{", "UserKeys", "userKeys", "=", "getCachedUserKeys", "(", "uid", ")", ";", "if", "(", "userKeys", "==", "null", ")", "{", "return", ";", "}", "UserKeys", "up...
Handler for removing key group @param uid User's id @param keyGroupId Removed key group id
[ "Handler", "for", "removing", "key", "group" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/KeyManagerActor.java#L460-L470
jfinal/jfinal
src/main/java/com/jfinal/plugin/activerecord/generator/MetaBuilder.java
MetaBuilder.handleJavaType
protected String handleJavaType(String typeStr, ResultSetMetaData rsmd, int column) throws SQLException { // 当前实现只处理 Oracle if ( ! dialect.isOracle() ) { return typeStr; } // 默认实现只处理 BigDecimal 类型 if ("java.math.BigDecimal".equals(typeStr)) { int scale = rsmd.getScale(column); // 小数点右边的位数,值为 0 表示整数 int precision = rsmd.getPrecision(column); // 最大精度 if (scale == 0) { if (precision <= 9) { typeStr = "java.lang.Integer"; } else if (precision <= 18) { typeStr = "java.lang.Long"; } else { typeStr = "java.math.BigDecimal"; } } else { // 非整数都采用 BigDecimal 类型,需要转成 double 的可以覆盖并改写下面的代码 typeStr = "java.math.BigDecimal"; } } return typeStr; }
java
protected String handleJavaType(String typeStr, ResultSetMetaData rsmd, int column) throws SQLException { // 当前实现只处理 Oracle if ( ! dialect.isOracle() ) { return typeStr; } // 默认实现只处理 BigDecimal 类型 if ("java.math.BigDecimal".equals(typeStr)) { int scale = rsmd.getScale(column); // 小数点右边的位数,值为 0 表示整数 int precision = rsmd.getPrecision(column); // 最大精度 if (scale == 0) { if (precision <= 9) { typeStr = "java.lang.Integer"; } else if (precision <= 18) { typeStr = "java.lang.Long"; } else { typeStr = "java.math.BigDecimal"; } } else { // 非整数都采用 BigDecimal 类型,需要转成 double 的可以覆盖并改写下面的代码 typeStr = "java.math.BigDecimal"; } } return typeStr; }
[ "protected", "String", "handleJavaType", "(", "String", "typeStr", ",", "ResultSetMetaData", "rsmd", ",", "int", "column", ")", "throws", "SQLException", "{", "// 当前实现只处理 Oracle\r", "if", "(", "!", "dialect", ".", "isOracle", "(", ")", ")", "{", "return", "typ...
handleJavaType(...) 方法是用于处理 java 类型的回调方法,当 jfinal 默认 处理规则无法满足需求时,用户可以通过继承 MetaBuilder 并覆盖此方法定制自己的 类型转换规则 当前实现只处理了 Oracle 数据库的 NUMBER 类型,根据精度与小数位数转换成 Integer、 Long、BigDecimal。其它数据库直接返回原值 typeStr Oracle 数据库 number 类型对应 java 类型: 1:如果不指定number的长度,或指定长度 n > 18 number 对应 java.math.BigDecimal 2:如果number的长度在10 <= n <= 18 number(n) 对应 java.lang.Long 3:如果number的长度在1 <= n <= 9 number(n) 对应 java.lang.Integer 类型 社区分享:《Oracle NUMBER 类型映射改进》http://www.jfinal.com/share/1145
[ "handleJavaType", "(", "...", ")", "方法是用于处理", "java", "类型的回调方法,当", "jfinal", "默认", "处理规则无法满足需求时,用户可以通过继承", "MetaBuilder", "并覆盖此方法定制自己的", "类型转换规则" ]
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/generator/MetaBuilder.java#L355-L380
FINRAOS/JTAF-ExtWebDriver
src/main/java/org/finra/jtaf/ewd/utils/ScreenshotUtils.java
ScreenshotUtils.isSimilarToScreenshot
public static boolean isSimilarToScreenshot(IElement element, File controlPicture, File toSaveAs) throws IOException, WidgetException { return isSimilarToScreenshot(element, controlPicture, toSaveAs, .85); }
java
public static boolean isSimilarToScreenshot(IElement element, File controlPicture, File toSaveAs) throws IOException, WidgetException { return isSimilarToScreenshot(element, controlPicture, toSaveAs, .85); }
[ "public", "static", "boolean", "isSimilarToScreenshot", "(", "IElement", "element", ",", "File", "controlPicture", ",", "File", "toSaveAs", ")", "throws", "IOException", ",", "WidgetException", "{", "return", "isSimilarToScreenshot", "(", "element", ",", "controlPictu...
* Prereq: The page on which you are taking the screenshot is fully loaded Take a screenshot of the element identified by element and save the file as toSaveAs (Note that this file should be saved as a png). Test that the control picture, controlPicture, is both the same size as, and, has a similarity value greater than or equal to the default threshold of .85. @param element - the element to be tested @param controlPicture - the file of the picture that will serve as the control @param toSaveAs - for example, save the file at "testData/textFieldWidget/screenshot.png" @throws IOException @throws WidgetException
[ "*", "Prereq", ":", "The", "page", "on", "which", "you", "are", "taking", "the", "screenshot", "is", "fully", "loaded" ]
train
https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/utils/ScreenshotUtils.java#L174-L177
johnkil/Android-AppMsg
library/src/com/devspark/appmsg/AppMsg.java
AppMsg.makeText
public static AppMsg makeText(Activity context, int resId, Style style) throws Resources.NotFoundException { return makeText(context, context.getResources().getText(resId), style); }
java
public static AppMsg makeText(Activity context, int resId, Style style) throws Resources.NotFoundException { return makeText(context, context.getResources().getText(resId), style); }
[ "public", "static", "AppMsg", "makeText", "(", "Activity", "context", ",", "int", "resId", ",", "Style", "style", ")", "throws", "Resources", ".", "NotFoundException", "{", "return", "makeText", "(", "context", ",", "context", ".", "getResources", "(", ")", ...
Make a {@link AppMsg} that just contains a text view with the text from a resource. @param context The context to use. Usually your {@link android.app.Activity} object. @param resId The resource id of the string resource to use. Can be formatted text. @param style The style with a background and a duration. @throws Resources.NotFoundException if the resource can't be found.
[ "Make", "a", "{", "@link", "AppMsg", "}", "that", "just", "contains", "a", "text", "view", "with", "the", "text", "from", "a", "resource", "." ]
train
https://github.com/johnkil/Android-AppMsg/blob/e7fdd7870530a24e6d825278ee0863be0521e8b8/library/src/com/devspark/appmsg/AppMsg.java#L408-L411
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WFieldSetExample.java
WFieldSetExample.addFieldSet
private WFieldSet addFieldSet(final String title, final WFieldSet.FrameType type) { final WFieldSet fieldset = new WFieldSet(title); fieldset.setFrameType(type); fieldset.setMargin(new Margin(null, null, Size.LARGE, null)); final WFieldLayout layout = new WFieldLayout(); fieldset.add(layout); layout.setLabelWidth(25); layout.addField("Street address", new WTextField()); final WField add2Field = layout.addField("Street address line 2", new WTextField()); add2Field.getLabel().setHidden(true); layout.addField("Suburb", new WTextField()); layout.addField("State/Territory", new WDropdown( new String[]{"", "ACT", "NSW", "NT", "QLD", "SA", "TAS", "VIC", "WA"})); //NOTE: this is an Australia-specific post code field. An Australian post code is not a number as they may contain a leading zero. final WTextField postcode = new WTextField(); postcode.setMaxLength(4); postcode.setColumns(4); postcode.setMinLength(3); layout.addField("Postcode", postcode); add(fieldset); return fieldset; }
java
private WFieldSet addFieldSet(final String title, final WFieldSet.FrameType type) { final WFieldSet fieldset = new WFieldSet(title); fieldset.setFrameType(type); fieldset.setMargin(new Margin(null, null, Size.LARGE, null)); final WFieldLayout layout = new WFieldLayout(); fieldset.add(layout); layout.setLabelWidth(25); layout.addField("Street address", new WTextField()); final WField add2Field = layout.addField("Street address line 2", new WTextField()); add2Field.getLabel().setHidden(true); layout.addField("Suburb", new WTextField()); layout.addField("State/Territory", new WDropdown( new String[]{"", "ACT", "NSW", "NT", "QLD", "SA", "TAS", "VIC", "WA"})); //NOTE: this is an Australia-specific post code field. An Australian post code is not a number as they may contain a leading zero. final WTextField postcode = new WTextField(); postcode.setMaxLength(4); postcode.setColumns(4); postcode.setMinLength(3); layout.addField("Postcode", postcode); add(fieldset); return fieldset; }
[ "private", "WFieldSet", "addFieldSet", "(", "final", "String", "title", ",", "final", "WFieldSet", ".", "FrameType", "type", ")", "{", "final", "WFieldSet", "fieldset", "=", "new", "WFieldSet", "(", "title", ")", ";", "fieldset", ".", "setFrameType", "(", "t...
Creates a WFieldSet with content and a given FrameType. @param title The title to give to the WFieldSet. @param type The decorative model of the WFieldSet @return a WFieldSet with form control content.
[ "Creates", "a", "WFieldSet", "with", "content", "and", "a", "given", "FrameType", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WFieldSetExample.java#L88-L109
logic-ng/LogicNG
src/main/java/org/logicng/solvers/maxsat/algorithms/MaxSAT.java
MaxSAT.searchSATSolver
public static Tristate searchSATSolver(final MiniSatStyleSolver s, final SATHandler handler, final LNGIntVector assumptions) { return s.solve(handler, assumptions); }
java
public static Tristate searchSATSolver(final MiniSatStyleSolver s, final SATHandler handler, final LNGIntVector assumptions) { return s.solve(handler, assumptions); }
[ "public", "static", "Tristate", "searchSATSolver", "(", "final", "MiniSatStyleSolver", "s", ",", "final", "SATHandler", "handler", ",", "final", "LNGIntVector", "assumptions", ")", "{", "return", "s", ".", "solve", "(", "handler", ",", "assumptions", ")", ";", ...
Solves the formula that is currently loaded in the SAT solver with a set of assumptions. @param s the SAT solver @param handler a SAT handler @param assumptions the assumptions @return the result of the solving process
[ "Solves", "the", "formula", "that", "is", "currently", "loaded", "in", "the", "SAT", "solver", "with", "a", "set", "of", "assumptions", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/algorithms/MaxSAT.java#L164-L166
RallyTools/RallyRestToolkitForJava
src/main/java/com/rallydev/rest/client/HttpClient.java
HttpClient.setProxy
public void setProxy(URI proxy, String userName, String password) { setProxy(proxy); setClientCredentials(proxy, userName, password); }
java
public void setProxy(URI proxy, String userName, String password) { setProxy(proxy); setClientCredentials(proxy, userName, password); }
[ "public", "void", "setProxy", "(", "URI", "proxy", ",", "String", "userName", ",", "String", "password", ")", "{", "setProxy", "(", "proxy", ")", ";", "setClientCredentials", "(", "proxy", ",", "userName", ",", "password", ")", ";", "}" ]
Set the authenticated proxy server to use. By default no proxy is configured. @param proxy The proxy server, e.g. {@code new URI("http://my.proxy.com:8000")} @param userName The username to be used for authentication. @param password The password to be used for authentication.
[ "Set", "the", "authenticated", "proxy", "server", "to", "use", ".", "By", "default", "no", "proxy", "is", "configured", "." ]
train
https://github.com/RallyTools/RallyRestToolkitForJava/blob/542afa16ea44c9c64cebb0299500dcbbb50b6d7d/src/main/java/com/rallydev/rest/client/HttpClient.java#L70-L73
eclipse/xtext-extras
org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xbase/annotations/xAnnotations/util/XAnnotationsSwitch.java
XAnnotationsSwitch.doSwitch
@Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case XAnnotationsPackage.XANNOTATION: { XAnnotation xAnnotation = (XAnnotation)theEObject; T result = caseXAnnotation(xAnnotation); if (result == null) result = caseXExpression(xAnnotation); if (result == null) result = defaultCase(theEObject); return result; } case XAnnotationsPackage.XANNOTATION_ELEMENT_VALUE_PAIR: { XAnnotationElementValuePair xAnnotationElementValuePair = (XAnnotationElementValuePair)theEObject; T result = caseXAnnotationElementValuePair(xAnnotationElementValuePair); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } }
java
@Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case XAnnotationsPackage.XANNOTATION: { XAnnotation xAnnotation = (XAnnotation)theEObject; T result = caseXAnnotation(xAnnotation); if (result == null) result = caseXExpression(xAnnotation); if (result == null) result = defaultCase(theEObject); return result; } case XAnnotationsPackage.XANNOTATION_ELEMENT_VALUE_PAIR: { XAnnotationElementValuePair xAnnotationElementValuePair = (XAnnotationElementValuePair)theEObject; T result = caseXAnnotationElementValuePair(xAnnotationElementValuePair); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } }
[ "@", "Override", "protected", "T", "doSwitch", "(", "int", "classifierID", ",", "EObject", "theEObject", ")", "{", "switch", "(", "classifierID", ")", "{", "case", "XAnnotationsPackage", ".", "XANNOTATION", ":", "{", "XAnnotation", "xAnnotation", "=", "(", "XA...
Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. <!-- begin-user-doc --> <!-- end-user-doc --> @return the first non-null result returned by a <code>caseXXX</code> call. @generated
[ "Calls", "<code", ">", "caseXXX<", "/", "code", ">", "for", "each", "class", "of", "the", "model", "until", "one", "returns", "a", "non", "null", "result", ";", "it", "yields", "that", "result", ".", "<!", "--", "begin", "-", "user", "-", "doc", "--"...
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/emf-gen/org/eclipse/xtext/xbase/annotations/xAnnotations/util/XAnnotationsSwitch.java#L77-L99
mapbox/mapbox-java
services-core/src/main/java/com/mapbox/core/utils/TextUtils.java
TextUtils.formatCoordinate
public static String formatCoordinate(double coordinate, int precision) { String pattern = "0." + new String(new char[precision]).replace("\0", "0"); DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US); df.applyPattern(pattern); df.setRoundingMode(RoundingMode.FLOOR); return df.format(coordinate); }
java
public static String formatCoordinate(double coordinate, int precision) { String pattern = "0." + new String(new char[precision]).replace("\0", "0"); DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US); df.applyPattern(pattern); df.setRoundingMode(RoundingMode.FLOOR); return df.format(coordinate); }
[ "public", "static", "String", "formatCoordinate", "(", "double", "coordinate", ",", "int", "precision", ")", "{", "String", "pattern", "=", "\"0.\"", "+", "new", "String", "(", "new", "char", "[", "precision", "]", ")", ".", "replace", "(", "\"\\0\"", ",",...
Allows the specific adjusting of a coordinates precision. @param coordinate a double value representing a coordinate. @param precision an integer value you'd like the precision to be at. @return a formatted string. @since 2.1.0
[ "Allows", "the", "specific", "adjusting", "of", "a", "coordinates", "precision", "." ]
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-core/src/main/java/com/mapbox/core/utils/TextUtils.java#L82-L88
OpenLiberty/open-liberty
dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedCompletableFuture.java
ManagedCompletableFuture.failedFuture
@Trivial public static <U> CompletableFuture<U> failedFuture(Throwable x) { throw new UnsupportedOperationException(Tr.formatMessage(tc, "CWWKC1156.not.supported", "ManagedExecutor.failedFuture")); }
java
@Trivial public static <U> CompletableFuture<U> failedFuture(Throwable x) { throw new UnsupportedOperationException(Tr.formatMessage(tc, "CWWKC1156.not.supported", "ManagedExecutor.failedFuture")); }
[ "@", "Trivial", "public", "static", "<", "U", ">", "CompletableFuture", "<", "U", ">", "failedFuture", "(", "Throwable", "x", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "Tr", ".", "formatMessage", "(", "tc", ",", "\"CWWKC1156.not.supported\"...
Because CompletableFuture.failedFuture is static, this is not a true override. It will be difficult for the user to invoke this method because they would need to get the class of the CompletableFuture implementation and locate the static failedFuture method on that. @throws UnsupportedOperationException directing the user to use the ManagedExecutor spec interface instead.
[ "Because", "CompletableFuture", ".", "failedFuture", "is", "static", "this", "is", "not", "a", "true", "override", ".", "It", "will", "be", "difficult", "for", "the", "user", "to", "invoke", "this", "method", "because", "they", "would", "need", "to", "get", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.concurrent.mp.1.0/src/com/ibm/ws/concurrent/mp/ManagedCompletableFuture.java#L354-L357
jayantk/jklol
src/com/jayantkrish/jklol/nlpannotation/AnnotatedSentence.java
AnnotatedSentence.addAnnotation
public AnnotatedSentence addAnnotation(String annotationName, Object value) { Map<String, Object> newAnnotations = Maps.newHashMap(annotations); newAnnotations.put(annotationName, value); return new AnnotatedSentence(words, posTags, newAnnotations); }
java
public AnnotatedSentence addAnnotation(String annotationName, Object value) { Map<String, Object> newAnnotations = Maps.newHashMap(annotations); newAnnotations.put(annotationName, value); return new AnnotatedSentence(words, posTags, newAnnotations); }
[ "public", "AnnotatedSentence", "addAnnotation", "(", "String", "annotationName", ",", "Object", "value", ")", "{", "Map", "<", "String", ",", "Object", ">", "newAnnotations", "=", "Maps", ".", "newHashMap", "(", "annotations", ")", ";", "newAnnotations", ".", ...
Gets a copy of this annotated sentence containing the provided annotation in addition to the annotations on {@code this}. This method overwrites any other annotation with the same name. @param annotationName @param value @return
[ "Gets", "a", "copy", "of", "this", "annotated", "sentence", "containing", "the", "provided", "annotation", "in", "addition", "to", "the", "annotations", "on", "{", "@code", "this", "}", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/nlpannotation/AnnotatedSentence.java#L101-L105
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/ROCEvaluation.java
ROCEvaluation.materializeROC
public static <I extends ScoreIter> XYCurve materializeROC(Predicate<? super I> predicate, I iter) { int poscnt = 0, negcnt = 0; XYCurve curve = new XYCurve("False Positive Rate", "True Positive Rate"); // start in bottom left curve.add(0.0, 0.0); while(iter.valid()) { // positive or negative match? do { if(predicate.test(iter)) { ++poscnt; } else { ++negcnt; } iter.advance(); } // Loop while tied: while(iter.valid() && iter.tiedToPrevious()); // Add a new point. curve.addAndSimplify(negcnt, poscnt); } // Ensure we end up in the top right corner. // Simplification will skip this if we already were. curve.addAndSimplify(negcnt, poscnt); curve.rescale(1. / negcnt, 1. / poscnt); return curve; }
java
public static <I extends ScoreIter> XYCurve materializeROC(Predicate<? super I> predicate, I iter) { int poscnt = 0, negcnt = 0; XYCurve curve = new XYCurve("False Positive Rate", "True Positive Rate"); // start in bottom left curve.add(0.0, 0.0); while(iter.valid()) { // positive or negative match? do { if(predicate.test(iter)) { ++poscnt; } else { ++negcnt; } iter.advance(); } // Loop while tied: while(iter.valid() && iter.tiedToPrevious()); // Add a new point. curve.addAndSimplify(negcnt, poscnt); } // Ensure we end up in the top right corner. // Simplification will skip this if we already were. curve.addAndSimplify(negcnt, poscnt); curve.rescale(1. / negcnt, 1. / poscnt); return curve; }
[ "public", "static", "<", "I", "extends", "ScoreIter", ">", "XYCurve", "materializeROC", "(", "Predicate", "<", "?", "super", "I", ">", "predicate", ",", "I", "iter", ")", "{", "int", "poscnt", "=", "0", ",", "negcnt", "=", "0", ";", "XYCurve", "curve",...
Compute a ROC curve given a set of positive IDs and a sorted list of (comparable, ID)s, where the comparable object is used to decided when two objects are interchangeable. @param <I> Iterator type @param predicate Predicate to test for positive objects @param iter Iterator over results, with ties. @return area under curve
[ "Compute", "a", "ROC", "curve", "given", "a", "set", "of", "positive", "IDs", "and", "a", "sorted", "list", "of", "(", "comparable", "ID", ")", "s", "where", "the", "comparable", "object", "is", "used", "to", "decided", "when", "two", "objects", "are", ...
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/evaluation/scores/ROCEvaluation.java#L69-L96
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java
SlotManager.reportSlotStatus
public boolean reportSlotStatus(InstanceID instanceId, SlotReport slotReport) { checkInit(); LOG.debug("Received slot report from instance {}: {}.", instanceId, slotReport); TaskManagerRegistration taskManagerRegistration = taskManagerRegistrations.get(instanceId); if (null != taskManagerRegistration) { for (SlotStatus slotStatus : slotReport) { updateSlot(slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID()); } return true; } else { LOG.debug("Received slot report for unknown task manager with instance id {}. Ignoring this report.", instanceId); return false; } }
java
public boolean reportSlotStatus(InstanceID instanceId, SlotReport slotReport) { checkInit(); LOG.debug("Received slot report from instance {}: {}.", instanceId, slotReport); TaskManagerRegistration taskManagerRegistration = taskManagerRegistrations.get(instanceId); if (null != taskManagerRegistration) { for (SlotStatus slotStatus : slotReport) { updateSlot(slotStatus.getSlotID(), slotStatus.getAllocationID(), slotStatus.getJobID()); } return true; } else { LOG.debug("Received slot report for unknown task manager with instance id {}. Ignoring this report.", instanceId); return false; } }
[ "public", "boolean", "reportSlotStatus", "(", "InstanceID", "instanceId", ",", "SlotReport", "slotReport", ")", "{", "checkInit", "(", ")", ";", "LOG", ".", "debug", "(", "\"Received slot report from instance {}: {}.\"", ",", "instanceId", ",", "slotReport", ")", ";...
Reports the current slot allocations for a task manager identified by the given instance id. @param instanceId identifying the task manager for which to report the slot status @param slotReport containing the status for all of its slots @return true if the slot status has been updated successfully, otherwise false
[ "Reports", "the", "current", "slot", "allocations", "for", "a", "task", "manager", "identified", "by", "the", "given", "instance", "id", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java#L408-L427
spotify/helios
helios-services/src/main/java/com/spotify/helios/master/resources/JobsResource.java
JobsResource.post
@POST @Produces(APPLICATION_JSON) @Timed @ExceptionMetered public CreateJobResponse post(@Valid final Job job, @RequestUser final String username) { final Job.Builder clone = job.toBuilder() .setCreatingUser(username) .setCreated(clock.now().getMillis()) // If the job had a hash coming in, preserve it .setHash(job.getId().getHash()); final Job actualJob = clone.build(); final Collection<String> errors = jobValidator.validate(actualJob); final String jobIdString = actualJob.getId().toString(); if (!errors.isEmpty()) { throw badRequest(new CreateJobResponse(INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors), jobIdString)); } try { model.addJob(actualJob); } catch (JobExistsException e) { throw badRequest(new CreateJobResponse(JOB_ALREADY_EXISTS, ImmutableList.<String>of(), jobIdString)); } log.info("created job: {}", actualJob); return new CreateJobResponse(CreateJobResponse.Status.OK, ImmutableList.<String>of(), jobIdString); }
java
@POST @Produces(APPLICATION_JSON) @Timed @ExceptionMetered public CreateJobResponse post(@Valid final Job job, @RequestUser final String username) { final Job.Builder clone = job.toBuilder() .setCreatingUser(username) .setCreated(clock.now().getMillis()) // If the job had a hash coming in, preserve it .setHash(job.getId().getHash()); final Job actualJob = clone.build(); final Collection<String> errors = jobValidator.validate(actualJob); final String jobIdString = actualJob.getId().toString(); if (!errors.isEmpty()) { throw badRequest(new CreateJobResponse(INVALID_JOB_DEFINITION, ImmutableList.copyOf(errors), jobIdString)); } try { model.addJob(actualJob); } catch (JobExistsException e) { throw badRequest(new CreateJobResponse(JOB_ALREADY_EXISTS, ImmutableList.<String>of(), jobIdString)); } log.info("created job: {}", actualJob); return new CreateJobResponse(CreateJobResponse.Status.OK, ImmutableList.<String>of(), jobIdString); }
[ "@", "POST", "@", "Produces", "(", "APPLICATION_JSON", ")", "@", "Timed", "@", "ExceptionMetered", "public", "CreateJobResponse", "post", "(", "@", "Valid", "final", "Job", "job", ",", "@", "RequestUser", "final", "String", "username", ")", "{", "final", "Jo...
Create a job given the definition in {@code job}. @param job The job to create. @param username The user creating the job. @return The response.
[ "Create", "a", "job", "given", "the", "definition", "in", "{", "@code", "job", "}", "." ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-services/src/main/java/com/spotify/helios/master/resources/JobsResource.java#L169-L196
jfinal/jfinal
src/main/java/com/jfinal/plugin/activerecord/Db.java
Db.queryFirst
public static <T> T queryFirst(String sql, Object... paras) { return MAIN.queryFirst(sql, paras); }
java
public static <T> T queryFirst(String sql, Object... paras) { return MAIN.queryFirst(sql, paras); }
[ "public", "static", "<", "T", ">", "T", "queryFirst", "(", "String", "sql", ",", "Object", "...", "paras", ")", "{", "return", "MAIN", ".", "queryFirst", "(", "sql", ",", "paras", ")", ";", "}" ]
Execute sql query and return the first result. I recommend add "limit 1" in your sql. @param sql an SQL statement that may contain one or more '?' IN parameter placeholders @param paras the parameters of sql @return Object[] if your sql has select more than one column, and it return Object if your sql has select only one column.
[ "Execute", "sql", "query", "and", "return", "the", "first", "result", ".", "I", "recommend", "add", "limit", "1", "in", "your", "sql", "." ]
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Db.java#L95-L97
haraldk/TwelveMonkeys
imageio/imageio-jpeg/src/main/java/com/twelvemonkeys/imageio/plugins/jpeg/JPEGLosslessDecoderWrapper.java
JPEGLosslessDecoderWrapper.to8Bit1ComponentGrayScale
private BufferedImage to8Bit1ComponentGrayScale(int[][] decoded, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < imageBuffer.length; i++) { imageBuffer[i] = (byte) decoded[0][i]; } return image; }
java
private BufferedImage to8Bit1ComponentGrayScale(int[][] decoded, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < imageBuffer.length; i++) { imageBuffer[i] = (byte) decoded[0][i]; } return image; }
[ "private", "BufferedImage", "to8Bit1ComponentGrayScale", "(", "int", "[", "]", "[", "]", "decoded", ",", "int", "width", ",", "int", "height", ")", "{", "BufferedImage", "image", "=", "new", "BufferedImage", "(", "width", ",", "height", ",", "BufferedImage", ...
Converts the decoded buffer into a BufferedImage. precision: 8 bit, componentCount = 1 @param decoded data buffer @param width of the image @param height of the image @return a BufferedImage.TYPE_BYTE_GRAY
[ "Converts", "the", "decoded", "buffer", "into", "a", "BufferedImage", ".", "precision", ":", "8", "bit", "componentCount", "=", "1" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-jpeg/src/main/java/com/twelvemonkeys/imageio/plugins/jpeg/JPEGLosslessDecoderWrapper.java#L160-L169
adorsys/hbci4java-adorsys
src/main/java/org/kapott/hbci/sepa/SepaVersion.java
SepaVersion.byURN
public static SepaVersion byURN(String urn) { SepaVersion test = new SepaVersion(null, 0, urn, null, false); if (urn == null || urn.length() == 0) return test; for (List<SepaVersion> types : knownVersions.values()) { for (SepaVersion v : types) { if (v.equals(test)) return v; } } // keine passende Version gefunden. Dann erzeugen wir selbst eine return test; }
java
public static SepaVersion byURN(String urn) { SepaVersion test = new SepaVersion(null, 0, urn, null, false); if (urn == null || urn.length() == 0) return test; for (List<SepaVersion> types : knownVersions.values()) { for (SepaVersion v : types) { if (v.equals(test)) return v; } } // keine passende Version gefunden. Dann erzeugen wir selbst eine return test; }
[ "public", "static", "SepaVersion", "byURN", "(", "String", "urn", ")", "{", "SepaVersion", "test", "=", "new", "SepaVersion", "(", "null", ",", "0", ",", "urn", ",", "null", ",", "false", ")", ";", "if", "(", "urn", "==", "null", "||", "urn", ".", ...
Liefert die SEPA-Version aus dem URN. @param urn URN. In der Form "urn:iso:std:iso:20022:tech:xsd:pain.001.002.03" oder in der alten Form "sepade.pain.001.001.02.xsd". @return die SEPA-Version.
[ "Liefert", "die", "SEPA", "-", "Version", "aus", "dem", "URN", "." ]
train
https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/sepa/SepaVersion.java#L157-L172
Netflix/conductor
core/src/main/java/com/netflix/conductor/service/utils/ServiceUtils.java
ServiceUtils.checkNotNullOrEmpty
public static void checkNotNullOrEmpty(String input, String errorMessage) { try { Preconditions.checkArgument(StringUtils.isNotBlank(input), errorMessage); } catch (IllegalArgumentException exception) { throw new ApplicationException(ApplicationException.Code.INVALID_INPUT, errorMessage); } }
java
public static void checkNotNullOrEmpty(String input, String errorMessage) { try { Preconditions.checkArgument(StringUtils.isNotBlank(input), errorMessage); } catch (IllegalArgumentException exception) { throw new ApplicationException(ApplicationException.Code.INVALID_INPUT, errorMessage); } }
[ "public", "static", "void", "checkNotNullOrEmpty", "(", "String", "input", ",", "String", "errorMessage", ")", "{", "try", "{", "Preconditions", ".", "checkArgument", "(", "StringUtils", ".", "isNotBlank", "(", "input", ")", ",", "errorMessage", ")", ";", "}",...
This method checks it the input string is null or empty. @param input input of type {@link String} @param errorMessage The exception message use if the string is empty or null @throws com.netflix.conductor.core.execution.ApplicationException if input string is not valid
[ "This", "method", "checks", "it", "the", "input", "string", "is", "null", "or", "empty", "." ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/core/src/main/java/com/netflix/conductor/service/utils/ServiceUtils.java#L88-L94
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/map/cache/TileCache.java
TileCache.addTile
public VectorTile addTile(TileCode tileCode) { String code = tileCode.toString(); VectorTile tile = tiles.get(code); if (tile == null) { tile = new VectorTile(tileCode, calcBoundsForTileCode(tileCode), this); tile.setPictureStyle(new PictureStyle(layer.getOpacity())); tiles.put(code, tile); } return tile; }
java
public VectorTile addTile(TileCode tileCode) { String code = tileCode.toString(); VectorTile tile = tiles.get(code); if (tile == null) { tile = new VectorTile(tileCode, calcBoundsForTileCode(tileCode), this); tile.setPictureStyle(new PictureStyle(layer.getOpacity())); tiles.put(code, tile); } return tile; }
[ "public", "VectorTile", "addTile", "(", "TileCode", "tileCode", ")", "{", "String", "code", "=", "tileCode", ".", "toString", "(", ")", ";", "VectorTile", "tile", "=", "tiles", ".", "get", "(", "code", ")", ";", "if", "(", "tile", "==", "null", ")", ...
Adds the tile with the specified code to the cache or returns the tile if it's already in the cache. @param tileCode A {@link TileCode} instance.
[ "Adds", "the", "tile", "with", "the", "specified", "code", "to", "the", "cache", "or", "returns", "the", "tile", "if", "it", "s", "already", "in", "the", "cache", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/cache/TileCache.java#L104-L113
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/BroxWarpingSpacial.java
BroxWarpingSpacial.process
public void process(ImagePyramid<GrayF32> image1 , ImagePyramid<GrayF32> image2 ) { // Process the pyramid from low resolution to high resolution boolean first = true; for( int i = image1.getNumLayers()-1; i >= 0; i-- ) { GrayF32 layer1 = image1.getLayer(i); GrayF32 layer2 = image2.getLayer(i); resizeForLayer(layer1.width,layer2.height); // compute image derivatives gradient.process(layer1,deriv1X,deriv1Y); gradient.process(layer2,deriv2X,deriv2Y); hessian.process(deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); if( !first ) { // interpolate initial flow from previous layer interpolateFlowScale(layer1.width, layer1.height); } else { // for the very first layer there is no information on flow so set everything to 0 first = false; flowU.reshape(layer1.width, layer1.height); flowV.reshape(layer1.width, layer1.height); ImageMiscOps.fill(flowU,0); ImageMiscOps.fill(flowV,0); } // compute flow for this layer processLayer(layer1,layer2,deriv1X,deriv1Y,deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); } }
java
public void process(ImagePyramid<GrayF32> image1 , ImagePyramid<GrayF32> image2 ) { // Process the pyramid from low resolution to high resolution boolean first = true; for( int i = image1.getNumLayers()-1; i >= 0; i-- ) { GrayF32 layer1 = image1.getLayer(i); GrayF32 layer2 = image2.getLayer(i); resizeForLayer(layer1.width,layer2.height); // compute image derivatives gradient.process(layer1,deriv1X,deriv1Y); gradient.process(layer2,deriv2X,deriv2Y); hessian.process(deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); if( !first ) { // interpolate initial flow from previous layer interpolateFlowScale(layer1.width, layer1.height); } else { // for the very first layer there is no information on flow so set everything to 0 first = false; flowU.reshape(layer1.width, layer1.height); flowV.reshape(layer1.width, layer1.height); ImageMiscOps.fill(flowU,0); ImageMiscOps.fill(flowV,0); } // compute flow for this layer processLayer(layer1,layer2,deriv1X,deriv1Y,deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); } }
[ "public", "void", "process", "(", "ImagePyramid", "<", "GrayF32", ">", "image1", ",", "ImagePyramid", "<", "GrayF32", ">", "image2", ")", "{", "// Process the pyramid from low resolution to high resolution", "boolean", "first", "=", "true", ";", "for", "(", "int", ...
Computes dense optical flow from the provided image pyramid. Image gradient for each layer should be computed directly from the layer images. @param image1 Pyramid of first image @param image2 Pyramid of second image
[ "Computes", "dense", "optical", "flow", "from", "the", "provided", "image", "pyramid", ".", "Image", "gradient", "for", "each", "layer", "should", "be", "computed", "directly", "from", "the", "layer", "images", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/BroxWarpingSpacial.java#L145-L177
radkovo/CSSBox
src/main/java/org/fit/cssbox/css/NormalOutput.java
NormalOutput.dumpTo
public void dumpTo(OutputStream out) { PrintWriter writer; try { writer = new PrintWriter(new OutputStreamWriter(out, "utf-8")); } catch (UnsupportedEncodingException e) { writer = new PrintWriter(out); } recursiveDump(root, 0, writer); writer.close(); }
java
public void dumpTo(OutputStream out) { PrintWriter writer; try { writer = new PrintWriter(new OutputStreamWriter(out, "utf-8")); } catch (UnsupportedEncodingException e) { writer = new PrintWriter(out); } recursiveDump(root, 0, writer); writer.close(); }
[ "public", "void", "dumpTo", "(", "OutputStream", "out", ")", "{", "PrintWriter", "writer", ";", "try", "{", "writer", "=", "new", "PrintWriter", "(", "new", "OutputStreamWriter", "(", "out", ",", "\"utf-8\"", ")", ")", ";", "}", "catch", "(", "UnsupportedE...
Formats the complete tag tree to an output stream. @param out The output stream to be used for the output.
[ "Formats", "the", "complete", "tag", "tree", "to", "an", "output", "stream", "." ]
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/css/NormalOutput.java#L54-L64
knowm/XChange
xchange-bitso/src/main/java/org/knowm/xchange/bitso/service/BitsoAccountServiceRaw.java
BitsoAccountServiceRaw.withdrawToRipple
public boolean withdrawToRipple(BigDecimal amount, Currency currency, String rippleAddress) throws IOException { final String result = bitsoAuthenticated.withdrawToRipple( exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), amount, currency.getCurrencyCode(), rippleAddress); return "ok".equals(result); }
java
public boolean withdrawToRipple(BigDecimal amount, Currency currency, String rippleAddress) throws IOException { final String result = bitsoAuthenticated.withdrawToRipple( exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), amount, currency.getCurrencyCode(), rippleAddress); return "ok".equals(result); }
[ "public", "boolean", "withdrawToRipple", "(", "BigDecimal", "amount", ",", "Currency", "currency", ",", "String", "rippleAddress", ")", "throws", "IOException", "{", "final", "String", "result", "=", "bitsoAuthenticated", ".", "withdrawToRipple", "(", "exchange", "....
Withdraws funds to Ripple and associates the receiving Ripple address with the Bitso account for deposits. NOTE: The Ripple address associated to your account for deposits will be updated accordingly! Please ensure that any subsequent Ripple funding emanates from this address. @return true if withdrawal was successful.
[ "Withdraws", "funds", "to", "Ripple", "and", "associates", "the", "receiving", "Ripple", "address", "with", "the", "Bitso", "account", "for", "deposits", ".", "NOTE", ":", "The", "Ripple", "address", "associated", "to", "your", "account", "for", "deposits", "w...
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bitso/src/main/java/org/knowm/xchange/bitso/service/BitsoAccountServiceRaw.java#L82-L94
VoltDB/voltdb
third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java
ZooKeeper.setData
public Stat setData(final String path, byte data[], int version) throws KeeperException, InterruptedException { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.setData); SetDataRequest request = new SetDataRequest(); request.setPath(serverPath); request.setData(data); request.setVersion(version); SetDataResponse response = new SetDataResponse(); ReplyHeader r = cnxn.submitRequest(h, request, response, null); if (r.getErr() != 0) { throw KeeperException.create(KeeperException.Code.get(r.getErr()), clientPath); } return response.getStat(); }
java
public Stat setData(final String path, byte data[], int version) throws KeeperException, InterruptedException { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.setData); SetDataRequest request = new SetDataRequest(); request.setPath(serverPath); request.setData(data); request.setVersion(version); SetDataResponse response = new SetDataResponse(); ReplyHeader r = cnxn.submitRequest(h, request, response, null); if (r.getErr() != 0) { throw KeeperException.create(KeeperException.Code.get(r.getErr()), clientPath); } return response.getStat(); }
[ "public", "Stat", "setData", "(", "final", "String", "path", ",", "byte", "data", "[", "]", ",", "int", "version", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "verbotenThreadCheck", "(", ")", ";", "final", "String", "clientPath", "=", ...
Set the data for the node of the given path if such a node exists and the given version matches the version of the node (if the given version is -1, it matches any node's versions). Return the stat of the node. <p> This operation, if successful, will trigger all the watches on the node of the given path left by getData calls. <p> A KeeperException with error code KeeperException.NoNode will be thrown if no node with the given path exists. <p> A KeeperException with error code KeeperException.BadVersion will be thrown if the given version does not match the node's version. <p> The maximum allowable size of the data array is 1 MB (1,048,576 bytes). Arrays larger than this will cause a KeeperExecption to be thrown. @param path the path of the node @param data the data to set @param version the expected matching version @return the state of the node @throws InterruptedException If the server transaction is interrupted. @throws KeeperException If the server signals an error with a non-zero error code. @throws IllegalArgumentException if an invalid path is specified
[ "Set", "the", "data", "for", "the", "node", "of", "the", "given", "path", "if", "such", "a", "node", "exists", "and", "the", "given", "version", "matches", "the", "version", "of", "the", "node", "(", "if", "the", "given", "version", "is", "-", "1", "...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1074-L1095
Netflix/governator
governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationOwnershipPolicies.java
ConfigurationOwnershipPolicies.ownsAll
public static ConfigurationOwnershipPolicy ownsAll() { return new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return true; } }; }
java
public static ConfigurationOwnershipPolicy ownsAll() { return new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return true; } }; }
[ "public", "static", "ConfigurationOwnershipPolicy", "ownsAll", "(", ")", "{", "return", "new", "ConfigurationOwnershipPolicy", "(", ")", "{", "@", "Override", "public", "boolean", "has", "(", "ConfigurationKey", "key", ",", "Map", "<", "String", ",", "String", "...
Return an ownership policy that returns true for {@link ConfigurationOwnershipPolicy#has(ConfigurationKey, Map)} @return policy
[ "Return", "an", "ownership", "policy", "that", "returns", "true", "for", "{", "@link", "ConfigurationOwnershipPolicy#has", "(", "ConfigurationKey", "Map", ")", "}" ]
train
https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationOwnershipPolicies.java#L47-L57
xcesco/kripton
kripton/src/main/java/com/abubusoft/kripton/xml/XMLParser.java
XMLParser.peekType
private int peekType(boolean inDeclaration) throws IOException, KriptonRuntimeException { if (position >= limit && !fillBuffer(1)) { return END_DOCUMENT; } switch (buffer[position]) { case '&': return ENTITY_REF; // & case '<': if (position + 3 >= limit && !fillBuffer(4)) { throw new KriptonRuntimeException("Dangling <", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null); } switch (buffer[position + 1]) { case '/': return END_TAG; // </ case '?': // we're looking for "<?xml " with case insensitivity if ((position + 5 < limit || fillBuffer(6)) && (buffer[position + 2] == 'x' || buffer[position + 2] == 'X') && (buffer[position + 3] == 'm' || buffer[position + 3] == 'M') && (buffer[position + 4] == 'l' || buffer[position + 4] == 'L') && (buffer[position + 5] == ' ')) { return XML_DECLARATION; // <?xml } else { return PROCESSING_INSTRUCTION; // <? } case '!': switch (buffer[position + 2]) { case 'D': return DOCDECL; // <!D case '[': return CDSECT; // <![ case '-': return COMMENT; // <!- case 'E': switch (buffer[position + 3]) { case 'L': return ELEMENTDECL; // <!EL case 'N': return ENTITYDECL; // <!EN } break; case 'A': return ATTLISTDECL; // <!A case 'N': return NOTATIONDECL; // <!N } throw new KriptonRuntimeException("Unexpected <!", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null); default: return START_TAG; // < } case '%': return inDeclaration ? PARAMETER_ENTITY_REF : TEXT; default: return TEXT; } }
java
private int peekType(boolean inDeclaration) throws IOException, KriptonRuntimeException { if (position >= limit && !fillBuffer(1)) { return END_DOCUMENT; } switch (buffer[position]) { case '&': return ENTITY_REF; // & case '<': if (position + 3 >= limit && !fillBuffer(4)) { throw new KriptonRuntimeException("Dangling <", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null); } switch (buffer[position + 1]) { case '/': return END_TAG; // </ case '?': // we're looking for "<?xml " with case insensitivity if ((position + 5 < limit || fillBuffer(6)) && (buffer[position + 2] == 'x' || buffer[position + 2] == 'X') && (buffer[position + 3] == 'm' || buffer[position + 3] == 'M') && (buffer[position + 4] == 'l' || buffer[position + 4] == 'L') && (buffer[position + 5] == ' ')) { return XML_DECLARATION; // <?xml } else { return PROCESSING_INSTRUCTION; // <? } case '!': switch (buffer[position + 2]) { case 'D': return DOCDECL; // <!D case '[': return CDSECT; // <![ case '-': return COMMENT; // <!- case 'E': switch (buffer[position + 3]) { case 'L': return ELEMENTDECL; // <!EL case 'N': return ENTITYDECL; // <!EN } break; case 'A': return ATTLISTDECL; // <!A case 'N': return NOTATIONDECL; // <!N } throw new KriptonRuntimeException("Unexpected <!", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null); default: return START_TAG; // < } case '%': return inDeclaration ? PARAMETER_ENTITY_REF : TEXT; default: return TEXT; } }
[ "private", "int", "peekType", "(", "boolean", "inDeclaration", ")", "throws", "IOException", ",", "KriptonRuntimeException", "{", "if", "(", "position", ">=", "limit", "&&", "!", "fillBuffer", "(", "1", ")", ")", "{", "return", "END_DOCUMENT", ";", "}", "swi...
Returns the type of the next token. @param inDeclaration the in declaration @return the int @throws IOException Signals that an I/O exception has occurred. @throws KriptonRuntimeException the kripton runtime exception
[ "Returns", "the", "type", "of", "the", "next", "token", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLParser.java#L1195-L1249
alkacon/opencms-core
src/org/opencms/security/CmsDefaultPasswordGenerator.java
CmsDefaultPasswordGenerator.getRandomPWD
public static String getRandomPWD(int countTotal, int countCapitals, int countSpecials) { CmsDefaultPasswordGenerator generator = new CmsDefaultPasswordGenerator(); return generator.getRandomPassword(countTotal, countCapitals, countSpecials); }
java
public static String getRandomPWD(int countTotal, int countCapitals, int countSpecials) { CmsDefaultPasswordGenerator generator = new CmsDefaultPasswordGenerator(); return generator.getRandomPassword(countTotal, countCapitals, countSpecials); }
[ "public", "static", "String", "getRandomPWD", "(", "int", "countTotal", ",", "int", "countCapitals", ",", "int", "countSpecials", ")", "{", "CmsDefaultPasswordGenerator", "generator", "=", "new", "CmsDefaultPasswordGenerator", "(", ")", ";", "return", "generator", "...
Get a random password.<p> @param countTotal Desired password length @param countCapitals minimal count of Capital letters @param countSpecials count of special chars @return random password
[ "Get", "a", "random", "password", ".", "<p", ">", "@param", "countTotal", "Desired", "password", "length", "@param", "countCapitals", "minimal", "count", "of", "Capital", "letters", "@param", "countSpecials", "count", "of", "special", "chars" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsDefaultPasswordGenerator.java#L136-L140
OpenLiberty/open-liberty
dev/com.ibm.ws.app.manager/src/com/ibm/ws/app/manager/internal/FutureCollectionCompletionListener.java
FutureCollectionCompletionListener.newFutureCollectionCompletionListener
public static void newFutureCollectionCompletionListener(Collection<ApplicationDependency> futureConditions, CompletionListener<Boolean> newCL) { if (futureConditions.isEmpty()) { newCL.successfulCompletion(null, true); } else { FutureCollectionCompletionListener futureListener = new FutureCollectionCompletionListener(futureConditions.size(), newCL); futureListener.onCompletion(futureConditions); } }
java
public static void newFutureCollectionCompletionListener(Collection<ApplicationDependency> futureConditions, CompletionListener<Boolean> newCL) { if (futureConditions.isEmpty()) { newCL.successfulCompletion(null, true); } else { FutureCollectionCompletionListener futureListener = new FutureCollectionCompletionListener(futureConditions.size(), newCL); futureListener.onCompletion(futureConditions); } }
[ "public", "static", "void", "newFutureCollectionCompletionListener", "(", "Collection", "<", "ApplicationDependency", ">", "futureConditions", ",", "CompletionListener", "<", "Boolean", ">", "newCL", ")", "{", "if", "(", "futureConditions", ".", "isEmpty", "(", ")", ...
/* Caller is responsible for ensuring that the futureConditions collection is immutable.
[ "/", "*", "Caller", "is", "responsible", "for", "ensuring", "that", "the", "futureConditions", "collection", "is", "immutable", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.app.manager/src/com/ibm/ws/app/manager/internal/FutureCollectionCompletionListener.java#L29-L36
deeplearning4j/deeplearning4j
datavec/datavec-jdbc/src/main/java/org/datavec/api/records/reader/impl/jdbc/JDBCRecordReader.java
JDBCRecordReader.nextRecord
@Override public Record nextRecord() { Object[] next = iter.next(); invokeListeners(next); URI location; try { location = new URI(conn.getMetaData().getURL()); } catch (SQLException | URISyntaxException e) { throw new IllegalStateException("Could not get sql connection metadata", e); } List<Object> params = new ArrayList<>(); if (metadataIndices != null) { for (int index : metadataIndices) { params.add(next[index]); } } RecordMetaDataJdbc rmd = new RecordMetaDataJdbc(location, this.metadataQuery, params, getClass()); return new org.datavec.api.records.impl.Record(toWritable(next), rmd); }
java
@Override public Record nextRecord() { Object[] next = iter.next(); invokeListeners(next); URI location; try { location = new URI(conn.getMetaData().getURL()); } catch (SQLException | URISyntaxException e) { throw new IllegalStateException("Could not get sql connection metadata", e); } List<Object> params = new ArrayList<>(); if (metadataIndices != null) { for (int index : metadataIndices) { params.add(next[index]); } } RecordMetaDataJdbc rmd = new RecordMetaDataJdbc(location, this.metadataQuery, params, getClass()); return new org.datavec.api.records.impl.Record(toWritable(next), rmd); }
[ "@", "Override", "public", "Record", "nextRecord", "(", ")", "{", "Object", "[", "]", "next", "=", "iter", ".", "next", "(", ")", ";", "invokeListeners", "(", "next", ")", ";", "URI", "location", ";", "try", "{", "location", "=", "new", "URI", "(", ...
Get next record with metadata. See {@link #loadFromMetaData(RecordMetaData)} for details on metadata structure.
[ "Get", "next", "record", "with", "metadata", ".", "See", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-jdbc/src/main/java/org/datavec/api/records/reader/impl/jdbc/JDBCRecordReader.java#L246-L267
FXMisc/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java
MultiChangeBuilder.deleteTextAbsolutely
public MultiChangeBuilder<PS, SEG, S> deleteTextAbsolutely(int startParagraph, int startColumn, int endParagraph, int endColumn) { int start = area.getAbsolutePosition(startParagraph, startColumn); int end = area.getAbsolutePosition(endParagraph, endColumn); return replaceTextAbsolutely(start, end, ""); }
java
public MultiChangeBuilder<PS, SEG, S> deleteTextAbsolutely(int startParagraph, int startColumn, int endParagraph, int endColumn) { int start = area.getAbsolutePosition(startParagraph, startColumn); int end = area.getAbsolutePosition(endParagraph, endColumn); return replaceTextAbsolutely(start, end, ""); }
[ "public", "MultiChangeBuilder", "<", "PS", ",", "SEG", ",", "S", ">", "deleteTextAbsolutely", "(", "int", "startParagraph", ",", "int", "startColumn", ",", "int", "endParagraph", ",", "int", "endColumn", ")", "{", "int", "start", "=", "area", ".", "getAbsolu...
Removes a range of text. It must hold {@code 0 <= start <= end <= getLength()} where {@code start = getAbsolutePosition(startParagraph, startColumn);} and is <b>inclusive</b>, and {@code int end = getAbsolutePosition(endParagraph, endColumn);} and is <b>exclusive</b>. <p><b>Caution:</b> see {@link StyledDocument#getAbsolutePosition(int, int)} to know how the column index argument can affect the returned position.</p>
[ "Removes", "a", "range", "of", "text", "." ]
train
https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java#L304-L308
LableOrg/java-uniqueid
uniqueid-core/src/main/java/org/lable/oss/uniqueid/LocalUniqueIDGeneratorFactory.java
LocalUniqueIDGeneratorFactory.generatorFor
public synchronized static IDGenerator generatorFor(int generatorId, int clusterId, Mode mode) { assertParameterWithinBounds("generatorId", 0, Blueprint.MAX_GENERATOR_ID, generatorId); assertParameterWithinBounds("clusterId", 0, Blueprint.MAX_CLUSTER_ID, clusterId); String generatorAndCluster = String.format("%d_%d", generatorId, clusterId); if (!instances.containsKey(generatorAndCluster)) { GeneratorIdentityHolder identityHolder = LocalGeneratorIdentity.with(clusterId, generatorId); instances.putIfAbsent(generatorAndCluster, new BaseUniqueIDGenerator(identityHolder, mode)); } return instances.get(generatorAndCluster); }
java
public synchronized static IDGenerator generatorFor(int generatorId, int clusterId, Mode mode) { assertParameterWithinBounds("generatorId", 0, Blueprint.MAX_GENERATOR_ID, generatorId); assertParameterWithinBounds("clusterId", 0, Blueprint.MAX_CLUSTER_ID, clusterId); String generatorAndCluster = String.format("%d_%d", generatorId, clusterId); if (!instances.containsKey(generatorAndCluster)) { GeneratorIdentityHolder identityHolder = LocalGeneratorIdentity.with(clusterId, generatorId); instances.putIfAbsent(generatorAndCluster, new BaseUniqueIDGenerator(identityHolder, mode)); } return instances.get(generatorAndCluster); }
[ "public", "synchronized", "static", "IDGenerator", "generatorFor", "(", "int", "generatorId", ",", "int", "clusterId", ",", "Mode", "mode", ")", "{", "assertParameterWithinBounds", "(", "\"generatorId\"", ",", "0", ",", "Blueprint", ".", "MAX_GENERATOR_ID", ",", "...
Return the UniqueIDGenerator instance for this specific generator-ID, cluster-ID combination. If one was already created, that is returned. @param generatorId Generator ID to use (0 ≤ n ≤ 255). @param clusterId Cluster ID to use (0 ≤ n ≤ 15). @param mode Generator mode. @return A thread-safe UniqueIDGenerator instance.
[ "Return", "the", "UniqueIDGenerator", "instance", "for", "this", "specific", "generator", "-", "ID", "cluster", "-", "ID", "combination", ".", "If", "one", "was", "already", "created", "that", "is", "returned", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-core/src/main/java/org/lable/oss/uniqueid/LocalUniqueIDGeneratorFactory.java#L45-L54
zalando/riptide
riptide-stream/src/main/java/org/zalando/riptide/stream/Streams.java
Streams.streamConverter
@SuppressWarnings("unchecked") public static <T> StreamConverter<T> streamConverter(final ObjectMapper mapper, final List<MediaType> supportedMediaTypes) { return new StreamConverter(mapper, supportedMediaTypes); }
java
@SuppressWarnings("unchecked") public static <T> StreamConverter<T> streamConverter(final ObjectMapper mapper, final List<MediaType> supportedMediaTypes) { return new StreamConverter(mapper, supportedMediaTypes); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "StreamConverter", "<", "T", ">", "streamConverter", "(", "final", "ObjectMapper", "mapper", ",", "final", "List", "<", "MediaType", ">", "supportedMediaTypes", ")", "{", "r...
Create stream converter with custom {@link ObjectMapper object mapper}, and custom list of {@link MediaType supported media types}. @param <T> generic stream element type @param mapper custom {@link ObjectMapper object mapper}. @param supportedMediaTypes custom list of {@link MediaType media types}. @return stream converter with customer object mapper.
[ "Create", "stream", "converter", "with", "custom", "{", "@link", "ObjectMapper", "object", "mapper", "}", "and", "custom", "list", "of", "{", "@link", "MediaType", "supported", "media", "types", "}", "." ]
train
https://github.com/zalando/riptide/blob/0f53529a69c864203ced5fa067dcf3d42dba0e26/riptide-stream/src/main/java/org/zalando/riptide/stream/Streams.java#L147-L151
haifengl/smile
core/src/main/java/smile/regression/NeuralNetwork.java
NeuralNetwork.computeOutputError
private double computeOutputError(double output, double[] gradient) { double error = 0.0; double out = outputLayer.output[0]; double g = output - out; error += (0.5*g * g); gradient[0] = g; return error; }
java
private double computeOutputError(double output, double[] gradient) { double error = 0.0; double out = outputLayer.output[0]; double g = output - out; error += (0.5*g * g); gradient[0] = g; return error; }
[ "private", "double", "computeOutputError", "(", "double", "output", ",", "double", "[", "]", "gradient", ")", "{", "double", "error", "=", "0.0", ";", "double", "out", "=", "outputLayer", ".", "output", "[", "0", "]", ";", "double", "g", "=", "output", ...
Compute the network output error. @param output the desired output. @param gradient the array to store gradient on output. @return the error defined by loss function.
[ "Compute", "the", "network", "output", "error", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/regression/NeuralNetwork.java#L477-L489
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/widget/LayerTree.java
LayerTree.processNode
private void processNode(final ClientLayerTreeNodeInfo treeNode, final TreeNode nodeRoot, final Tree tree, final MapModel mapModel, final boolean refresh) { if (null != treeNode) { String treeNodeLabel = treeNode.getLabel(); final TreeNode node = new TreeNode(treeNodeLabel); tree.add(node, nodeRoot); // (final leafs) for (ClientLayerInfo info : treeNode.getLayers()) { Layer<?> layer = mapModel.getLayer(info.getId()); tree.add(new LayerTreeTreeNode(this.tree, layer), node); } // treeNodes List<ClientLayerTreeNodeInfo> children = treeNode.getTreeNodes(); for (ClientLayerTreeNodeInfo newNode : children) { processNode(newNode, node, tree, mapModel, refresh); } // expand tree nodes // when not refreshing expand them like configured // when refreshing expand them as before the refresh boolean isTreeNodeExpanded = treeNode.isExpanded(); if (!refresh) { if (isTreeNodeExpanded) { tree.openFolder(node); } } else { // TODO close previously opened tree nodes, close others } } }
java
private void processNode(final ClientLayerTreeNodeInfo treeNode, final TreeNode nodeRoot, final Tree tree, final MapModel mapModel, final boolean refresh) { if (null != treeNode) { String treeNodeLabel = treeNode.getLabel(); final TreeNode node = new TreeNode(treeNodeLabel); tree.add(node, nodeRoot); // (final leafs) for (ClientLayerInfo info : treeNode.getLayers()) { Layer<?> layer = mapModel.getLayer(info.getId()); tree.add(new LayerTreeTreeNode(this.tree, layer), node); } // treeNodes List<ClientLayerTreeNodeInfo> children = treeNode.getTreeNodes(); for (ClientLayerTreeNodeInfo newNode : children) { processNode(newNode, node, tree, mapModel, refresh); } // expand tree nodes // when not refreshing expand them like configured // when refreshing expand them as before the refresh boolean isTreeNodeExpanded = treeNode.isExpanded(); if (!refresh) { if (isTreeNodeExpanded) { tree.openFolder(node); } } else { // TODO close previously opened tree nodes, close others } } }
[ "private", "void", "processNode", "(", "final", "ClientLayerTreeNodeInfo", "treeNode", ",", "final", "TreeNode", "nodeRoot", ",", "final", "Tree", "tree", ",", "final", "MapModel", "mapModel", ",", "final", "boolean", "refresh", ")", "{", "if", "(", "null", "!...
Processes a treeNode (add it to the TreeGrid) @param treeNode The treeNode to process @param nodeRoot The root node to which the treeNode has te be added @param tree The tree to which the node has to be added @param mapModel map model @param refresh True if the tree is refreshed (causing it to keep its expanded state)
[ "Processes", "a", "treeNode", "(", "add", "it", "to", "the", "TreeGrid", ")" ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/widget/LayerTree.java#L341-L373
alibaba/transmittable-thread-local
src/main/java/com/alibaba/ttl/TtlTimerTask.java
TtlTimerTask.get
@Nullable public static TtlTimerTask get(@Nullable TimerTask timerTask, boolean releaseTtlValueReferenceAfterRun, boolean idempotent) { if (null == timerTask) return null; if (timerTask instanceof TtlEnhanced) { // avoid redundant decoration, and ensure idempotency if (idempotent) return (TtlTimerTask) timerTask; else throw new IllegalStateException("Already TtlTimerTask!"); } return new TtlTimerTask(timerTask, releaseTtlValueReferenceAfterRun); }
java
@Nullable public static TtlTimerTask get(@Nullable TimerTask timerTask, boolean releaseTtlValueReferenceAfterRun, boolean idempotent) { if (null == timerTask) return null; if (timerTask instanceof TtlEnhanced) { // avoid redundant decoration, and ensure idempotency if (idempotent) return (TtlTimerTask) timerTask; else throw new IllegalStateException("Already TtlTimerTask!"); } return new TtlTimerTask(timerTask, releaseTtlValueReferenceAfterRun); }
[ "@", "Nullable", "public", "static", "TtlTimerTask", "get", "(", "@", "Nullable", "TimerTask", "timerTask", ",", "boolean", "releaseTtlValueReferenceAfterRun", ",", "boolean", "idempotent", ")", "{", "if", "(", "null", "==", "timerTask", ")", "return", "null", "...
Factory method, wrap input {@link TimerTask} to {@link TtlTimerTask}. <p> This method is idempotent. @param timerTask input {@link TimerTask} @param releaseTtlValueReferenceAfterRun release TTL value reference after run, avoid memory leak even if {@link TtlTimerTask} is referred. @param idempotent is idempotent or not. {@code true} will cover up bugs! <b>DO NOT</b> set, only when you know why. @return Wrapped {@link TimerTask}
[ "Factory", "method", "wrap", "input", "{", "@link", "TimerTask", "}", "to", "{", "@link", "TtlTimerTask", "}", ".", "<p", ">", "This", "method", "is", "idempotent", "." ]
train
https://github.com/alibaba/transmittable-thread-local/blob/30b4d99cdb7064b4c1797d2e40bfa07adce8e7f9/src/main/java/com/alibaba/ttl/TtlTimerTask.java#L120-L130
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/ws/tcpchannel/internal/TCPPort.java
TCPPort.attemptSocketBind
private void attemptSocketBind(InetSocketAddress address, boolean reuseflag) throws IOException { this.serverSocket.setReuseAddress(reuseflag); this.serverSocket.bind(address, this.tcpChannel.getConfig().getListenBacklog()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "ServerSocket bind worked, reuse=" + this.serverSocket.getReuseAddress()); } }
java
private void attemptSocketBind(InetSocketAddress address, boolean reuseflag) throws IOException { this.serverSocket.setReuseAddress(reuseflag); this.serverSocket.bind(address, this.tcpChannel.getConfig().getListenBacklog()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "ServerSocket bind worked, reuse=" + this.serverSocket.getReuseAddress()); } }
[ "private", "void", "attemptSocketBind", "(", "InetSocketAddress", "address", ",", "boolean", "reuseflag", ")", "throws", "IOException", "{", "this", ".", "serverSocket", ".", "setReuseAddress", "(", "reuseflag", ")", ";", "this", ".", "serverSocket", ".", "bind", ...
Attempt a socket bind to the input address with the given re-use option flag. @param address @param reuseflag @throws IOException
[ "Attempt", "a", "socket", "bind", "to", "the", "input", "address", "with", "the", "given", "re", "-", "use", "option", "flag", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/tcpchannel/internal/TCPPort.java#L85-L91
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.pressImage
public static void pressImage(Image srcImage, File outFile, Image pressImg, int x, int y, float alpha) throws IORuntimeException { write(pressImage(srcImage, pressImg, x, y, alpha), outFile); }
java
public static void pressImage(Image srcImage, File outFile, Image pressImg, int x, int y, float alpha) throws IORuntimeException { write(pressImage(srcImage, pressImg, x, y, alpha), outFile); }
[ "public", "static", "void", "pressImage", "(", "Image", "srcImage", ",", "File", "outFile", ",", "Image", "pressImg", ",", "int", "x", ",", "int", "y", ",", "float", "alpha", ")", "throws", "IORuntimeException", "{", "write", "(", "pressImage", "(", "srcIm...
给图片添加图片水印<br> 此方法并不关闭流 @param srcImage 源图像流 @param outFile 写出文件 @param pressImg 水印图片,可以使用{@link ImageIO#read(File)}方法读取文件 @param x 修正值。 默认在中间,偏移量相对于中间偏移 @param y 修正值。 默认在中间,偏移量相对于中间偏移 @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字 @throws IORuntimeException IO异常 @since 3.2.2
[ "给图片添加图片水印<br", ">", "此方法并不关闭流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L924-L926
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java
BankCardMagneticTrack.from
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
java
public static BankCardMagneticTrack from(final String rawTrackData) { final Track1FormatB track1 = Track1FormatB.from(rawTrackData); final Track2 track2 = Track2.from(rawTrackData); final Track3 track3 = Track3.from(rawTrackData); return new BankCardMagneticTrack(rawTrackData, track1, track2, track3); }
[ "public", "static", "BankCardMagneticTrack", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Track1FormatB", "track1", "=", "Track1FormatB", ".", "from", "(", "rawTrackData", ")", ";", "final", "Track2", "track2", "=", "Track2", ".", "from", ...
Parses magnetic track data into a BankCardMagneticTrack object. @param rawTrackData Raw track data as a string. Can include newlines, and all 3 tracks. @return A BankCardMagneticTrack instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "data", "into", "a", "BankCardMagneticTrack", "object", "." ]
train
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/BankCardMagneticTrack.java#L48-L55
nats-io/java-nats
src/main/java/io/nats/client/NKey.java
NKey.fromPublicKey
public static NKey fromPublicKey(char[] publicKey) { byte[] raw = decode(publicKey); int prefix = raw[0] & 0xFF; if (!checkValidPublicPrefixByte(prefix)) { throw new IllegalArgumentException("Not a valid public NKey"); } Type type = NKey.Type.fromPrefix(prefix); return new NKey(type, publicKey, null); }
java
public static NKey fromPublicKey(char[] publicKey) { byte[] raw = decode(publicKey); int prefix = raw[0] & 0xFF; if (!checkValidPublicPrefixByte(prefix)) { throw new IllegalArgumentException("Not a valid public NKey"); } Type type = NKey.Type.fromPrefix(prefix); return new NKey(type, publicKey, null); }
[ "public", "static", "NKey", "fromPublicKey", "(", "char", "[", "]", "publicKey", ")", "{", "byte", "[", "]", "raw", "=", "decode", "(", "publicKey", ")", ";", "int", "prefix", "=", "raw", "[", "0", "]", "&", "0xFF", ";", "if", "(", "!", "checkValid...
Create an NKey object from the encoded public key. This NKey can be used for verification but not for signing. @param publicKey the string encoded public key @return the new Nkey
[ "Create", "an", "NKey", "object", "from", "the", "encoded", "public", "key", ".", "This", "NKey", "can", "be", "used", "for", "verification", "but", "not", "for", "signing", "." ]
train
https://github.com/nats-io/java-nats/blob/5f291048fd30192ba39b3fe2925ecd60aaad6b48/src/main/java/io/nats/client/NKey.java#L562-L572
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.createProject
public Project createProject(String name, CreateProjectOptionalParameter createProjectOptionalParameter) { return createProjectWithServiceResponseAsync(name, createProjectOptionalParameter).toBlocking().single().body(); }
java
public Project createProject(String name, CreateProjectOptionalParameter createProjectOptionalParameter) { return createProjectWithServiceResponseAsync(name, createProjectOptionalParameter).toBlocking().single().body(); }
[ "public", "Project", "createProject", "(", "String", "name", ",", "CreateProjectOptionalParameter", "createProjectOptionalParameter", ")", "{", "return", "createProjectWithServiceResponseAsync", "(", "name", ",", "createProjectOptionalParameter", ")", ".", "toBlocking", "(", ...
Create a project. @param name Name of the project @param createProjectOptionalParameter the object representing the optional parameters to be set before calling this API @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 Project object if successful.
[ "Create", "a", "project", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L2359-L2361
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
HttpBuilder.traceAsync
public CompletableFuture<Object> traceAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> trace(closure), getExecutor()); }
java
public CompletableFuture<Object> traceAsync(@DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> trace(closure), getExecutor()); }
[ "public", "CompletableFuture", "<", "Object", ">", "traceAsync", "(", "@", "DelegatesTo", "(", "HttpConfig", ".", "class", ")", "final", "Closure", "closure", ")", "{", "return", "CompletableFuture", ".", "supplyAsync", "(", "(", ")", "->", "trace", "(", "cl...
Executes an asynchronous TRACE request on the configured URI (asynchronous alias to the `trace(Closure)` method), with additional configuration provided by the configuration closure. [source,groovy] ---- def http = HttpBuilder.configure { request.uri = 'http://localhost:10101' } http.traceAsync(){ request.uri.path = '/something' } ---- The configuration `closure` allows additional configuration for this request based on the {@link HttpConfig} interface. @param closure the additional configuration closure (delegated to {@link HttpConfig}) @return the resulting content
[ "Executes", "an", "asynchronous", "TRACE", "request", "on", "the", "configured", "URI", "(", "asynchronous", "alias", "to", "the", "trace", "(", "Closure", ")", "method", ")", "with", "additional", "configuration", "provided", "by", "the", "configuration", "clos...
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L2139-L2141
chr78rm/tracelogger
src/main/java/de/christofreichardt/diagnosis/NullTracer.java
NullTracer.logMessage
@Override public void logMessage(LogLevel logLevel, String message, Class clazz, String methodName) { }
java
@Override public void logMessage(LogLevel logLevel, String message, Class clazz, String methodName) { }
[ "@", "Override", "public", "void", "logMessage", "(", "LogLevel", "logLevel", ",", "String", "message", ",", "Class", "clazz", ",", "String", "methodName", ")", "{", "}" ]
Pseudo logMessage()-method. Derived classes should provide code which connects to an alternative logging system. @param logLevel (ignored) @param message (ignored) @param clazz (ignored)
[ "Pseudo", "logMessage", "()", "-", "method", ".", "Derived", "classes", "should", "provide", "code", "which", "connects", "to", "an", "alternative", "logging", "system", "." ]
train
https://github.com/chr78rm/tracelogger/blob/ad22452b20f8111ad4d367302c2b26a100a20200/src/main/java/de/christofreichardt/diagnosis/NullTracer.java#L173-L175
JOML-CI/JOML
src/org/joml/Matrix3f.java
Matrix3f.rotateLocalY
public Matrix3f rotateLocalY(float ang, Matrix3f dest) { float sin = (float) Math.sin(ang); float cos = (float) Math.cosFromSin(sin, ang); float nm00 = cos * m00 + sin * m02; float nm02 = -sin * m00 + cos * m02; float nm10 = cos * m10 + sin * m12; float nm12 = -sin * m10 + cos * m12; float nm20 = cos * m20 + sin * m22; float nm22 = -sin * m20 + cos * m22; dest.m00 = nm00; dest.m01 = m01; dest.m02 = nm02; dest.m10 = nm10; dest.m11 = m11; dest.m12 = nm12; dest.m20 = nm20; dest.m21 = m21; dest.m22 = nm22; return dest; }
java
public Matrix3f rotateLocalY(float ang, Matrix3f dest) { float sin = (float) Math.sin(ang); float cos = (float) Math.cosFromSin(sin, ang); float nm00 = cos * m00 + sin * m02; float nm02 = -sin * m00 + cos * m02; float nm10 = cos * m10 + sin * m12; float nm12 = -sin * m10 + cos * m12; float nm20 = cos * m20 + sin * m22; float nm22 = -sin * m20 + cos * m22; dest.m00 = nm00; dest.m01 = m01; dest.m02 = nm02; dest.m10 = nm10; dest.m11 = m11; dest.m12 = nm12; dest.m20 = nm20; dest.m21 = m21; dest.m22 = nm22; return dest; }
[ "public", "Matrix3f", "rotateLocalY", "(", "float", "ang", ",", "Matrix3f", "dest", ")", "{", "float", "sin", "=", "(", "float", ")", "Math", ".", "sin", "(", "ang", ")", ";", "float", "cos", "=", "(", "float", ")", "Math", ".", "cosFromSin", "(", ...
Pre-multiply a rotation around the Y axis to this matrix by rotating the given amount of radians about the Y axis and store the result in <code>dest</code>. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>R * M</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the rotation will be applied last! <p> In order to set the matrix to a rotation matrix without pre-multiplying the rotation transformation, use {@link #rotationY(float) rotationY()}. <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> @see #rotationY(float) @param ang the angle in radians to rotate about the Y axis @param dest will hold the result @return dest
[ "Pre", "-", "multiply", "a", "rotation", "around", "the", "Y", "axis", "to", "this", "matrix", "by", "rotating", "the", "given", "amount", "of", "radians", "about", "the", "Y", "axis", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3f.java#L2547-L2566
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsSlideAnimation.java
CmsSlideAnimation.slideIn
public static CmsSlideAnimation slideIn(Element element, Command callback, int duration) { CmsSlideAnimation animation = new CmsSlideAnimation(element, true, callback); animation.run(duration); return animation; }
java
public static CmsSlideAnimation slideIn(Element element, Command callback, int duration) { CmsSlideAnimation animation = new CmsSlideAnimation(element, true, callback); animation.run(duration); return animation; }
[ "public", "static", "CmsSlideAnimation", "slideIn", "(", "Element", "element", ",", "Command", "callback", ",", "int", "duration", ")", "{", "CmsSlideAnimation", "animation", "=", "new", "CmsSlideAnimation", "(", "element", ",", "true", ",", "callback", ")", ";"...
Slides the given element into view executing the callback afterwards.<p> @param element the element to slide in @param callback the callback @param duration the animation duration @return the running animation object
[ "Slides", "the", "given", "element", "into", "view", "executing", "the", "callback", "afterwards", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsSlideAnimation.java#L86-L91
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Scanner.java
Scanner.findWithinHorizon
public String findWithinHorizon(String pattern, int horizon) { return findWithinHorizon(patternCache.forName(pattern), horizon); }
java
public String findWithinHorizon(String pattern, int horizon) { return findWithinHorizon(patternCache.forName(pattern), horizon); }
[ "public", "String", "findWithinHorizon", "(", "String", "pattern", ",", "int", "horizon", ")", "{", "return", "findWithinHorizon", "(", "patternCache", ".", "forName", "(", "pattern", ")", ",", "horizon", ")", ";", "}" ]
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. <p>An invocation of this method of the form <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as the invocation <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>. @param pattern a string specifying the pattern to search for @param horizon the search horizon @return the text that matched the specified pattern @throws IllegalStateException if this scanner is closed @throws IllegalArgumentException if horizon is negative
[ "Attempts", "to", "find", "the", "next", "occurrence", "of", "a", "pattern", "constructed", "from", "the", "specified", "string", "ignoring", "delimiters", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Scanner.java#L1606-L1608
jbundle/jbundle
base/model/src/main/java/org/jbundle/base/model/Utility.java
Utility.transformMessage
public static void transformMessage(String strXMLIn, String strXMLOut, String strTransformer) { try { Reader reader = new FileReader(strXMLIn); Writer stringWriter = new FileWriter(strXMLOut); Reader readerxsl = new FileReader(strTransformer); Utility.transformMessage(reader, stringWriter, readerxsl); } catch (IOException ex) { ex.printStackTrace(); } }
java
public static void transformMessage(String strXMLIn, String strXMLOut, String strTransformer) { try { Reader reader = new FileReader(strXMLIn); Writer stringWriter = new FileWriter(strXMLOut); Reader readerxsl = new FileReader(strTransformer); Utility.transformMessage(reader, stringWriter, readerxsl); } catch (IOException ex) { ex.printStackTrace(); } }
[ "public", "static", "void", "transformMessage", "(", "String", "strXMLIn", ",", "String", "strXMLOut", ",", "String", "strTransformer", ")", "{", "try", "{", "Reader", "reader", "=", "new", "FileReader", "(", "strXMLIn", ")", ";", "Writer", "stringWriter", "="...
Use XSLT to convert this source tree into a new tree. @param result If this is specified, transform the message to this result (and return null). @param source The source to convert. @param streamTransformer The (optional) input stream that contains the XSLT document. If you don't supply a streamTransformer, you should override getTransforerStream() method. @return The new tree.
[ "Use", "XSLT", "to", "convert", "this", "source", "tree", "into", "a", "new", "tree", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/model/src/main/java/org/jbundle/base/model/Utility.java#L717-L730
rpau/javalang-compiler
src/main/java/org/walkmod/javalang/compiler/types/TypesLoaderVisitor.java
TypesLoaderVisitor.addPreliminaryThis
private void addPreliminaryThis(Scope scope, Symbol symbol, TypeDeclaration type) { Symbol<TypeDeclaration> thisSymbol = new Symbol<TypeDeclaration>("this", symbol.getType(), type, ReferenceType.VARIABLE); thisSymbol.setInnerScope(scope); scope.addSymbol(thisSymbol); }
java
private void addPreliminaryThis(Scope scope, Symbol symbol, TypeDeclaration type) { Symbol<TypeDeclaration> thisSymbol = new Symbol<TypeDeclaration>("this", symbol.getType(), type, ReferenceType.VARIABLE); thisSymbol.setInnerScope(scope); scope.addSymbol(thisSymbol); }
[ "private", "void", "addPreliminaryThis", "(", "Scope", "scope", ",", "Symbol", "symbol", ",", "TypeDeclaration", "type", ")", "{", "Symbol", "<", "TypeDeclaration", ">", "thisSymbol", "=", "new", "Symbol", "<", "TypeDeclaration", ">", "(", "\"this\"", ",", "sy...
preliminary "this" to allow depth first inheritance tree scope loading
[ "preliminary", "this", "to", "allow", "depth", "first", "inheritance", "tree", "scope", "loading" ]
train
https://github.com/rpau/javalang-compiler/blob/d7da81359161feef2bc7ff186c4e1b73c6a5a8ef/src/main/java/org/walkmod/javalang/compiler/types/TypesLoaderVisitor.java#L286-L291
spotify/helios
helios-tools/src/main/java/com/spotify/helios/cli/CliConfig.java
CliConfig.fromFile
public static CliConfig fromFile(final File defaultsFile, final Map<String, String> environmentVariables) throws IOException, URISyntaxException { final Config config; if (defaultsFile.exists() && defaultsFile.canRead()) { config = ConfigFactory.parseFile(defaultsFile); } else { config = ConfigFactory.empty(); } return fromEnvVar(config, environmentVariables); }
java
public static CliConfig fromFile(final File defaultsFile, final Map<String, String> environmentVariables) throws IOException, URISyntaxException { final Config config; if (defaultsFile.exists() && defaultsFile.canRead()) { config = ConfigFactory.parseFile(defaultsFile); } else { config = ConfigFactory.empty(); } return fromEnvVar(config, environmentVariables); }
[ "public", "static", "CliConfig", "fromFile", "(", "final", "File", "defaultsFile", ",", "final", "Map", "<", "String", ",", "String", ">", "environmentVariables", ")", "throws", "IOException", ",", "URISyntaxException", "{", "final", "Config", "config", ";", "if...
Returns a CliConfig instance with values parsed from the specified file. <p>If the file is not found, a CliConfig with pre-defined values will be returned. @param defaultsFile The file to parse from @return The configuration @throws IOException If the file exists but could not be read @throws URISyntaxException If a HELIOS_MASTER env var is present and doesn't parse as a URI
[ "Returns", "a", "CliConfig", "instance", "with", "values", "parsed", "from", "the", "specified", "file", "." ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-tools/src/main/java/com/spotify/helios/cli/CliConfig.java#L127-L138
landawn/AbacusUtil
src/com/landawn/abacus/util/JdbcUtil.java
JdbcUtil.beginTransaction
public static SimpleTransaction beginTransaction(javax.sql.DataSource dataSource, IsolationLevel isolationLevel) throws UncheckedSQLException { N.checkArgNotNull(dataSource); N.checkArgNotNull(isolationLevel); final String ttid = SimpleTransaction.getTransactionThreadId(dataSource); SimpleTransaction tran = SimpleTransaction.threadTransacionMap.get(ttid); if (tran == null) { Connection conn = null; boolean isOk = false; try { conn = dataSource.getConnection(); tran = new SimpleTransaction(ttid, conn, isolationLevel, true); tran.incrementAndGet(isolationLevel); isOk = true; } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { if (isOk == false) { closeQuietly(conn); } } logger.info("Create a new transaction(id={})", tran.id()); SimpleTransaction.threadTransacionMap.put(ttid, tran); } else { logger.info("Reusing the existing transaction(id={})", tran.id()); tran.incrementAndGet(isolationLevel); } logger.debug("Current active transaction: {}", SimpleTransaction.threadTransacionMap.values()); return tran; }
java
public static SimpleTransaction beginTransaction(javax.sql.DataSource dataSource, IsolationLevel isolationLevel) throws UncheckedSQLException { N.checkArgNotNull(dataSource); N.checkArgNotNull(isolationLevel); final String ttid = SimpleTransaction.getTransactionThreadId(dataSource); SimpleTransaction tran = SimpleTransaction.threadTransacionMap.get(ttid); if (tran == null) { Connection conn = null; boolean isOk = false; try { conn = dataSource.getConnection(); tran = new SimpleTransaction(ttid, conn, isolationLevel, true); tran.incrementAndGet(isolationLevel); isOk = true; } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { if (isOk == false) { closeQuietly(conn); } } logger.info("Create a new transaction(id={})", tran.id()); SimpleTransaction.threadTransacionMap.put(ttid, tran); } else { logger.info("Reusing the existing transaction(id={})", tran.id()); tran.incrementAndGet(isolationLevel); } logger.debug("Current active transaction: {}", SimpleTransaction.threadTransacionMap.values()); return tran; }
[ "public", "static", "SimpleTransaction", "beginTransaction", "(", "javax", ".", "sql", ".", "DataSource", "dataSource", ",", "IsolationLevel", "isolationLevel", ")", "throws", "UncheckedSQLException", "{", "N", ".", "checkArgNotNull", "(", "dataSource", ")", ";", "N...
>>>>>>> .merge-right.r1119 Here is the general code pattern to work with {@code SimpleTransaction}. The transaction will be shared in the same thread for the same {@code DataSource} or {@code Connection}. <pre> <code> public void doSomethingA() { ... final SimpleTransaction tranA = JdbcUtil.beginTransacion(dataSource1, isolation); final Connection conn = tranA.connection(); try { // do your work with the conn... ... doSomethingB(); // Share the same transaction 'tranA' because they're in the same thread and start transaction with same DataSource 'dataSource1'. ... doSomethingC(); // won't share the same transaction 'tranA' although they're in the same thread but start transaction with different DataSources. ... tranA.commit(); } finally { tranA.rollbackIfNotCommitted(); } } public void doSomethingB() { ... final SimpleTransaction tranB = JdbcUtil.beginTransacion(dataSource1, isolation); final Connection conn = tranB.connection(); try { // do your work with the conn... ... tranB.commit(); } finally { tranB.rollbackIfNotCommitted(); } } public void doSomethingC() { ... final SimpleTransaction tranC = JdbcUtil.beginTransacion(dataSource2, isolation); final Connection conn = tranC.connection(); try { // do your work with the conn... ... tranC.commit(); } finally { tranC.rollbackIfNotCommitted(); } } </pre> </code> It's incorrect to use flag to identity the transaction should be committed or rolled back. Don't write below code: <pre> <code> public void doSomethingA() { ... final SimpleTransaction tranA = JdbcUtil.beginTransacion(dataSource1, isolation); final Connection conn = tranA.connection(); boolean flagToCommit = false; try { // do your work with the conn... ... flagToCommit = true; } finally { if (flagToCommit) { tranA.commit(); } else { tranA.rollbackIfNotCommitted(); } } } </code> </pre> @param dataSource @param isolationLevel @return @throws SQLException
[ ">>>>>>>", ".", "merge", "-", "right", ".", "r1119", "Here", "is", "the", "general", "code", "pattern", "to", "work", "with", "{", "@code", "SimpleTransaction", "}", ".", "The", "transaction", "will", "be", "shared", "in", "the", "same", "thread", "for", ...
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L1078-L1112
Azure/azure-functions-java-worker
src/main/java/com/microsoft/azure/functions/worker/handler/FunctionEnvironmentReloadRequestHandler.java
FunctionEnvironmentReloadRequestHandler.setEnv
public void setEnv(Map<String, String> newSettings) throws Exception { if (newSettings == null || newSettings.isEmpty()) { return; } // Update Environment variables in the JVM try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.clear(); env.putAll(newSettings); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.clear(); cienv.putAll(newSettings); WorkerLogManager.getSystemLogger().log(Level.INFO, "Finished resetting environment variables in the JVM"); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newSettings); } } } }
java
public void setEnv(Map<String, String> newSettings) throws Exception { if (newSettings == null || newSettings.isEmpty()) { return; } // Update Environment variables in the JVM try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.clear(); env.putAll(newSettings); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.clear(); cienv.putAll(newSettings); WorkerLogManager.getSystemLogger().log(Level.INFO, "Finished resetting environment variables in the JVM"); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newSettings); } } } }
[ "public", "void", "setEnv", "(", "Map", "<", "String", ",", "String", ">", "newSettings", ")", "throws", "Exception", "{", "if", "(", "newSettings", "==", "null", "||", "newSettings", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "// Update Env...
/* This is a helper utility specifically to reload environment variables if java language worker is started in standby mode by the functions runtime and should not be used for other purposes
[ "/", "*", "This", "is", "a", "helper", "utility", "specifically", "to", "reload", "environment", "variables", "if", "java", "language", "worker", "is", "started", "in", "standby", "mode", "by", "the", "functions", "runtime", "and", "should", "not", "be", "us...
train
https://github.com/Azure/azure-functions-java-worker/blob/12dcee7ca829a5f961a23cfd1b03a7eb7feae5e0/src/main/java/com/microsoft/azure/functions/worker/handler/FunctionEnvironmentReloadRequestHandler.java#L42-L77
aerogear/aerogear-unifiedpush-server
model/api/src/main/java/org/jboss/aerogear/unifiedpush/api/validation/DeviceTokenValidator.java
DeviceTokenValidator.isValidDeviceTokenForVariant
public static boolean isValidDeviceTokenForVariant(final String deviceToken, final VariantType type) { switch (type) { case IOS: return IOS_DEVICE_TOKEN.matcher(deviceToken).matches(); case ANDROID: return ANDROID_DEVICE_TOKEN.matcher(deviceToken).matches(); case WINDOWS_WNS: return WINDOWS_DEVICE_TOKEN.matcher(deviceToken).matches(); } return false; }
java
public static boolean isValidDeviceTokenForVariant(final String deviceToken, final VariantType type) { switch (type) { case IOS: return IOS_DEVICE_TOKEN.matcher(deviceToken).matches(); case ANDROID: return ANDROID_DEVICE_TOKEN.matcher(deviceToken).matches(); case WINDOWS_WNS: return WINDOWS_DEVICE_TOKEN.matcher(deviceToken).matches(); } return false; }
[ "public", "static", "boolean", "isValidDeviceTokenForVariant", "(", "final", "String", "deviceToken", ",", "final", "VariantType", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "IOS", ":", "return", "IOS_DEVICE_TOKEN", ".", "matcher", "(", "deviceTo...
Helper to run quick up-front validations. @param deviceToken the submitted device token @param type type of the variant @return true if the token is valid
[ "Helper", "to", "run", "quick", "up", "-", "front", "validations", "." ]
train
https://github.com/aerogear/aerogear-unifiedpush-server/blob/c7b798f085449117d84345d8c378b27165cad32b/model/api/src/main/java/org/jboss/aerogear/unifiedpush/api/validation/DeviceTokenValidator.java#L70-L80
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java
Descriptor.replaceAllTopicCalls
public Descriptor replaceAllTopicCalls(PSequence<TopicCall<?>> topicCalls) { return new Descriptor(name, calls, pathParamSerializers, messageSerializers, serializerFactory, exceptionSerializer, autoAcl, acls, headerFilter, locatableService, circuitBreaker, topicCalls); }
java
public Descriptor replaceAllTopicCalls(PSequence<TopicCall<?>> topicCalls) { return new Descriptor(name, calls, pathParamSerializers, messageSerializers, serializerFactory, exceptionSerializer, autoAcl, acls, headerFilter, locatableService, circuitBreaker, topicCalls); }
[ "public", "Descriptor", "replaceAllTopicCalls", "(", "PSequence", "<", "TopicCall", "<", "?", ">", ">", "topicCalls", ")", "{", "return", "new", "Descriptor", "(", "name", ",", "calls", ",", "pathParamSerializers", ",", "messageSerializers", ",", "serializerFactor...
Replace all the topic calls provided by this descriptor with the the given topic calls. @param topicCalls The topic calls to replace the existing ones with. @return A copy of this descriptor with the new topic calls.
[ "Replace", "all", "the", "topic", "calls", "provided", "by", "this", "descriptor", "with", "the", "the", "given", "topic", "calls", "." ]
train
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L750-L752
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Waiter.java
Waiter.waitForView
public <T extends View> boolean waitForView(final Class<T> viewClass, final int index, final int timeout, final boolean scroll){ Set<T> uniqueViews = new HashSet<T>(); final long endTime = SystemClock.uptimeMillis() + timeout; boolean foundMatchingView; while (SystemClock.uptimeMillis() < endTime) { sleeper.sleep(); foundMatchingView = searcher.searchFor(uniqueViews, viewClass, index); if(foundMatchingView) return true; if(scroll) scroller.scrollDown(); } return false; }
java
public <T extends View> boolean waitForView(final Class<T> viewClass, final int index, final int timeout, final boolean scroll){ Set<T> uniqueViews = new HashSet<T>(); final long endTime = SystemClock.uptimeMillis() + timeout; boolean foundMatchingView; while (SystemClock.uptimeMillis() < endTime) { sleeper.sleep(); foundMatchingView = searcher.searchFor(uniqueViews, viewClass, index); if(foundMatchingView) return true; if(scroll) scroller.scrollDown(); } return false; }
[ "public", "<", "T", "extends", "View", ">", "boolean", "waitForView", "(", "final", "Class", "<", "T", ">", "viewClass", ",", "final", "int", "index", ",", "final", "int", "timeout", ",", "final", "boolean", "scroll", ")", "{", "Set", "<", "T", ">", ...
Waits for a view to be shown. @param viewClass the {@code View} class to wait for @param index the index of the view that is expected to be shown. @param timeout the amount of time in milliseconds to wait @param scroll {@code true} if scrolling should be performed @return {@code true} if view is shown and {@code false} if it is not shown before the timeout
[ "Waits", "for", "a", "view", "to", "be", "shown", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Waiter.java#L244-L261
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.setCertificateIssuerAsync
public Observable<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() { @Override public IssuerBundle call(ServiceResponse<IssuerBundle> response) { return response.body(); } }); }
java
public Observable<IssuerBundle> setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, attributes).map(new Func1<ServiceResponse<IssuerBundle>, IssuerBundle>() { @Override public IssuerBundle call(ServiceResponse<IssuerBundle> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IssuerBundle", ">", "setCertificateIssuerAsync", "(", "String", "vaultBaseUrl", ",", "String", "issuerName", ",", "String", "provider", ",", "IssuerCredentials", "credentials", ",", "OrganizationDetails", "organizationDetails", ",", "IssuerAt...
Sets the specified certificate issuer. The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param issuerName The name of the issuer. @param provider The issuer provider. @param credentials The credentials to be used for the issuer. @param organizationDetails Details of the organization as provided to the issuer. @param attributes Attributes of the issuer object. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IssuerBundle object
[ "Sets", "the", "specified", "certificate", "issuer", ".", "The", "SetCertificateIssuer", "operation", "adds", "or", "updates", "the", "specified", "certificate", "issuer", ".", "This", "operation", "requires", "the", "certificates", "/", "setissuers", "permission", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L6034-L6041
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.addColumnUpdate
private BoundStatement addColumnUpdate(String tableName, String key, DColumn column, boolean isBinaryValue) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.INSERT_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, column.getName()); if (isBinaryValue) { boundState.setBytes(2, ByteBuffer.wrap(column.getRawValue())); } else { boundState.setString(2, column.getValue()); } return boundState; }
java
private BoundStatement addColumnUpdate(String tableName, String key, DColumn column, boolean isBinaryValue) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.INSERT_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, column.getName()); if (isBinaryValue) { boundState.setBytes(2, ByteBuffer.wrap(column.getRawValue())); } else { boundState.setString(2, column.getValue()); } return boundState; }
[ "private", "BoundStatement", "addColumnUpdate", "(", "String", "tableName", ",", "String", "key", ",", "DColumn", "column", ",", "boolean", "isBinaryValue", ")", "{", "PreparedStatement", "prepState", "=", "m_dbservice", ".", "getPreparedUpdate", "(", "Update", ".",...
Create and return a BoundStatement for the given column update.
[ "Create", "and", "return", "a", "BoundStatement", "for", "the", "given", "column", "update", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L115-L126
liferay/com-liferay-commerce
commerce-tax-engine-fixed-service/src/main/java/com/liferay/commerce/tax/engine/fixed/service/persistence/impl/CommerceTaxFixedRatePersistenceImpl.java
CommerceTaxFixedRatePersistenceImpl.findByCommerceTaxMethodId
@Override public List<CommerceTaxFixedRate> findByCommerceTaxMethodId( long commerceTaxMethodId, int start, int end) { return findByCommerceTaxMethodId(commerceTaxMethodId, start, end, null); }
java
@Override public List<CommerceTaxFixedRate> findByCommerceTaxMethodId( long commerceTaxMethodId, int start, int end) { return findByCommerceTaxMethodId(commerceTaxMethodId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceTaxFixedRate", ">", "findByCommerceTaxMethodId", "(", "long", "commerceTaxMethodId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCommerceTaxMethodId", "(", "commerceTaxMethodId", ",", "start", "...
Returns a range of all the commerce tax fixed rates where commerceTaxMethodId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTaxFixedRateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param commerceTaxMethodId the commerce tax method ID @param start the lower bound of the range of commerce tax fixed rates @param end the upper bound of the range of commerce tax fixed rates (not inclusive) @return the range of matching commerce tax fixed rates
[ "Returns", "a", "range", "of", "all", "the", "commerce", "tax", "fixed", "rates", "where", "commerceTaxMethodId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-engine-fixed-service/src/main/java/com/liferay/commerce/tax/engine/fixed/service/persistence/impl/CommerceTaxFixedRatePersistenceImpl.java#L670-L674
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.updateLocalEntityCaps
private void updateLocalEntityCaps() { XMPPConnection connection = connection(); DiscoverInfo discoverInfo = new DiscoverInfo(); discoverInfo.setType(IQ.Type.result); sdm.addDiscoverInfoTo(discoverInfo); // getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore // set it first and then call getLocalNodeVer() currentCapsVersion = generateVerificationString(discoverInfo); final String localNodeVer = getLocalNodeVer(); discoverInfo.setNode(localNodeVer); addDiscoverInfoByNode(localNodeVer, discoverInfo); if (lastLocalCapsVersions.size() > 10) { CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions.poll(); sdm.removeNodeInformationProvider(entityNode + '#' + oldCapsVersion.version); } lastLocalCapsVersions.add(currentCapsVersion); if (connection != null) JID_TO_NODEVER_CACHE.put(connection.getUser(), new NodeVerHash(entityNode, currentCapsVersion)); final List<Identity> identities = new LinkedList<>(ServiceDiscoveryManager.getInstanceFor(connection).getIdentities()); sdm.setNodeInformationProvider(localNodeVer, new AbstractNodeInformationProvider() { List<String> features = sdm.getFeatures(); List<ExtensionElement> packetExtensions = sdm.getExtendedInfoAsList(); @Override public List<String> getNodeFeatures() { return features; } @Override public List<Identity> getNodeIdentities() { return identities; } @Override public List<ExtensionElement> getNodePacketExtensions() { return packetExtensions; } }); // Re-send the last sent presence, and let the stanza interceptor // add a <c/> node to it. // See http://xmpp.org/extensions/xep-0115.html#advertise // We only send a presence packet if there was already one send // to respect ConnectionConfiguration.isSendPresence() if (connection != null && connection.isAuthenticated() && presenceSend != null) { try { connection.sendStanza(presenceSend.cloneWithNewId()); } catch (InterruptedException | NotConnectedException e) { LOGGER.log(Level.WARNING, "Could could not update presence with caps info", e); } } }
java
private void updateLocalEntityCaps() { XMPPConnection connection = connection(); DiscoverInfo discoverInfo = new DiscoverInfo(); discoverInfo.setType(IQ.Type.result); sdm.addDiscoverInfoTo(discoverInfo); // getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore // set it first and then call getLocalNodeVer() currentCapsVersion = generateVerificationString(discoverInfo); final String localNodeVer = getLocalNodeVer(); discoverInfo.setNode(localNodeVer); addDiscoverInfoByNode(localNodeVer, discoverInfo); if (lastLocalCapsVersions.size() > 10) { CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions.poll(); sdm.removeNodeInformationProvider(entityNode + '#' + oldCapsVersion.version); } lastLocalCapsVersions.add(currentCapsVersion); if (connection != null) JID_TO_NODEVER_CACHE.put(connection.getUser(), new NodeVerHash(entityNode, currentCapsVersion)); final List<Identity> identities = new LinkedList<>(ServiceDiscoveryManager.getInstanceFor(connection).getIdentities()); sdm.setNodeInformationProvider(localNodeVer, new AbstractNodeInformationProvider() { List<String> features = sdm.getFeatures(); List<ExtensionElement> packetExtensions = sdm.getExtendedInfoAsList(); @Override public List<String> getNodeFeatures() { return features; } @Override public List<Identity> getNodeIdentities() { return identities; } @Override public List<ExtensionElement> getNodePacketExtensions() { return packetExtensions; } }); // Re-send the last sent presence, and let the stanza interceptor // add a <c/> node to it. // See http://xmpp.org/extensions/xep-0115.html#advertise // We only send a presence packet if there was already one send // to respect ConnectionConfiguration.isSendPresence() if (connection != null && connection.isAuthenticated() && presenceSend != null) { try { connection.sendStanza(presenceSend.cloneWithNewId()); } catch (InterruptedException | NotConnectedException e) { LOGGER.log(Level.WARNING, "Could could not update presence with caps info", e); } } }
[ "private", "void", "updateLocalEntityCaps", "(", ")", "{", "XMPPConnection", "connection", "=", "connection", "(", ")", ";", "DiscoverInfo", "discoverInfo", "=", "new", "DiscoverInfo", "(", ")", ";", "discoverInfo", ".", "setType", "(", "IQ", ".", "Type", ".",...
Updates the local user Entity Caps information with the data provided If we are connected and there was already a presence send, another presence is send to inform others about your new Entity Caps node string.
[ "Updates", "the", "local", "user", "Entity", "Caps", "information", "with", "the", "data", "provided" ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L517-L570
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/classify/LinearClassifier.java
LinearClassifier.justificationOf
public void justificationOf(Datum<L, F> example, PrintWriter pw) { justificationOf(example, pw, null); }
java
public void justificationOf(Datum<L, F> example, PrintWriter pw) { justificationOf(example, pw, null); }
[ "public", "void", "justificationOf", "(", "Datum", "<", "L", ",", "F", ">", "example", ",", "PrintWriter", "pw", ")", "{", "justificationOf", "(", "example", ",", "pw", ",", "null", ")", ";", "}" ]
Print all features active for a particular datum and the weight that the classifier assigns to each class for those features.
[ "Print", "all", "features", "active", "for", "a", "particular", "datum", "and", "the", "weight", "that", "the", "classifier", "assigns", "to", "each", "class", "for", "those", "features", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/classify/LinearClassifier.java#L1195-L1197
spothero/volley-jackson-extension
Library/src/com/spothero/volley/JacksonNetwork.java
JacksonNetwork.newRequestQueue
public static RequestQueue newRequestQueue(Context context) { HttpStack stack; if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance("volley")); } return newRequestQueue(context, stack); }
java
public static RequestQueue newRequestQueue(Context context) { HttpStack stack; if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance("volley")); } return newRequestQueue(context, stack); }
[ "public", "static", "RequestQueue", "newRequestQueue", "(", "Context", "context", ")", "{", "HttpStack", "stack", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "9", ")", "{", "stack", "=", "new", "HurlStack", "(", ")", ";", "}", "else", ...
Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. @param context A {@link Context} to use for creating the cache dir. @return A started {@link RequestQueue} instance.
[ "Creates", "a", "default", "instance", "of", "the", "worker", "pool", "and", "calls", "{", "@link", "RequestQueue#start", "()", "}", "on", "it", "." ]
train
https://github.com/spothero/volley-jackson-extension/blob/9b02df3e3e8fc648c80aec2dfae456de949fb74b/Library/src/com/spothero/volley/JacksonNetwork.java#L175-L183
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/EigenOps_DDRM.java
EigenOps_DDRM.createMatrixV
public static DMatrixRMaj createMatrixV(EigenDecomposition_F64<DMatrixRMaj> eig ) { int N = eig.getNumberOfEigenvalues(); DMatrixRMaj V = new DMatrixRMaj( N , N ); for( int i = 0; i < N; i++ ) { Complex_F64 c = eig.getEigenvalue(i); if( c.isReal() ) { DMatrixRMaj v = eig.getEigenVector(i); if( v != null ) { for( int j = 0; j < N; j++ ) { V.set(j,i,v.get(j,0)); } } } } return V; }
java
public static DMatrixRMaj createMatrixV(EigenDecomposition_F64<DMatrixRMaj> eig ) { int N = eig.getNumberOfEigenvalues(); DMatrixRMaj V = new DMatrixRMaj( N , N ); for( int i = 0; i < N; i++ ) { Complex_F64 c = eig.getEigenvalue(i); if( c.isReal() ) { DMatrixRMaj v = eig.getEigenVector(i); if( v != null ) { for( int j = 0; j < N; j++ ) { V.set(j,i,v.get(j,0)); } } } } return V; }
[ "public", "static", "DMatrixRMaj", "createMatrixV", "(", "EigenDecomposition_F64", "<", "DMatrixRMaj", ">", "eig", ")", "{", "int", "N", "=", "eig", ".", "getNumberOfEigenvalues", "(", ")", ";", "DMatrixRMaj", "V", "=", "new", "DMatrixRMaj", "(", "N", ",", "...
<p> Puts all the real eigenvectors into the columns of a matrix. If an eigenvalue is imaginary then the corresponding eigenvector will have zeros in its column. </p> @param eig An eigenvalue decomposition which has already decomposed a matrix. @return An m by m matrix containing eigenvectors in its columns.
[ "<p", ">", "Puts", "all", "the", "real", "eigenvectors", "into", "the", "columns", "of", "a", "matrix", ".", "If", "an", "eigenvalue", "is", "imaginary", "then", "the", "corresponding", "eigenvector", "will", "have", "zeros", "in", "its", "column", ".", "<...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/EigenOps_DDRM.java#L281-L302
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java
MessageRetriever.printNotice
private void printNotice(SourcePosition pos, String msg) { configuration.root.printNotice(pos, msg); }
java
private void printNotice(SourcePosition pos, String msg) { configuration.root.printNotice(pos, msg); }
[ "private", "void", "printNotice", "(", "SourcePosition", "pos", ",", "String", "msg", ")", "{", "configuration", ".", "root", ".", "printNotice", "(", "pos", ",", "msg", ")", ";", "}" ]
Print a message. @param pos the position of the source @param msg message to print
[ "Print", "a", "message", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java#L173-L175
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.getView
public View getView(String id, int index){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "getView(\""+id+"\", "+index+")"); } View viewToReturn = getter.getView(id, index); if(viewToReturn == null) { int match = index + 1; if(match > 1){ Assert.fail(match + " Views with id: '" + id + "' are not found!"); } else { Assert.fail("View with id: '" + id + "' is not found!"); } } return viewToReturn; }
java
public View getView(String id, int index){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "getView(\""+id+"\", "+index+")"); } View viewToReturn = getter.getView(id, index); if(viewToReturn == null) { int match = index + 1; if(match > 1){ Assert.fail(match + " Views with id: '" + id + "' are not found!"); } else { Assert.fail("View with id: '" + id + "' is not found!"); } } return viewToReturn; }
[ "public", "View", "getView", "(", "String", "id", ",", "int", "index", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"getView(\\\"\"", "+", "id", "+", "\"\\\", \"", "+", ...
Returns a View matching the specified resource id and index. @param id the id of the {@link View} to return @param index the index of the {@link View}. {@code 0} if only one is available @return a {@link View} matching the specified id and index
[ "Returns", "a", "View", "matching", "the", "specified", "resource", "id", "and", "index", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3131-L3148
dyu/protostuff-1.0.x
protostuff-core/src/main/java/com/dyuproject/protostuff/ProtostuffIOUtil.java
ProtostuffIOUtil.parseListFrom
public static <T> List<T> parseListFrom(final InputStream in, final Schema<T> schema) throws IOException { int size = in.read(); if(size == -1) return Collections.emptyList(); if(size > 0x7f) size = CodedInput.readRawVarint32(in, size); final ArrayList<T> list = new ArrayList<T>(size); final CodedInput input = new CodedInput(in, true); for(int i = 0; i < size; i++) { final T message = schema.newMessage(); list.add(message); schema.mergeFrom(input, message); input.checkLastTagWas(0); } assert in.read() == -1; return list; }
java
public static <T> List<T> parseListFrom(final InputStream in, final Schema<T> schema) throws IOException { int size = in.read(); if(size == -1) return Collections.emptyList(); if(size > 0x7f) size = CodedInput.readRawVarint32(in, size); final ArrayList<T> list = new ArrayList<T>(size); final CodedInput input = new CodedInput(in, true); for(int i = 0; i < size; i++) { final T message = schema.newMessage(); list.add(message); schema.mergeFrom(input, message); input.checkLastTagWas(0); } assert in.read() == -1; return list; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "parseListFrom", "(", "final", "InputStream", "in", ",", "final", "Schema", "<", "T", ">", "schema", ")", "throws", "IOException", "{", "int", "size", "=", "in", ".", "read", "(", ")", ";", ...
Parses the {@code messages} (delimited) from the {@link InputStream} using the given {@code schema}. @return the list containing the messages.
[ "Parses", "the", "{", "@code", "messages", "}", "(", "delimited", ")", "from", "the", "{", "@link", "InputStream", "}", "using", "the", "given", "{", "@code", "schema", "}", "." ]
train
https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-core/src/main/java/com/dyuproject/protostuff/ProtostuffIOUtil.java#L308-L331
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java
Item.withShort
public Item withShort(String attrName, short val) { checkInvalidAttrName(attrName); return withNumber(attrName, Short.valueOf(val)); }
java
public Item withShort(String attrName, short val) { checkInvalidAttrName(attrName); return withNumber(attrName, Short.valueOf(val)); }
[ "public", "Item", "withShort", "(", "String", "attrName", ",", "short", "val", ")", "{", "checkInvalidAttrName", "(", "attrName", ")", ";", "return", "withNumber", "(", "attrName", ",", "Short", ".", "valueOf", "(", "val", ")", ")", ";", "}" ]
Sets the value of the specified attribute in the current item to the given value.
[ "Sets", "the", "value", "of", "the", "specified", "attribute", "in", "the", "current", "item", "to", "the", "given", "value", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java#L305-L308
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.singleStepConference
public ApiSuccessResponse singleStepConference(String id, SingleStepConferenceData singleStepConferenceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = singleStepConferenceWithHttpInfo(id, singleStepConferenceData); return resp.getData(); }
java
public ApiSuccessResponse singleStepConference(String id, SingleStepConferenceData singleStepConferenceData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = singleStepConferenceWithHttpInfo(id, singleStepConferenceData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "singleStepConference", "(", "String", "id", ",", "SingleStepConferenceData", "singleStepConferenceData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "singleStepConferenceWithHttpInfo", "(", ...
Create a conference in a single step Perform a single-step conference to the specified destination. This adds the destination to the existing call, creating a conference if necessary. @param id The connection ID of the call to conference. (required) @param singleStepConferenceData (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Create", "a", "conference", "in", "a", "single", "step", "Perform", "a", "single", "-", "step", "conference", "to", "the", "specified", "destination", ".", "This", "adds", "the", "destination", "to", "the", "existing", "call", "creating", "a", "conference", ...
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L4215-L4218
buschmais/jqa-maven3-plugin
src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java
MavenModelScannerPlugin.addLicenses
private void addLicenses(MavenPomDescriptor pomDescriptor, Model model, Store store) { List<License> licenses = model.getLicenses(); for (License license : licenses) { MavenLicenseDescriptor licenseDescriptor = store.create(MavenLicenseDescriptor.class); licenseDescriptor.setUrl(license.getUrl()); licenseDescriptor.setComments(license.getComments()); licenseDescriptor.setName(license.getName()); licenseDescriptor.setDistribution(license.getDistribution()); pomDescriptor.getLicenses().add(licenseDescriptor); } }
java
private void addLicenses(MavenPomDescriptor pomDescriptor, Model model, Store store) { List<License> licenses = model.getLicenses(); for (License license : licenses) { MavenLicenseDescriptor licenseDescriptor = store.create(MavenLicenseDescriptor.class); licenseDescriptor.setUrl(license.getUrl()); licenseDescriptor.setComments(license.getComments()); licenseDescriptor.setName(license.getName()); licenseDescriptor.setDistribution(license.getDistribution()); pomDescriptor.getLicenses().add(licenseDescriptor); } }
[ "private", "void", "addLicenses", "(", "MavenPomDescriptor", "pomDescriptor", ",", "Model", "model", ",", "Store", "store", ")", "{", "List", "<", "License", ">", "licenses", "=", "model", ".", "getLicenses", "(", ")", ";", "for", "(", "License", "license", ...
Adds information about references licenses. @param pomDescriptor The descriptor for the current POM. @param model The Maven Model. @param store The database.
[ "Adds", "information", "about", "references", "licenses", "." ]
train
https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L338-L349
apache/groovy
src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java
StaticImportVisitor.setSourcePosition
private static void setSourcePosition(Expression toSet, Expression origNode) { toSet.setSourcePosition(origNode); if (toSet instanceof PropertyExpression) { ((PropertyExpression) toSet).getProperty().setSourcePosition(origNode); } }
java
private static void setSourcePosition(Expression toSet, Expression origNode) { toSet.setSourcePosition(origNode); if (toSet instanceof PropertyExpression) { ((PropertyExpression) toSet).getProperty().setSourcePosition(origNode); } }
[ "private", "static", "void", "setSourcePosition", "(", "Expression", "toSet", ",", "Expression", "origNode", ")", "{", "toSet", ".", "setSourcePosition", "(", "origNode", ")", ";", "if", "(", "toSet", "instanceof", "PropertyExpression", ")", "{", "(", "(", "Pr...
Set the source position of toSet including its property expression if it has one. @param toSet resulting node @param origNode original node
[ "Set", "the", "source", "position", "of", "toSet", "including", "its", "property", "expression", "if", "it", "has", "one", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/control/StaticImportVisitor.java#L232-L237
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java
ResourceCopy.copyInternalResources
public static void copyInternalResources(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.MAIN_RESOURCES_DIR); if (!in.exists()) { return; } File out = new File(mojo.buildDirectory, "classes"); filterAndCopy(mojo, filtering, in, out); }
java
public static void copyInternalResources(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.MAIN_RESOURCES_DIR); if (!in.exists()) { return; } File out = new File(mojo.buildDirectory, "classes"); filterAndCopy(mojo, filtering, in, out); }
[ "public", "static", "void", "copyInternalResources", "(", "AbstractWisdomMojo", "mojo", ",", "MavenResourcesFiltering", "filtering", ")", "throws", "IOException", "{", "File", "in", "=", "new", "File", "(", "mojo", ".", "basedir", ",", "Constants", ".", "MAIN_RESO...
Copies the internal resources from "src/main/resources" to "target/classes". Copied resources are filtered. Notice that these resources are embedded in the application's bundle. @param mojo the mojo @param filtering the component required to filter resources @throws IOException if a file cannot be copied
[ "Copies", "the", "internal", "resources", "from", "src", "/", "main", "/", "resources", "to", "target", "/", "classes", ".", "Copied", "resources", "are", "filtered", ".", "Notice", "that", "these", "resources", "are", "embedded", "in", "the", "application", ...
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java#L248-L256
blinkfox/zealot
src/main/java/com/blinkfox/zealot/core/ZealotKhala.java
ZealotKhala.andLike
public ZealotKhala andLike(String field, Object value) { return this.doLike(ZealotConst.AND_PREFIX, field, value, true, true); }
java
public ZealotKhala andLike(String field, Object value) { return this.doLike(ZealotConst.AND_PREFIX, field, value, true, true); }
[ "public", "ZealotKhala", "andLike", "(", "String", "field", ",", "Object", "value", ")", "{", "return", "this", ".", "doLike", "(", "ZealotConst", ".", "AND_PREFIX", ",", "field", ",", "value", ",", "true", ",", "true", ")", ";", "}" ]
生成带" AND "前缀的like模糊查询的SQL片段. @param field 数据库字段 @param value 值 @return ZealotKhala实例
[ "生成带", "AND", "前缀的like模糊查询的SQL片段", "." ]
train
https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L921-L923
CenturyLinkCloud/mdw
mdw-workflow/assets/com/centurylink/mdw/system/filepanel/FilePanelService.java
FilePanelService.include
private static boolean include(String host, java.nio.file.Path path) throws ServiceException { List<java.nio.file.Path> roots = getRootPaths(host); if (roots != null) { for (java.nio.file.Path rootPath : roots) { if (path.startsWith(rootPath)) return true; } } return false; }
java
private static boolean include(String host, java.nio.file.Path path) throws ServiceException { List<java.nio.file.Path> roots = getRootPaths(host); if (roots != null) { for (java.nio.file.Path rootPath : roots) { if (path.startsWith(rootPath)) return true; } } return false; }
[ "private", "static", "boolean", "include", "(", "String", "host", ",", "java", ".", "nio", ".", "file", ".", "Path", "path", ")", "throws", "ServiceException", "{", "List", "<", "java", ".", "nio", ".", "file", ".", "Path", ">", "roots", "=", "getRootP...
Checks whether subpath of a designated root dir. Root dirs must be configured per host or globally (not both).
[ "Checks", "whether", "subpath", "of", "a", "designated", "root", "dir", ".", "Root", "dirs", "must", "be", "configured", "per", "host", "or", "globally", "(", "not", "both", ")", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/system/filepanel/FilePanelService.java#L381-L390
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/tokens/TagLinkToken.java
TagLinkToken.sortList
private void sortList(ArrayList candidateList) { java.util.Collections.sort(candidateList, new java.util.Comparator() { public int compare(Object o1, Object o2) { double scoreT = ( (TagLink.Candidates) o1).getScore(); double scoreU = ( (TagLink.Candidates) o2).getScore(); if(scoreU > scoreT){ return 1; } if(scoreU > scoreT){ return -1; } return 0; } } ); }
java
private void sortList(ArrayList candidateList) { java.util.Collections.sort(candidateList, new java.util.Comparator() { public int compare(Object o1, Object o2) { double scoreT = ( (TagLink.Candidates) o1).getScore(); double scoreU = ( (TagLink.Candidates) o2).getScore(); if(scoreU > scoreT){ return 1; } if(scoreU > scoreT){ return -1; } return 0; } } ); }
[ "private", "void", "sortList", "(", "ArrayList", "candidateList", ")", "{", "java", ".", "util", ".", "Collections", ".", "sort", "(", "candidateList", ",", "new", "java", ".", "util", ".", "Comparator", "(", ")", "{", "public", "int", "compare", "(", "O...
sortList sort a candidate list by its scores. @param candidateList ArrayList
[ "sortList", "sort", "a", "candidate", "list", "by", "its", "scores", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/tokens/TagLinkToken.java#L236-L251
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LocationsInner.java
LocationsInner.checkNameAvailabilityAsync
public Observable<EntityNameAvailabilityCheckOutputInner> checkNameAvailabilityAsync(String locationName, CheckNameAvailabilityInput parameters) { return checkNameAvailabilityWithServiceResponseAsync(locationName, parameters).map(new Func1<ServiceResponse<EntityNameAvailabilityCheckOutputInner>, EntityNameAvailabilityCheckOutputInner>() { @Override public EntityNameAvailabilityCheckOutputInner call(ServiceResponse<EntityNameAvailabilityCheckOutputInner> response) { return response.body(); } }); }
java
public Observable<EntityNameAvailabilityCheckOutputInner> checkNameAvailabilityAsync(String locationName, CheckNameAvailabilityInput parameters) { return checkNameAvailabilityWithServiceResponseAsync(locationName, parameters).map(new Func1<ServiceResponse<EntityNameAvailabilityCheckOutputInner>, EntityNameAvailabilityCheckOutputInner>() { @Override public EntityNameAvailabilityCheckOutputInner call(ServiceResponse<EntityNameAvailabilityCheckOutputInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "EntityNameAvailabilityCheckOutputInner", ">", "checkNameAvailabilityAsync", "(", "String", "locationName", ",", "CheckNameAvailabilityInput", "parameters", ")", "{", "return", "checkNameAvailabilityWithServiceResponseAsync", "(", "locationName", ",",...
Check Name Availability. Checks whether the Media Service resource name is available. @param locationName the String value @param parameters The request parameters @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the EntityNameAvailabilityCheckOutputInner object
[ "Check", "Name", "Availability", ".", "Checks", "whether", "the", "Media", "Service", "resource", "name", "is", "available", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LocationsInner.java#L101-L108
joestelmach/natty
src/main/java/com/joestelmach/natty/WalkerState.java
WalkerState.seekToHolidayYear
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
java
public void seekToHolidayYear(String holidayString, String yearString) { Holiday holiday = Holiday.valueOf(holidayString); assert(holiday != null); seekToIcsEventYear(HOLIDAY_ICS_FILE, yearString, holiday.getSummary()); }
[ "public", "void", "seekToHolidayYear", "(", "String", "holidayString", ",", "String", "yearString", ")", "{", "Holiday", "holiday", "=", "Holiday", ".", "valueOf", "(", "holidayString", ")", ";", "assert", "(", "holiday", "!=", "null", ")", ";", "seekToIcsEven...
Seeks to the given holiday within the given year @param holidayString @param yearString
[ "Seeks", "to", "the", "given", "holiday", "within", "the", "given", "year" ]
train
https://github.com/joestelmach/natty/blob/74389feb4c9372e51cd51eb0800a0177fec3e5a0/src/main/java/com/joestelmach/natty/WalkerState.java#L402-L407
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockInlineChecksumWriter.java
BlockInlineChecksumWriter.setChannelPosition
public void setChannelPosition(long dataOffset, boolean startWithPartialChunk) throws IOException { long channelSize = blockDataWriter.getChannelSize(); if (channelSize < dataOffset) { String msg = "Trying to change block file offset of block " + block + "file " + ((blockDataFile.getFile() != null) ? blockDataFile.getFile() : "unknown") + " to " + dataOffset + " but actual size of file is " + blockDataWriter.getChannelSize(); throw new IOException(msg); } if (dataOffset > channelSize) { throw new IOException("Set position over the end of the data file."); } if (startWithPartialChunk && channelSize != dataOffset + checksumSize) { DFSClient.LOG.warn("Inline Checksum Block " + block + " channel size " + channelSize + " but packet needs to start from " + dataOffset); } // This flush should be a no-op since we always flush at the end of // writePacket() and hence the buffer should be empty. // However we do this just to be extra careful so that the // channel.position() doesn't mess up things with respect to the // buffered dataOut stream. blockDataWriter.flush(); blockDataWriter.position(dataOffset); }
java
public void setChannelPosition(long dataOffset, boolean startWithPartialChunk) throws IOException { long channelSize = blockDataWriter.getChannelSize(); if (channelSize < dataOffset) { String msg = "Trying to change block file offset of block " + block + "file " + ((blockDataFile.getFile() != null) ? blockDataFile.getFile() : "unknown") + " to " + dataOffset + " but actual size of file is " + blockDataWriter.getChannelSize(); throw new IOException(msg); } if (dataOffset > channelSize) { throw new IOException("Set position over the end of the data file."); } if (startWithPartialChunk && channelSize != dataOffset + checksumSize) { DFSClient.LOG.warn("Inline Checksum Block " + block + " channel size " + channelSize + " but packet needs to start from " + dataOffset); } // This flush should be a no-op since we always flush at the end of // writePacket() and hence the buffer should be empty. // However we do this just to be extra careful so that the // channel.position() doesn't mess up things with respect to the // buffered dataOut stream. blockDataWriter.flush(); blockDataWriter.position(dataOffset); }
[ "public", "void", "setChannelPosition", "(", "long", "dataOffset", ",", "boolean", "startWithPartialChunk", ")", "throws", "IOException", "{", "long", "channelSize", "=", "blockDataWriter", ".", "getChannelSize", "(", ")", ";", "if", "(", "channelSize", "<", "data...
Sets the offset in the block to which the the next write will write data to.
[ "Sets", "the", "offset", "in", "the", "block", "to", "which", "the", "the", "next", "write", "will", "write", "data", "to", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockInlineChecksumWriter.java#L292-L320