repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.appendString
public static File appendString(String content, File file, String charset) throws IORuntimeException { """ 将String写入文件,追加模式 @param content 写入的内容 @param file 文件 @param charset 字符集 @return 写入的文件 @throws IORuntimeException IO异常 """ return FileWriter.create(file, CharsetUtil.charset(charset)).append(content); }
java
public static File appendString(String content, File file, String charset) throws IORuntimeException { return FileWriter.create(file, CharsetUtil.charset(charset)).append(content); }
[ "public", "static", "File", "appendString", "(", "String", "content", ",", "File", "file", ",", "String", "charset", ")", "throws", "IORuntimeException", "{", "return", "FileWriter", ".", "create", "(", "file", ",", "CharsetUtil", ".", "charset", "(", "charset", ")", ")", ".", "append", "(", "content", ")", ";", "}" ]
将String写入文件,追加模式 @param content 写入的内容 @param file 文件 @param charset 字符集 @return 写入的文件 @throws IORuntimeException IO异常
[ "将String写入文件,追加模式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2826-L2828
elki-project/elki
elki-gui-minigui/src/main/java/de/lmu/ifi/dbs/elki/gui/util/LogPanel.java
LogPanel.publishTextRecord
private void publishTextRecord(final LogRecord record) { """ Publish a text record to the pane @param record Record to publish """ try { logpane.publish(record); } catch(Exception e) { throw new RuntimeException("Error writing a log-like message.", e); } }
java
private void publishTextRecord(final LogRecord record) { try { logpane.publish(record); } catch(Exception e) { throw new RuntimeException("Error writing a log-like message.", e); } }
[ "private", "void", "publishTextRecord", "(", "final", "LogRecord", "record", ")", "{", "try", "{", "logpane", ".", "publish", "(", "record", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error writing a log-like message.\"", ",", "e", ")", ";", "}", "}" ]
Publish a text record to the pane @param record Record to publish
[ "Publish", "a", "text", "record", "to", "the", "pane" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-gui-minigui/src/main/java/de/lmu/ifi/dbs/elki/gui/util/LogPanel.java#L117-L124
mboudreau/Alternator
src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java
DynamoDBMapper.safeInvoke
private Object safeInvoke(Method method, Object object, Object... arguments) { """ Swallows the checked exceptions around Method.invoke and repackages them as {@link DynamoDBMappingException} """ try { return method.invoke(object, arguments); } catch ( IllegalAccessException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } catch ( IllegalArgumentException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } catch ( InvocationTargetException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } }
java
private Object safeInvoke(Method method, Object object, Object... arguments) { try { return method.invoke(object, arguments); } catch ( IllegalAccessException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } catch ( IllegalArgumentException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } catch ( InvocationTargetException e ) { throw new DynamoDBMappingException("Couldn't invoke " + method, e); } }
[ "private", "Object", "safeInvoke", "(", "Method", "method", ",", "Object", "object", ",", "Object", "...", "arguments", ")", "{", "try", "{", "return", "method", ".", "invoke", "(", "object", ",", "arguments", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "DynamoDBMappingException", "(", "\"Couldn't invoke \"", "+", "method", ",", "e", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "DynamoDBMappingException", "(", "\"Couldn't invoke \"", "+", "method", ",", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "throw", "new", "DynamoDBMappingException", "(", "\"Couldn't invoke \"", "+", "method", ",", "e", ")", ";", "}", "}" ]
Swallows the checked exceptions around Method.invoke and repackages them as {@link DynamoDBMappingException}
[ "Swallows", "the", "checked", "exceptions", "around", "Method", ".", "invoke", "and", "repackages", "them", "as", "{" ]
train
https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java#L968-L978
wildfly/wildfly-core
elytron/src/main/java/org/wildfly/extension/elytron/ProviderAttributeDefinition.java
ProviderAttributeDefinition.populateProviders
static void populateProviders(final ModelNode response, final Provider[] providers) { """ Populate the supplied response {@link ModelNode} with information about each {@link Provider} in the included array. @param response the response to populate. @param providers the array or {@link Provider} instances to use to populate the response. """ for (Provider current : providers) { ModelNode providerModel = new ModelNode(); populateProvider(providerModel, current, true); response.add(providerModel); } }
java
static void populateProviders(final ModelNode response, final Provider[] providers) { for (Provider current : providers) { ModelNode providerModel = new ModelNode(); populateProvider(providerModel, current, true); response.add(providerModel); } }
[ "static", "void", "populateProviders", "(", "final", "ModelNode", "response", ",", "final", "Provider", "[", "]", "providers", ")", "{", "for", "(", "Provider", "current", ":", "providers", ")", "{", "ModelNode", "providerModel", "=", "new", "ModelNode", "(", ")", ";", "populateProvider", "(", "providerModel", ",", "current", ",", "true", ")", ";", "response", ".", "add", "(", "providerModel", ")", ";", "}", "}" ]
Populate the supplied response {@link ModelNode} with information about each {@link Provider} in the included array. @param response the response to populate. @param providers the array or {@link Provider} instances to use to populate the response.
[ "Populate", "the", "supplied", "response", "{", "@link", "ModelNode", "}", "with", "information", "about", "each", "{", "@link", "Provider", "}", "in", "the", "included", "array", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/elytron/src/main/java/org/wildfly/extension/elytron/ProviderAttributeDefinition.java#L180-L186
alkacon/opencms-core
src/org/opencms/jsp/search/controller/CmsSearchControllerFacetRange.java
CmsSearchControllerFacetRange.addFacetOptions
protected void addFacetOptions(StringBuffer query) { """ Adds the query parts for the facet options, except the filter parts. @param query The query part that is extended with the facet options. """ // start appendFacetOption(query, "range.start", m_config.getStart()); // end appendFacetOption(query, "range.end", m_config.getEnd()); // gap appendFacetOption(query, "range.gap", m_config.getGap()); // other for (I_CmsSearchConfigurationFacetRange.Other o : m_config.getOther()) { appendFacetOption(query, "range.other", o.toString()); } // hardend appendFacetOption(query, "range.hardend", Boolean.toString(m_config.getHardEnd())); // mincount if (m_config.getMinCount() != null) { appendFacetOption(query, "mincount", m_config.getMinCount().toString()); } }
java
protected void addFacetOptions(StringBuffer query) { // start appendFacetOption(query, "range.start", m_config.getStart()); // end appendFacetOption(query, "range.end", m_config.getEnd()); // gap appendFacetOption(query, "range.gap", m_config.getGap()); // other for (I_CmsSearchConfigurationFacetRange.Other o : m_config.getOther()) { appendFacetOption(query, "range.other", o.toString()); } // hardend appendFacetOption(query, "range.hardend", Boolean.toString(m_config.getHardEnd())); // mincount if (m_config.getMinCount() != null) { appendFacetOption(query, "mincount", m_config.getMinCount().toString()); } }
[ "protected", "void", "addFacetOptions", "(", "StringBuffer", "query", ")", "{", "// start", "appendFacetOption", "(", "query", ",", "\"range.start\"", ",", "m_config", ".", "getStart", "(", ")", ")", ";", "// end", "appendFacetOption", "(", "query", ",", "\"range.end\"", ",", "m_config", ".", "getEnd", "(", ")", ")", ";", "// gap", "appendFacetOption", "(", "query", ",", "\"range.gap\"", ",", "m_config", ".", "getGap", "(", ")", ")", ";", "// other", "for", "(", "I_CmsSearchConfigurationFacetRange", ".", "Other", "o", ":", "m_config", ".", "getOther", "(", ")", ")", "{", "appendFacetOption", "(", "query", ",", "\"range.other\"", ",", "o", ".", "toString", "(", ")", ")", ";", "}", "// hardend", "appendFacetOption", "(", "query", ",", "\"range.hardend\"", ",", "Boolean", ".", "toString", "(", "m_config", ".", "getHardEnd", "(", ")", ")", ")", ";", "// mincount", "if", "(", "m_config", ".", "getMinCount", "(", ")", "!=", "null", ")", "{", "appendFacetOption", "(", "query", ",", "\"mincount\"", ",", "m_config", ".", "getMinCount", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Adds the query parts for the facet options, except the filter parts. @param query The query part that is extended with the facet options.
[ "Adds", "the", "query", "parts", "for", "the", "facet", "options", "except", "the", "filter", "parts", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/search/controller/CmsSearchControllerFacetRange.java#L139-L157
ocelotds/ocelot
ocelot-core/src/main/java/org/ocelotds/messaging/JsTopicInterceptor.java
JsTopicInterceptor.computeTopic
String computeTopic(JsTopicName jsTopicName, String topic) { """ Compute full topicname from jsTopicName.prefix, topic and jsTopicName.postfix @param jsTopicName @param topic @return """ StringBuilder result = new StringBuilder(); if (!jsTopicName.prefix().isEmpty()) { result.append(jsTopicName.prefix()).append(Constants.Topic.COLON); } result.append(topic); if (!jsTopicName.postfix().isEmpty()) { result.append(Constants.Topic.COLON).append(jsTopicName.postfix()); } return result.toString(); }
java
String computeTopic(JsTopicName jsTopicName, String topic) { StringBuilder result = new StringBuilder(); if (!jsTopicName.prefix().isEmpty()) { result.append(jsTopicName.prefix()).append(Constants.Topic.COLON); } result.append(topic); if (!jsTopicName.postfix().isEmpty()) { result.append(Constants.Topic.COLON).append(jsTopicName.postfix()); } return result.toString(); }
[ "String", "computeTopic", "(", "JsTopicName", "jsTopicName", ",", "String", "topic", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "!", "jsTopicName", ".", "prefix", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "result", ".", "append", "(", "jsTopicName", ".", "prefix", "(", ")", ")", ".", "append", "(", "Constants", ".", "Topic", ".", "COLON", ")", ";", "}", "result", ".", "append", "(", "topic", ")", ";", "if", "(", "!", "jsTopicName", ".", "postfix", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "result", ".", "append", "(", "Constants", ".", "Topic", ".", "COLON", ")", ".", "append", "(", "jsTopicName", ".", "postfix", "(", ")", ")", ";", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Compute full topicname from jsTopicName.prefix, topic and jsTopicName.postfix @param jsTopicName @param topic @return
[ "Compute", "full", "topicname", "from", "jsTopicName", ".", "prefix", "topic", "and", "jsTopicName", ".", "postfix" ]
train
https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-core/src/main/java/org/ocelotds/messaging/JsTopicInterceptor.java#L131-L141
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java
BouncyCastleCertProcessingFactory.createCertificateRequest
public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException { """ Creates a certificate request from the specified certificate and a key pair. The certificate's subject DN with <I>"CN=proxy"</I> name component appended to the subject is used as the subject of the certificate request. Also the certificate's signing algorithm is used as the certificate request signing algorithm. @param cert the certificate to create the certificate request from. @param keyPair the key pair of the certificate request @return the certificate request. @exception GeneralSecurityException if security error occurs. """ String issuer = cert.getSubjectDN().getName(); X509Name subjectDN = new X509Name(issuer + ",CN=proxy"); String sigAlgName = cert.getSigAlgName(); return createCertificateRequest(subjectDN, sigAlgName, keyPair); }
java
public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException { String issuer = cert.getSubjectDN().getName(); X509Name subjectDN = new X509Name(issuer + ",CN=proxy"); String sigAlgName = cert.getSigAlgName(); return createCertificateRequest(subjectDN, sigAlgName, keyPair); }
[ "public", "byte", "[", "]", "createCertificateRequest", "(", "X509Certificate", "cert", ",", "KeyPair", "keyPair", ")", "throws", "GeneralSecurityException", "{", "String", "issuer", "=", "cert", ".", "getSubjectDN", "(", ")", ".", "getName", "(", ")", ";", "X509Name", "subjectDN", "=", "new", "X509Name", "(", "issuer", "+", "\",CN=proxy\"", ")", ";", "String", "sigAlgName", "=", "cert", ".", "getSigAlgName", "(", ")", ";", "return", "createCertificateRequest", "(", "subjectDN", ",", "sigAlgName", ",", "keyPair", ")", ";", "}" ]
Creates a certificate request from the specified certificate and a key pair. The certificate's subject DN with <I>"CN=proxy"</I> name component appended to the subject is used as the subject of the certificate request. Also the certificate's signing algorithm is used as the certificate request signing algorithm. @param cert the certificate to create the certificate request from. @param keyPair the key pair of the certificate request @return the certificate request. @exception GeneralSecurityException if security error occurs.
[ "Creates", "a", "certificate", "request", "from", "the", "specified", "certificate", "and", "a", "key", "pair", ".", "The", "certificate", "s", "subject", "DN", "with", "<I", ">", "CN", "=", "proxy", "<", "/", "I", ">", "name", "component", "appended", "to", "the", "subject", "is", "used", "as", "the", "subject", "of", "the", "certificate", "request", ".", "Also", "the", "certificate", "s", "signing", "algorithm", "is", "used", "as", "the", "certificate", "request", "signing", "algorithm", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java#L962-L968
powermock/powermock
powermock-core/src/main/java/org/powermock/core/MockRepository.java
MockRepository.putAdditionalState
public static synchronized Object putAdditionalState(String key, Object value) { """ When a mock framework API needs to store additional state not applicable for the other methods, it may use this method to do so. @param key The key under which the <tt>value</tt> is stored. @param value The value to store under the specified <tt>key</tt>. @return The previous object under the specified <tt>key</tt> or {@code null}. """ return additionalState.put(key, value); }
java
public static synchronized Object putAdditionalState(String key, Object value) { return additionalState.put(key, value); }
[ "public", "static", "synchronized", "Object", "putAdditionalState", "(", "String", "key", ",", "Object", "value", ")", "{", "return", "additionalState", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
When a mock framework API needs to store additional state not applicable for the other methods, it may use this method to do so. @param key The key under which the <tt>value</tt> is stored. @param value The value to store under the specified <tt>key</tt>. @return The previous object under the specified <tt>key</tt> or {@code null}.
[ "When", "a", "mock", "framework", "API", "needs", "to", "store", "additional", "state", "not", "applicable", "for", "the", "other", "methods", "it", "may", "use", "this", "method", "to", "do", "so", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L240-L242
duracloud/management-console
account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java
DuplicationMonitor.getSpaceCount
private long getSpaceCount(ContentStore store, String spaceId) throws ContentStoreException { """ /* Count the number of content items in a space in a DuraCloud account """ SpaceStatsDTOList stats = store.getSpaceStats(spaceId, new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)), new Date()); long count = 0; if (stats != null && stats.size() > 0) { count = stats.getLast().getObjectCount(); } return count; }
java
private long getSpaceCount(ContentStore store, String spaceId) throws ContentStoreException { SpaceStatsDTOList stats = store.getSpaceStats(spaceId, new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000)), new Date()); long count = 0; if (stats != null && stats.size() > 0) { count = stats.getLast().getObjectCount(); } return count; }
[ "private", "long", "getSpaceCount", "(", "ContentStore", "store", ",", "String", "spaceId", ")", "throws", "ContentStoreException", "{", "SpaceStatsDTOList", "stats", "=", "store", ".", "getSpaceStats", "(", "spaceId", ",", "new", "Date", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "(", "24", "*", "60", "*", "60", "*", "1000", ")", ")", ",", "new", "Date", "(", ")", ")", ";", "long", "count", "=", "0", ";", "if", "(", "stats", "!=", "null", "&&", "stats", ".", "size", "(", ")", ">", "0", ")", "{", "count", "=", "stats", ".", "getLast", "(", ")", ".", "getObjectCount", "(", ")", ";", "}", "return", "count", ";", "}" ]
/* Count the number of content items in a space in a DuraCloud account
[ "/", "*", "Count", "the", "number", "of", "content", "items", "in", "a", "space", "in", "a", "DuraCloud", "account" ]
train
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-monitor/src/main/java/org/duracloud/account/monitor/duplication/DuplicationMonitor.java#L209-L221
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java
DomainsInner.createOrUpdateOwnershipIdentifier
public DomainOwnershipIdentifierInner createOrUpdateOwnershipIdentifier(String resourceGroupName, String domainName, String name, DomainOwnershipIdentifierInner domainOwnershipIdentifier) { """ Creates an ownership identifier for a domain or updates identifier details for an existing identifer. Creates an ownership identifier for a domain or updates identifier details for an existing identifer. @param resourceGroupName Name of the resource group to which the resource belongs. @param domainName Name of domain. @param name Name of identifier. @param domainOwnershipIdentifier A JSON representation of the domain ownership properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws DefaultErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DomainOwnershipIdentifierInner object if successful. """ return createOrUpdateOwnershipIdentifierWithServiceResponseAsync(resourceGroupName, domainName, name, domainOwnershipIdentifier).toBlocking().single().body(); }
java
public DomainOwnershipIdentifierInner createOrUpdateOwnershipIdentifier(String resourceGroupName, String domainName, String name, DomainOwnershipIdentifierInner domainOwnershipIdentifier) { return createOrUpdateOwnershipIdentifierWithServiceResponseAsync(resourceGroupName, domainName, name, domainOwnershipIdentifier).toBlocking().single().body(); }
[ "public", "DomainOwnershipIdentifierInner", "createOrUpdateOwnershipIdentifier", "(", "String", "resourceGroupName", ",", "String", "domainName", ",", "String", "name", ",", "DomainOwnershipIdentifierInner", "domainOwnershipIdentifier", ")", "{", "return", "createOrUpdateOwnershipIdentifierWithServiceResponseAsync", "(", "resourceGroupName", ",", "domainName", ",", "name", ",", "domainOwnershipIdentifier", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates an ownership identifier for a domain or updates identifier details for an existing identifer. Creates an ownership identifier for a domain or updates identifier details for an existing identifer. @param resourceGroupName Name of the resource group to which the resource belongs. @param domainName Name of domain. @param name Name of identifier. @param domainOwnershipIdentifier A JSON representation of the domain ownership properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws DefaultErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the DomainOwnershipIdentifierInner object if successful.
[ "Creates", "an", "ownership", "identifier", "for", "a", "domain", "or", "updates", "identifier", "details", "for", "an", "existing", "identifer", ".", "Creates", "an", "ownership", "identifier", "for", "a", "domain", "or", "updates", "identifier", "details", "for", "an", "existing", "identifer", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java#L1521-L1523
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ServletStartedListener.java
ServletStartedListener.getConstraintFromHttpElement
private SecurityConstraint getConstraintFromHttpElement(SecurityMetadata securityMetadataFromDD, Collection<String> urlPatterns, ServletSecurityElement servletSecurity) { """ Gets the security constraint from the HttpConstraint element defined in the given ServletSecurityElement with the given list of url patterns. This constraint applies to all methods that are not explicitly overridden by the HttpMethodConstraint element. The method constraints are defined as omission methods in this security constraint. @param securityMetadataFromDD the security metadata processed from the deployment descriptor, for updating the roles @param urlPatterns the list of URL patterns defined in the @WebServlet annotation @param servletSecurity the ServletSecurityElement that represents the information parsed from the @ServletSecurity annotation @return the security constraint defined by the @HttpConstraint annotation """ List<String> omissionMethods = new ArrayList<String>(); if (!servletSecurity.getMethodNames().isEmpty()) { omissionMethods.addAll(servletSecurity.getMethodNames()); //list of methods named by @HttpMethodConstraint } WebResourceCollection webResourceCollection = new WebResourceCollection((List<String>) urlPatterns, new ArrayList<String>(), omissionMethods, securityMetadataFromDD.isDenyUncoveredHttpMethods()); List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>(); webResourceCollections.add(webResourceCollection); return createSecurityConstraint(securityMetadataFromDD, webResourceCollections, servletSecurity, true); }
java
private SecurityConstraint getConstraintFromHttpElement(SecurityMetadata securityMetadataFromDD, Collection<String> urlPatterns, ServletSecurityElement servletSecurity) { List<String> omissionMethods = new ArrayList<String>(); if (!servletSecurity.getMethodNames().isEmpty()) { omissionMethods.addAll(servletSecurity.getMethodNames()); //list of methods named by @HttpMethodConstraint } WebResourceCollection webResourceCollection = new WebResourceCollection((List<String>) urlPatterns, new ArrayList<String>(), omissionMethods, securityMetadataFromDD.isDenyUncoveredHttpMethods()); List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>(); webResourceCollections.add(webResourceCollection); return createSecurityConstraint(securityMetadataFromDD, webResourceCollections, servletSecurity, true); }
[ "private", "SecurityConstraint", "getConstraintFromHttpElement", "(", "SecurityMetadata", "securityMetadataFromDD", ",", "Collection", "<", "String", ">", "urlPatterns", ",", "ServletSecurityElement", "servletSecurity", ")", "{", "List", "<", "String", ">", "omissionMethods", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "if", "(", "!", "servletSecurity", ".", "getMethodNames", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "omissionMethods", ".", "addAll", "(", "servletSecurity", ".", "getMethodNames", "(", ")", ")", ";", "//list of methods named by @HttpMethodConstraint", "}", "WebResourceCollection", "webResourceCollection", "=", "new", "WebResourceCollection", "(", "(", "List", "<", "String", ">", ")", "urlPatterns", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ",", "omissionMethods", ",", "securityMetadataFromDD", ".", "isDenyUncoveredHttpMethods", "(", ")", ")", ";", "List", "<", "WebResourceCollection", ">", "webResourceCollections", "=", "new", "ArrayList", "<", "WebResourceCollection", ">", "(", ")", ";", "webResourceCollections", ".", "add", "(", "webResourceCollection", ")", ";", "return", "createSecurityConstraint", "(", "securityMetadataFromDD", ",", "webResourceCollections", ",", "servletSecurity", ",", "true", ")", ";", "}" ]
Gets the security constraint from the HttpConstraint element defined in the given ServletSecurityElement with the given list of url patterns. This constraint applies to all methods that are not explicitly overridden by the HttpMethodConstraint element. The method constraints are defined as omission methods in this security constraint. @param securityMetadataFromDD the security metadata processed from the deployment descriptor, for updating the roles @param urlPatterns the list of URL patterns defined in the @WebServlet annotation @param servletSecurity the ServletSecurityElement that represents the information parsed from the @ServletSecurity annotation @return the security constraint defined by the @HttpConstraint annotation
[ "Gets", "the", "security", "constraint", "from", "the", "HttpConstraint", "element", "defined", "in", "the", "given", "ServletSecurityElement", "with", "the", "given", "list", "of", "url", "patterns", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ServletStartedListener.java#L322-L332
strator-dev/greenpepper
samples-application/src/main/java/com/greenpepper/samples/application/system/AccountManager.java
AccountManager.deleteGroup
public boolean deleteGroup(String name) { """ <p>deleteGroup.</p> @param name a {@link java.lang.String} object. @return a boolean. """ if (ADMINISTRATOR_GROUP_ID.equals(name)) { throw new SystemException(String.format("Cannot delete '%s' group.", ADMINISTRATOR_GROUP_ID)); } if (USER_GROUP_ID.equals(name)) { throw new SystemException(String.format("Cannot delete '%s' group.", USER_GROUP_ID)); } if (!isGroupExist(name)) { throw new SystemException(String.format("Group '%s' does not exist.", name)); } if (getGroupUserCount(name) > 0) { throw new SystemException("Cannot delete a group containing users."); } return allGroups.remove(name); }
java
public boolean deleteGroup(String name) { if (ADMINISTRATOR_GROUP_ID.equals(name)) { throw new SystemException(String.format("Cannot delete '%s' group.", ADMINISTRATOR_GROUP_ID)); } if (USER_GROUP_ID.equals(name)) { throw new SystemException(String.format("Cannot delete '%s' group.", USER_GROUP_ID)); } if (!isGroupExist(name)) { throw new SystemException(String.format("Group '%s' does not exist.", name)); } if (getGroupUserCount(name) > 0) { throw new SystemException("Cannot delete a group containing users."); } return allGroups.remove(name); }
[ "public", "boolean", "deleteGroup", "(", "String", "name", ")", "{", "if", "(", "ADMINISTRATOR_GROUP_ID", ".", "equals", "(", "name", ")", ")", "{", "throw", "new", "SystemException", "(", "String", ".", "format", "(", "\"Cannot delete '%s' group.\"", ",", "ADMINISTRATOR_GROUP_ID", ")", ")", ";", "}", "if", "(", "USER_GROUP_ID", ".", "equals", "(", "name", ")", ")", "{", "throw", "new", "SystemException", "(", "String", ".", "format", "(", "\"Cannot delete '%s' group.\"", ",", "USER_GROUP_ID", ")", ")", ";", "}", "if", "(", "!", "isGroupExist", "(", "name", ")", ")", "{", "throw", "new", "SystemException", "(", "String", ".", "format", "(", "\"Group '%s' does not exist.\"", ",", "name", ")", ")", ";", "}", "if", "(", "getGroupUserCount", "(", "name", ")", ">", "0", ")", "{", "throw", "new", "SystemException", "(", "\"Cannot delete a group containing users.\"", ")", ";", "}", "return", "allGroups", ".", "remove", "(", "name", ")", ";", "}" ]
<p>deleteGroup.</p> @param name a {@link java.lang.String} object. @return a boolean.
[ "<p", ">", "deleteGroup", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/samples-application/src/main/java/com/greenpepper/samples/application/system/AccountManager.java#L79-L102
google/truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java
MapWithProtoValuesSubject.usingDoubleToleranceForFieldDescriptorsForValues
public MapWithProtoValuesFluentAssertion<M> usingDoubleToleranceForFieldDescriptorsForValues( double tolerance, Iterable<FieldDescriptor> fieldDescriptors) { """ Compares double fields with these explicitly specified fields using the provided absolute tolerance. @param tolerance A finite, non-negative tolerance. """ return usingConfig(config.usingDoubleToleranceForFieldDescriptors(tolerance, fieldDescriptors)); }
java
public MapWithProtoValuesFluentAssertion<M> usingDoubleToleranceForFieldDescriptorsForValues( double tolerance, Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.usingDoubleToleranceForFieldDescriptors(tolerance, fieldDescriptors)); }
[ "public", "MapWithProtoValuesFluentAssertion", "<", "M", ">", "usingDoubleToleranceForFieldDescriptorsForValues", "(", "double", "tolerance", ",", "Iterable", "<", "FieldDescriptor", ">", "fieldDescriptors", ")", "{", "return", "usingConfig", "(", "config", ".", "usingDoubleToleranceForFieldDescriptors", "(", "tolerance", ",", "fieldDescriptors", ")", ")", ";", "}" ]
Compares double fields with these explicitly specified fields using the provided absolute tolerance. @param tolerance A finite, non-negative tolerance.
[ "Compares", "double", "fields", "with", "these", "explicitly", "specified", "fields", "using", "the", "provided", "absolute", "tolerance", "." ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/extensions/proto/src/main/java/com/google/common/truth/extensions/proto/MapWithProtoValuesSubject.java#L552-L555
wcm-io-caravan/caravan-hal
resource/src/main/java/io/wcm/caravan/hal/resource/HalResourceFactory.java
HalResourceFactory.createResource
@Deprecated public static HalResource createResource(ObjectNode model, String href) { """ Creates a HAL resource with state and a self link. @param model The state of the resource @param href The self link for the resource @return New HAL resource @deprecated just create {@link HalResource} and {@link Link} instances using the new constructors """ return new HalResource(model, href); }
java
@Deprecated public static HalResource createResource(ObjectNode model, String href) { return new HalResource(model, href); }
[ "@", "Deprecated", "public", "static", "HalResource", "createResource", "(", "ObjectNode", "model", ",", "String", "href", ")", "{", "return", "new", "HalResource", "(", "model", ",", "href", ")", ";", "}" ]
Creates a HAL resource with state and a self link. @param model The state of the resource @param href The self link for the resource @return New HAL resource @deprecated just create {@link HalResource} and {@link Link} instances using the new constructors
[ "Creates", "a", "HAL", "resource", "with", "state", "and", "a", "self", "link", "." ]
train
https://github.com/wcm-io-caravan/caravan-hal/blob/25d58756b58c70c8c48a17fe781e673dd93d5085/resource/src/main/java/io/wcm/caravan/hal/resource/HalResourceFactory.java#L91-L94
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/Languages.java
Languages.getLanguageForLocale
public static Language getLanguageForLocale(Locale locale) { """ Get the best match for a locale, using American English as the final fallback if nothing else fits. The returned language will be a country variant language (e.g. British English, not just English) if available. Note: this does not consider languages added dynamically @throws RuntimeException if no language was found and American English as a fallback is not available """ Language language = getLanguageForLanguageNameAndCountry(locale); if (language != null) { return language; } else { Language firstFallbackLanguage = getLanguageForLanguageNameOnly(locale); if (firstFallbackLanguage != null) { return firstFallbackLanguage; } } for (Language aLanguage : languages) { if (aLanguage.getShortCodeWithCountryAndVariant().equals("en-US")) { return aLanguage; } } throw new RuntimeException("No appropriate language found, not even en-US. Supported languages: " + get()); }
java
public static Language getLanguageForLocale(Locale locale) { Language language = getLanguageForLanguageNameAndCountry(locale); if (language != null) { return language; } else { Language firstFallbackLanguage = getLanguageForLanguageNameOnly(locale); if (firstFallbackLanguage != null) { return firstFallbackLanguage; } } for (Language aLanguage : languages) { if (aLanguage.getShortCodeWithCountryAndVariant().equals("en-US")) { return aLanguage; } } throw new RuntimeException("No appropriate language found, not even en-US. Supported languages: " + get()); }
[ "public", "static", "Language", "getLanguageForLocale", "(", "Locale", "locale", ")", "{", "Language", "language", "=", "getLanguageForLanguageNameAndCountry", "(", "locale", ")", ";", "if", "(", "language", "!=", "null", ")", "{", "return", "language", ";", "}", "else", "{", "Language", "firstFallbackLanguage", "=", "getLanguageForLanguageNameOnly", "(", "locale", ")", ";", "if", "(", "firstFallbackLanguage", "!=", "null", ")", "{", "return", "firstFallbackLanguage", ";", "}", "}", "for", "(", "Language", "aLanguage", ":", "languages", ")", "{", "if", "(", "aLanguage", ".", "getShortCodeWithCountryAndVariant", "(", ")", ".", "equals", "(", "\"en-US\"", ")", ")", "{", "return", "aLanguage", ";", "}", "}", "throw", "new", "RuntimeException", "(", "\"No appropriate language found, not even en-US. Supported languages: \"", "+", "get", "(", ")", ")", ";", "}" ]
Get the best match for a locale, using American English as the final fallback if nothing else fits. The returned language will be a country variant language (e.g. British English, not just English) if available. Note: this does not consider languages added dynamically @throws RuntimeException if no language was found and American English as a fallback is not available
[ "Get", "the", "best", "match", "for", "a", "locale", "using", "American", "English", "as", "the", "final", "fallback", "if", "nothing", "else", "fits", ".", "The", "returned", "language", "will", "be", "a", "country", "variant", "language", "(", "e", ".", "g", ".", "British", "English", "not", "just", "English", ")", "if", "available", ".", "Note", ":", "this", "does", "not", "consider", "languages", "added", "dynamically" ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/Languages.java#L262-L278
spotify/crtauth-java
src/main/java/com/spotify/crtauth/CrtAuthClient.java
CrtAuthClient.createResponse
public String createResponse(String challenge) throws IllegalArgumentException, KeyNotFoundException, ProtocolVersionException { """ Generate a response String using the Signer of this instance, additionally verifying that the embedded serverName matches the serverName of this instance. @param challenge A challenge String obtained from a server. @return The response String to be returned to the server. @throws IllegalArgumentException if there is something wrong with the challenge. """ byte[] decodedChallenge = decode(challenge); Challenge deserializedChallenge = CrtAuthCodec.deserializeChallenge(decodedChallenge); if (!deserializedChallenge.getServerName().equals(serverName)) { throw new IllegalArgumentException( String.format("Server name mismatch (%s != %s). Possible MITM attack.", deserializedChallenge.getServerName(), serverName) ); } byte[] signature = signer.sign(decodedChallenge, deserializedChallenge.getFingerprint()); return encode(CrtAuthCodec.serialize(new Response(decodedChallenge, signature))); }
java
public String createResponse(String challenge) throws IllegalArgumentException, KeyNotFoundException, ProtocolVersionException { byte[] decodedChallenge = decode(challenge); Challenge deserializedChallenge = CrtAuthCodec.deserializeChallenge(decodedChallenge); if (!deserializedChallenge.getServerName().equals(serverName)) { throw new IllegalArgumentException( String.format("Server name mismatch (%s != %s). Possible MITM attack.", deserializedChallenge.getServerName(), serverName) ); } byte[] signature = signer.sign(decodedChallenge, deserializedChallenge.getFingerprint()); return encode(CrtAuthCodec.serialize(new Response(decodedChallenge, signature))); }
[ "public", "String", "createResponse", "(", "String", "challenge", ")", "throws", "IllegalArgumentException", ",", "KeyNotFoundException", ",", "ProtocolVersionException", "{", "byte", "[", "]", "decodedChallenge", "=", "decode", "(", "challenge", ")", ";", "Challenge", "deserializedChallenge", "=", "CrtAuthCodec", ".", "deserializeChallenge", "(", "decodedChallenge", ")", ";", "if", "(", "!", "deserializedChallenge", ".", "getServerName", "(", ")", ".", "equals", "(", "serverName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Server name mismatch (%s != %s). Possible MITM attack.\"", ",", "deserializedChallenge", ".", "getServerName", "(", ")", ",", "serverName", ")", ")", ";", "}", "byte", "[", "]", "signature", "=", "signer", ".", "sign", "(", "decodedChallenge", ",", "deserializedChallenge", ".", "getFingerprint", "(", ")", ")", ";", "return", "encode", "(", "CrtAuthCodec", ".", "serialize", "(", "new", "Response", "(", "decodedChallenge", ",", "signature", ")", ")", ")", ";", "}" ]
Generate a response String using the Signer of this instance, additionally verifying that the embedded serverName matches the serverName of this instance. @param challenge A challenge String obtained from a server. @return The response String to be returned to the server. @throws IllegalArgumentException if there is something wrong with the challenge.
[ "Generate", "a", "response", "String", "using", "the", "Signer", "of", "this", "instance", "additionally", "verifying", "that", "the", "embedded", "serverName", "matches", "the", "serverName", "of", "this", "instance", "." ]
train
https://github.com/spotify/crtauth-java/blob/90f3b40323848740c915b195ad1b547fbeb41700/src/main/java/com/spotify/crtauth/CrtAuthClient.java#L60-L72
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.translationRotateTowards
public Matrix4d translationRotateTowards(Vector3dc pos, Vector3dc dir, Vector3dc up) { """ Set this matrix to a model transformation for a right-handed coordinate system, that translates to the given <code>pos</code> and aligns the local <code>-z</code> axis with <code>dir</code>. <p> This method is equivalent to calling: <code>translation(pos).rotateTowards(dir, up)</code> @see #translation(Vector3dc) @see #rotateTowards(Vector3dc, Vector3dc) @param pos the position to translate to @param dir the direction to rotate towards @param up the up vector @return this """ return translationRotateTowards(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
java
public Matrix4d translationRotateTowards(Vector3dc pos, Vector3dc dir, Vector3dc up) { return translationRotateTowards(pos.x(), pos.y(), pos.z(), dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
[ "public", "Matrix4d", "translationRotateTowards", "(", "Vector3dc", "pos", ",", "Vector3dc", "dir", ",", "Vector3dc", "up", ")", "{", "return", "translationRotateTowards", "(", "pos", ".", "x", "(", ")", ",", "pos", ".", "y", "(", ")", ",", "pos", ".", "z", "(", ")", ",", "dir", ".", "x", "(", ")", ",", "dir", ".", "y", "(", ")", ",", "dir", ".", "z", "(", ")", ",", "up", ".", "x", "(", ")", ",", "up", ".", "y", "(", ")", ",", "up", ".", "z", "(", ")", ")", ";", "}" ]
Set this matrix to a model transformation for a right-handed coordinate system, that translates to the given <code>pos</code> and aligns the local <code>-z</code> axis with <code>dir</code>. <p> This method is equivalent to calling: <code>translation(pos).rotateTowards(dir, up)</code> @see #translation(Vector3dc) @see #rotateTowards(Vector3dc, Vector3dc) @param pos the position to translate to @param dir the direction to rotate towards @param up the up vector @return this
[ "Set", "this", "matrix", "to", "a", "model", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "that", "translates", "to", "the", "given", "<code", ">", "pos<", "/", "code", ">", "and", "aligns", "the", "local", "<code", ">", "-", "z<", "/", "code", ">", "axis", "with", "<code", ">", "dir<", "/", "code", ">", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", ":", "<code", ">", "translation", "(", "pos", ")", ".", "rotateTowards", "(", "dir", "up", ")", "<", "/", "code", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L15377-L15379
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java
DocTreeScanner.visitParam
@Override public R visitParam(ParamTree node, P p) { """ {@inheritDoc} This implementation scans the children in left to right order. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of scanning """ R r = scan(node.getName(), p); r = scanAndReduce(node.getDescription(), p, r); return r; }
java
@Override public R visitParam(ParamTree node, P p) { R r = scan(node.getName(), p); r = scanAndReduce(node.getDescription(), p, r); return r; }
[ "@", "Override", "public", "R", "visitParam", "(", "ParamTree", "node", ",", "P", "p", ")", "{", "R", "r", "=", "scan", "(", "node", ".", "getName", "(", ")", ",", "p", ")", ";", "r", "=", "scanAndReduce", "(", "node", ".", "getDescription", "(", ")", ",", "p", ",", "r", ")", ";", "return", "r", ";", "}" ]
{@inheritDoc} This implementation scans the children in left to right order. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of scanning
[ "{", "@inheritDoc", "}", "This", "implementation", "scans", "the", "children", "in", "left", "to", "right", "order", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/DocTreeScanner.java#L320-L325
alkacon/opencms-core
src/org/opencms/importexport/CmsExport.java
CmsExport.exportFile
protected void exportFile(CmsFile file) throws CmsImportExportException, SAXException, IOException { """ Exports one single file with all its data and content.<p> @param file the file to be exported @throws CmsImportExportException if something goes wrong @throws SAXException if something goes wrong processing the manifest.xml @throws IOException if the ZIP entry for the file could be appended to the ZIP archive """ String source = trimResourceName(getCms().getSitePath(file)); I_CmsReport report = getReport(); m_exportCount++; report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_1, String.valueOf(m_exportCount)), I_CmsReport.FORMAT_NOTE); report.print(Messages.get().container(Messages.RPT_EXPORT_0), I_CmsReport.FORMAT_NOTE); report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, getCms().getSitePath(file))); report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); // store content in zip-file // check if the content of this resource was not already exported if (!m_exportedResources.contains(file.getResourceId())) { // write the file using the export writer m_exportWriter.writeFile(file, source); // add the resource id to the storage to mark that this resource was already exported m_exportedResources.add(file.getResourceId()); // create the manifest-entries appendResourceToManifest(file, true); } else { // only create the manifest-entries appendResourceToManifest(file, false); } if (LOG.isInfoEnabled()) { LOG.info( Messages.get().getBundle().key(Messages.LOG_EXPORTING_OK_2, String.valueOf(m_exportCount), source)); } report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); }
java
protected void exportFile(CmsFile file) throws CmsImportExportException, SAXException, IOException { String source = trimResourceName(getCms().getSitePath(file)); I_CmsReport report = getReport(); m_exportCount++; report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_1, String.valueOf(m_exportCount)), I_CmsReport.FORMAT_NOTE); report.print(Messages.get().container(Messages.RPT_EXPORT_0), I_CmsReport.FORMAT_NOTE); report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, getCms().getSitePath(file))); report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); // store content in zip-file // check if the content of this resource was not already exported if (!m_exportedResources.contains(file.getResourceId())) { // write the file using the export writer m_exportWriter.writeFile(file, source); // add the resource id to the storage to mark that this resource was already exported m_exportedResources.add(file.getResourceId()); // create the manifest-entries appendResourceToManifest(file, true); } else { // only create the manifest-entries appendResourceToManifest(file, false); } if (LOG.isInfoEnabled()) { LOG.info( Messages.get().getBundle().key(Messages.LOG_EXPORTING_OK_2, String.valueOf(m_exportCount), source)); } report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); }
[ "protected", "void", "exportFile", "(", "CmsFile", "file", ")", "throws", "CmsImportExportException", ",", "SAXException", ",", "IOException", "{", "String", "source", "=", "trimResourceName", "(", "getCms", "(", ")", ".", "getSitePath", "(", "file", ")", ")", ";", "I_CmsReport", "report", "=", "getReport", "(", ")", ";", "m_exportCount", "++", ";", "report", ".", "print", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_SUCCESSION_1", ",", "String", ".", "valueOf", "(", "m_exportCount", ")", ")", ",", "I_CmsReport", ".", "FORMAT_NOTE", ")", ";", "report", ".", "print", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "RPT_EXPORT_0", ")", ",", "I_CmsReport", ".", "FORMAT_NOTE", ")", ";", "report", ".", "print", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_ARGUMENT_1", ",", "getCms", "(", ")", ".", "getSitePath", "(", "file", ")", ")", ")", ";", "report", ".", "print", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_DOTS_0", ")", ")", ";", "// store content in zip-file", "// check if the content of this resource was not already exported", "if", "(", "!", "m_exportedResources", ".", "contains", "(", "file", ".", "getResourceId", "(", ")", ")", ")", "{", "// write the file using the export writer", "m_exportWriter", ".", "writeFile", "(", "file", ",", "source", ")", ";", "// add the resource id to the storage to mark that this resource was already exported", "m_exportedResources", ".", "add", "(", "file", ".", "getResourceId", "(", ")", ")", ";", "// create the manifest-entries", "appendResourceToManifest", "(", "file", ",", "true", ")", ";", "}", "else", "{", "// only create the manifest-entries", "appendResourceToManifest", "(", "file", ",", "false", ")", ";", "}", "if", "(", "LOG", ".", "isInfoEnabled", "(", ")", ")", "{", "LOG", ".", "info", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_EXPORTING_OK_2", ",", "String", ".", "valueOf", "(", "m_exportCount", ")", ",", "source", ")", ")", ";", "}", "report", ".", "println", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "get", "(", ")", ".", "container", "(", "org", ".", "opencms", ".", "report", ".", "Messages", ".", "RPT_OK_0", ")", ",", "I_CmsReport", ".", "FORMAT_OK", ")", ";", "}" ]
Exports one single file with all its data and content.<p> @param file the file to be exported @throws CmsImportExportException if something goes wrong @throws SAXException if something goes wrong processing the manifest.xml @throws IOException if the ZIP entry for the file could be appended to the ZIP archive
[ "Exports", "one", "single", "file", "with", "all", "its", "data", "and", "content", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExport.java#L889-L927
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java
CertificatesImpl.listNextAsync
public Observable<Page<Certificate>> listNextAsync(final String nextPageLink, final CertificateListNextOptions certificateListNextOptions) { """ Lists all of the certificates that have been added to the specified account. @param nextPageLink The NextLink from the previous successful call to List operation. @param certificateListNextOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;Certificate&gt; object """ return listNextWithServiceResponseAsync(nextPageLink, certificateListNextOptions) .map(new Func1<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>, Page<Certificate>>() { @Override public Page<Certificate> call(ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders> response) { return response.body(); } }); }
java
public Observable<Page<Certificate>> listNextAsync(final String nextPageLink, final CertificateListNextOptions certificateListNextOptions) { return listNextWithServiceResponseAsync(nextPageLink, certificateListNextOptions) .map(new Func1<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>, Page<Certificate>>() { @Override public Page<Certificate> call(ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "Certificate", ">", ">", "listNextAsync", "(", "final", "String", "nextPageLink", ",", "final", "CertificateListNextOptions", "certificateListNextOptions", ")", "{", "return", "listNextWithServiceResponseAsync", "(", "nextPageLink", ",", "certificateListNextOptions", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "Page", "<", "Certificate", ">", ",", "CertificateListHeaders", ">", ",", "Page", "<", "Certificate", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "Certificate", ">", "call", "(", "ServiceResponseWithHeaders", "<", "Page", "<", "Certificate", ">", ",", "CertificateListHeaders", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Lists all of the certificates that have been added to the specified account. @param nextPageLink The NextLink from the previous successful call to List operation. @param certificateListNextOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;Certificate&gt; object
[ "Lists", "all", "of", "the", "certificates", "that", "have", "been", "added", "to", "the", "specified", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/CertificatesImpl.java#L1354-L1362
aboutsip/pkts
pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipParser.java
SipParser.consumeSeparator
private static int consumeSeparator(final Buffer buffer, final byte b) throws IndexOutOfBoundsException, IOException { """ Helper function for checking stuff as described below. It is all the same pattern so... (from rfc 3261 section 25.1) When tokens are used or separators are used between elements, whitespace is often allowed before or after these characters: STAR = SWS "*" SWS ; asterisk SLASH = SWS "/" SWS ; slash EQUAL = SWS "=" SWS ; equal LPAREN = SWS "(" SWS ; left parenthesis RPAREN = SWS ")" SWS ; right parenthesis RAQUOT = ">" SWS ; right angle quote LAQUOT = SWS "<"; left angle quote COMMA = SWS "," SWS ; comma SEMI = SWS ";" SWS ; semicolon COLON = SWS ":" SWS ; colon LDQUOT = SWS DQUOTE; open double quotation mark RDQUOT = DQUOTE SWS ; close double quotation mark @param buffer @param b @return the number of bytes that was consumed. @throws IOException @throws IndexOutOfBoundsException """ buffer.markReaderIndex(); int consumed = consumeSWS(buffer); if (isNext(buffer, b)) { buffer.readByte(); ++consumed; } else { buffer.resetReaderIndex(); return 0; } consumed += consumeSWS(buffer); return consumed; }
java
private static int consumeSeparator(final Buffer buffer, final byte b) throws IndexOutOfBoundsException, IOException { buffer.markReaderIndex(); int consumed = consumeSWS(buffer); if (isNext(buffer, b)) { buffer.readByte(); ++consumed; } else { buffer.resetReaderIndex(); return 0; } consumed += consumeSWS(buffer); return consumed; }
[ "private", "static", "int", "consumeSeparator", "(", "final", "Buffer", "buffer", ",", "final", "byte", "b", ")", "throws", "IndexOutOfBoundsException", ",", "IOException", "{", "buffer", ".", "markReaderIndex", "(", ")", ";", "int", "consumed", "=", "consumeSWS", "(", "buffer", ")", ";", "if", "(", "isNext", "(", "buffer", ",", "b", ")", ")", "{", "buffer", ".", "readByte", "(", ")", ";", "++", "consumed", ";", "}", "else", "{", "buffer", ".", "resetReaderIndex", "(", ")", ";", "return", "0", ";", "}", "consumed", "+=", "consumeSWS", "(", "buffer", ")", ";", "return", "consumed", ";", "}" ]
Helper function for checking stuff as described below. It is all the same pattern so... (from rfc 3261 section 25.1) When tokens are used or separators are used between elements, whitespace is often allowed before or after these characters: STAR = SWS "*" SWS ; asterisk SLASH = SWS "/" SWS ; slash EQUAL = SWS "=" SWS ; equal LPAREN = SWS "(" SWS ; left parenthesis RPAREN = SWS ")" SWS ; right parenthesis RAQUOT = ">" SWS ; right angle quote LAQUOT = SWS "<"; left angle quote COMMA = SWS "," SWS ; comma SEMI = SWS ";" SWS ; semicolon COLON = SWS ":" SWS ; colon LDQUOT = SWS DQUOTE; open double quotation mark RDQUOT = DQUOTE SWS ; close double quotation mark @param buffer @param b @return the number of bytes that was consumed. @throws IOException @throws IndexOutOfBoundsException
[ "Helper", "function", "for", "checking", "stuff", "as", "described", "below", ".", "It", "is", "all", "the", "same", "pattern", "so", "...", "(", "from", "rfc", "3261", "section", "25", ".", "1", ")" ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipParser.java#L957-L970
threerings/narya
core/src/main/java/com/threerings/presents/server/ShutdownManager.java
ShutdownManager.addConstraint
public void addConstraint (Shutdowner lhs, Constraint constraint, Shutdowner rhs) { """ Adds a constraint that a certain shutdowner must be run before another. """ switch (constraint) { case RUNS_BEFORE: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_BEFORE, rhs); break; case RUNS_AFTER: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_AFTER, rhs); break; } }
java
public void addConstraint (Shutdowner lhs, Constraint constraint, Shutdowner rhs) { switch (constraint) { case RUNS_BEFORE: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_BEFORE, rhs); break; case RUNS_AFTER: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_AFTER, rhs); break; } }
[ "public", "void", "addConstraint", "(", "Shutdowner", "lhs", ",", "Constraint", "constraint", ",", "Shutdowner", "rhs", ")", "{", "switch", "(", "constraint", ")", "{", "case", "RUNS_BEFORE", ":", "_cycle", ".", "addShutdownConstraint", "(", "lhs", ",", "Lifecycle", ".", "Constraint", ".", "RUNS_BEFORE", ",", "rhs", ")", ";", "break", ";", "case", "RUNS_AFTER", ":", "_cycle", ".", "addShutdownConstraint", "(", "lhs", ",", "Lifecycle", ".", "Constraint", ".", "RUNS_AFTER", ",", "rhs", ")", ";", "break", ";", "}", "}" ]
Adds a constraint that a certain shutdowner must be run before another.
[ "Adds", "a", "constraint", "that", "a", "certain", "shutdowner", "must", "be", "run", "before", "another", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/ShutdownManager.java#L64-L74
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/ResultIterator.java
ResultIterator.onCheckRelation
private void onCheckRelation() { """ on check relation event, invokes populate entities and set relational entities, in case relations are present. """ try { results = populateEntities(entityMetadata, client); if (entityMetadata.isRelationViaJoinTable() || (entityMetadata.getRelationNames() != null && !(entityMetadata.getRelationNames().isEmpty()))) { query.setRelationalEntities(results, client, entityMetadata); } } catch (Exception e) { throw new PersistenceException("Error while scrolling over results, Caused by :.", e); } }
java
private void onCheckRelation() { try { results = populateEntities(entityMetadata, client); if (entityMetadata.isRelationViaJoinTable() || (entityMetadata.getRelationNames() != null && !(entityMetadata.getRelationNames().isEmpty()))) { query.setRelationalEntities(results, client, entityMetadata); } } catch (Exception e) { throw new PersistenceException("Error while scrolling over results, Caused by :.", e); } }
[ "private", "void", "onCheckRelation", "(", ")", "{", "try", "{", "results", "=", "populateEntities", "(", "entityMetadata", ",", "client", ")", ";", "if", "(", "entityMetadata", ".", "isRelationViaJoinTable", "(", ")", "||", "(", "entityMetadata", ".", "getRelationNames", "(", ")", "!=", "null", "&&", "!", "(", "entityMetadata", ".", "getRelationNames", "(", ")", ".", "isEmpty", "(", ")", ")", ")", ")", "{", "query", ".", "setRelationalEntities", "(", "results", ",", "client", ",", "entityMetadata", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PersistenceException", "(", "\"Error while scrolling over results, Caused by :.\"", ",", "e", ")", ";", "}", "}" ]
on check relation event, invokes populate entities and set relational entities, in case relations are present.
[ "on", "check", "relation", "event", "invokes", "populate", "entities", "and", "set", "relational", "entities", "in", "case", "relations", "are", "present", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/ResultIterator.java#L238-L254
mapsforge/mapsforge
sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java
SQLiteDatabase.rawQueryWithFactory
public Cursor rawQueryWithFactory( CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable) { """ Runs the provided SQL and returns a cursor over the result set. @param cursorFactory the cursor factory to use, or null for the default factory @param sql the SQL query. The SQL string must not be ; terminated @param selectionArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings. @param editTable the name of the first table, which is editable @return A {@link Cursor} object, which is positioned before the first entry. Note that {@link Cursor}s are not synchronized, see the documentation for more details. """ return rawQueryWithFactory(cursorFactory, sql, selectionArgs, editTable, null); }
java
public Cursor rawQueryWithFactory( CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable) { return rawQueryWithFactory(cursorFactory, sql, selectionArgs, editTable, null); }
[ "public", "Cursor", "rawQueryWithFactory", "(", "CursorFactory", "cursorFactory", ",", "String", "sql", ",", "String", "[", "]", "selectionArgs", ",", "String", "editTable", ")", "{", "return", "rawQueryWithFactory", "(", "cursorFactory", ",", "sql", ",", "selectionArgs", ",", "editTable", ",", "null", ")", ";", "}" ]
Runs the provided SQL and returns a cursor over the result set. @param cursorFactory the cursor factory to use, or null for the default factory @param sql the SQL query. The SQL string must not be ; terminated @param selectionArgs You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings. @param editTable the name of the first table, which is editable @return A {@link Cursor} object, which is positioned before the first entry. Note that {@link Cursor}s are not synchronized, see the documentation for more details.
[ "Runs", "the", "provided", "SQL", "and", "returns", "a", "cursor", "over", "the", "result", "set", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/sqlite/SQLiteDatabase.java#L1292-L1296
looly/hutool
hutool-core/src/main/java/cn/hutool/core/math/Combination.java
Combination.count
public static long count(int n, int m) { """ 计算组合数,即C(n, m) = n!/((n-m)! * m!) @param n 总数 @param m 选择的个数 @return 组合数 """ if(0 == m) { return 1; } if(n == m) { return NumberUtil.factorial(n) / NumberUtil.factorial(m); } return (n > m) ? NumberUtil.factorial(n, n - m) / NumberUtil.factorial(m) : 0; }
java
public static long count(int n, int m) { if(0 == m) { return 1; } if(n == m) { return NumberUtil.factorial(n) / NumberUtil.factorial(m); } return (n > m) ? NumberUtil.factorial(n, n - m) / NumberUtil.factorial(m) : 0; }
[ "public", "static", "long", "count", "(", "int", "n", ",", "int", "m", ")", "{", "if", "(", "0", "==", "m", ")", "{", "return", "1", ";", "}", "if", "(", "n", "==", "m", ")", "{", "return", "NumberUtil", ".", "factorial", "(", "n", ")", "/", "NumberUtil", ".", "factorial", "(", "m", ")", ";", "}", "return", "(", "n", ">", "m", ")", "?", "NumberUtil", ".", "factorial", "(", "n", ",", "n", "-", "m", ")", "/", "NumberUtil", ".", "factorial", "(", "m", ")", ":", "0", ";", "}" ]
计算组合数,即C(n, m) = n!/((n-m)! * m!) @param n 总数 @param m 选择的个数 @return 组合数
[ "计算组合数,即C", "(", "n", "m", ")", "=", "n!", "/", "((", "n", "-", "m", ")", "!", "*", "m!", ")" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/math/Combination.java#L37-L45
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.updateState
private void updateState(CmsDbContext dbc, CmsResource resource, boolean resourceState) throws CmsDataAccessException { """ Updates the state of a resource, depending on the <code>resourceState</code> parameter.<p> @param dbc the db context @param resource the resource @param resourceState if <code>true</code> the resource state will be updated, if not just the structure state. @throws CmsDataAccessException if something goes wrong """ CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); resource.setUserLastModified(dbc.currentUser().getId()); if (resourceState) { // update the whole resource state getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_RESOURCE_STATE); } else { // update the structure state getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_STRUCTURE_STATE); } }
java
private void updateState(CmsDbContext dbc, CmsResource resource, boolean resourceState) throws CmsDataAccessException { CmsUUID projectId = ((dbc.getProjectId() == null) || dbc.getProjectId().isNullUUID()) ? dbc.currentProject().getUuid() : dbc.getProjectId(); resource.setUserLastModified(dbc.currentUser().getId()); if (resourceState) { // update the whole resource state getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_RESOURCE_STATE); } else { // update the structure state getVfsDriver(dbc).writeResource(dbc, projectId, resource, UPDATE_STRUCTURE_STATE); } }
[ "private", "void", "updateState", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ",", "boolean", "resourceState", ")", "throws", "CmsDataAccessException", "{", "CmsUUID", "projectId", "=", "(", "(", "dbc", ".", "getProjectId", "(", ")", "==", "null", ")", "||", "dbc", ".", "getProjectId", "(", ")", ".", "isNullUUID", "(", ")", ")", "?", "dbc", ".", "currentProject", "(", ")", ".", "getUuid", "(", ")", ":", "dbc", ".", "getProjectId", "(", ")", ";", "resource", ".", "setUserLastModified", "(", "dbc", ".", "currentUser", "(", ")", ".", "getId", "(", ")", ")", ";", "if", "(", "resourceState", ")", "{", "// update the whole resource state", "getVfsDriver", "(", "dbc", ")", ".", "writeResource", "(", "dbc", ",", "projectId", ",", "resource", ",", "UPDATE_RESOURCE_STATE", ")", ";", "}", "else", "{", "// update the structure state", "getVfsDriver", "(", "dbc", ")", ".", "writeResource", "(", "dbc", ",", "projectId", ",", "resource", ",", "UPDATE_STRUCTURE_STATE", ")", ";", "}", "}" ]
Updates the state of a resource, depending on the <code>resourceState</code> parameter.<p> @param dbc the db context @param resource the resource @param resourceState if <code>true</code> the resource state will be updated, if not just the structure state. @throws CmsDataAccessException if something goes wrong
[ "Updates", "the", "state", "of", "a", "resource", "depending", "on", "the", "<code", ">", "resourceState<", "/", "code", ">", "parameter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L11962-L11976
52inc/android-52Kit
library/src/main/java/com/ftinc/kit/util/MediaUtils.java
MediaUtils.nonDuplicateFile
public static File nonDuplicateFile(File dir, String name) { """ Create a non duplicate file in the given directory with the given name, appending a duplicate counter to the end of the name but before the extension like: `some_file(1).jpg` @param dir The parent directory of the desired file @param name The desired name of the file @return The non-duplicate file """ int count = 1; File outputFile = new File(dir, name); while(outputFile.exists()){ String cleanName = cleanFilename(name); int extIndex = name.lastIndexOf("."); String extension = ""; if(extIndex != -1) { extension = name.substring(extIndex + 1); } String revisedFileName = String.format(Locale.US, "%s(%d).%s", cleanName, count, extension); outputFile = new File(dir, revisedFileName); count++; } return outputFile; }
java
public static File nonDuplicateFile(File dir, String name){ int count = 1; File outputFile = new File(dir, name); while(outputFile.exists()){ String cleanName = cleanFilename(name); int extIndex = name.lastIndexOf("."); String extension = ""; if(extIndex != -1) { extension = name.substring(extIndex + 1); } String revisedFileName = String.format(Locale.US, "%s(%d).%s", cleanName, count, extension); outputFile = new File(dir, revisedFileName); count++; } return outputFile; }
[ "public", "static", "File", "nonDuplicateFile", "(", "File", "dir", ",", "String", "name", ")", "{", "int", "count", "=", "1", ";", "File", "outputFile", "=", "new", "File", "(", "dir", ",", "name", ")", ";", "while", "(", "outputFile", ".", "exists", "(", ")", ")", "{", "String", "cleanName", "=", "cleanFilename", "(", "name", ")", ";", "int", "extIndex", "=", "name", ".", "lastIndexOf", "(", "\".\"", ")", ";", "String", "extension", "=", "\"\"", ";", "if", "(", "extIndex", "!=", "-", "1", ")", "{", "extension", "=", "name", ".", "substring", "(", "extIndex", "+", "1", ")", ";", "}", "String", "revisedFileName", "=", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"%s(%d).%s\"", ",", "cleanName", ",", "count", ",", "extension", ")", ";", "outputFile", "=", "new", "File", "(", "dir", ",", "revisedFileName", ")", ";", "count", "++", ";", "}", "return", "outputFile", ";", "}" ]
Create a non duplicate file in the given directory with the given name, appending a duplicate counter to the end of the name but before the extension like: `some_file(1).jpg` @param dir The parent directory of the desired file @param name The desired name of the file @return The non-duplicate file
[ "Create", "a", "non", "duplicate", "file", "in", "the", "given", "directory", "with", "the", "given", "name", "appending", "a", "duplicate", "counter", "to", "the", "end", "of", "the", "name", "but", "before", "the", "extension", "like", ":", "some_file", "(", "1", ")", ".", "jpg" ]
train
https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/MediaUtils.java#L317-L334
sniffy/sniffy
sniffy-core/src/main/java/io/sniffy/LegacySpy.java
LegacySpy.expectBetween
@Deprecated public C expectBetween(int minAllowedStatements, int maxAllowedStatements) { """ Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments {@code minAllowedStatements}, {@code maxAllowedStatements}, {@link Threads#CURRENT}, {@link Query#ANY} @since 2.0 """ return expect(SqlQueries.queriesBetween(minAllowedStatements, maxAllowedStatements)); }
java
@Deprecated public C expectBetween(int minAllowedStatements, int maxAllowedStatements) { return expect(SqlQueries.queriesBetween(minAllowedStatements, maxAllowedStatements)); }
[ "@", "Deprecated", "public", "C", "expectBetween", "(", "int", "minAllowedStatements", ",", "int", "maxAllowedStatements", ")", "{", "return", "expect", "(", "SqlQueries", ".", "queriesBetween", "(", "minAllowedStatements", ",", "maxAllowedStatements", ")", ")", ";", "}" ]
Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments {@code minAllowedStatements}, {@code maxAllowedStatements}, {@link Threads#CURRENT}, {@link Query#ANY} @since 2.0
[ "Alias", "for", "{" ]
train
https://github.com/sniffy/sniffy/blob/7bdddb9593e6b6e9fe5c7c87519f864acbc3a5c0/sniffy-core/src/main/java/io/sniffy/LegacySpy.java#L586-L589
guardtime/ksi-java-sdk
ksi-common/src/main/java/com/guardtime/ksi/util/Base16.java
Base16.encodeWithColons
public static String encodeWithColons(byte[] in, int off, int len) { """ Encodes the given bytes into a base-16 string, inserting colons after every 2 characters of output. @param in the bytes to encode. @param off the start offset of the data within {@code in}. @param len the number of bytes to encode. @return The formatted base-16 string. """ return inst.encode(in, off, len, ":", 2).toString(); }
java
public static String encodeWithColons(byte[] in, int off, int len) { return inst.encode(in, off, len, ":", 2).toString(); }
[ "public", "static", "String", "encodeWithColons", "(", "byte", "[", "]", "in", ",", "int", "off", ",", "int", "len", ")", "{", "return", "inst", ".", "encode", "(", "in", ",", "off", ",", "len", ",", "\":\"", ",", "2", ")", ".", "toString", "(", ")", ";", "}" ]
Encodes the given bytes into a base-16 string, inserting colons after every 2 characters of output. @param in the bytes to encode. @param off the start offset of the data within {@code in}. @param len the number of bytes to encode. @return The formatted base-16 string.
[ "Encodes", "the", "given", "bytes", "into", "a", "base", "-", "16", "string", "inserting", "colons", "after", "every", "2", "characters", "of", "output", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-common/src/main/java/com/guardtime/ksi/util/Base16.java#L95-L97
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/storage/DataSet.java
DataSet.findRowIgnoreCase
public DataRow findRowIgnoreCase(int columnIndex, String value) { """ checks whether dataset contains the value given (ignoring the case) @param columnIndex @param value @return """ for (DataRow dataRow : dataRows) { String columnValue = (String) dataRow.getColumn(columnIndex); if (value.equalsIgnoreCase(columnValue)) { return dataRow; } } return null; }
java
public DataRow findRowIgnoreCase(int columnIndex, String value) { for (DataRow dataRow : dataRows) { String columnValue = (String) dataRow.getColumn(columnIndex); if (value.equalsIgnoreCase(columnValue)) { return dataRow; } } return null; }
[ "public", "DataRow", "findRowIgnoreCase", "(", "int", "columnIndex", ",", "String", "value", ")", "{", "for", "(", "DataRow", "dataRow", ":", "dataRows", ")", "{", "String", "columnValue", "=", "(", "String", ")", "dataRow", ".", "getColumn", "(", "columnIndex", ")", ";", "if", "(", "value", ".", "equalsIgnoreCase", "(", "columnValue", ")", ")", "{", "return", "dataRow", ";", "}", "}", "return", "null", ";", "}" ]
checks whether dataset contains the value given (ignoring the case) @param columnIndex @param value @return
[ "checks", "whether", "dataset", "contains", "the", "value", "given", "(", "ignoring", "the", "case", ")" ]
train
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/storage/DataSet.java#L76-L87
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSImageCompression.java
FSImageCompression.createCompression
static FSImageCompression createCompression(Configuration conf, boolean forceUncompressed) throws IOException { """ Create a compression instance based on the user's configuration in the given Configuration object. @throws IOException if the specified codec is not available. """ boolean compressImage = (!forceUncompressed) && conf.getBoolean( HdfsConstants.DFS_IMAGE_COMPRESS_KEY, HdfsConstants.DFS_IMAGE_COMPRESS_DEFAULT); if (!compressImage) { return createNoopCompression(); } String codecClassName = conf.get( HdfsConstants.DFS_IMAGE_COMPRESSION_CODEC_KEY, HdfsConstants.DFS_IMAGE_COMPRESSION_CODEC_DEFAULT); return createCompression(conf, codecClassName); }
java
static FSImageCompression createCompression(Configuration conf, boolean forceUncompressed) throws IOException { boolean compressImage = (!forceUncompressed) && conf.getBoolean( HdfsConstants.DFS_IMAGE_COMPRESS_KEY, HdfsConstants.DFS_IMAGE_COMPRESS_DEFAULT); if (!compressImage) { return createNoopCompression(); } String codecClassName = conf.get( HdfsConstants.DFS_IMAGE_COMPRESSION_CODEC_KEY, HdfsConstants.DFS_IMAGE_COMPRESSION_CODEC_DEFAULT); return createCompression(conf, codecClassName); }
[ "static", "FSImageCompression", "createCompression", "(", "Configuration", "conf", ",", "boolean", "forceUncompressed", ")", "throws", "IOException", "{", "boolean", "compressImage", "=", "(", "!", "forceUncompressed", ")", "&&", "conf", ".", "getBoolean", "(", "HdfsConstants", ".", "DFS_IMAGE_COMPRESS_KEY", ",", "HdfsConstants", ".", "DFS_IMAGE_COMPRESS_DEFAULT", ")", ";", "if", "(", "!", "compressImage", ")", "{", "return", "createNoopCompression", "(", ")", ";", "}", "String", "codecClassName", "=", "conf", ".", "get", "(", "HdfsConstants", ".", "DFS_IMAGE_COMPRESSION_CODEC_KEY", ",", "HdfsConstants", ".", "DFS_IMAGE_COMPRESSION_CODEC_DEFAULT", ")", ";", "return", "createCompression", "(", "conf", ",", "codecClassName", ")", ";", "}" ]
Create a compression instance based on the user's configuration in the given Configuration object. @throws IOException if the specified codec is not available.
[ "Create", "a", "compression", "instance", "based", "on", "the", "user", "s", "configuration", "in", "the", "given", "Configuration", "object", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSImageCompression.java#L72-L86
aaberg/sql2o
core/src/main/java/org/sql2o/Sql2o.java
Sql2o.runInTransaction
public void runInTransaction(StatementRunnable runnable, Object argument) { """ Calls the {@link StatementRunnable#run(Connection, Object)} method on the {@link StatementRunnable} parameter. All statements run on the {@link Connection} instance in the {@link StatementRunnable#run(Connection, Object) run} method will be executed in a transaction. The transaction will automatically be committed if the {@link StatementRunnable#run(Connection, Object) run} method finishes without throwing an exception. If an exception is thrown within the {@link StatementRunnable#run(Connection, Object) run} method, the transaction will automatically be rolled back. The isolation level of the transaction will be set to {@link java.sql.Connection#TRANSACTION_READ_COMMITTED} @param runnable The {@link StatementRunnable} instance. @param argument An argument which will be forwarded to the {@link StatementRunnable#run(Connection, Object) run} method """ runInTransaction(runnable, argument, java.sql.Connection.TRANSACTION_READ_COMMITTED); }
java
public void runInTransaction(StatementRunnable runnable, Object argument){ runInTransaction(runnable, argument, java.sql.Connection.TRANSACTION_READ_COMMITTED); }
[ "public", "void", "runInTransaction", "(", "StatementRunnable", "runnable", ",", "Object", "argument", ")", "{", "runInTransaction", "(", "runnable", ",", "argument", ",", "java", ".", "sql", ".", "Connection", ".", "TRANSACTION_READ_COMMITTED", ")", ";", "}" ]
Calls the {@link StatementRunnable#run(Connection, Object)} method on the {@link StatementRunnable} parameter. All statements run on the {@link Connection} instance in the {@link StatementRunnable#run(Connection, Object) run} method will be executed in a transaction. The transaction will automatically be committed if the {@link StatementRunnable#run(Connection, Object) run} method finishes without throwing an exception. If an exception is thrown within the {@link StatementRunnable#run(Connection, Object) run} method, the transaction will automatically be rolled back. The isolation level of the transaction will be set to {@link java.sql.Connection#TRANSACTION_READ_COMMITTED} @param runnable The {@link StatementRunnable} instance. @param argument An argument which will be forwarded to the {@link StatementRunnable#run(Connection, Object) run} method
[ "Calls", "the", "{", "@link", "StatementRunnable#run", "(", "Connection", "Object", ")", "}", "method", "on", "the", "{", "@link", "StatementRunnable", "}", "parameter", ".", "All", "statements", "run", "on", "the", "{", "@link", "Connection", "}", "instance", "in", "the", "{", "@link", "StatementRunnable#run", "(", "Connection", "Object", ")", "run", "}", "method", "will", "be", "executed", "in", "a", "transaction", ".", "The", "transaction", "will", "automatically", "be", "committed", "if", "the", "{", "@link", "StatementRunnable#run", "(", "Connection", "Object", ")", "run", "}", "method", "finishes", "without", "throwing", "an", "exception", ".", "If", "an", "exception", "is", "thrown", "within", "the", "{", "@link", "StatementRunnable#run", "(", "Connection", "Object", ")", "run", "}", "method", "the", "transaction", "will", "automatically", "be", "rolled", "back", "." ]
train
https://github.com/aaberg/sql2o/blob/01d3490a6d2440cf60f973d23508ac4ed57a8e20/core/src/main/java/org/sql2o/Sql2o.java#L360-L362
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/util/SparseDoubleArray.java
SparseDoubleArray.dividePrimitive
public double dividePrimitive(int index, double value) { """ Divides the specified value to the index by the provided value and stores the result at the index (just as {@code array[index] /= value}) @param index the position in the array @param value the value by which the value at the index will be divided @return the new value stored at the index """ if (index < 0 || index >= maxLength) throw new ArrayIndexOutOfBoundsException( "invalid index: " + index); int pos = Arrays.binarySearch(indices, index); // The divide operation is dividing a non-existent value in the // array, which is always 0, so the corresponding result is 0. // Therefore, we don't need to make room. if (pos < 0) return 0; else { double newValue = values[pos] / value; // The new value is zero, so remove its position and shift // everything over if (newValue == 0) { int newLength = indices.length - 1; int[] newIndices = new int[newLength]; double[] newValues = new double[newLength]; for (int i = 0, j = 0; i < indices.length; ++i) { if (i != pos) { newIndices[j] = indices[i]; newValues[j] = values[i]; j++; } } // swap the arrays indices = newIndices; values = newValues; } // Otherwise, the new value is still non-zero, so update it in the // array else values[pos] = newValue; return newValue; } }
java
public double dividePrimitive(int index, double value) { if (index < 0 || index >= maxLength) throw new ArrayIndexOutOfBoundsException( "invalid index: " + index); int pos = Arrays.binarySearch(indices, index); // The divide operation is dividing a non-existent value in the // array, which is always 0, so the corresponding result is 0. // Therefore, we don't need to make room. if (pos < 0) return 0; else { double newValue = values[pos] / value; // The new value is zero, so remove its position and shift // everything over if (newValue == 0) { int newLength = indices.length - 1; int[] newIndices = new int[newLength]; double[] newValues = new double[newLength]; for (int i = 0, j = 0; i < indices.length; ++i) { if (i != pos) { newIndices[j] = indices[i]; newValues[j] = values[i]; j++; } } // swap the arrays indices = newIndices; values = newValues; } // Otherwise, the new value is still non-zero, so update it in the // array else values[pos] = newValue; return newValue; } }
[ "public", "double", "dividePrimitive", "(", "int", "index", ",", "double", "value", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">=", "maxLength", ")", "throw", "new", "ArrayIndexOutOfBoundsException", "(", "\"invalid index: \"", "+", "index", ")", ";", "int", "pos", "=", "Arrays", ".", "binarySearch", "(", "indices", ",", "index", ")", ";", "// The divide operation is dividing a non-existent value in the", "// array, which is always 0, so the corresponding result is 0.", "// Therefore, we don't need to make room.", "if", "(", "pos", "<", "0", ")", "return", "0", ";", "else", "{", "double", "newValue", "=", "values", "[", "pos", "]", "/", "value", ";", "// The new value is zero, so remove its position and shift", "// everything over", "if", "(", "newValue", "==", "0", ")", "{", "int", "newLength", "=", "indices", ".", "length", "-", "1", ";", "int", "[", "]", "newIndices", "=", "new", "int", "[", "newLength", "]", ";", "double", "[", "]", "newValues", "=", "new", "double", "[", "newLength", "]", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "indices", ".", "length", ";", "++", "i", ")", "{", "if", "(", "i", "!=", "pos", ")", "{", "newIndices", "[", "j", "]", "=", "indices", "[", "i", "]", ";", "newValues", "[", "j", "]", "=", "values", "[", "i", "]", ";", "j", "++", ";", "}", "}", "// swap the arrays", "indices", "=", "newIndices", ";", "values", "=", "newValues", ";", "}", "// Otherwise, the new value is still non-zero, so update it in the", "// array", "else", "values", "[", "pos", "]", "=", "newValue", ";", "return", "newValue", ";", "}", "}" ]
Divides the specified value to the index by the provided value and stores the result at the index (just as {@code array[index] /= value}) @param index the position in the array @param value the value by which the value at the index will be divided @return the new value stored at the index
[ "Divides", "the", "specified", "value", "to", "the", "index", "by", "the", "provided", "value", "and", "stores", "the", "result", "at", "the", "index", "(", "just", "as", "{", "@code", "array", "[", "index", "]", "/", "=", "value", "}", ")" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/SparseDoubleArray.java#L252-L290
dhanji/sitebricks
sitebricks-mail/src/main/java/com/google/sitebricks/mail/imap/MessageStatusExtractor.java
MessageStatusExtractor.isUnterminatedString
@VisibleForTesting static boolean isUnterminatedString(String message, boolean alreadyInString) { """ Check for string termination, will check for quote escaping, but only if it's escaped within a string... otherwise it's illegal and we'll treat it as a regular quote. A trailing backslash indicates a \CRLF was received (as envisaged in RFC 822 3.4.5). """ boolean escaped = false; boolean inString = alreadyInString; for (int i = 0; i < message.length(); i++) { final char c = message.charAt(i); if (inString) { if (c == '\\') { escaped = !escaped; } else if (c == '"') { if (!escaped) inString = false; escaped = false; } else escaped = false; } else inString = c == '"'; } return inString; }
java
@VisibleForTesting static boolean isUnterminatedString(String message, boolean alreadyInString) { boolean escaped = false; boolean inString = alreadyInString; for (int i = 0; i < message.length(); i++) { final char c = message.charAt(i); if (inString) { if (c == '\\') { escaped = !escaped; } else if (c == '"') { if (!escaped) inString = false; escaped = false; } else escaped = false; } else inString = c == '"'; } return inString; }
[ "@", "VisibleForTesting", "static", "boolean", "isUnterminatedString", "(", "String", "message", ",", "boolean", "alreadyInString", ")", "{", "boolean", "escaped", "=", "false", ";", "boolean", "inString", "=", "alreadyInString", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "message", ".", "length", "(", ")", ";", "i", "++", ")", "{", "final", "char", "c", "=", "message", ".", "charAt", "(", "i", ")", ";", "if", "(", "inString", ")", "{", "if", "(", "c", "==", "'", "'", ")", "{", "escaped", "=", "!", "escaped", ";", "}", "else", "if", "(", "c", "==", "'", "'", ")", "{", "if", "(", "!", "escaped", ")", "inString", "=", "false", ";", "escaped", "=", "false", ";", "}", "else", "escaped", "=", "false", ";", "}", "else", "inString", "=", "c", "==", "'", "'", ";", "}", "return", "inString", ";", "}" ]
Check for string termination, will check for quote escaping, but only if it's escaped within a string... otherwise it's illegal and we'll treat it as a regular quote. A trailing backslash indicates a \CRLF was received (as envisaged in RFC 822 3.4.5).
[ "Check", "for", "string", "termination", "will", "check", "for", "quote", "escaping", "but", "only", "if", "it", "s", "escaped", "within", "a", "string", "...", "otherwise", "it", "s", "illegal", "and", "we", "ll", "treat", "it", "as", "a", "regular", "quote", ".", "A", "trailing", "backslash", "indicates", "a", "\\", "CRLF", "was", "received", "(", "as", "envisaged", "in", "RFC", "822", "3", ".", "4", ".", "5", ")", "." ]
train
https://github.com/dhanji/sitebricks/blob/8682029a78bd48fb8566173d970800499e9e5d97/sitebricks-mail/src/main/java/com/google/sitebricks/mail/imap/MessageStatusExtractor.java#L138-L157
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.vpnDeviceConfigurationScript
public String vpnDeviceConfigurationScript(String resourceGroupName, String virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters) { """ Gets a xml format representation for vpn device configuration script. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection for which the configuration script is generated. @param parameters Parameters supplied to the generate vpn device script operation. @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 String object if successful. """ return vpnDeviceConfigurationScriptWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().single().body(); }
java
public String vpnDeviceConfigurationScript(String resourceGroupName, String virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters) { return vpnDeviceConfigurationScriptWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().single().body(); }
[ "public", "String", "vpnDeviceConfigurationScript", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayConnectionName", ",", "VpnDeviceScriptParameters", "parameters", ")", "{", "return", "vpnDeviceConfigurationScriptWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayConnectionName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Gets a xml format representation for vpn device configuration script. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection for which the configuration script is generated. @param parameters Parameters supplied to the generate vpn device script operation. @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 String object if successful.
[ "Gets", "a", "xml", "format", "representation", "for", "vpn", "device", "configuration", "script", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2978-L2980
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/MutableDocument.java
MutableDocument.setBoolean
@NonNull @Override public MutableDocument setBoolean(@NonNull String key, boolean value) { """ Set a boolean value for the given key @param key the key. @param key the boolean value. @return this MutableDocument instance """ return setValue(key, value); }
java
@NonNull @Override public MutableDocument setBoolean(@NonNull String key, boolean value) { return setValue(key, value); }
[ "@", "NonNull", "@", "Override", "public", "MutableDocument", "setBoolean", "(", "@", "NonNull", "String", "key", ",", "boolean", "value", ")", "{", "return", "setValue", "(", "key", ",", "value", ")", ";", "}" ]
Set a boolean value for the given key @param key the key. @param key the boolean value. @return this MutableDocument instance
[ "Set", "a", "boolean", "value", "for", "the", "given", "key" ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/MutableDocument.java#L236-L240
JoeKerouac/utils
src/main/java/com/joe/utils/collection/CollectionUtil.java
CollectionUtil.intersection
public static <T> List<T> intersection(List<T> arr1, List<T> arr2) { """ 求集合交集 @param arr1 集合1 @param arr2 集合2 @param <T> 集合中的数据 @return 集合的交集 """ return intersection(arr1, 0, arr1.size(), arr2, 0, arr2.size()); }
java
public static <T> List<T> intersection(List<T> arr1, List<T> arr2) { return intersection(arr1, 0, arr1.size(), arr2, 0, arr2.size()); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "intersection", "(", "List", "<", "T", ">", "arr1", ",", "List", "<", "T", ">", "arr2", ")", "{", "return", "intersection", "(", "arr1", ",", "0", ",", "arr1", ".", "size", "(", ")", ",", "arr2", ",", "0", ",", "arr2", ".", "size", "(", ")", ")", ";", "}" ]
求集合交集 @param arr1 集合1 @param arr2 集合2 @param <T> 集合中的数据 @return 集合的交集
[ "求集合交集" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/collection/CollectionUtil.java#L467-L469
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/data/Parser.java
Parser.parseString
public Object parseString(Schema schema, String input) { """ Method is used to parse String data to the proper Java types. @param schema Input schema to parse the String data by. @param input Java type specific to the schema supplied. @return Java type for the @throws DataException Exception is thrown when there is an exception thrown while parsing the input string. @throws UnsupportedOperationException Exception is thrown if there is no type parser registered for the schema. @throws NullPointerException Exception is thrown if the schema passed is not optional and a null input value is passed. """ checkSchemaAndInput(schema, input); if (null == input) { return null; } TypeParser parser = findParser(schema); try { Object result = parser.parseString(input, schema); return result; } catch (Exception ex) { String message = String.format("Could not parse '%s' to '%s'", input, parser.expectedClass().getSimpleName()); throw new DataException(message, ex); } }
java
public Object parseString(Schema schema, String input) { checkSchemaAndInput(schema, input); if (null == input) { return null; } TypeParser parser = findParser(schema); try { Object result = parser.parseString(input, schema); return result; } catch (Exception ex) { String message = String.format("Could not parse '%s' to '%s'", input, parser.expectedClass().getSimpleName()); throw new DataException(message, ex); } }
[ "public", "Object", "parseString", "(", "Schema", "schema", ",", "String", "input", ")", "{", "checkSchemaAndInput", "(", "schema", ",", "input", ")", ";", "if", "(", "null", "==", "input", ")", "{", "return", "null", ";", "}", "TypeParser", "parser", "=", "findParser", "(", "schema", ")", ";", "try", "{", "Object", "result", "=", "parser", ".", "parseString", "(", "input", ",", "schema", ")", ";", "return", "result", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "String", "message", "=", "String", ".", "format", "(", "\"Could not parse '%s' to '%s'\"", ",", "input", ",", "parser", ".", "expectedClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "throw", "new", "DataException", "(", "message", ",", "ex", ")", ";", "}", "}" ]
Method is used to parse String data to the proper Java types. @param schema Input schema to parse the String data by. @param input Java type specific to the schema supplied. @return Java type for the @throws DataException Exception is thrown when there is an exception thrown while parsing the input string. @throws UnsupportedOperationException Exception is thrown if there is no type parser registered for the schema. @throws NullPointerException Exception is thrown if the schema passed is not optional and a null input value is passed.
[ "Method", "is", "used", "to", "parse", "String", "data", "to", "the", "proper", "Java", "types", "." ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/data/Parser.java#L99-L115
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java
LocalSubjectUserAccessControl.verifyPermissionToGrantRoles
private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) { """ Verifies whether the user has permission to grant all of the provided roles. If not it throws an UnauthorizedException. @throws UnauthorizedException User did not have the permission to grant at least one role. """ Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet(); boolean anyAuthorized = false; for (RoleIdentifier roleId : roleIds) { // Verify the caller has permission to grant this role if (subject.hasPermission(Permissions.grantRole(roleId))) { anyAuthorized = true; } else { unauthorizedIds.add(roleId); } } if (!unauthorizedIds.isEmpty()) { // If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise // the exception provides insight as to which roles were unauthorized. This provides some helpful feedback // where appropriate without exposing potentially exploitable information about whether the subject's API key // is valid. if (!anyAuthorized) { throw new UnauthorizedException(); } else { throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds)); } } }
java
private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) { Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet(); boolean anyAuthorized = false; for (RoleIdentifier roleId : roleIds) { // Verify the caller has permission to grant this role if (subject.hasPermission(Permissions.grantRole(roleId))) { anyAuthorized = true; } else { unauthorizedIds.add(roleId); } } if (!unauthorizedIds.isEmpty()) { // If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise // the exception provides insight as to which roles were unauthorized. This provides some helpful feedback // where appropriate without exposing potentially exploitable information about whether the subject's API key // is valid. if (!anyAuthorized) { throw new UnauthorizedException(); } else { throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds)); } } }
[ "private", "void", "verifyPermissionToGrantRoles", "(", "Subject", "subject", ",", "Iterable", "<", "RoleIdentifier", ">", "roleIds", ")", "{", "Set", "<", "RoleIdentifier", ">", "unauthorizedIds", "=", "Sets", ".", "newTreeSet", "(", ")", ";", "boolean", "anyAuthorized", "=", "false", ";", "for", "(", "RoleIdentifier", "roleId", ":", "roleIds", ")", "{", "// Verify the caller has permission to grant this role", "if", "(", "subject", ".", "hasPermission", "(", "Permissions", ".", "grantRole", "(", "roleId", ")", ")", ")", "{", "anyAuthorized", "=", "true", ";", "}", "else", "{", "unauthorizedIds", ".", "add", "(", "roleId", ")", ";", "}", "}", "if", "(", "!", "unauthorizedIds", ".", "isEmpty", "(", ")", ")", "{", "// If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise", "// the exception provides insight as to which roles were unauthorized. This provides some helpful feedback", "// where appropriate without exposing potentially exploitable information about whether the subject's API key", "// is valid.", "if", "(", "!", "anyAuthorized", ")", "{", "throw", "new", "UnauthorizedException", "(", ")", ";", "}", "else", "{", "throw", "new", "UnauthorizedException", "(", "\"Not authorized for roles: \"", "+", "Joiner", ".", "on", "(", "\", \"", ")", ".", "join", "(", "unauthorizedIds", ")", ")", ";", "}", "}", "}" ]
Verifies whether the user has permission to grant all of the provided roles. If not it throws an UnauthorizedException. @throws UnauthorizedException User did not have the permission to grant at least one role.
[ "Verifies", "whether", "the", "user", "has", "permission", "to", "grant", "all", "of", "the", "provided", "roles", ".", "If", "not", "it", "throws", "an", "UnauthorizedException", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java#L594-L618
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/apploader/impl/GuiceFactory.java
GuiceFactory.applyConfigs
private static void applyConfigs(final ClassLoader classloader, final GuiceConfig config) { """ Discover and add to the configuration any properties on disk and on the network @param classloader @param config """ // Load all the local configs for (String configFile : getPropertyFiles(config)) { try { for (PropertyFile properties : loadConfig(classloader, configFile)) config.setAll(properties); } catch (IOException e) { throw new IllegalArgumentException("Error loading configuration URLs from " + configFile, e); } } // Load the network config (if enabled) try { applyNetworkConfiguration(config); } catch (Throwable t) { throw new RuntimeException("Failed to retrieve configuration from network!", t); } }
java
private static void applyConfigs(final ClassLoader classloader, final GuiceConfig config) { // Load all the local configs for (String configFile : getPropertyFiles(config)) { try { for (PropertyFile properties : loadConfig(classloader, configFile)) config.setAll(properties); } catch (IOException e) { throw new IllegalArgumentException("Error loading configuration URLs from " + configFile, e); } } // Load the network config (if enabled) try { applyNetworkConfiguration(config); } catch (Throwable t) { throw new RuntimeException("Failed to retrieve configuration from network!", t); } }
[ "private", "static", "void", "applyConfigs", "(", "final", "ClassLoader", "classloader", ",", "final", "GuiceConfig", "config", ")", "{", "// Load all the local configs", "for", "(", "String", "configFile", ":", "getPropertyFiles", "(", "config", ")", ")", "{", "try", "{", "for", "(", "PropertyFile", "properties", ":", "loadConfig", "(", "classloader", ",", "configFile", ")", ")", "config", ".", "setAll", "(", "properties", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Error loading configuration URLs from \"", "+", "configFile", ",", "e", ")", ";", "}", "}", "// Load the network config (if enabled)", "try", "{", "applyNetworkConfiguration", "(", "config", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to retrieve configuration from network!\"", ",", "t", ")", ";", "}", "}" ]
Discover and add to the configuration any properties on disk and on the network @param classloader @param config
[ "Discover", "and", "add", "to", "the", "configuration", "any", "properties", "on", "disk", "and", "on", "the", "network" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/apploader/impl/GuiceFactory.java#L338-L363
OpenLiberty/open-liberty
dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java
CommonMpJwtFat.buildAppSecureUrl
public String buildAppSecureUrl(LibertyServer theServer, String root, String app) throws Exception { """ Build the https app url @param theServer - The server where the app is running (used to get the port) @param root - the root context of the app @param app - the specific app to run @return - returns the full url to invoke @throws Exception """ return SecurityFatHttpUtils.getServerSecureUrlBase(theServer) + root + "/rest/" + app + "/" + MpJwtFatConstants.MPJWT_GENERIC_APP_NAME; }
java
public String buildAppSecureUrl(LibertyServer theServer, String root, String app) throws Exception { return SecurityFatHttpUtils.getServerSecureUrlBase(theServer) + root + "/rest/" + app + "/" + MpJwtFatConstants.MPJWT_GENERIC_APP_NAME; }
[ "public", "String", "buildAppSecureUrl", "(", "LibertyServer", "theServer", ",", "String", "root", ",", "String", "app", ")", "throws", "Exception", "{", "return", "SecurityFatHttpUtils", ".", "getServerSecureUrlBase", "(", "theServer", ")", "+", "root", "+", "\"/rest/\"", "+", "app", "+", "\"/\"", "+", "MpJwtFatConstants", ".", "MPJWT_GENERIC_APP_NAME", ";", "}" ]
Build the https app url @param theServer - The server where the app is running (used to get the port) @param root - the root context of the app @param app - the specific app to run @return - returns the full url to invoke @throws Exception
[ "Build", "the", "https", "app", "url" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java#L144-L148
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/converter/AbstractTypeConverter.java
AbstractTypeConverter.parse
public Object parse(String value, Class type) { """ {@inheritDoc} Template implementation of the <code>convert()</code> method. Takes care of handling null and empty string values. Once these basic operations are handled, will delegate to the <code>doConvert()</code> method of subclasses. """ if (StringUtil.isBlank(value)) { return null; } return doConvert(value.trim(), type); }
java
public Object parse(String value, Class type) { if (StringUtil.isBlank(value)) { return null; } return doConvert(value.trim(), type); }
[ "public", "Object", "parse", "(", "String", "value", ",", "Class", "type", ")", "{", "if", "(", "StringUtil", ".", "isBlank", "(", "value", ")", ")", "{", "return", "null", ";", "}", "return", "doConvert", "(", "value", ".", "trim", "(", ")", ",", "type", ")", ";", "}" ]
{@inheritDoc} Template implementation of the <code>convert()</code> method. Takes care of handling null and empty string values. Once these basic operations are handled, will delegate to the <code>doConvert()</code> method of subclasses.
[ "{", "@inheritDoc", "}" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/converter/AbstractTypeConverter.java#L43-L51
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java
MemberSummaryBuilder.buildEnumConstantsSummary
public void buildEnumConstantsSummary(XMLNode node, Content memberSummaryTree) { """ Build the summary for the enum constants. @param node the XML element that specifies which components to document @param memberSummaryTree the content tree to which the documentation will be added """ MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.ENUM_CONSTANTS]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.ENUM_CONSTANTS]; addSummary(writer, visibleMemberMap, false, memberSummaryTree); }
java
public void buildEnumConstantsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.ENUM_CONSTANTS]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.ENUM_CONSTANTS]; addSummary(writer, visibleMemberMap, false, memberSummaryTree); }
[ "public", "void", "buildEnumConstantsSummary", "(", "XMLNode", "node", ",", "Content", "memberSummaryTree", ")", "{", "MemberSummaryWriter", "writer", "=", "memberSummaryWriters", "[", "VisibleMemberMap", ".", "ENUM_CONSTANTS", "]", ";", "VisibleMemberMap", "visibleMemberMap", "=", "visibleMemberMaps", "[", "VisibleMemberMap", ".", "ENUM_CONSTANTS", "]", ";", "addSummary", "(", "writer", ",", "visibleMemberMap", ",", "false", ",", "memberSummaryTree", ")", ";", "}" ]
Build the summary for the enum constants. @param node the XML element that specifies which components to document @param memberSummaryTree the content tree to which the documentation will be added
[ "Build", "the", "summary", "for", "the", "enum", "constants", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java#L208-L214
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_line_serviceName_automaticCall_identifier_GET
public OvhCallsGenerated billingAccount_line_serviceName_automaticCall_identifier_GET(String billingAccount, String serviceName, String identifier) throws IOException { """ Get this object properties REST: GET /telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier} @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param identifier [required] Generated call identifier """ String qPath = "/telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier}"; StringBuilder sb = path(qPath, billingAccount, serviceName, identifier); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCallsGenerated.class); }
java
public OvhCallsGenerated billingAccount_line_serviceName_automaticCall_identifier_GET(String billingAccount, String serviceName, String identifier) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier}"; StringBuilder sb = path(qPath, billingAccount, serviceName, identifier); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhCallsGenerated.class); }
[ "public", "OvhCallsGenerated", "billingAccount_line_serviceName_automaticCall_identifier_GET", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "identifier", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ",", "identifier", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhCallsGenerated", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier} @param billingAccount [required] The name of your billingAccount @param serviceName [required] @param identifier [required] Generated call identifier
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1784-L1789
neoremind/fluent-validator
fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/QuickValidator.java
QuickValidator.doAndGetComplexResult2
public static ComplexResult2 doAndGetComplexResult2(Decorator decorator) { """ Execute validation by using a new FluentValidator instance and without a shared context. The result type is {@link ComplexResult2} @param decorator Same as decorator design pattern, provided to add more functions to the fluentValidator @return ComplexResult2 """ return validate(decorator, FluentValidator.checkAll(), null, ResultCollectors.toComplex2()); }
java
public static ComplexResult2 doAndGetComplexResult2(Decorator decorator) { return validate(decorator, FluentValidator.checkAll(), null, ResultCollectors.toComplex2()); }
[ "public", "static", "ComplexResult2", "doAndGetComplexResult2", "(", "Decorator", "decorator", ")", "{", "return", "validate", "(", "decorator", ",", "FluentValidator", ".", "checkAll", "(", ")", ",", "null", ",", "ResultCollectors", ".", "toComplex2", "(", ")", ")", ";", "}" ]
Execute validation by using a new FluentValidator instance and without a shared context. The result type is {@link ComplexResult2} @param decorator Same as decorator design pattern, provided to add more functions to the fluentValidator @return ComplexResult2
[ "Execute", "validation", "by", "using", "a", "new", "FluentValidator", "instance", "and", "without", "a", "shared", "context", ".", "The", "result", "type", "is", "{", "@link", "ComplexResult2", "}" ]
train
https://github.com/neoremind/fluent-validator/blob/b516970591aa9468b44ba63938b98ec341fd6ead/fluent-validator/src/main/java/com/baidu/unbiz/fluentvalidator/QuickValidator.java#L62-L64
MenoData/Time4J
base/src/main/java/net/time4j/tz/model/GregorianTimezoneRule.java
GregorianTimezoneRule.ofFixedDay
public static GregorianTimezoneRule ofFixedDay( Month month, int dayOfMonth, int timeOfDay, OffsetIndicator indicator, int savings ) { """ /*[deutsch] <p>Konstruiert ein Muster f&uuml;r einen festen Tag im angegebenen Monat. </p> @param month calendar month @param dayOfMonth day of month (1 - 31) @param timeOfDay clock time in seconds after midnight when time switch happens @param indicator offset indicator @param savings fixed DST-offset in seconds @return new daylight saving rule @throws IllegalArgumentException if the last argument is out of range or if the day of month is not valid in context of given month @since 5.0 """ return new FixedDayPattern(month, dayOfMonth, timeOfDay, indicator, savings); }
java
public static GregorianTimezoneRule ofFixedDay( Month month, int dayOfMonth, int timeOfDay, OffsetIndicator indicator, int savings ) { return new FixedDayPattern(month, dayOfMonth, timeOfDay, indicator, savings); }
[ "public", "static", "GregorianTimezoneRule", "ofFixedDay", "(", "Month", "month", ",", "int", "dayOfMonth", ",", "int", "timeOfDay", ",", "OffsetIndicator", "indicator", ",", "int", "savings", ")", "{", "return", "new", "FixedDayPattern", "(", "month", ",", "dayOfMonth", ",", "timeOfDay", ",", "indicator", ",", "savings", ")", ";", "}" ]
/*[deutsch] <p>Konstruiert ein Muster f&uuml;r einen festen Tag im angegebenen Monat. </p> @param month calendar month @param dayOfMonth day of month (1 - 31) @param timeOfDay clock time in seconds after midnight when time switch happens @param indicator offset indicator @param savings fixed DST-offset in seconds @return new daylight saving rule @throws IllegalArgumentException if the last argument is out of range or if the day of month is not valid in context of given month @since 5.0
[ "/", "*", "[", "deutsch", "]", "<p", ">", "Konstruiert", "ein", "Muster", "f&uuml", ";", "r", "einen", "festen", "Tag", "im", "angegebenen", "Monat", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/tz/model/GregorianTimezoneRule.java#L166-L176
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java
OdsElements.writeSettings
public void writeSettings(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException { """ Write the settings element to a writer. @param xmlUtil the xml util @param writer the writer @throws IOException if write fails """ this.settingsElement.setTables(this.getTables()); this.logger.log(Level.FINER, "Writing odselement: settingsElement to zip file"); this.settingsElement.write(xmlUtil, writer); }
java
public void writeSettings(final XMLUtil xmlUtil, final ZipUTF8Writer writer) throws IOException { this.settingsElement.setTables(this.getTables()); this.logger.log(Level.FINER, "Writing odselement: settingsElement to zip file"); this.settingsElement.write(xmlUtil, writer); }
[ "public", "void", "writeSettings", "(", "final", "XMLUtil", "xmlUtil", ",", "final", "ZipUTF8Writer", "writer", ")", "throws", "IOException", "{", "this", ".", "settingsElement", ".", "setTables", "(", "this", ".", "getTables", "(", ")", ")", ";", "this", ".", "logger", ".", "log", "(", "Level", ".", "FINER", ",", "\"Writing odselement: settingsElement to zip file\"", ")", ";", "this", ".", "settingsElement", ".", "write", "(", "xmlUtil", ",", "writer", ")", ";", "}" ]
Write the settings element to a writer. @param xmlUtil the xml util @param writer the writer @throws IOException if write fails
[ "Write", "the", "settings", "element", "to", "a", "writer", "." ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/OdsElements.java#L411-L415
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/parser/PdfContentStreamProcessor.java
PdfContentStreamProcessor.getStringWidth
public float getStringWidth(String string, float tj) { """ Gets the width of a String. @param string the string that needs measuring @param tj text adjustment @return the width of a String """ DocumentFont font = gs().font; char[] chars = string.toCharArray(); float totalWidth = 0; for (int i = 0; i < chars.length; i++) { float w = font.getWidth(chars[i]) / 1000.0f; float wordSpacing = chars[i] == 32 ? gs().wordSpacing : 0f; totalWidth += ((w - tj / 1000f) * gs().fontSize + gs().characterSpacing + wordSpacing) * gs().horizontalScaling; } return totalWidth; }
java
public float getStringWidth(String string, float tj) { DocumentFont font = gs().font; char[] chars = string.toCharArray(); float totalWidth = 0; for (int i = 0; i < chars.length; i++) { float w = font.getWidth(chars[i]) / 1000.0f; float wordSpacing = chars[i] == 32 ? gs().wordSpacing : 0f; totalWidth += ((w - tj / 1000f) * gs().fontSize + gs().characterSpacing + wordSpacing) * gs().horizontalScaling; } return totalWidth; }
[ "public", "float", "getStringWidth", "(", "String", "string", ",", "float", "tj", ")", "{", "DocumentFont", "font", "=", "gs", "(", ")", ".", "font", ";", "char", "[", "]", "chars", "=", "string", ".", "toCharArray", "(", ")", ";", "float", "totalWidth", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "chars", ".", "length", ";", "i", "++", ")", "{", "float", "w", "=", "font", ".", "getWidth", "(", "chars", "[", "i", "]", ")", "/", "1000.0f", ";", "float", "wordSpacing", "=", "chars", "[", "i", "]", "==", "32", "?", "gs", "(", ")", ".", "wordSpacing", ":", "0f", ";", "totalWidth", "+=", "(", "(", "w", "-", "tj", "/", "1000f", ")", "*", "gs", "(", ")", ".", "fontSize", "+", "gs", "(", ")", ".", "characterSpacing", "+", "wordSpacing", ")", "*", "gs", "(", ")", ".", "horizontalScaling", ";", "}", "return", "totalWidth", ";", "}" ]
Gets the width of a String. @param string the string that needs measuring @param tj text adjustment @return the width of a String
[ "Gets", "the", "width", "of", "a", "String", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/parser/PdfContentStreamProcessor.java#L225-L237
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_worklight_new_GET
public ArrayList<String> license_worklight_new_GET(String ip, Boolean lessThan1000Users, OvhWorkLightVersionEnum version) throws IOException { """ Get allowed durations for 'new' option REST: GET /order/license/worklight/new @param version [required] This license version @param ip [required] Ip on which this license would be installed (for dedicated your main server Ip) @param lessThan1000Users [required] Does your company have less than 1000 potential users """ String qPath = "/order/license/worklight/new"; StringBuilder sb = path(qPath); query(sb, "ip", ip); query(sb, "lessThan1000Users", lessThan1000Users); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> license_worklight_new_GET(String ip, Boolean lessThan1000Users, OvhWorkLightVersionEnum version) throws IOException { String qPath = "/order/license/worklight/new"; StringBuilder sb = path(qPath); query(sb, "ip", ip); query(sb, "lessThan1000Users", lessThan1000Users); query(sb, "version", version); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "license_worklight_new_GET", "(", "String", "ip", ",", "Boolean", "lessThan1000Users", ",", "OvhWorkLightVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/license/worklight/new\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", ",", "\"ip\"", ",", "ip", ")", ";", "query", "(", "sb", ",", "\"lessThan1000Users\"", ",", "lessThan1000Users", ")", ";", "query", "(", "sb", ",", "\"version\"", ",", "version", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t1", ")", ";", "}" ]
Get allowed durations for 'new' option REST: GET /order/license/worklight/new @param version [required] This license version @param ip [required] Ip on which this license would be installed (for dedicated your main server Ip) @param lessThan1000Users [required] Does your company have less than 1000 potential users
[ "Get", "allowed", "durations", "for", "new", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1597-L1605
azkaban/azkaban
azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java
ExecutorComparator.getLstDispatchedTimeComparator
private static FactorComparator<Executor> getLstDispatchedTimeComparator(final int weight) { """ function defines the last dispatched time comparator. @param weight weight of the comparator. """ return FactorComparator .create(LSTDISPATCHED_COMPARATOR_NAME, weight, new Comparator<Executor>() { @Override public int compare(final Executor o1, final Executor o2) { final ExecutorInfo stat1 = o1.getExecutorInfo(); final ExecutorInfo stat2 = o2.getExecutorInfo(); final int result = 0; if (statisticsObjectCheck(stat1, stat2, LSTDISPATCHED_COMPARATOR_NAME)) { return result; } // Note: an earlier date time indicates higher weight. return ((Long) stat2.getLastDispatchedTime()).compareTo(stat1.getLastDispatchedTime()); } }); }
java
private static FactorComparator<Executor> getLstDispatchedTimeComparator(final int weight) { return FactorComparator .create(LSTDISPATCHED_COMPARATOR_NAME, weight, new Comparator<Executor>() { @Override public int compare(final Executor o1, final Executor o2) { final ExecutorInfo stat1 = o1.getExecutorInfo(); final ExecutorInfo stat2 = o2.getExecutorInfo(); final int result = 0; if (statisticsObjectCheck(stat1, stat2, LSTDISPATCHED_COMPARATOR_NAME)) { return result; } // Note: an earlier date time indicates higher weight. return ((Long) stat2.getLastDispatchedTime()).compareTo(stat1.getLastDispatchedTime()); } }); }
[ "private", "static", "FactorComparator", "<", "Executor", ">", "getLstDispatchedTimeComparator", "(", "final", "int", "weight", ")", "{", "return", "FactorComparator", ".", "create", "(", "LSTDISPATCHED_COMPARATOR_NAME", ",", "weight", ",", "new", "Comparator", "<", "Executor", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "final", "Executor", "o1", ",", "final", "Executor", "o2", ")", "{", "final", "ExecutorInfo", "stat1", "=", "o1", ".", "getExecutorInfo", "(", ")", ";", "final", "ExecutorInfo", "stat2", "=", "o2", ".", "getExecutorInfo", "(", ")", ";", "final", "int", "result", "=", "0", ";", "if", "(", "statisticsObjectCheck", "(", "stat1", ",", "stat2", ",", "LSTDISPATCHED_COMPARATOR_NAME", ")", ")", "{", "return", "result", ";", "}", "// Note: an earlier date time indicates higher weight.", "return", "(", "(", "Long", ")", "stat2", ".", "getLastDispatchedTime", "(", ")", ")", ".", "compareTo", "(", "stat1", ".", "getLastDispatchedTime", "(", ")", ")", ";", "}", "}", ")", ";", "}" ]
function defines the last dispatched time comparator. @param weight weight of the comparator.
[ "function", "defines", "the", "last", "dispatched", "time", "comparator", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java#L197-L214
pravega/pravega
client/src/main/java/io/pravega/client/stream/impl/ModelHelper.java
ModelHelper.encode
public static final Transaction.Status encode(final TxnState.State state, final String logString) { """ Returns actual status of given transaction status instance. @param state TxnState object instance. @param logString Description text to be logged when transaction status is invalid. @return Transaction.Status """ Preconditions.checkNotNull(state, "state"); Exceptions.checkNotNullOrEmpty(logString, "logString"); Transaction.Status result; switch (state) { case COMMITTED: result = Transaction.Status.COMMITTED; break; case ABORTED: result = Transaction.Status.ABORTED; break; case OPEN: result = Transaction.Status.OPEN; break; case ABORTING: result = Transaction.Status.ABORTING; break; case COMMITTING: result = Transaction.Status.COMMITTING; break; case UNKNOWN: throw new RuntimeException("Unknown transaction: " + logString); case UNRECOGNIZED: default: throw new IllegalStateException("Unknown status: " + state); } return result; }
java
public static final Transaction.Status encode(final TxnState.State state, final String logString) { Preconditions.checkNotNull(state, "state"); Exceptions.checkNotNullOrEmpty(logString, "logString"); Transaction.Status result; switch (state) { case COMMITTED: result = Transaction.Status.COMMITTED; break; case ABORTED: result = Transaction.Status.ABORTED; break; case OPEN: result = Transaction.Status.OPEN; break; case ABORTING: result = Transaction.Status.ABORTING; break; case COMMITTING: result = Transaction.Status.COMMITTING; break; case UNKNOWN: throw new RuntimeException("Unknown transaction: " + logString); case UNRECOGNIZED: default: throw new IllegalStateException("Unknown status: " + state); } return result; }
[ "public", "static", "final", "Transaction", ".", "Status", "encode", "(", "final", "TxnState", ".", "State", "state", ",", "final", "String", "logString", ")", "{", "Preconditions", ".", "checkNotNull", "(", "state", ",", "\"state\"", ")", ";", "Exceptions", ".", "checkNotNullOrEmpty", "(", "logString", ",", "\"logString\"", ")", ";", "Transaction", ".", "Status", "result", ";", "switch", "(", "state", ")", "{", "case", "COMMITTED", ":", "result", "=", "Transaction", ".", "Status", ".", "COMMITTED", ";", "break", ";", "case", "ABORTED", ":", "result", "=", "Transaction", ".", "Status", ".", "ABORTED", ";", "break", ";", "case", "OPEN", ":", "result", "=", "Transaction", ".", "Status", ".", "OPEN", ";", "break", ";", "case", "ABORTING", ":", "result", "=", "Transaction", ".", "Status", ".", "ABORTING", ";", "break", ";", "case", "COMMITTING", ":", "result", "=", "Transaction", ".", "Status", ".", "COMMITTING", ";", "break", ";", "case", "UNKNOWN", ":", "throw", "new", "RuntimeException", "(", "\"Unknown transaction: \"", "+", "logString", ")", ";", "case", "UNRECOGNIZED", ":", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown status: \"", "+", "state", ")", ";", "}", "return", "result", ";", "}" ]
Returns actual status of given transaction status instance. @param state TxnState object instance. @param logString Description text to be logged when transaction status is invalid. @return Transaction.Status
[ "Returns", "actual", "status", "of", "given", "transaction", "status", "instance", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/ModelHelper.java#L146-L174
belaban/JGroups
src/org/jgroups/protocols/pbcast/FLUSH.java
FLUSH.maxSeqnos
protected static Digest maxSeqnos(final View view, List<Digest> digests) { """ Returns a digest which contains, for all members of view, the highest delivered and received seqno of all digests """ if(view == null || digests == null) return null; MutableDigest digest=new MutableDigest(view.getMembersRaw()); digests.forEach(digest::merge); return digest; }
java
protected static Digest maxSeqnos(final View view, List<Digest> digests) { if(view == null || digests == null) return null; MutableDigest digest=new MutableDigest(view.getMembersRaw()); digests.forEach(digest::merge); return digest; }
[ "protected", "static", "Digest", "maxSeqnos", "(", "final", "View", "view", ",", "List", "<", "Digest", ">", "digests", ")", "{", "if", "(", "view", "==", "null", "||", "digests", "==", "null", ")", "return", "null", ";", "MutableDigest", "digest", "=", "new", "MutableDigest", "(", "view", ".", "getMembersRaw", "(", ")", ")", ";", "digests", ".", "forEach", "(", "digest", "::", "merge", ")", ";", "return", "digest", ";", "}" ]
Returns a digest which contains, for all members of view, the highest delivered and received seqno of all digests
[ "Returns", "a", "digest", "which", "contains", "for", "all", "members", "of", "view", "the", "highest", "delivered", "and", "received", "seqno", "of", "all", "digests" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/pbcast/FLUSH.java#L872-L879
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_datacenter_datacenterId_filer_filerId_GET
public OvhFiler serviceName_datacenter_datacenterId_filer_filerId_GET(String serviceName, Long datacenterId, Long filerId) throws IOException { """ Get this object properties REST: GET /dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId} @param serviceName [required] Domain of the service @param datacenterId [required] @param filerId [required] Filer Id """ String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId}"; StringBuilder sb = path(qPath, serviceName, datacenterId, filerId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhFiler.class); }
java
public OvhFiler serviceName_datacenter_datacenterId_filer_filerId_GET(String serviceName, Long datacenterId, Long filerId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId}"; StringBuilder sb = path(qPath, serviceName, datacenterId, filerId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhFiler.class); }
[ "public", "OvhFiler", "serviceName_datacenter_datacenterId_filer_filerId_GET", "(", "String", "serviceName", ",", "Long", "datacenterId", ",", "Long", "filerId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "datacenterId", ",", "filerId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhFiler", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId} @param serviceName [required] Domain of the service @param datacenterId [required] @param filerId [required] Filer Id
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L2253-L2258
OpenBEL/openbel-framework
org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseOneApplication.java
PhaseOneApplication.stage6
public boolean stage6(final Document doc, final ProtoNetwork pn) { """ Stage six expansion of the document. @param doc the original {@link Document document} needed as a dependency when using {@link ProtoNetworkBuilder proto network builder} @param pn the {@link ProtoNetwork proto network} to expand into """ beginStage(PHASE1_STAGE6_HDR, "6", NUM_PHASES); final StringBuilder bldr = new StringBuilder(); boolean stmtSuccess = false, termSuccess = false; bldr.append("Expanding statements and terms"); stageOutput(bldr.toString()); long t1 = currentTimeMillis(); boolean stmtExpand = !hasOption(NO_NS_LONG_OPT); p1.stage6Expansion(doc, pn, stmtExpand); termSuccess = true; stmtSuccess = true; long t2 = currentTimeMillis(); bldr.setLength(0); markTime(bldr, t1, t2); markEndStage(bldr); stageOutput(bldr.toString()); return stmtSuccess && termSuccess; }
java
public boolean stage6(final Document doc, final ProtoNetwork pn) { beginStage(PHASE1_STAGE6_HDR, "6", NUM_PHASES); final StringBuilder bldr = new StringBuilder(); boolean stmtSuccess = false, termSuccess = false; bldr.append("Expanding statements and terms"); stageOutput(bldr.toString()); long t1 = currentTimeMillis(); boolean stmtExpand = !hasOption(NO_NS_LONG_OPT); p1.stage6Expansion(doc, pn, stmtExpand); termSuccess = true; stmtSuccess = true; long t2 = currentTimeMillis(); bldr.setLength(0); markTime(bldr, t1, t2); markEndStage(bldr); stageOutput(bldr.toString()); return stmtSuccess && termSuccess; }
[ "public", "boolean", "stage6", "(", "final", "Document", "doc", ",", "final", "ProtoNetwork", "pn", ")", "{", "beginStage", "(", "PHASE1_STAGE6_HDR", ",", "\"6\"", ",", "NUM_PHASES", ")", ";", "final", "StringBuilder", "bldr", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "stmtSuccess", "=", "false", ",", "termSuccess", "=", "false", ";", "bldr", ".", "append", "(", "\"Expanding statements and terms\"", ")", ";", "stageOutput", "(", "bldr", ".", "toString", "(", ")", ")", ";", "long", "t1", "=", "currentTimeMillis", "(", ")", ";", "boolean", "stmtExpand", "=", "!", "hasOption", "(", "NO_NS_LONG_OPT", ")", ";", "p1", ".", "stage6Expansion", "(", "doc", ",", "pn", ",", "stmtExpand", ")", ";", "termSuccess", "=", "true", ";", "stmtSuccess", "=", "true", ";", "long", "t2", "=", "currentTimeMillis", "(", ")", ";", "bldr", ".", "setLength", "(", "0", ")", ";", "markTime", "(", "bldr", ",", "t1", ",", "t2", ")", ";", "markEndStage", "(", "bldr", ")", ";", "stageOutput", "(", "bldr", ".", "toString", "(", ")", ")", ";", "return", "stmtSuccess", "&&", "termSuccess", ";", "}" ]
Stage six expansion of the document. @param doc the original {@link Document document} needed as a dependency when using {@link ProtoNetworkBuilder proto network builder} @param pn the {@link ProtoNetwork proto network} to expand into
[ "Stage", "six", "expansion", "of", "the", "document", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/PhaseOneApplication.java#L569-L591
infinispan/infinispan
hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/InvalidationCacheAccessDelegate.java
InvalidationCacheAccessDelegate.putFromLoad
@Override @SuppressWarnings("UnusedParameters") public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { """ Attempt to cache an object, after loading from the database, explicitly specifying the minimalPut behavior. @param session Current session @param key The item key @param value The item @param txTimestamp a timestamp prior to the transaction start time @param version the item version number @param minimalPutOverride Explicit minimalPut flag @return <tt>true</tt> if the object was successfully cached @throws CacheException if storing the object failed """ if ( !region.checkValid() ) { if (trace) { log.tracef( "Region %s not valid", region.getName() ); } return false; } // In theory, since putForExternalRead is already as minimal as it can // get, we shouldn't be need this check. However, without the check and // without https://issues.jboss.org/browse/ISPN-1986, it's impossible to // know whether the put actually occurred. Knowing this is crucial so // that Hibernate can expose accurate statistics. if ( minimalPutOverride && cache.containsKey( key ) ) { return false; } PutFromLoadValidator.Lock lock = putValidator.acquirePutFromLoadLock(session, key, txTimestamp); if ( lock == null) { if (trace) { log.tracef( "Put from load lock not acquired for key %s", key ); } return false; } try { writeCache.putForExternalRead( key, value ); } finally { putValidator.releasePutFromLoadLock( key, lock); } return true; }
java
@Override @SuppressWarnings("UnusedParameters") public boolean putFromLoad(Object session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if ( !region.checkValid() ) { if (trace) { log.tracef( "Region %s not valid", region.getName() ); } return false; } // In theory, since putForExternalRead is already as minimal as it can // get, we shouldn't be need this check. However, without the check and // without https://issues.jboss.org/browse/ISPN-1986, it's impossible to // know whether the put actually occurred. Knowing this is crucial so // that Hibernate can expose accurate statistics. if ( minimalPutOverride && cache.containsKey( key ) ) { return false; } PutFromLoadValidator.Lock lock = putValidator.acquirePutFromLoadLock(session, key, txTimestamp); if ( lock == null) { if (trace) { log.tracef( "Put from load lock not acquired for key %s", key ); } return false; } try { writeCache.putForExternalRead( key, value ); } finally { putValidator.releasePutFromLoadLock( key, lock); } return true; }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"UnusedParameters\"", ")", "public", "boolean", "putFromLoad", "(", "Object", "session", ",", "Object", "key", ",", "Object", "value", ",", "long", "txTimestamp", ",", "Object", "version", ",", "boolean", "minimalPutOverride", ")", "throws", "CacheException", "{", "if", "(", "!", "region", ".", "checkValid", "(", ")", ")", "{", "if", "(", "trace", ")", "{", "log", ".", "tracef", "(", "\"Region %s not valid\"", ",", "region", ".", "getName", "(", ")", ")", ";", "}", "return", "false", ";", "}", "// In theory, since putForExternalRead is already as minimal as it can", "// get, we shouldn't be need this check. However, without the check and", "// without https://issues.jboss.org/browse/ISPN-1986, it's impossible to", "// know whether the put actually occurred. Knowing this is crucial so", "// that Hibernate can expose accurate statistics.", "if", "(", "minimalPutOverride", "&&", "cache", ".", "containsKey", "(", "key", ")", ")", "{", "return", "false", ";", "}", "PutFromLoadValidator", ".", "Lock", "lock", "=", "putValidator", ".", "acquirePutFromLoadLock", "(", "session", ",", "key", ",", "txTimestamp", ")", ";", "if", "(", "lock", "==", "null", ")", "{", "if", "(", "trace", ")", "{", "log", ".", "tracef", "(", "\"Put from load lock not acquired for key %s\"", ",", "key", ")", ";", "}", "return", "false", ";", "}", "try", "{", "writeCache", ".", "putForExternalRead", "(", "key", ",", "value", ")", ";", "}", "finally", "{", "putValidator", ".", "releasePutFromLoadLock", "(", "key", ",", "lock", ")", ";", "}", "return", "true", ";", "}" ]
Attempt to cache an object, after loading from the database, explicitly specifying the minimalPut behavior. @param session Current session @param key The item key @param value The item @param txTimestamp a timestamp prior to the transaction start time @param version the item version number @param minimalPutOverride Explicit minimalPut flag @return <tt>true</tt> if the object was successfully cached @throws CacheException if storing the object failed
[ "Attempt", "to", "cache", "an", "object", "after", "loading", "from", "the", "database", "explicitly", "specifying", "the", "minimalPut", "behavior", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/hibernate/cache-commons/src/main/java/org/infinispan/hibernate/cache/commons/access/InvalidationCacheAccessDelegate.java#L85-L121
mhshams/jnbis
src/main/java/org/jnbis/api/handler/FileHandler.java
FileHandler.asFile
public File asFile(String fileName) { """ Writes the file data in the specified file and returns the final <code>File</code>. @param fileName the given file name, not null @return the final File, not null """ File file = new File(fileName); try (FileOutputStream bos = new FileOutputStream(file)) { bos.write(data); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return file; }
java
public File asFile(String fileName) { File file = new File(fileName); try (FileOutputStream bos = new FileOutputStream(file)) { bos.write(data); } catch (IOException e) { throw new RuntimeException("unexpected error", e); } return file; }
[ "public", "File", "asFile", "(", "String", "fileName", ")", "{", "File", "file", "=", "new", "File", "(", "fileName", ")", ";", "try", "(", "FileOutputStream", "bos", "=", "new", "FileOutputStream", "(", "file", ")", ")", "{", "bos", ".", "write", "(", "data", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"unexpected error\"", ",", "e", ")", ";", "}", "return", "file", ";", "}" ]
Writes the file data in the specified file and returns the final <code>File</code>. @param fileName the given file name, not null @return the final File, not null
[ "Writes", "the", "file", "data", "in", "the", "specified", "file", "and", "returns", "the", "final", "<code", ">", "File<", "/", "code", ">", "." ]
train
https://github.com/mhshams/jnbis/blob/e0f4ac750cc98a0363507395a121183fface330e/src/main/java/org/jnbis/api/handler/FileHandler.java#L26-L34
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java
ServletUtil.handleError
public static void handleError(final HttpServletHelper helper, final Throwable throwable) throws ServletException, IOException { """ Called if a Throwable is caught by the top-level service method. By default we display an error and terminate the session. @param helper the current servlet helper @param throwable the throwable @throws ServletException a servlet exception @throws IOException an IO Exception """ HttpServletRequest httpServletRequest = helper.getBackingRequest(); HttpServletResponse httpServletResponse = helper.getBackingResponse(); // Allow for multi part requests Map<String, String[]> parameters = getRequestParameters(httpServletRequest); // Set error code for AJAX, Content or data requests boolean dataRequest = parameters.get(WServlet.DATA_LIST_PARAM_NAME) != null; Object target = parameters.get(WServlet.AJAX_TRIGGER_PARAM_NAME); if (target == null) { target = parameters.get(WServlet.TARGET_ID_PARAM_NAME); } if (target != null || dataRequest) { httpServletResponse.sendError(500, "Internal Error"); return; } // Decide whether we should use the ErrorPageFactory. boolean handleErrorWithFatalErrorPageFactory = ConfigurationProperties.getHandleErrorWithFatalErrorPageFactory(); // use the new technique and delegate to the ErrorPageFactory. if (handleErrorWithFatalErrorPageFactory) { helper.handleError(throwable); helper.dispose(); } else { // use the old technique and just display a raw message. // First, decide whether we are in friendly mode or not. boolean friendly = ConfigurationProperties.getDeveloperErrorHandling(); String message = InternalMessages.DEFAULT_SYSTEM_ERROR; // If we are unfriendly, terminate the session if (!friendly) { HttpSession session = httpServletRequest.getSession(true); session.invalidate(); message = InternalMessages.DEFAULT_SYSTEM_ERROR_SEVERE; } // Display an error to the user. UIContext uic = helper.getUIContext(); Locale locale = uic == null ? null : uic.getLocale(); message = I18nUtilities.format(locale, message); httpServletResponse.getWriter().println(message); } }
java
public static void handleError(final HttpServletHelper helper, final Throwable throwable) throws ServletException, IOException { HttpServletRequest httpServletRequest = helper.getBackingRequest(); HttpServletResponse httpServletResponse = helper.getBackingResponse(); // Allow for multi part requests Map<String, String[]> parameters = getRequestParameters(httpServletRequest); // Set error code for AJAX, Content or data requests boolean dataRequest = parameters.get(WServlet.DATA_LIST_PARAM_NAME) != null; Object target = parameters.get(WServlet.AJAX_TRIGGER_PARAM_NAME); if (target == null) { target = parameters.get(WServlet.TARGET_ID_PARAM_NAME); } if (target != null || dataRequest) { httpServletResponse.sendError(500, "Internal Error"); return; } // Decide whether we should use the ErrorPageFactory. boolean handleErrorWithFatalErrorPageFactory = ConfigurationProperties.getHandleErrorWithFatalErrorPageFactory(); // use the new technique and delegate to the ErrorPageFactory. if (handleErrorWithFatalErrorPageFactory) { helper.handleError(throwable); helper.dispose(); } else { // use the old technique and just display a raw message. // First, decide whether we are in friendly mode or not. boolean friendly = ConfigurationProperties.getDeveloperErrorHandling(); String message = InternalMessages.DEFAULT_SYSTEM_ERROR; // If we are unfriendly, terminate the session if (!friendly) { HttpSession session = httpServletRequest.getSession(true); session.invalidate(); message = InternalMessages.DEFAULT_SYSTEM_ERROR_SEVERE; } // Display an error to the user. UIContext uic = helper.getUIContext(); Locale locale = uic == null ? null : uic.getLocale(); message = I18nUtilities.format(locale, message); httpServletResponse.getWriter().println(message); } }
[ "public", "static", "void", "handleError", "(", "final", "HttpServletHelper", "helper", ",", "final", "Throwable", "throwable", ")", "throws", "ServletException", ",", "IOException", "{", "HttpServletRequest", "httpServletRequest", "=", "helper", ".", "getBackingRequest", "(", ")", ";", "HttpServletResponse", "httpServletResponse", "=", "helper", ".", "getBackingResponse", "(", ")", ";", "// Allow for multi part requests", "Map", "<", "String", ",", "String", "[", "]", ">", "parameters", "=", "getRequestParameters", "(", "httpServletRequest", ")", ";", "// Set error code for AJAX, Content or data requests", "boolean", "dataRequest", "=", "parameters", ".", "get", "(", "WServlet", ".", "DATA_LIST_PARAM_NAME", ")", "!=", "null", ";", "Object", "target", "=", "parameters", ".", "get", "(", "WServlet", ".", "AJAX_TRIGGER_PARAM_NAME", ")", ";", "if", "(", "target", "==", "null", ")", "{", "target", "=", "parameters", ".", "get", "(", "WServlet", ".", "TARGET_ID_PARAM_NAME", ")", ";", "}", "if", "(", "target", "!=", "null", "||", "dataRequest", ")", "{", "httpServletResponse", ".", "sendError", "(", "500", ",", "\"Internal Error\"", ")", ";", "return", ";", "}", "// Decide whether we should use the ErrorPageFactory.", "boolean", "handleErrorWithFatalErrorPageFactory", "=", "ConfigurationProperties", ".", "getHandleErrorWithFatalErrorPageFactory", "(", ")", ";", "// use the new technique and delegate to the ErrorPageFactory.", "if", "(", "handleErrorWithFatalErrorPageFactory", ")", "{", "helper", ".", "handleError", "(", "throwable", ")", ";", "helper", ".", "dispose", "(", ")", ";", "}", "else", "{", "// use the old technique and just display a raw message.", "// First, decide whether we are in friendly mode or not.", "boolean", "friendly", "=", "ConfigurationProperties", ".", "getDeveloperErrorHandling", "(", ")", ";", "String", "message", "=", "InternalMessages", ".", "DEFAULT_SYSTEM_ERROR", ";", "// If we are unfriendly, terminate the session", "if", "(", "!", "friendly", ")", "{", "HttpSession", "session", "=", "httpServletRequest", ".", "getSession", "(", "true", ")", ";", "session", ".", "invalidate", "(", ")", ";", "message", "=", "InternalMessages", ".", "DEFAULT_SYSTEM_ERROR_SEVERE", ";", "}", "// Display an error to the user.", "UIContext", "uic", "=", "helper", ".", "getUIContext", "(", ")", ";", "Locale", "locale", "=", "uic", "==", "null", "?", "null", ":", "uic", ".", "getLocale", "(", ")", ";", "message", "=", "I18nUtilities", ".", "format", "(", "locale", ",", "message", ")", ";", "httpServletResponse", ".", "getWriter", "(", ")", ".", "println", "(", "message", ")", ";", "}", "}" ]
Called if a Throwable is caught by the top-level service method. By default we display an error and terminate the session. @param helper the current servlet helper @param throwable the throwable @throws ServletException a servlet exception @throws IOException an IO Exception
[ "Called", "if", "a", "Throwable", "is", "caught", "by", "the", "top", "-", "level", "service", "method", ".", "By", "default", "we", "display", "an", "error", "and", "terminate", "the", "session", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java#L465-L512
wuman/JReadability
src/main/java/com/wuman/jreadability/Readability.java
Readability.getCharCount
private static int getCharCount(Element e, String s) { """ Get the number of times a string s appears in the node e. @param e @param s @return """ if (s == null || s.length() == 0) { s = ","; } return getInnerText(e, true).split(s).length; }
java
private static int getCharCount(Element e, String s) { if (s == null || s.length() == 0) { s = ","; } return getInnerText(e, true).split(s).length; }
[ "private", "static", "int", "getCharCount", "(", "Element", "e", ",", "String", "s", ")", "{", "if", "(", "s", "==", "null", "||", "s", ".", "length", "(", ")", "==", "0", ")", "{", "s", "=", "\",\"", ";", "}", "return", "getInnerText", "(", "e", ",", "true", ")", ".", "split", "(", "s", ")", ".", "length", ";", "}" ]
Get the number of times a string s appears in the node e. @param e @param s @return
[ "Get", "the", "number", "of", "times", "a", "string", "s", "appears", "in", "the", "node", "e", "." ]
train
https://github.com/wuman/JReadability/blob/16c18c42402bd13c6e024c2fd3a86dd28ba53e74/src/main/java/com/wuman/jreadability/Readability.java#L511-L516
SonarSource/sonarqube
server/sonar-db-dao/src/main/java/org/sonar/db/source/FileSourceDao.java
FileSourceDao.scrollLineHashes
public void scrollLineHashes(DbSession dbSession, Collection<String> fileUUids, ResultHandler<LineHashesWithUuidDto> rowHandler) { """ Scroll line hashes of all <strong>enabled</strong> components (should be files, but not enforced) with specified uuids in no specific order with 'SOURCE' source and a non null path. """ for (List<String> partition : toUniqueAndSortedPartitions(fileUUids)) { mapper(dbSession).scrollLineHashes(partition, rowHandler); } }
java
public void scrollLineHashes(DbSession dbSession, Collection<String> fileUUids, ResultHandler<LineHashesWithUuidDto> rowHandler) { for (List<String> partition : toUniqueAndSortedPartitions(fileUUids)) { mapper(dbSession).scrollLineHashes(partition, rowHandler); } }
[ "public", "void", "scrollLineHashes", "(", "DbSession", "dbSession", ",", "Collection", "<", "String", ">", "fileUUids", ",", "ResultHandler", "<", "LineHashesWithUuidDto", ">", "rowHandler", ")", "{", "for", "(", "List", "<", "String", ">", "partition", ":", "toUniqueAndSortedPartitions", "(", "fileUUids", ")", ")", "{", "mapper", "(", "dbSession", ")", ".", "scrollLineHashes", "(", "partition", ",", "rowHandler", ")", ";", "}", "}" ]
Scroll line hashes of all <strong>enabled</strong> components (should be files, but not enforced) with specified uuids in no specific order with 'SOURCE' source and a non null path.
[ "Scroll", "line", "hashes", "of", "all", "<strong", ">", "enabled<", "/", "strong", ">", "components", "(", "should", "be", "files", "but", "not", "enforced", ")", "with", "specified", "uuids", "in", "no", "specific", "order", "with", "SOURCE", "source", "and", "a", "non", "null", "path", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/source/FileSourceDao.java#L84-L88
landawn/AbacusUtil
src/com/landawn/abacus/util/SQLExecutor.java
SQLExecutor.queryForSingleResult
@SuppressWarnings("unchecked") @SafeVarargs public final <V> Nullable<V> queryForSingleResult(final Class<V> targetClass, final Connection conn, final String sql, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { """ Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}. <br /> Special note for type conversion for {@code boolean} or {@code Boolean} type: {@code true} is returned if the {@code String} value of the target column is {@code "true"}, case insensitive. or it's an integer with value > 0. Otherwise, {@code false} is returned. Remember to add {@code limit} condition if big result will be returned by the query. @param targetClass set result type to avoid the NullPointerException if result is null and T is primitive type "int, long. short ... char, boolean..". @param conn @param sql @param statementSetter @param jdbcSettings @param parameters """ return query(conn, sql, statementSetter, createSingleResultExtractor(targetClass), jdbcSettings, parameters); }
java
@SuppressWarnings("unchecked") @SafeVarargs public final <V> Nullable<V> queryForSingleResult(final Class<V> targetClass, final Connection conn, final String sql, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { return query(conn, sql, statementSetter, createSingleResultExtractor(targetClass), jdbcSettings, parameters); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "SafeVarargs", "public", "final", "<", "V", ">", "Nullable", "<", "V", ">", "queryForSingleResult", "(", "final", "Class", "<", "V", ">", "targetClass", ",", "final", "Connection", "conn", ",", "final", "String", "sql", ",", "final", "StatementSetter", "statementSetter", ",", "final", "JdbcSettings", "jdbcSettings", ",", "final", "Object", "...", "parameters", ")", "{", "return", "query", "(", "conn", ",", "sql", ",", "statementSetter", ",", "createSingleResultExtractor", "(", "targetClass", ")", ",", "jdbcSettings", ",", "parameters", ")", ";", "}" ]
Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}. <br /> Special note for type conversion for {@code boolean} or {@code Boolean} type: {@code true} is returned if the {@code String} value of the target column is {@code "true"}, case insensitive. or it's an integer with value > 0. Otherwise, {@code false} is returned. Remember to add {@code limit} condition if big result will be returned by the query. @param targetClass set result type to avoid the NullPointerException if result is null and T is primitive type "int, long. short ... char, boolean..". @param conn @param sql @param statementSetter @param jdbcSettings @param parameters
[ "Returns", "a", "{", "@code", "Nullable", "}", "describing", "the", "value", "in", "the", "first", "row", "/", "column", "if", "it", "exists", "otherwise", "return", "an", "empty", "{", "@code", "Nullable", "}", ".", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/SQLExecutor.java#L2284-L2289
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AbstractEntityReader.java
AbstractEntityReader.findById
protected EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client) { """ Retrieves an entity from ID @param primaryKey @param m @param client @return """ try { Object o = client.find(m.getEntityClazz(), primaryKey); if (o == null) { // No entity found return null; } else { return o instanceof EnhanceEntity ? (EnhanceEntity) o : new EnhanceEntity(o, getId(o, m), null); } } catch (Exception e) { throw new EntityReaderException(e); } }
java
protected EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client) { try { Object o = client.find(m.getEntityClazz(), primaryKey); if (o == null) { // No entity found return null; } else { return o instanceof EnhanceEntity ? (EnhanceEntity) o : new EnhanceEntity(o, getId(o, m), null); } } catch (Exception e) { throw new EntityReaderException(e); } }
[ "protected", "EnhanceEntity", "findById", "(", "Object", "primaryKey", ",", "EntityMetadata", "m", ",", "Client", "client", ")", "{", "try", "{", "Object", "o", "=", "client", ".", "find", "(", "m", ".", "getEntityClazz", "(", ")", ",", "primaryKey", ")", ";", "if", "(", "o", "==", "null", ")", "{", "// No entity found", "return", "null", ";", "}", "else", "{", "return", "o", "instanceof", "EnhanceEntity", "?", "(", "EnhanceEntity", ")", "o", ":", "new", "EnhanceEntity", "(", "o", ",", "getId", "(", "o", ",", "m", ")", ",", "null", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "EntityReaderException", "(", "e", ")", ";", "}", "}" ]
Retrieves an entity from ID @param primaryKey @param m @param client @return
[ "Retrieves", "an", "entity", "from", "ID" ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AbstractEntityReader.java#L77-L97
square/okhttp
mockwebserver/src/main/java/okhttp3/mockwebserver/MockWebServer.java
MockWebServer.takeRequest
public RecordedRequest takeRequest(long timeout, TimeUnit unit) throws InterruptedException { """ Awaits the next HTTP request (waiting up to the specified wait time if necessary), removes it, and returns it. Callers should use this to verify the request was sent as intended within the given time. @param timeout how long to wait before giving up, in units of {@code unit} @param unit a {@code TimeUnit} determining how to interpret the {@code timeout} parameter @return the head of the request queue """ return requestQueue.poll(timeout, unit); }
java
public RecordedRequest takeRequest(long timeout, TimeUnit unit) throws InterruptedException { return requestQueue.poll(timeout, unit); }
[ "public", "RecordedRequest", "takeRequest", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "return", "requestQueue", ".", "poll", "(", "timeout", ",", "unit", ")", ";", "}" ]
Awaits the next HTTP request (waiting up to the specified wait time if necessary), removes it, and returns it. Callers should use this to verify the request was sent as intended within the given time. @param timeout how long to wait before giving up, in units of {@code unit} @param unit a {@code TimeUnit} determining how to interpret the {@code timeout} parameter @return the head of the request queue
[ "Awaits", "the", "next", "HTTP", "request", "(", "waiting", "up", "to", "the", "specified", "wait", "time", "if", "necessary", ")", "removes", "it", "and", "returns", "it", ".", "Callers", "should", "use", "this", "to", "verify", "the", "request", "was", "sent", "as", "intended", "within", "the", "given", "time", "." ]
train
https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/mockwebserver/src/main/java/okhttp3/mockwebserver/MockWebServer.java#L309-L311
spotify/helios
helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java
ZooKeeperMasterModel.rolloutOptionsWithFallback
static RolloutOptions rolloutOptionsWithFallback(final RolloutOptions options, final Job job) { """ Returns a {@link RolloutOptions} instance that will replace null attributes in options with values from two tiers of fallbacks. First fallback to job then {@link RolloutOptions#getDefault()}. """ return options.withFallback( job.getRolloutOptions() == null ? RolloutOptions.getDefault() : job.getRolloutOptions().withFallback(RolloutOptions.getDefault())); }
java
static RolloutOptions rolloutOptionsWithFallback(final RolloutOptions options, final Job job) { return options.withFallback( job.getRolloutOptions() == null ? RolloutOptions.getDefault() : job.getRolloutOptions().withFallback(RolloutOptions.getDefault())); }
[ "static", "RolloutOptions", "rolloutOptionsWithFallback", "(", "final", "RolloutOptions", "options", ",", "final", "Job", "job", ")", "{", "return", "options", ".", "withFallback", "(", "job", ".", "getRolloutOptions", "(", ")", "==", "null", "?", "RolloutOptions", ".", "getDefault", "(", ")", ":", "job", ".", "getRolloutOptions", "(", ")", ".", "withFallback", "(", "RolloutOptions", ".", "getDefault", "(", ")", ")", ")", ";", "}" ]
Returns a {@link RolloutOptions} instance that will replace null attributes in options with values from two tiers of fallbacks. First fallback to job then {@link RolloutOptions#getDefault()}.
[ "Returns", "a", "{" ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-services/src/main/java/com/spotify/helios/master/ZooKeeperMasterModel.java#L625-L630
PistoiaHELM/HELM2NotationToolkit
src/main/java/org/helm/notation2/tools/RNAUtils.java
RNAUtils.areAntiparallel
public static boolean areAntiparallel(PolymerNotation polymerOne, PolymerNotation polymerTwo) throws RNAUtilsException, HELM2HandledException, ChemistryException, NucleotideLoadingException { """ method to check if two given polymers are complement to each other @param polymerOne PolymerNotation of the first polymer @param polymerTwo PolymerNotation of the second polymer @return true, if they are opposite to each other, false otherwise @throws RNAUtilsException if the polymers are not rna/dna or the antiparallel strand can not be built from polymerOne @throws HELM2HandledException if the polymers contain HELM2 features @throws ChemistryException if the Chemistry Engine can not be initialized @throws NucleotideLoadingException if nucleotides can not be loaded """ checkRNA(polymerOne); checkRNA(polymerTwo); PolymerNotation antiparallel = getAntiparallel(polymerOne); String sequenceOne = FastaFormat .generateFastaFromRNA(MethodsMonomerUtils.getListOfHandledMonomers(antiparallel.getListMonomers())); String sequenceTwo = FastaFormat .generateFastaFromRNA(MethodsMonomerUtils.getListOfHandledMonomers(polymerTwo.getListMonomers())); return sequenceOne.equals(sequenceTwo); }
java
public static boolean areAntiparallel(PolymerNotation polymerOne, PolymerNotation polymerTwo) throws RNAUtilsException, HELM2HandledException, ChemistryException, NucleotideLoadingException { checkRNA(polymerOne); checkRNA(polymerTwo); PolymerNotation antiparallel = getAntiparallel(polymerOne); String sequenceOne = FastaFormat .generateFastaFromRNA(MethodsMonomerUtils.getListOfHandledMonomers(antiparallel.getListMonomers())); String sequenceTwo = FastaFormat .generateFastaFromRNA(MethodsMonomerUtils.getListOfHandledMonomers(polymerTwo.getListMonomers())); return sequenceOne.equals(sequenceTwo); }
[ "public", "static", "boolean", "areAntiparallel", "(", "PolymerNotation", "polymerOne", ",", "PolymerNotation", "polymerTwo", ")", "throws", "RNAUtilsException", ",", "HELM2HandledException", ",", "ChemistryException", ",", "NucleotideLoadingException", "{", "checkRNA", "(", "polymerOne", ")", ";", "checkRNA", "(", "polymerTwo", ")", ";", "PolymerNotation", "antiparallel", "=", "getAntiparallel", "(", "polymerOne", ")", ";", "String", "sequenceOne", "=", "FastaFormat", ".", "generateFastaFromRNA", "(", "MethodsMonomerUtils", ".", "getListOfHandledMonomers", "(", "antiparallel", ".", "getListMonomers", "(", ")", ")", ")", ";", "String", "sequenceTwo", "=", "FastaFormat", ".", "generateFastaFromRNA", "(", "MethodsMonomerUtils", ".", "getListOfHandledMonomers", "(", "polymerTwo", ".", "getListMonomers", "(", ")", ")", ")", ";", "return", "sequenceOne", ".", "equals", "(", "sequenceTwo", ")", ";", "}" ]
method to check if two given polymers are complement to each other @param polymerOne PolymerNotation of the first polymer @param polymerTwo PolymerNotation of the second polymer @return true, if they are opposite to each other, false otherwise @throws RNAUtilsException if the polymers are not rna/dna or the antiparallel strand can not be built from polymerOne @throws HELM2HandledException if the polymers contain HELM2 features @throws ChemistryException if the Chemistry Engine can not be initialized @throws NucleotideLoadingException if nucleotides can not be loaded
[ "method", "to", "check", "if", "two", "given", "polymers", "are", "complement", "to", "each", "other" ]
train
https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/RNAUtils.java#L147-L157
wso2/transport-http
components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/HttpCarbonMessage.java
HttpCarbonMessage.pushResponse
public HttpResponseFuture pushResponse(HttpCarbonMessage httpCarbonMessage, Http2PushPromise pushPromise) throws ServerConnectorException { """ Sends a push response message back to the client. @param httpCarbonMessage the push response message @param pushPromise the push promise associated with the push response message @return HttpResponseFuture which gives the status of the operation @throws ServerConnectorException if there is an error occurs while doing the operation """ httpOutboundRespFuture.notifyHttpListener(httpCarbonMessage, pushPromise); return httpOutboundRespStatusFuture; }
java
public HttpResponseFuture pushResponse(HttpCarbonMessage httpCarbonMessage, Http2PushPromise pushPromise) throws ServerConnectorException { httpOutboundRespFuture.notifyHttpListener(httpCarbonMessage, pushPromise); return httpOutboundRespStatusFuture; }
[ "public", "HttpResponseFuture", "pushResponse", "(", "HttpCarbonMessage", "httpCarbonMessage", ",", "Http2PushPromise", "pushPromise", ")", "throws", "ServerConnectorException", "{", "httpOutboundRespFuture", ".", "notifyHttpListener", "(", "httpCarbonMessage", ",", "pushPromise", ")", ";", "return", "httpOutboundRespStatusFuture", ";", "}" ]
Sends a push response message back to the client. @param httpCarbonMessage the push response message @param pushPromise the push promise associated with the push response message @return HttpResponseFuture which gives the status of the operation @throws ServerConnectorException if there is an error occurs while doing the operation
[ "Sends", "a", "push", "response", "message", "back", "to", "the", "client", "." ]
train
https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/HttpCarbonMessage.java#L311-L315
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.createSSHKey
public GitlabSSHKey createSSHKey(Integer targetUserId, String title, String key) throws IOException { """ Create a new ssh key for the user @param targetUserId The id of the Gitlab user @param title The title of the ssh key @param key The public key @return The new GitlabSSHKey @throws IOException on gitlab api call error """ Query query = new Query() .append("title", title) .append("key", key); String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabSSHKey.KEYS_URL + query.toString(); return dispatch().to(tailUrl, GitlabSSHKey.class); }
java
public GitlabSSHKey createSSHKey(Integer targetUserId, String title, String key) throws IOException { Query query = new Query() .append("title", title) .append("key", key); String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabSSHKey.KEYS_URL + query.toString(); return dispatch().to(tailUrl, GitlabSSHKey.class); }
[ "public", "GitlabSSHKey", "createSSHKey", "(", "Integer", "targetUserId", ",", "String", "title", ",", "String", "key", ")", "throws", "IOException", "{", "Query", "query", "=", "new", "Query", "(", ")", ".", "append", "(", "\"title\"", ",", "title", ")", ".", "append", "(", "\"key\"", ",", "key", ")", ";", "String", "tailUrl", "=", "GitlabUser", ".", "USERS_URL", "+", "\"/\"", "+", "targetUserId", "+", "GitlabSSHKey", ".", "KEYS_URL", "+", "query", ".", "toString", "(", ")", ";", "return", "dispatch", "(", ")", ".", "to", "(", "tailUrl", ",", "GitlabSSHKey", ".", "class", ")", ";", "}" ]
Create a new ssh key for the user @param targetUserId The id of the Gitlab user @param title The title of the ssh key @param key The public key @return The new GitlabSSHKey @throws IOException on gitlab api call error
[ "Create", "a", "new", "ssh", "key", "for", "the", "user" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L385-L394
cloudiator/flexiant-client
src/main/java/de/uniulm/omi/cloudiator/flexiant/client/compute/FlexiantComputeClient.java
FlexiantComputeClient.createServer
public de.uniulm.omi.cloudiator.flexiant.client.domain.Server createServer( final ServerTemplate serverTemplate) throws FlexiantException { """ Creates a server with the given properties. @param serverTemplate A template describing the server which should be started. @return the created server. @throws FlexiantException """ checkNotNull(serverTemplate); io.github.cloudiator.flexiant.extility.Server server = new io.github.cloudiator.flexiant.extility.Server(); server.setResourceName(serverTemplate.getServerName()); server.setCustomerUUID(this.getCustomerUUID()); server.setProductOfferUUID(serverTemplate.getServerProductOffer()); server.setVdcUUID(serverTemplate.getVdc()); server.setImageUUID(serverTemplate.getImage()); Disk disk = new Disk(); disk.setProductOfferUUID(serverTemplate.getDiskProductOffer()); disk.setIndex(0); server.getDisks().add(disk); final Set<String> networks = new HashSet<String>(); if (serverTemplate.getTemplateOptions().getNetworks().isEmpty()) { //no network configured, find it out by ourselves. if (this.getNetworks(serverTemplate.getVdc()).size() == 1) { networks.add(this.getNetworks(serverTemplate.getVdc()).iterator().next().getId()); } else { throw new FlexiantException("Could not uniquely identify network."); } } else { networks.addAll(serverTemplate.getTemplateOptions().getNetworks()); } //assign the networks for (String network : networks) { Nic nic = new Nic(); nic.setNetworkUUID(network); server.getNics().add(nic); } try { Job serverJob = this.getService().createServer(server, null, null, null); this.waitForJob(serverJob); final de.uniulm.omi.cloudiator.flexiant.client.domain.Server createdServer = this.getServer(serverJob.getItemUUID()); checkState(createdServer != null, String.format( "Execution of job %s for server %s was returned as successful, but the server could not be queried.", serverJob.getResourceUUID(), serverJob.getItemUUID())); this.startServer(createdServer); return createdServer; } catch (ExtilityException e) { throw new FlexiantException("Could not create server", e); } }
java
public de.uniulm.omi.cloudiator.flexiant.client.domain.Server createServer( final ServerTemplate serverTemplate) throws FlexiantException { checkNotNull(serverTemplate); io.github.cloudiator.flexiant.extility.Server server = new io.github.cloudiator.flexiant.extility.Server(); server.setResourceName(serverTemplate.getServerName()); server.setCustomerUUID(this.getCustomerUUID()); server.setProductOfferUUID(serverTemplate.getServerProductOffer()); server.setVdcUUID(serverTemplate.getVdc()); server.setImageUUID(serverTemplate.getImage()); Disk disk = new Disk(); disk.setProductOfferUUID(serverTemplate.getDiskProductOffer()); disk.setIndex(0); server.getDisks().add(disk); final Set<String> networks = new HashSet<String>(); if (serverTemplate.getTemplateOptions().getNetworks().isEmpty()) { //no network configured, find it out by ourselves. if (this.getNetworks(serverTemplate.getVdc()).size() == 1) { networks.add(this.getNetworks(serverTemplate.getVdc()).iterator().next().getId()); } else { throw new FlexiantException("Could not uniquely identify network."); } } else { networks.addAll(serverTemplate.getTemplateOptions().getNetworks()); } //assign the networks for (String network : networks) { Nic nic = new Nic(); nic.setNetworkUUID(network); server.getNics().add(nic); } try { Job serverJob = this.getService().createServer(server, null, null, null); this.waitForJob(serverJob); final de.uniulm.omi.cloudiator.flexiant.client.domain.Server createdServer = this.getServer(serverJob.getItemUUID()); checkState(createdServer != null, String.format( "Execution of job %s for server %s was returned as successful, but the server could not be queried.", serverJob.getResourceUUID(), serverJob.getItemUUID())); this.startServer(createdServer); return createdServer; } catch (ExtilityException e) { throw new FlexiantException("Could not create server", e); } }
[ "public", "de", ".", "uniulm", ".", "omi", ".", "cloudiator", ".", "flexiant", ".", "client", ".", "domain", ".", "Server", "createServer", "(", "final", "ServerTemplate", "serverTemplate", ")", "throws", "FlexiantException", "{", "checkNotNull", "(", "serverTemplate", ")", ";", "io", ".", "github", ".", "cloudiator", ".", "flexiant", ".", "extility", ".", "Server", "server", "=", "new", "io", ".", "github", ".", "cloudiator", ".", "flexiant", ".", "extility", ".", "Server", "(", ")", ";", "server", ".", "setResourceName", "(", "serverTemplate", ".", "getServerName", "(", ")", ")", ";", "server", ".", "setCustomerUUID", "(", "this", ".", "getCustomerUUID", "(", ")", ")", ";", "server", ".", "setProductOfferUUID", "(", "serverTemplate", ".", "getServerProductOffer", "(", ")", ")", ";", "server", ".", "setVdcUUID", "(", "serverTemplate", ".", "getVdc", "(", ")", ")", ";", "server", ".", "setImageUUID", "(", "serverTemplate", ".", "getImage", "(", ")", ")", ";", "Disk", "disk", "=", "new", "Disk", "(", ")", ";", "disk", ".", "setProductOfferUUID", "(", "serverTemplate", ".", "getDiskProductOffer", "(", ")", ")", ";", "disk", ".", "setIndex", "(", "0", ")", ";", "server", ".", "getDisks", "(", ")", ".", "add", "(", "disk", ")", ";", "final", "Set", "<", "String", ">", "networks", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "if", "(", "serverTemplate", ".", "getTemplateOptions", "(", ")", ".", "getNetworks", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "//no network configured, find it out by ourselves.", "if", "(", "this", ".", "getNetworks", "(", "serverTemplate", ".", "getVdc", "(", ")", ")", ".", "size", "(", ")", "==", "1", ")", "{", "networks", ".", "add", "(", "this", ".", "getNetworks", "(", "serverTemplate", ".", "getVdc", "(", ")", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getId", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "FlexiantException", "(", "\"Could not uniquely identify network.\"", ")", ";", "}", "}", "else", "{", "networks", ".", "addAll", "(", "serverTemplate", ".", "getTemplateOptions", "(", ")", ".", "getNetworks", "(", ")", ")", ";", "}", "//assign the networks", "for", "(", "String", "network", ":", "networks", ")", "{", "Nic", "nic", "=", "new", "Nic", "(", ")", ";", "nic", ".", "setNetworkUUID", "(", "network", ")", ";", "server", ".", "getNics", "(", ")", ".", "add", "(", "nic", ")", ";", "}", "try", "{", "Job", "serverJob", "=", "this", ".", "getService", "(", ")", ".", "createServer", "(", "server", ",", "null", ",", "null", ",", "null", ")", ";", "this", ".", "waitForJob", "(", "serverJob", ")", ";", "final", "de", ".", "uniulm", ".", "omi", ".", "cloudiator", ".", "flexiant", ".", "client", ".", "domain", ".", "Server", "createdServer", "=", "this", ".", "getServer", "(", "serverJob", ".", "getItemUUID", "(", ")", ")", ";", "checkState", "(", "createdServer", "!=", "null", ",", "String", ".", "format", "(", "\"Execution of job %s for server %s was returned as successful, but the server could not be queried.\"", ",", "serverJob", ".", "getResourceUUID", "(", ")", ",", "serverJob", ".", "getItemUUID", "(", ")", ")", ")", ";", "this", ".", "startServer", "(", "createdServer", ")", ";", "return", "createdServer", ";", "}", "catch", "(", "ExtilityException", "e", ")", "{", "throw", "new", "FlexiantException", "(", "\"Could not create server\"", ",", "e", ")", ";", "}", "}" ]
Creates a server with the given properties. @param serverTemplate A template describing the server which should be started. @return the created server. @throws FlexiantException
[ "Creates", "a", "server", "with", "the", "given", "properties", "." ]
train
https://github.com/cloudiator/flexiant-client/blob/30024501a6ae034ea3646f71ec0761c8bc5daa69/src/main/java/de/uniulm/omi/cloudiator/flexiant/client/compute/FlexiantComputeClient.java#L216-L266
google/j2objc
translator/src/main/java/com/google/devtools/j2objc/util/Version.java
Version.jarVersion
public static String jarVersion(Class<?> jarClass) { """ Returns the "version" entry from a jar file's manifest, if available. If the class isn't in a jar file, or that jar file doesn't define a "version" entry, then a "not available" string is returned. @param jarClass any class from the target jar """ String j2objcVersion = null; String path = jarClass.getProtectionDomain().getCodeSource().getLocation().getPath(); try (JarFile jar = new JarFile(URLDecoder.decode(path, "UTF-8"))) { Manifest manifest = jar.getManifest(); j2objcVersion = manifest.getMainAttributes().getValue("version"); } catch (IOException e) { // fall-through } if (j2objcVersion == null) { j2objcVersion = "(j2objc version not available)"; } String javacVersion = Parser.newParser(null).version(); return String.format("%s (javac %s)", j2objcVersion, javacVersion); }
java
public static String jarVersion(Class<?> jarClass) { String j2objcVersion = null; String path = jarClass.getProtectionDomain().getCodeSource().getLocation().getPath(); try (JarFile jar = new JarFile(URLDecoder.decode(path, "UTF-8"))) { Manifest manifest = jar.getManifest(); j2objcVersion = manifest.getMainAttributes().getValue("version"); } catch (IOException e) { // fall-through } if (j2objcVersion == null) { j2objcVersion = "(j2objc version not available)"; } String javacVersion = Parser.newParser(null).version(); return String.format("%s (javac %s)", j2objcVersion, javacVersion); }
[ "public", "static", "String", "jarVersion", "(", "Class", "<", "?", ">", "jarClass", ")", "{", "String", "j2objcVersion", "=", "null", ";", "String", "path", "=", "jarClass", ".", "getProtectionDomain", "(", ")", ".", "getCodeSource", "(", ")", ".", "getLocation", "(", ")", ".", "getPath", "(", ")", ";", "try", "(", "JarFile", "jar", "=", "new", "JarFile", "(", "URLDecoder", ".", "decode", "(", "path", ",", "\"UTF-8\"", ")", ")", ")", "{", "Manifest", "manifest", "=", "jar", ".", "getManifest", "(", ")", ";", "j2objcVersion", "=", "manifest", ".", "getMainAttributes", "(", ")", ".", "getValue", "(", "\"version\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// fall-through", "}", "if", "(", "j2objcVersion", "==", "null", ")", "{", "j2objcVersion", "=", "\"(j2objc version not available)\"", ";", "}", "String", "javacVersion", "=", "Parser", ".", "newParser", "(", "null", ")", ".", "version", "(", ")", ";", "return", "String", ".", "format", "(", "\"%s (javac %s)\"", ",", "j2objcVersion", ",", "javacVersion", ")", ";", "}" ]
Returns the "version" entry from a jar file's manifest, if available. If the class isn't in a jar file, or that jar file doesn't define a "version" entry, then a "not available" string is returned. @param jarClass any class from the target jar
[ "Returns", "the", "version", "entry", "from", "a", "jar", "file", "s", "manifest", "if", "available", ".", "If", "the", "class", "isn", "t", "in", "a", "jar", "file", "or", "that", "jar", "file", "doesn", "t", "define", "a", "version", "entry", "then", "a", "not", "available", "string", "is", "returned", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/translator/src/main/java/com/google/devtools/j2objc/util/Version.java#L31-L47
korpling/ANNIS
annis-interfaces/src/main/java/annis/TimelineReconstructor.java
TimelineReconstructor.removeVirtualTokenizationUsingNamespace
public static void removeVirtualTokenizationUsingNamespace(SDocumentGraph graph) { """ Removes the virtual tokenization from a {@link SDocumentGraph} and replaces it with an {@link STimeline} and multiple {@link STextualDS}. This alters the original graph. @param orig @return """ if(graph.getTimeline() != null) { // do nothing if the graph does not contain any virtual tokenization return; } TimelineReconstructor reconstructor = new TimelineReconstructor(graph, true); reconstructor.addTimeline(); reconstructor.createTokenFromSOrder(); reconstructor.cleanup(); }
java
public static void removeVirtualTokenizationUsingNamespace(SDocumentGraph graph) { if(graph.getTimeline() != null) { // do nothing if the graph does not contain any virtual tokenization return; } TimelineReconstructor reconstructor = new TimelineReconstructor(graph, true); reconstructor.addTimeline(); reconstructor.createTokenFromSOrder(); reconstructor.cleanup(); }
[ "public", "static", "void", "removeVirtualTokenizationUsingNamespace", "(", "SDocumentGraph", "graph", ")", "{", "if", "(", "graph", ".", "getTimeline", "(", ")", "!=", "null", ")", "{", "// do nothing if the graph does not contain any virtual tokenization", "return", ";", "}", "TimelineReconstructor", "reconstructor", "=", "new", "TimelineReconstructor", "(", "graph", ",", "true", ")", ";", "reconstructor", ".", "addTimeline", "(", ")", ";", "reconstructor", ".", "createTokenFromSOrder", "(", ")", ";", "reconstructor", ".", "cleanup", "(", ")", ";", "}" ]
Removes the virtual tokenization from a {@link SDocumentGraph} and replaces it with an {@link STimeline} and multiple {@link STextualDS}. This alters the original graph. @param orig @return
[ "Removes", "the", "virtual", "tokenization", "from", "a", "{", "@link", "SDocumentGraph", "}", "and", "replaces", "it", "with", "an", "{", "@link", "STimeline", "}", "and", "multiple", "{", "@link", "STextualDS", "}", "." ]
train
https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-interfaces/src/main/java/annis/TimelineReconstructor.java#L449-L463
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/chrome/ChromeOptions.java
ChromeOptions.setExperimentalOption
public ChromeOptions setExperimentalOption(String name, Object value) { """ Sets an experimental option. Useful for new ChromeDriver options not yet exposed through the {@link ChromeOptions} API. @param name Name of the experimental option. @param value Value of the experimental option, which must be convertible to JSON. """ experimentalOptions.put(checkNotNull(name), value); return this; }
java
public ChromeOptions setExperimentalOption(String name, Object value) { experimentalOptions.put(checkNotNull(name), value); return this; }
[ "public", "ChromeOptions", "setExperimentalOption", "(", "String", "name", ",", "Object", "value", ")", "{", "experimentalOptions", ".", "put", "(", "checkNotNull", "(", "name", ")", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets an experimental option. Useful for new ChromeDriver options not yet exposed through the {@link ChromeOptions} API. @param name Name of the experimental option. @param value Value of the experimental option, which must be convertible to JSON.
[ "Sets", "an", "experimental", "option", ".", "Useful", "for", "new", "ChromeDriver", "options", "not", "yet", "exposed", "through", "the", "{", "@link", "ChromeOptions", "}", "API", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/chrome/ChromeOptions.java#L198-L201
threerings/narya
core/src/main/java/com/threerings/io/ObjectInputStream.java
ObjectInputStream.createClassMapping
protected ClassMapping createClassMapping (short code, String cname) throws IOException, ClassNotFoundException { """ Creates and returns a class mapping for the specified code and class name. """ // resolve the class and streamer ClassLoader loader = (_loader != null) ? _loader : Thread.currentThread().getContextClassLoader(); Class<?> sclass = Class.forName(cname, true, loader); Streamer streamer = Streamer.getStreamer(sclass); if (STREAM_DEBUG) { log.info(hashCode() + ": New class '" + cname + "'", "code", code); } // sanity check if (streamer == null) { String errmsg = "Aiya! Unable to create streamer for newly seen class " + "[code=" + code + ", class=" + cname + "]"; throw new RuntimeException(errmsg); } return new ClassMapping(code, sclass, streamer); }
java
protected ClassMapping createClassMapping (short code, String cname) throws IOException, ClassNotFoundException { // resolve the class and streamer ClassLoader loader = (_loader != null) ? _loader : Thread.currentThread().getContextClassLoader(); Class<?> sclass = Class.forName(cname, true, loader); Streamer streamer = Streamer.getStreamer(sclass); if (STREAM_DEBUG) { log.info(hashCode() + ": New class '" + cname + "'", "code", code); } // sanity check if (streamer == null) { String errmsg = "Aiya! Unable to create streamer for newly seen class " + "[code=" + code + ", class=" + cname + "]"; throw new RuntimeException(errmsg); } return new ClassMapping(code, sclass, streamer); }
[ "protected", "ClassMapping", "createClassMapping", "(", "short", "code", ",", "String", "cname", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "// resolve the class and streamer", "ClassLoader", "loader", "=", "(", "_loader", "!=", "null", ")", "?", "_loader", ":", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "Class", "<", "?", ">", "sclass", "=", "Class", ".", "forName", "(", "cname", ",", "true", ",", "loader", ")", ";", "Streamer", "streamer", "=", "Streamer", ".", "getStreamer", "(", "sclass", ")", ";", "if", "(", "STREAM_DEBUG", ")", "{", "log", ".", "info", "(", "hashCode", "(", ")", "+", "\": New class '\"", "+", "cname", "+", "\"'\"", ",", "\"code\"", ",", "code", ")", ";", "}", "// sanity check", "if", "(", "streamer", "==", "null", ")", "{", "String", "errmsg", "=", "\"Aiya! Unable to create streamer for newly seen class \"", "+", "\"[code=\"", "+", "code", "+", "\", class=\"", "+", "cname", "+", "\"]\"", ";", "throw", "new", "RuntimeException", "(", "errmsg", ")", ";", "}", "return", "new", "ClassMapping", "(", "code", ",", "sclass", ",", "streamer", ")", ";", "}" ]
Creates and returns a class mapping for the specified code and class name.
[ "Creates", "and", "returns", "a", "class", "mapping", "for", "the", "specified", "code", "and", "class", "name", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectInputStream.java#L238-L258
flow/caustic
api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java
MeshGenerator.generateNormals
public static void generateNormals(TFloatList positions, TIntList indices, TFloatList normals) { """ Generate the normals for the positions, according to the indices. This assumes that the positions have 3 components, in the x, y, z order. The normals are stored as a 3 component vector, in the x, y, z order. @param positions The position components @param indices The indices @param normals The list in which to store the normals """ // Initialize normals to (0, 0, 0) normals.fill(0, positions.size(), 0); // Iterate over the entire mesh for (int i = 0; i < indices.size(); i += 3) { // Triangle position indices final int pos0 = indices.get(i) * 3; final int pos1 = indices.get(i + 1) * 3; final int pos2 = indices.get(i + 2) * 3; // First triangle vertex position final float x0 = positions.get(pos0); final float y0 = positions.get(pos0 + 1); final float z0 = positions.get(pos0 + 2); // Second triangle vertex position final float x1 = positions.get(pos1); final float y1 = positions.get(pos1 + 1); final float z1 = positions.get(pos1 + 2); // Third triangle vertex position final float x2 = positions.get(pos2); final float y2 = positions.get(pos2 + 1); final float z2 = positions.get(pos2 + 2); // First edge position difference final float x10 = x1 - x0; final float y10 = y1 - y0; final float z10 = z1 - z0; // Second edge position difference final float x20 = x2 - x0; final float y20 = y2 - y0; final float z20 = z2 - z0; // Cross both edges to obtain the normal final float nx = y10 * z20 - z10 * y20; final float ny = z10 * x20 - x10 * z20; final float nz = x10 * y20 - y10 * x20; // Add the normal to the first vertex normals.set(pos0, normals.get(pos0) + nx); normals.set(pos0 + 1, normals.get(pos0 + 1) + ny); normals.set(pos0 + 2, normals.get(pos0 + 2) + nz); // Add the normal to the second vertex normals.set(pos1, normals.get(pos1) + nx); normals.set(pos1 + 1, normals.get(pos1 + 1) + ny); normals.set(pos1 + 2, normals.get(pos1 + 2) + nz); // Add the normal to the third vertex normals.set(pos2, normals.get(pos2) + nx); normals.set(pos2 + 1, normals.get(pos2 + 1) + ny); normals.set(pos2 + 2, normals.get(pos2 + 2) + nz); } // Iterate over all the normals for (int i = 0; i < indices.size(); i++) { // Index for the normal final int nor = indices.get(i) * 3; // Get the normal float nx = normals.get(nor); float ny = normals.get(nor + 1); float nz = normals.get(nor + 2); // Length of the normal final float l = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); // Normalize the normal nx /= l; ny /= l; nz /= l; // Update the normal normals.set(nor, nx); normals.set(nor + 1, ny); normals.set(nor + 2, nz); } }
java
public static void generateNormals(TFloatList positions, TIntList indices, TFloatList normals) { // Initialize normals to (0, 0, 0) normals.fill(0, positions.size(), 0); // Iterate over the entire mesh for (int i = 0; i < indices.size(); i += 3) { // Triangle position indices final int pos0 = indices.get(i) * 3; final int pos1 = indices.get(i + 1) * 3; final int pos2 = indices.get(i + 2) * 3; // First triangle vertex position final float x0 = positions.get(pos0); final float y0 = positions.get(pos0 + 1); final float z0 = positions.get(pos0 + 2); // Second triangle vertex position final float x1 = positions.get(pos1); final float y1 = positions.get(pos1 + 1); final float z1 = positions.get(pos1 + 2); // Third triangle vertex position final float x2 = positions.get(pos2); final float y2 = positions.get(pos2 + 1); final float z2 = positions.get(pos2 + 2); // First edge position difference final float x10 = x1 - x0; final float y10 = y1 - y0; final float z10 = z1 - z0; // Second edge position difference final float x20 = x2 - x0; final float y20 = y2 - y0; final float z20 = z2 - z0; // Cross both edges to obtain the normal final float nx = y10 * z20 - z10 * y20; final float ny = z10 * x20 - x10 * z20; final float nz = x10 * y20 - y10 * x20; // Add the normal to the first vertex normals.set(pos0, normals.get(pos0) + nx); normals.set(pos0 + 1, normals.get(pos0 + 1) + ny); normals.set(pos0 + 2, normals.get(pos0 + 2) + nz); // Add the normal to the second vertex normals.set(pos1, normals.get(pos1) + nx); normals.set(pos1 + 1, normals.get(pos1 + 1) + ny); normals.set(pos1 + 2, normals.get(pos1 + 2) + nz); // Add the normal to the third vertex normals.set(pos2, normals.get(pos2) + nx); normals.set(pos2 + 1, normals.get(pos2 + 1) + ny); normals.set(pos2 + 2, normals.get(pos2 + 2) + nz); } // Iterate over all the normals for (int i = 0; i < indices.size(); i++) { // Index for the normal final int nor = indices.get(i) * 3; // Get the normal float nx = normals.get(nor); float ny = normals.get(nor + 1); float nz = normals.get(nor + 2); // Length of the normal final float l = (float) Math.sqrt(nx * nx + ny * ny + nz * nz); // Normalize the normal nx /= l; ny /= l; nz /= l; // Update the normal normals.set(nor, nx); normals.set(nor + 1, ny); normals.set(nor + 2, nz); } }
[ "public", "static", "void", "generateNormals", "(", "TFloatList", "positions", ",", "TIntList", "indices", ",", "TFloatList", "normals", ")", "{", "// Initialize normals to (0, 0, 0)", "normals", ".", "fill", "(", "0", ",", "positions", ".", "size", "(", ")", ",", "0", ")", ";", "// Iterate over the entire mesh", "for", "(", "int", "i", "=", "0", ";", "i", "<", "indices", ".", "size", "(", ")", ";", "i", "+=", "3", ")", "{", "// Triangle position indices", "final", "int", "pos0", "=", "indices", ".", "get", "(", "i", ")", "*", "3", ";", "final", "int", "pos1", "=", "indices", ".", "get", "(", "i", "+", "1", ")", "*", "3", ";", "final", "int", "pos2", "=", "indices", ".", "get", "(", "i", "+", "2", ")", "*", "3", ";", "// First triangle vertex position", "final", "float", "x0", "=", "positions", ".", "get", "(", "pos0", ")", ";", "final", "float", "y0", "=", "positions", ".", "get", "(", "pos0", "+", "1", ")", ";", "final", "float", "z0", "=", "positions", ".", "get", "(", "pos0", "+", "2", ")", ";", "// Second triangle vertex position", "final", "float", "x1", "=", "positions", ".", "get", "(", "pos1", ")", ";", "final", "float", "y1", "=", "positions", ".", "get", "(", "pos1", "+", "1", ")", ";", "final", "float", "z1", "=", "positions", ".", "get", "(", "pos1", "+", "2", ")", ";", "// Third triangle vertex position", "final", "float", "x2", "=", "positions", ".", "get", "(", "pos2", ")", ";", "final", "float", "y2", "=", "positions", ".", "get", "(", "pos2", "+", "1", ")", ";", "final", "float", "z2", "=", "positions", ".", "get", "(", "pos2", "+", "2", ")", ";", "// First edge position difference", "final", "float", "x10", "=", "x1", "-", "x0", ";", "final", "float", "y10", "=", "y1", "-", "y0", ";", "final", "float", "z10", "=", "z1", "-", "z0", ";", "// Second edge position difference", "final", "float", "x20", "=", "x2", "-", "x0", ";", "final", "float", "y20", "=", "y2", "-", "y0", ";", "final", "float", "z20", "=", "z2", "-", "z0", ";", "// Cross both edges to obtain the normal", "final", "float", "nx", "=", "y10", "*", "z20", "-", "z10", "*", "y20", ";", "final", "float", "ny", "=", "z10", "*", "x20", "-", "x10", "*", "z20", ";", "final", "float", "nz", "=", "x10", "*", "y20", "-", "y10", "*", "x20", ";", "// Add the normal to the first vertex", "normals", ".", "set", "(", "pos0", ",", "normals", ".", "get", "(", "pos0", ")", "+", "nx", ")", ";", "normals", ".", "set", "(", "pos0", "+", "1", ",", "normals", ".", "get", "(", "pos0", "+", "1", ")", "+", "ny", ")", ";", "normals", ".", "set", "(", "pos0", "+", "2", ",", "normals", ".", "get", "(", "pos0", "+", "2", ")", "+", "nz", ")", ";", "// Add the normal to the second vertex", "normals", ".", "set", "(", "pos1", ",", "normals", ".", "get", "(", "pos1", ")", "+", "nx", ")", ";", "normals", ".", "set", "(", "pos1", "+", "1", ",", "normals", ".", "get", "(", "pos1", "+", "1", ")", "+", "ny", ")", ";", "normals", ".", "set", "(", "pos1", "+", "2", ",", "normals", ".", "get", "(", "pos1", "+", "2", ")", "+", "nz", ")", ";", "// Add the normal to the third vertex", "normals", ".", "set", "(", "pos2", ",", "normals", ".", "get", "(", "pos2", ")", "+", "nx", ")", ";", "normals", ".", "set", "(", "pos2", "+", "1", ",", "normals", ".", "get", "(", "pos2", "+", "1", ")", "+", "ny", ")", ";", "normals", ".", "set", "(", "pos2", "+", "2", ",", "normals", ".", "get", "(", "pos2", "+", "2", ")", "+", "nz", ")", ";", "}", "// Iterate over all the normals", "for", "(", "int", "i", "=", "0", ";", "i", "<", "indices", ".", "size", "(", ")", ";", "i", "++", ")", "{", "// Index for the normal", "final", "int", "nor", "=", "indices", ".", "get", "(", "i", ")", "*", "3", ";", "// Get the normal", "float", "nx", "=", "normals", ".", "get", "(", "nor", ")", ";", "float", "ny", "=", "normals", ".", "get", "(", "nor", "+", "1", ")", ";", "float", "nz", "=", "normals", ".", "get", "(", "nor", "+", "2", ")", ";", "// Length of the normal", "final", "float", "l", "=", "(", "float", ")", "Math", ".", "sqrt", "(", "nx", "*", "nx", "+", "ny", "*", "ny", "+", "nz", "*", "nz", ")", ";", "// Normalize the normal", "nx", "/=", "l", ";", "ny", "/=", "l", ";", "nz", "/=", "l", ";", "// Update the normal", "normals", ".", "set", "(", "nor", ",", "nx", ")", ";", "normals", ".", "set", "(", "nor", "+", "1", ",", "ny", ")", ";", "normals", ".", "set", "(", "nor", "+", "2", ",", "nz", ")", ";", "}", "}" ]
Generate the normals for the positions, according to the indices. This assumes that the positions have 3 components, in the x, y, z order. The normals are stored as a 3 component vector, in the x, y, z order. @param positions The position components @param indices The indices @param normals The list in which to store the normals
[ "Generate", "the", "normals", "for", "the", "positions", "according", "to", "the", "indices", ".", "This", "assumes", "that", "the", "positions", "have", "3", "components", "in", "the", "x", "y", "z", "order", ".", "The", "normals", "are", "stored", "as", "a", "3", "component", "vector", "in", "the", "x", "y", "z", "order", "." ]
train
https://github.com/flow/caustic/blob/88652fcf0621ce158a0e92ce4c570ed6b1f6fca9/api/src/main/java/com/flowpowered/caustic/api/util/MeshGenerator.java#L156-L221
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.setup
public void setup(String host, String path, Map<String, Object> params) { """ Initialize connection. @param host Connection host @param path Connection path @param params Params passed from client """ this.host = host; this.path = path; this.params = params; if (Integer.valueOf(3).equals(params.get("objectEncoding"))) { if (log.isDebugEnabled()) { log.debug("Setting object encoding to AMF3"); } state.setEncoding(Encoding.AMF3); } }
java
public void setup(String host, String path, Map<String, Object> params) { this.host = host; this.path = path; this.params = params; if (Integer.valueOf(3).equals(params.get("objectEncoding"))) { if (log.isDebugEnabled()) { log.debug("Setting object encoding to AMF3"); } state.setEncoding(Encoding.AMF3); } }
[ "public", "void", "setup", "(", "String", "host", ",", "String", "path", ",", "Map", "<", "String", ",", "Object", ">", "params", ")", "{", "this", ".", "host", "=", "host", ";", "this", ".", "path", "=", "path", ";", "this", ".", "params", "=", "params", ";", "if", "(", "Integer", ".", "valueOf", "(", "3", ")", ".", "equals", "(", "params", ".", "get", "(", "\"objectEncoding\"", ")", ")", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Setting object encoding to AMF3\"", ")", ";", "}", "state", ".", "setEncoding", "(", "Encoding", ".", "AMF3", ")", ";", "}", "}" ]
Initialize connection. @param host Connection host @param path Connection path @param params Params passed from client
[ "Initialize", "connection", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L574-L584
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/PropertiesField.java
PropertiesField.doSetData
public int doSetData(Object data, boolean bDisplayOption, int iMoveMode) { """ Move this physical binary data to this field. @param data The physical data to move to this field (must be the correct raw data class). @param bDisplayOption If true, display after setting the data. @param iMoveMode The type of move. @return an error code (0 if success). """ int iErrorCode = super.doSetData(data, bDisplayOption, iMoveMode); if (this.isJustModified()) m_propertiesCache = null; // Cache is no longer valid return iErrorCode; }
java
public int doSetData(Object data, boolean bDisplayOption, int iMoveMode) { int iErrorCode = super.doSetData(data, bDisplayOption, iMoveMode); if (this.isJustModified()) m_propertiesCache = null; // Cache is no longer valid return iErrorCode; }
[ "public", "int", "doSetData", "(", "Object", "data", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "int", "iErrorCode", "=", "super", ".", "doSetData", "(", "data", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "if", "(", "this", ".", "isJustModified", "(", ")", ")", "m_propertiesCache", "=", "null", ";", "// Cache is no longer valid", "return", "iErrorCode", ";", "}" ]
Move this physical binary data to this field. @param data The physical data to move to this field (must be the correct raw data class). @param bDisplayOption If true, display after setting the data. @param iMoveMode The type of move. @return an error code (0 if success).
[ "Move", "this", "physical", "binary", "data", "to", "this", "field", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/PropertiesField.java#L292-L298
3pillarlabs/spring-data-simpledb
spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDbEntityInformationSupport.java
SimpleDbEntityInformationSupport.getMetadata
@SuppressWarnings( { """ Creates a {@link SimpleDbEntityInformation} for the given domain class. @param domainClass must not be {@literal null}. @return """ "rawtypes", "unchecked" }) public static <T> SimpleDbEntityInformation<T, ?> getMetadata(Class<T> domainClass, String simpleDbDomain) { Assert.notNull(domainClass); Assert.notNull(simpleDbDomain); return new SimpleDbMetamodelEntityInformation(domainClass, simpleDbDomain); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> SimpleDbEntityInformation<T, ?> getMetadata(Class<T> domainClass, String simpleDbDomain) { Assert.notNull(domainClass); Assert.notNull(simpleDbDomain); return new SimpleDbMetamodelEntityInformation(domainClass, simpleDbDomain); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "public", "static", "<", "T", ">", "SimpleDbEntityInformation", "<", "T", ",", "?", ">", "getMetadata", "(", "Class", "<", "T", ">", "domainClass", ",", "String", "simpleDbDomain", ")", "{", "Assert", ".", "notNull", "(", "domainClass", ")", ";", "Assert", ".", "notNull", "(", "simpleDbDomain", ")", ";", "return", "new", "SimpleDbMetamodelEntityInformation", "(", "domainClass", ",", "simpleDbDomain", ")", ";", "}" ]
Creates a {@link SimpleDbEntityInformation} for the given domain class. @param domainClass must not be {@literal null}. @return
[ "Creates", "a", "{", "@link", "SimpleDbEntityInformation", "}", "for", "the", "given", "domain", "class", "." ]
train
https://github.com/3pillarlabs/spring-data-simpledb/blob/f1e0eb4e48ec4674d3966e8f5bc04c95031f93ae/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/repository/support/entityinformation/SimpleDbEntityInformationSupport.java#L48-L54
Azure/azure-sdk-for-java
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/DeploymentsInner.java
DeploymentsInner.createOrUpdate
public DeploymentExtendedInner createOrUpdate(String resourceGroupName, String deploymentName, DeploymentProperties properties) { """ Deploys resources to a resource group. You can provide the template and parameters directly in the request or link to JSON files. @param resourceGroupName The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. @param deploymentName The name of the deployment. @param properties The deployment properties. @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 DeploymentExtendedInner object if successful. """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, deploymentName, properties).toBlocking().last().body(); }
java
public DeploymentExtendedInner createOrUpdate(String resourceGroupName, String deploymentName, DeploymentProperties properties) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, deploymentName, properties).toBlocking().last().body(); }
[ "public", "DeploymentExtendedInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "deploymentName", ",", "DeploymentProperties", "properties", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "deploymentName", ",", "properties", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Deploys resources to a resource group. You can provide the template and parameters directly in the request or link to JSON files. @param resourceGroupName The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. @param deploymentName The name of the deployment. @param properties The deployment properties. @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 DeploymentExtendedInner object if successful.
[ "Deploys", "resources", "to", "a", "resource", "group", ".", "You", "can", "provide", "the", "template", "and", "parameters", "directly", "in", "the", "request", "or", "link", "to", "JSON", "files", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/DeploymentsInner.java#L376-L378
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java
SparkUtils.balancedRandomSplit
public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaPairRDD<T, U> data) { """ Equivalent to {@link #balancedRandomSplit(int, int, JavaRDD)} but for Pair RDDs """ return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong()); }
java
public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit, JavaPairRDD<T, U> data) { return balancedRandomSplit(totalObjectCount, numObjectsPerSplit, data, new Random().nextLong()); }
[ "public", "static", "<", "T", ",", "U", ">", "JavaPairRDD", "<", "T", ",", "U", ">", "[", "]", "balancedRandomSplit", "(", "int", "totalObjectCount", ",", "int", "numObjectsPerSplit", ",", "JavaPairRDD", "<", "T", ",", "U", ">", "data", ")", "{", "return", "balancedRandomSplit", "(", "totalObjectCount", ",", "numObjectsPerSplit", ",", "data", ",", "new", "Random", "(", ")", ".", "nextLong", "(", ")", ")", ";", "}" ]
Equivalent to {@link #balancedRandomSplit(int, int, JavaRDD)} but for Pair RDDs
[ "Equivalent", "to", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L487-L490
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/PrimaryWorkitem.java
PrimaryWorkitem.createTask
public Task createTask(String name, Map<String, Object> attributes) { """ Create a task that belongs to this item. @param name The name of the task. @param attributes additional attributes for task. @return created task. """ return getInstance().create().task(name, this, attributes); }
java
public Task createTask(String name, Map<String, Object> attributes) { return getInstance().create().task(name, this, attributes); }
[ "public", "Task", "createTask", "(", "String", "name", ",", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "return", "getInstance", "(", ")", ".", "create", "(", ")", ".", "task", "(", "name", ",", "this", ",", "attributes", ")", ";", "}" ]
Create a task that belongs to this item. @param name The name of the task. @param attributes additional attributes for task. @return created task.
[ "Create", "a", "task", "that", "belongs", "to", "this", "item", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/PrimaryWorkitem.java#L187-L189
netkicorp/java-wns-resolver
src/main/java/com/netki/tlsa/TLSAValidator.java
TLSAValidator.getMatchingCert
public Certificate getMatchingCert(TLSARecord tlsaRecord, List<Certificate> certs) { """ Returns the certificate matching the TLSA record from the given certs @param tlsaRecord TLSARecord type describing the TLSA Record to be validated @param certs All certs retrieved from the URL's SSL/TLS connection @return Matching certificate or null """ for (Certificate cert : certs) { byte[] digestMatch = new byte[0]; byte[] selectorData = new byte[0]; try { // Get Selector Value switch (tlsaRecord.getSelector()) { case TLSARecord.Selector.FULL_CERTIFICATE: selectorData = cert.getEncoded(); break; case TLSARecord.Selector.SUBJECT_PUBLIC_KEY_INFO: selectorData = cert.getPublicKey().getEncoded(); break; } // Validate Matching Type switch (tlsaRecord.getMatchingType()) { case TLSARecord.MatchingType.EXACT: digestMatch = selectorData; break; case TLSARecord.MatchingType.SHA256: digestMatch = MessageDigest.getInstance("SHA-256").digest(selectorData); break; case TLSARecord.MatchingType.SHA512: digestMatch = MessageDigest.getInstance("SHA-512").digest(selectorData); break; } } catch (Exception e) { e.printStackTrace(); } if (Arrays.equals(digestMatch, tlsaRecord.getCertificateAssociationData())) { return cert; } } return null; }
java
public Certificate getMatchingCert(TLSARecord tlsaRecord, List<Certificate> certs) { for (Certificate cert : certs) { byte[] digestMatch = new byte[0]; byte[] selectorData = new byte[0]; try { // Get Selector Value switch (tlsaRecord.getSelector()) { case TLSARecord.Selector.FULL_CERTIFICATE: selectorData = cert.getEncoded(); break; case TLSARecord.Selector.SUBJECT_PUBLIC_KEY_INFO: selectorData = cert.getPublicKey().getEncoded(); break; } // Validate Matching Type switch (tlsaRecord.getMatchingType()) { case TLSARecord.MatchingType.EXACT: digestMatch = selectorData; break; case TLSARecord.MatchingType.SHA256: digestMatch = MessageDigest.getInstance("SHA-256").digest(selectorData); break; case TLSARecord.MatchingType.SHA512: digestMatch = MessageDigest.getInstance("SHA-512").digest(selectorData); break; } } catch (Exception e) { e.printStackTrace(); } if (Arrays.equals(digestMatch, tlsaRecord.getCertificateAssociationData())) { return cert; } } return null; }
[ "public", "Certificate", "getMatchingCert", "(", "TLSARecord", "tlsaRecord", ",", "List", "<", "Certificate", ">", "certs", ")", "{", "for", "(", "Certificate", "cert", ":", "certs", ")", "{", "byte", "[", "]", "digestMatch", "=", "new", "byte", "[", "0", "]", ";", "byte", "[", "]", "selectorData", "=", "new", "byte", "[", "0", "]", ";", "try", "{", "// Get Selector Value", "switch", "(", "tlsaRecord", ".", "getSelector", "(", ")", ")", "{", "case", "TLSARecord", ".", "Selector", ".", "FULL_CERTIFICATE", ":", "selectorData", "=", "cert", ".", "getEncoded", "(", ")", ";", "break", ";", "case", "TLSARecord", ".", "Selector", ".", "SUBJECT_PUBLIC_KEY_INFO", ":", "selectorData", "=", "cert", ".", "getPublicKey", "(", ")", ".", "getEncoded", "(", ")", ";", "break", ";", "}", "// Validate Matching Type", "switch", "(", "tlsaRecord", ".", "getMatchingType", "(", ")", ")", "{", "case", "TLSARecord", ".", "MatchingType", ".", "EXACT", ":", "digestMatch", "=", "selectorData", ";", "break", ";", "case", "TLSARecord", ".", "MatchingType", ".", "SHA256", ":", "digestMatch", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA-256\"", ")", ".", "digest", "(", "selectorData", ")", ";", "break", ";", "case", "TLSARecord", ".", "MatchingType", ".", "SHA512", ":", "digestMatch", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA-512\"", ")", ".", "digest", "(", "selectorData", ")", ";", "break", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "if", "(", "Arrays", ".", "equals", "(", "digestMatch", ",", "tlsaRecord", ".", "getCertificateAssociationData", "(", ")", ")", ")", "{", "return", "cert", ";", "}", "}", "return", "null", ";", "}" ]
Returns the certificate matching the TLSA record from the given certs @param tlsaRecord TLSARecord type describing the TLSA Record to be validated @param certs All certs retrieved from the URL's SSL/TLS connection @return Matching certificate or null
[ "Returns", "the", "certificate", "matching", "the", "TLSA", "record", "from", "the", "given", "certs" ]
train
https://github.com/netkicorp/java-wns-resolver/blob/a7aad04d96c03feb05536aef189617beb4f011bc/src/main/java/com/netki/tlsa/TLSAValidator.java#L140-L181
VoltDB/voltdb
src/frontend/org/voltdb/expressions/ComparisonExpression.java
ComparisonExpression.getGteFilterFromPrefixLike
public ComparisonExpression getGteFilterFromPrefixLike() { """ / Construct the lower bound comparison filter implied by a prefix LIKE comparison. """ ExpressionType rangeComparator = ExpressionType.COMPARE_GREATERTHANOREQUALTO; String comparand = extractLikePatternPrefix(); return rangeFilterFromPrefixLike(m_left, rangeComparator, comparand); }
java
public ComparisonExpression getGteFilterFromPrefixLike() { ExpressionType rangeComparator = ExpressionType.COMPARE_GREATERTHANOREQUALTO; String comparand = extractLikePatternPrefix(); return rangeFilterFromPrefixLike(m_left, rangeComparator, comparand); }
[ "public", "ComparisonExpression", "getGteFilterFromPrefixLike", "(", ")", "{", "ExpressionType", "rangeComparator", "=", "ExpressionType", ".", "COMPARE_GREATERTHANOREQUALTO", ";", "String", "comparand", "=", "extractLikePatternPrefix", "(", ")", ";", "return", "rangeFilterFromPrefixLike", "(", "m_left", ",", "rangeComparator", ",", "comparand", ")", ";", "}" ]
/ Construct the lower bound comparison filter implied by a prefix LIKE comparison.
[ "/", "Construct", "the", "lower", "bound", "comparison", "filter", "implied", "by", "a", "prefix", "LIKE", "comparison", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/expressions/ComparisonExpression.java#L189-L193
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/JavaClasspathParser.java
JavaClasspathParser.readFileEntriesWithException
public static IClasspathEntry[][] readFileEntriesWithException(String projectName, URL projectRootAbsoluteFullPath) throws CoreException, IOException, ClasspathEntry.AssertionFailedException, URISyntaxException { """ Reads entry of a .classpath file. @param projectName - the name of project containing the .classpath file @param projectRootAbsoluteFullPath - the path to project containing the .classpath file @return the set of CLasspath ENtries extracted from the .classpath @throws CoreException - exception during parsing of .classpath @throws IOException - exception during parsing of .classpath @throws ClasspathEntry.AssertionFailedException - exception during parsing of .classpath @throws URISyntaxException - exception during parsing of .classpath """ return readFileEntriesWithException(projectName, projectRootAbsoluteFullPath, null); }
java
public static IClasspathEntry[][] readFileEntriesWithException(String projectName, URL projectRootAbsoluteFullPath) throws CoreException, IOException, ClasspathEntry.AssertionFailedException, URISyntaxException { return readFileEntriesWithException(projectName, projectRootAbsoluteFullPath, null); }
[ "public", "static", "IClasspathEntry", "[", "]", "[", "]", "readFileEntriesWithException", "(", "String", "projectName", ",", "URL", "projectRootAbsoluteFullPath", ")", "throws", "CoreException", ",", "IOException", ",", "ClasspathEntry", ".", "AssertionFailedException", ",", "URISyntaxException", "{", "return", "readFileEntriesWithException", "(", "projectName", ",", "projectRootAbsoluteFullPath", ",", "null", ")", ";", "}" ]
Reads entry of a .classpath file. @param projectName - the name of project containing the .classpath file @param projectRootAbsoluteFullPath - the path to project containing the .classpath file @return the set of CLasspath ENtries extracted from the .classpath @throws CoreException - exception during parsing of .classpath @throws IOException - exception during parsing of .classpath @throws ClasspathEntry.AssertionFailedException - exception during parsing of .classpath @throws URISyntaxException - exception during parsing of .classpath
[ "Reads", "entry", "of", "a", ".", "classpath", "file", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/JavaClasspathParser.java#L125-L128
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/runtime/io/network/netty/InboundEnvelopeDecoder.java
InboundEnvelopeDecoder.copy
private void copy(ByteBuf src, ByteBuffer dst) { """ Copies min(from.readableBytes(), to.remaining() bytes from Nettys ByteBuf to the Java NIO ByteBuffer. """ // This branch is necessary, because an Exception is thrown if the // destination buffer has more remaining (writable) bytes than // currently readable from the Netty ByteBuf source. if (src.isReadable()) { if (src.readableBytes() < dst.remaining()) { int oldLimit = dst.limit(); dst.limit(dst.position() + src.readableBytes()); src.readBytes(dst); dst.limit(oldLimit); } else { src.readBytes(dst); } } }
java
private void copy(ByteBuf src, ByteBuffer dst) { // This branch is necessary, because an Exception is thrown if the // destination buffer has more remaining (writable) bytes than // currently readable from the Netty ByteBuf source. if (src.isReadable()) { if (src.readableBytes() < dst.remaining()) { int oldLimit = dst.limit(); dst.limit(dst.position() + src.readableBytes()); src.readBytes(dst); dst.limit(oldLimit); } else { src.readBytes(dst); } } }
[ "private", "void", "copy", "(", "ByteBuf", "src", ",", "ByteBuffer", "dst", ")", "{", "// This branch is necessary, because an Exception is thrown if the", "// destination buffer has more remaining (writable) bytes than", "// currently readable from the Netty ByteBuf source.", "if", "(", "src", ".", "isReadable", "(", ")", ")", "{", "if", "(", "src", ".", "readableBytes", "(", ")", "<", "dst", ".", "remaining", "(", ")", ")", "{", "int", "oldLimit", "=", "dst", ".", "limit", "(", ")", ";", "dst", ".", "limit", "(", "dst", ".", "position", "(", ")", "+", "src", ".", "readableBytes", "(", ")", ")", ";", "src", ".", "readBytes", "(", "dst", ")", ";", "dst", ".", "limit", "(", "oldLimit", ")", ";", "}", "else", "{", "src", ".", "readBytes", "(", "dst", ")", ";", "}", "}", "}" ]
Copies min(from.readableBytes(), to.remaining() bytes from Nettys ByteBuf to the Java NIO ByteBuffer.
[ "Copies", "min", "(", "from", ".", "readableBytes", "()", "to", ".", "remaining", "()", "bytes", "from", "Nettys", "ByteBuf", "to", "the", "Java", "NIO", "ByteBuffer", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/runtime/io/network/netty/InboundEnvelopeDecoder.java#L320-L336
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/Table.java
Table.getNextConstraintIndex
int getNextConstraintIndex(int from, int type) { """ Returns the next constraint of a given type @param from @param type """ for (int i = from, size = constraintList.length; i < size; i++) { Constraint c = constraintList[i]; if (c.getConstraintType() == type) { return i; } } return -1; }
java
int getNextConstraintIndex(int from, int type) { for (int i = from, size = constraintList.length; i < size; i++) { Constraint c = constraintList[i]; if (c.getConstraintType() == type) { return i; } } return -1; }
[ "int", "getNextConstraintIndex", "(", "int", "from", ",", "int", "type", ")", "{", "for", "(", "int", "i", "=", "from", ",", "size", "=", "constraintList", ".", "length", ";", "i", "<", "size", ";", "i", "++", ")", "{", "Constraint", "c", "=", "constraintList", "[", "i", "]", ";", "if", "(", "c", ".", "getConstraintType", "(", ")", "==", "type", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Returns the next constraint of a given type @param from @param type
[ "Returns", "the", "next", "constraint", "of", "a", "given", "type" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Table.java#L896-L907
infinispan/infinispan
core/src/main/java/org/infinispan/util/AbstractDelegatingIntCacheStream.java
AbstractDelegatingIntCacheStream.mapToDouble
@Override public DoubleCacheStream mapToDouble(IntToDoubleFunction mapper) { """ These are methods that convert to a different AbstractDelegating*CacheStream """ return new AbstractDelegatingDoubleCacheStream(delegateCacheStream, underlyingStream.mapToDouble(mapper)); }
java
@Override public DoubleCacheStream mapToDouble(IntToDoubleFunction mapper) { return new AbstractDelegatingDoubleCacheStream(delegateCacheStream, underlyingStream.mapToDouble(mapper)); }
[ "@", "Override", "public", "DoubleCacheStream", "mapToDouble", "(", "IntToDoubleFunction", "mapper", ")", "{", "return", "new", "AbstractDelegatingDoubleCacheStream", "(", "delegateCacheStream", ",", "underlyingStream", ".", "mapToDouble", "(", "mapper", ")", ")", ";", "}" ]
These are methods that convert to a different AbstractDelegating*CacheStream
[ "These", "are", "methods", "that", "convert", "to", "a", "different", "AbstractDelegating", "*", "CacheStream" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/util/AbstractDelegatingIntCacheStream.java#L52-L55
datastax/java-driver
query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java
SchemaBuilder.createMaterializedView
@NonNull public static CreateMaterializedViewStart createMaterializedView( @Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier viewName) { """ Starts a CREATE MATERIALIZED VIEW query with the given view name for the given keyspace name. """ return new DefaultCreateMaterializedView(keyspace, viewName); }
java
@NonNull public static CreateMaterializedViewStart createMaterializedView( @Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier viewName) { return new DefaultCreateMaterializedView(keyspace, viewName); }
[ "@", "NonNull", "public", "static", "CreateMaterializedViewStart", "createMaterializedView", "(", "@", "Nullable", "CqlIdentifier", "keyspace", ",", "@", "NonNull", "CqlIdentifier", "viewName", ")", "{", "return", "new", "DefaultCreateMaterializedView", "(", "keyspace", ",", "viewName", ")", ";", "}" ]
Starts a CREATE MATERIALIZED VIEW query with the given view name for the given keyspace name.
[ "Starts", "a", "CREATE", "MATERIALIZED", "VIEW", "query", "with", "the", "given", "view", "name", "for", "the", "given", "keyspace", "name", "." ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java#L221-L225
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java
PlatformBitmapFactory.createBitmap
public CloseableReference<Bitmap> createBitmap( Bitmap source, int x, int y, int width, int height, @Nullable Object callerContext) { """ Creates a bitmap from the specified subset of the source bitmap. It is initialized with the same density as the original bitmap. @param source The bitmap we are subsetting @param x The x coordinate of the first pixel in source @param y The y coordinate of the first pixel in source @param width The number of pixels in each row @param height The number of rows @param callerContext the Tag to track who create the Bitmap @return a reference to the bitmap @throws IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap, or width is <= 0, or height is <= 0 @throws TooManyBitmapsException if the pool is full @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated """ return createBitmap(source, x, y, width, height, null, false, callerContext); }
java
public CloseableReference<Bitmap> createBitmap( Bitmap source, int x, int y, int width, int height, @Nullable Object callerContext) { return createBitmap(source, x, y, width, height, null, false, callerContext); }
[ "public", "CloseableReference", "<", "Bitmap", ">", "createBitmap", "(", "Bitmap", "source", ",", "int", "x", ",", "int", "y", ",", "int", "width", ",", "int", "height", ",", "@", "Nullable", "Object", "callerContext", ")", "{", "return", "createBitmap", "(", "source", ",", "x", ",", "y", ",", "width", ",", "height", ",", "null", ",", "false", ",", "callerContext", ")", ";", "}" ]
Creates a bitmap from the specified subset of the source bitmap. It is initialized with the same density as the original bitmap. @param source The bitmap we are subsetting @param x The x coordinate of the first pixel in source @param y The y coordinate of the first pixel in source @param width The number of pixels in each row @param height The number of rows @param callerContext the Tag to track who create the Bitmap @return a reference to the bitmap @throws IllegalArgumentException if the x, y, width, height values are outside of the dimensions of the source bitmap, or width is <= 0, or height is <= 0 @throws TooManyBitmapsException if the pool is full @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
[ "Creates", "a", "bitmap", "from", "the", "specified", "subset", "of", "the", "source", "bitmap", ".", "It", "is", "initialized", "with", "the", "same", "density", "as", "the", "original", "bitmap", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L170-L178
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/items/RealmSampleUserItem.java
RealmSampleUserItem.bindView
@Override public void bindView(ViewHolder holder, List<Object> payloads) { """ Binds the data of this item to the given holder @param holder """ //set the selected state of this item. force this otherwise it may is missed when implementing an item holder.itemView.setSelected(isSelected()); //set the name holder.name.setText(name); }
java
@Override public void bindView(ViewHolder holder, List<Object> payloads) { //set the selected state of this item. force this otherwise it may is missed when implementing an item holder.itemView.setSelected(isSelected()); //set the name holder.name.setText(name); }
[ "@", "Override", "public", "void", "bindView", "(", "ViewHolder", "holder", ",", "List", "<", "Object", ">", "payloads", ")", "{", "//set the selected state of this item. force this otherwise it may is missed when implementing an item", "holder", ".", "itemView", ".", "setSelected", "(", "isSelected", "(", ")", ")", ";", "//set the name", "holder", ".", "name", ".", "setText", "(", "name", ")", ";", "}" ]
Binds the data of this item to the given holder @param holder
[ "Binds", "the", "data", "of", "this", "item", "to", "the", "given", "holder" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/items/RealmSampleUserItem.java#L238-L245
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java
QrCodeUtil.encode
public static BitMatrix encode(String content, BarcodeFormat format, QrConfig config) { """ 将文本内容编码为条形码或二维码 @param content 文本内容 @param format 格式枚举 @param config 二维码配置,包括长、宽、边距、颜色等 @return {@link BitMatrix} @since 4.1.2 """ final MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); if (null == config) { // 默认配置 config = new QrConfig(); } BitMatrix bitMatrix; try { bitMatrix = multiFormatWriter.encode(content, format, config.width, config.height, config.toHints()); } catch (WriterException e) { throw new QrCodeException(e); } return bitMatrix; }
java
public static BitMatrix encode(String content, BarcodeFormat format, QrConfig config) { final MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); if (null == config) { // 默认配置 config = new QrConfig(); } BitMatrix bitMatrix; try { bitMatrix = multiFormatWriter.encode(content, format, config.width, config.height, config.toHints()); } catch (WriterException e) { throw new QrCodeException(e); } return bitMatrix; }
[ "public", "static", "BitMatrix", "encode", "(", "String", "content", ",", "BarcodeFormat", "format", ",", "QrConfig", "config", ")", "{", "final", "MultiFormatWriter", "multiFormatWriter", "=", "new", "MultiFormatWriter", "(", ")", ";", "if", "(", "null", "==", "config", ")", "{", "// 默认配置\r", "config", "=", "new", "QrConfig", "(", ")", ";", "}", "BitMatrix", "bitMatrix", ";", "try", "{", "bitMatrix", "=", "multiFormatWriter", ".", "encode", "(", "content", ",", "format", ",", "config", ".", "width", ",", "config", ".", "height", ",", "config", ".", "toHints", "(", ")", ")", ";", "}", "catch", "(", "WriterException", "e", ")", "{", "throw", "new", "QrCodeException", "(", "e", ")", ";", "}", "return", "bitMatrix", ";", "}" ]
将文本内容编码为条形码或二维码 @param content 文本内容 @param format 格式枚举 @param config 二维码配置,包括长、宽、边距、颜色等 @return {@link BitMatrix} @since 4.1.2
[ "将文本内容编码为条形码或二维码" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java#L247-L261
netty/netty
buffer/src/main/java/io/netty/buffer/Unpooled.java
Unpooled.copiedBuffer
public static ByteBuf copiedBuffer( CharSequence string, int offset, int length, Charset charset) { """ Creates a new big-endian buffer whose content is a subregion of the specified {@code string} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively. """ if (string == null) { throw new NullPointerException("string"); } if (length == 0) { return EMPTY_BUFFER; } if (string instanceof CharBuffer) { CharBuffer buf = (CharBuffer) string; if (buf.hasArray()) { return copiedBuffer( buf.array(), buf.arrayOffset() + buf.position() + offset, length, charset); } buf = buf.slice(); buf.limit(length); buf.position(offset); return copiedBuffer(buf, charset); } return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); }
java
public static ByteBuf copiedBuffer( CharSequence string, int offset, int length, Charset charset) { if (string == null) { throw new NullPointerException("string"); } if (length == 0) { return EMPTY_BUFFER; } if (string instanceof CharBuffer) { CharBuffer buf = (CharBuffer) string; if (buf.hasArray()) { return copiedBuffer( buf.array(), buf.arrayOffset() + buf.position() + offset, length, charset); } buf = buf.slice(); buf.limit(length); buf.position(offset); return copiedBuffer(buf, charset); } return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); }
[ "public", "static", "ByteBuf", "copiedBuffer", "(", "CharSequence", "string", ",", "int", "offset", ",", "int", "length", ",", "Charset", "charset", ")", "{", "if", "(", "string", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"string\"", ")", ";", "}", "if", "(", "length", "==", "0", ")", "{", "return", "EMPTY_BUFFER", ";", "}", "if", "(", "string", "instanceof", "CharBuffer", ")", "{", "CharBuffer", "buf", "=", "(", "CharBuffer", ")", "string", ";", "if", "(", "buf", ".", "hasArray", "(", ")", ")", "{", "return", "copiedBuffer", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", "+", "buf", ".", "position", "(", ")", "+", "offset", ",", "length", ",", "charset", ")", ";", "}", "buf", "=", "buf", ".", "slice", "(", ")", ";", "buf", ".", "limit", "(", "length", ")", ";", "buf", ".", "position", "(", "offset", ")", ";", "return", "copiedBuffer", "(", "buf", ",", "charset", ")", ";", "}", "return", "copiedBuffer", "(", "CharBuffer", ".", "wrap", "(", "string", ",", "offset", ",", "offset", "+", "length", ")", ",", "charset", ")", ";", "}" ]
Creates a new big-endian buffer whose content is a subregion of the specified {@code string} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively.
[ "Creates", "a", "new", "big", "-", "endian", "buffer", "whose", "content", "is", "a", "subregion", "of", "the", "specified", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/Unpooled.java#L595-L620
structr/structr
structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java
HtmlServlet.findFile
private File findFile(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException { """ Find a file with its name matching last path part @param securityContext @param request @param path @return file @throws FrameworkException """ List<Linkable> entryPoints = findPossibleEntryPoints(securityContext, request, path); // If no results were found, try to replace whitespace by '+' or '%20' if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPlus(path)); } if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPercentTwenty(path)); } for (Linkable node : entryPoints) { if (node instanceof File && (path.equals(node.getPath()) || node.getUuid().equals(PathHelper.getName(path)))) { return (File) node; } } return null; }
java
private File findFile(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException { List<Linkable> entryPoints = findPossibleEntryPoints(securityContext, request, path); // If no results were found, try to replace whitespace by '+' or '%20' if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPlus(path)); } if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPercentTwenty(path)); } for (Linkable node : entryPoints) { if (node instanceof File && (path.equals(node.getPath()) || node.getUuid().equals(PathHelper.getName(path)))) { return (File) node; } } return null; }
[ "private", "File", "findFile", "(", "final", "SecurityContext", "securityContext", ",", "final", "HttpServletRequest", "request", ",", "final", "String", "path", ")", "throws", "FrameworkException", "{", "List", "<", "Linkable", ">", "entryPoints", "=", "findPossibleEntryPoints", "(", "securityContext", ",", "request", ",", "path", ")", ";", "// If no results were found, try to replace whitespace by '+' or '%20'", "if", "(", "entryPoints", ".", "isEmpty", "(", ")", ")", "{", "entryPoints", "=", "findPossibleEntryPoints", "(", "securityContext", ",", "request", ",", "PathHelper", ".", "replaceWhitespaceByPlus", "(", "path", ")", ")", ";", "}", "if", "(", "entryPoints", ".", "isEmpty", "(", ")", ")", "{", "entryPoints", "=", "findPossibleEntryPoints", "(", "securityContext", ",", "request", ",", "PathHelper", ".", "replaceWhitespaceByPercentTwenty", "(", "path", ")", ")", ";", "}", "for", "(", "Linkable", "node", ":", "entryPoints", ")", "{", "if", "(", "node", "instanceof", "File", "&&", "(", "path", ".", "equals", "(", "node", ".", "getPath", "(", ")", ")", "||", "node", ".", "getUuid", "(", ")", ".", "equals", "(", "PathHelper", ".", "getName", "(", "path", ")", ")", ")", ")", "{", "return", "(", "File", ")", "node", ";", "}", "}", "return", "null", ";", "}" ]
Find a file with its name matching last path part @param securityContext @param request @param path @return file @throws FrameworkException
[ "Find", "a", "file", "with", "its", "name", "matching", "last", "path", "part" ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java#L1025-L1046
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/ProtectedBranchesApi.java
ProtectedBranchesApi.protectBranch
public ProtectedBranch protectBranch(Integer projectIdOrPath, String branchName) throws GitLabApiException { """ Protects a single repository branch or several project repository branches using a wildcard protected branch. <pre><code>GitLab Endpoint: POST /projects/:id/protected_branches</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param branchName the name of the branch to protect @return the branch info for the protected branch @throws GitLabApiException if any exception occurs """ return protectBranch(projectIdOrPath, branchName, AccessLevel.MAINTAINER, AccessLevel.MAINTAINER); }
java
public ProtectedBranch protectBranch(Integer projectIdOrPath, String branchName) throws GitLabApiException { return protectBranch(projectIdOrPath, branchName, AccessLevel.MAINTAINER, AccessLevel.MAINTAINER); }
[ "public", "ProtectedBranch", "protectBranch", "(", "Integer", "projectIdOrPath", ",", "String", "branchName", ")", "throws", "GitLabApiException", "{", "return", "protectBranch", "(", "projectIdOrPath", ",", "branchName", ",", "AccessLevel", ".", "MAINTAINER", ",", "AccessLevel", ".", "MAINTAINER", ")", ";", "}" ]
Protects a single repository branch or several project repository branches using a wildcard protected branch. <pre><code>GitLab Endpoint: POST /projects/:id/protected_branches</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param branchName the name of the branch to protect @return the branch info for the protected branch @throws GitLabApiException if any exception occurs
[ "Protects", "a", "single", "repository", "branch", "or", "several", "project", "repository", "branches", "using", "a", "wildcard", "protected", "branch", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProtectedBranchesApi.java#L82-L84
bekkopen/NoCommons
src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java
NorwegianDateUtil.getDate
private static Date getDate(int day, int month, int year) { """ Get the date for the given values. @param day The day. @param month The month. @param year The year. @return The date represented by the given values. """ Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DATE, day); return cal.getTime(); }
java
private static Date getDate(int day, int month, int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DATE, day); return cal.getTime(); }
[ "private", "static", "Date", "getDate", "(", "int", "day", ",", "int", "month", ",", "int", "year", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "YEAR", ",", "year", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "MONTH", ",", "month", ")", ";", "cal", ".", "set", "(", "Calendar", ".", "DATE", ",", "day", ")", ";", "return", "cal", ".", "getTime", "(", ")", ";", "}" ]
Get the date for the given values. @param day The day. @param month The month. @param year The year. @return The date represented by the given values.
[ "Get", "the", "date", "for", "the", "given", "values", "." ]
train
https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/date/NorwegianDateUtil.java#L274-L280
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/taglib/el/EvalHelper.java
EvalHelper.evalString
public static String evalString(String propertyName, String propertyValue, Tag tag, PageContext pageContext) throws JspException { """ Evaluate the string EL expression passed as parameter @param propertyName the property name @param propertyValue the property value @param tag the tag @param pageContext the page context @return the value corresponding to the EL expression passed as parameter @throws JspException if an exception occurs """ return (String) ExpressionEvaluatorManager.evaluate(propertyName, propertyValue, String.class, tag, pageContext); }
java
public static String evalString(String propertyName, String propertyValue, Tag tag, PageContext pageContext) throws JspException{ return (String) ExpressionEvaluatorManager.evaluate(propertyName, propertyValue, String.class, tag, pageContext); }
[ "public", "static", "String", "evalString", "(", "String", "propertyName", ",", "String", "propertyValue", ",", "Tag", "tag", ",", "PageContext", "pageContext", ")", "throws", "JspException", "{", "return", "(", "String", ")", "ExpressionEvaluatorManager", ".", "evaluate", "(", "propertyName", ",", "propertyValue", ",", "String", ".", "class", ",", "tag", ",", "pageContext", ")", ";", "}" ]
Evaluate the string EL expression passed as parameter @param propertyName the property name @param propertyValue the property value @param tag the tag @param pageContext the page context @return the value corresponding to the EL expression passed as parameter @throws JspException if an exception occurs
[ "Evaluate", "the", "string", "EL", "expression", "passed", "as", "parameter" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/taglib/el/EvalHelper.java#L39-L43
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/ToolScreen.java
ToolScreen.isPrintableControl
public boolean isPrintableControl(ScreenField sField, int iPrintOptions) { """ Display this sub-control in html input format? @param iPrintOptions The view specific print options. @return True if this sub-control is printable. """ // Override this to break if ((sField == null) || (sField == this)) { // Asking about this control return false; // Tool screens are not printed as a sub-screen. } return super.isPrintableControl(sField, iPrintOptions); }
java
public boolean isPrintableControl(ScreenField sField, int iPrintOptions) { // Override this to break if ((sField == null) || (sField == this)) { // Asking about this control return false; // Tool screens are not printed as a sub-screen. } return super.isPrintableControl(sField, iPrintOptions); }
[ "public", "boolean", "isPrintableControl", "(", "ScreenField", "sField", ",", "int", "iPrintOptions", ")", "{", "// Override this to break", "if", "(", "(", "sField", "==", "null", ")", "||", "(", "sField", "==", "this", ")", ")", "{", "// Asking about this control", "return", "false", ";", "// Tool screens are not printed as a sub-screen.", "}", "return", "super", ".", "isPrintableControl", "(", "sField", ",", "iPrintOptions", ")", ";", "}" ]
Display this sub-control in html input format? @param iPrintOptions The view specific print options. @return True if this sub-control is printable.
[ "Display", "this", "sub", "-", "control", "in", "html", "input", "format?" ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/ToolScreen.java#L179-L187
apache/groovy
src/main/java/org/codehaus/groovy/runtime/typehandling/NumberMath.java
NumberMath.rightShiftUnsigned
public static Number rightShiftUnsigned(Number left, Number right) { """ For this operation, consider the operands independently. Throw an exception if the right operand (shift distance) is not an integral type. For the left operand (shift value) also require an integral type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the shift operators. """ if (isFloatingPoint(right) || isBigDecimal(right)) { throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied"); } return getMath(left).rightShiftUnsignedImpl(left, right); }
java
public static Number rightShiftUnsigned(Number left, Number right) { if (isFloatingPoint(right) || isBigDecimal(right)) { throw new UnsupportedOperationException("Shift distance must be an integral type, but " + right + " (" + right.getClass().getName() + ") was supplied"); } return getMath(left).rightShiftUnsignedImpl(left, right); }
[ "public", "static", "Number", "rightShiftUnsigned", "(", "Number", "left", ",", "Number", "right", ")", "{", "if", "(", "isFloatingPoint", "(", "right", ")", "||", "isBigDecimal", "(", "right", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Shift distance must be an integral type, but \"", "+", "right", "+", "\" (\"", "+", "right", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\") was supplied\"", ")", ";", "}", "return", "getMath", "(", "left", ")", ".", "rightShiftUnsignedImpl", "(", "left", ",", "right", ")", ";", "}" ]
For this operation, consider the operands independently. Throw an exception if the right operand (shift distance) is not an integral type. For the left operand (shift value) also require an integral type, but do NOT promote from Integer to Long. This is consistent with Java, and makes sense for the shift operators.
[ "For", "this", "operation", "consider", "the", "operands", "independently", ".", "Throw", "an", "exception", "if", "the", "right", "operand", "(", "shift", "distance", ")", "is", "not", "an", "integral", "type", ".", "For", "the", "left", "operand", "(", "shift", "value", ")", "also", "require", "an", "integral", "type", "but", "do", "NOT", "promote", "from", "Integer", "to", "Long", ".", "This", "is", "consistent", "with", "Java", "and", "makes", "sense", "for", "the", "shift", "operators", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/typehandling/NumberMath.java#L123-L128
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/BaseWorkflowExecutor.java
BaseWorkflowExecutor.addStepFailureContextData
protected void addStepFailureContextData( StepExecutionResult stepResult, ExecutionContextImpl.Builder builder ) { """ Add step result failure information to the data context @param stepResult result @return new context """ HashMap<String, String> resultData = new HashMap<>(); if (null != stepResult.getFailureData()) { //convert values to string for (final Map.Entry<String, Object> entry : stepResult.getFailureData().entrySet()) { resultData.put(entry.getKey(), entry.getValue().toString()); } } FailureReason reason = stepResult.getFailureReason(); if (null == reason) { reason = StepFailureReason.Unknown; } resultData.put("reason", reason.toString()); String message = stepResult.getFailureMessage(); if (null == message) { message = "No message"; } resultData.put("message", message); //add to data context builder.setContext("result", resultData); }
java
protected void addStepFailureContextData( StepExecutionResult stepResult, ExecutionContextImpl.Builder builder ) { HashMap<String, String> resultData = new HashMap<>(); if (null != stepResult.getFailureData()) { //convert values to string for (final Map.Entry<String, Object> entry : stepResult.getFailureData().entrySet()) { resultData.put(entry.getKey(), entry.getValue().toString()); } } FailureReason reason = stepResult.getFailureReason(); if (null == reason) { reason = StepFailureReason.Unknown; } resultData.put("reason", reason.toString()); String message = stepResult.getFailureMessage(); if (null == message) { message = "No message"; } resultData.put("message", message); //add to data context builder.setContext("result", resultData); }
[ "protected", "void", "addStepFailureContextData", "(", "StepExecutionResult", "stepResult", ",", "ExecutionContextImpl", ".", "Builder", "builder", ")", "{", "HashMap", "<", "String", ",", "String", ">", "resultData", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "null", "!=", "stepResult", ".", "getFailureData", "(", ")", ")", "{", "//convert values to string", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "stepResult", ".", "getFailureData", "(", ")", ".", "entrySet", "(", ")", ")", "{", "resultData", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "FailureReason", "reason", "=", "stepResult", ".", "getFailureReason", "(", ")", ";", "if", "(", "null", "==", "reason", ")", "{", "reason", "=", "StepFailureReason", ".", "Unknown", ";", "}", "resultData", ".", "put", "(", "\"reason\"", ",", "reason", ".", "toString", "(", ")", ")", ";", "String", "message", "=", "stepResult", ".", "getFailureMessage", "(", ")", ";", "if", "(", "null", "==", "message", ")", "{", "message", "=", "\"No message\"", ";", "}", "resultData", ".", "put", "(", "\"message\"", ",", "message", ")", ";", "//add to data context", "builder", ".", "setContext", "(", "\"result\"", ",", "resultData", ")", ";", "}" ]
Add step result failure information to the data context @param stepResult result @return new context
[ "Add", "step", "result", "failure", "information", "to", "the", "data", "context" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/workflow/BaseWorkflowExecutor.java#L381-L407
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/theta/DirectQuickSelectSketchR.java
DirectQuickSelectSketchR.readOnlyWrap
static DirectQuickSelectSketchR readOnlyWrap(final Memory srcMem, final long seed) { """ Wrap a sketch around the given source Memory containing sketch data that originated from this sketch. @param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a> The given Memory object must be in hash table form and not read only. @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a> @return instance of this sketch """ final int preambleLongs = extractPreLongs(srcMem); //byte 0 final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3 final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4 UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs); checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs); final DirectQuickSelectSketchR dqssr = new DirectQuickSelectSketchR(seed, (WritableMemory) srcMem); dqssr.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs); return dqssr; }
java
static DirectQuickSelectSketchR readOnlyWrap(final Memory srcMem, final long seed) { final int preambleLongs = extractPreLongs(srcMem); //byte 0 final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3 final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4 UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs); checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs); final DirectQuickSelectSketchR dqssr = new DirectQuickSelectSketchR(seed, (WritableMemory) srcMem); dqssr.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs); return dqssr; }
[ "static", "DirectQuickSelectSketchR", "readOnlyWrap", "(", "final", "Memory", "srcMem", ",", "final", "long", "seed", ")", "{", "final", "int", "preambleLongs", "=", "extractPreLongs", "(", "srcMem", ")", ";", "//byte 0", "final", "int", "lgNomLongs", "=", "extractLgNomLongs", "(", "srcMem", ")", ";", "//byte 3", "final", "int", "lgArrLongs", "=", "extractLgArrLongs", "(", "srcMem", ")", ";", "//byte 4", "UpdateSketch", ".", "checkUnionQuickSelectFamily", "(", "srcMem", ",", "preambleLongs", ",", "lgNomLongs", ")", ";", "checkMemIntegrity", "(", "srcMem", ",", "seed", ",", "preambleLongs", ",", "lgNomLongs", ",", "lgArrLongs", ")", ";", "final", "DirectQuickSelectSketchR", "dqssr", "=", "new", "DirectQuickSelectSketchR", "(", "seed", ",", "(", "WritableMemory", ")", "srcMem", ")", ";", "dqssr", ".", "hashTableThreshold_", "=", "setHashTableThreshold", "(", "lgNomLongs", ",", "lgArrLongs", ")", ";", "return", "dqssr", ";", "}" ]
Wrap a sketch around the given source Memory containing sketch data that originated from this sketch. @param srcMem <a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a> The given Memory object must be in hash table form and not read only. @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a> @return instance of this sketch
[ "Wrap", "a", "sketch", "around", "the", "given", "source", "Memory", "containing", "sketch", "data", "that", "originated", "from", "this", "sketch", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/DirectQuickSelectSketchR.java#L60-L72
chhh/MSFTBX
MSFileToolbox/src/main/java/umich/ms/util/IntervalST.java
IntervalST.prettyPrint
private void prettyPrint(Node<K, V> n) { """ Recursively prints the tree. @param n the node to start recursion at """ if (n.left != null) { prettyPrint(n.left); } System.out.println(n); if (n.right != null) { prettyPrint(n.right); } }
java
private void prettyPrint(Node<K, V> n) { if (n.left != null) { prettyPrint(n.left); } System.out.println(n); if (n.right != null) { prettyPrint(n.right); } }
[ "private", "void", "prettyPrint", "(", "Node", "<", "K", ",", "V", ">", "n", ")", "{", "if", "(", "n", ".", "left", "!=", "null", ")", "{", "prettyPrint", "(", "n", ".", "left", ")", ";", "}", "System", ".", "out", ".", "println", "(", "n", ")", ";", "if", "(", "n", ".", "right", "!=", "null", ")", "{", "prettyPrint", "(", "n", ".", "right", ")", ";", "}", "}" ]
Recursively prints the tree. @param n the node to start recursion at
[ "Recursively", "prints", "the", "tree", "." ]
train
https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/util/IntervalST.java#L209-L217
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/DataDecoder.java
DataDecoder.decodeCharacterObj
public static Character decodeCharacterObj(byte[] src, int srcOffset) throws CorruptEncodingException { """ Decodes a Character object from exactly 1 or 3 bytes. If null is returned, then 1 byte was read. @param src source of encoded bytes @param srcOffset offset into source array @return Character object or null """ try { int b = src[srcOffset]; if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) { return null; } return decodeChar(src, srcOffset + 1); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
java
public static Character decodeCharacterObj(byte[] src, int srcOffset) throws CorruptEncodingException { try { int b = src[srcOffset]; if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) { return null; } return decodeChar(src, srcOffset + 1); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
[ "public", "static", "Character", "decodeCharacterObj", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ")", "throws", "CorruptEncodingException", "{", "try", "{", "int", "b", "=", "src", "[", "srcOffset", "]", ";", "if", "(", "b", "==", "NULL_BYTE_HIGH", "||", "b", "==", "NULL_BYTE_LOW", ")", "{", "return", "null", ";", "}", "return", "decodeChar", "(", "src", ",", "srcOffset", "+", "1", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "e", ")", "{", "throw", "new", "CorruptEncodingException", "(", "null", ",", "e", ")", ";", "}", "}" ]
Decodes a Character object from exactly 1 or 3 bytes. If null is returned, then 1 byte was read. @param src source of encoded bytes @param srcOffset offset into source array @return Character object or null
[ "Decodes", "a", "Character", "object", "from", "exactly", "1", "or", "3", "bytes", ".", "If", "null", "is", "returned", "then", "1", "byte", "was", "read", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataDecoder.java#L231-L243
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/FrameAndRootPainter.java
FrameAndRootPainter.createTitleBarGradient
private Paint createTitleBarGradient(Shape s, int titleHeight, FourColors defColors) { """ Create the gradient to paint the frame interior. @param s the interior shape. @param titleHeight the height of the title bar, or 0 if none. @param defColors the color set to construct the gradient from. @return the gradient. """ Rectangle2D bounds = s.getBounds2D(); float midX = (float) bounds.getCenterX(); float y = (float) bounds.getY(); float h = (float) bounds.getHeight(); return createGradient(midX, y, midX, y + h, new float[] { 0.0f, 1.0f }, new Color[] { defColors.top, defColors.upperMid }); }
java
private Paint createTitleBarGradient(Shape s, int titleHeight, FourColors defColors) { Rectangle2D bounds = s.getBounds2D(); float midX = (float) bounds.getCenterX(); float y = (float) bounds.getY(); float h = (float) bounds.getHeight(); return createGradient(midX, y, midX, y + h, new float[] { 0.0f, 1.0f }, new Color[] { defColors.top, defColors.upperMid }); }
[ "private", "Paint", "createTitleBarGradient", "(", "Shape", "s", ",", "int", "titleHeight", ",", "FourColors", "defColors", ")", "{", "Rectangle2D", "bounds", "=", "s", ".", "getBounds2D", "(", ")", ";", "float", "midX", "=", "(", "float", ")", "bounds", ".", "getCenterX", "(", ")", ";", "float", "y", "=", "(", "float", ")", "bounds", ".", "getY", "(", ")", ";", "float", "h", "=", "(", "float", ")", "bounds", ".", "getHeight", "(", ")", ";", "return", "createGradient", "(", "midX", ",", "y", ",", "midX", ",", "y", "+", "h", ",", "new", "float", "[", "]", "{", "0.0f", ",", "1.0f", "}", ",", "new", "Color", "[", "]", "{", "defColors", ".", "top", ",", "defColors", ".", "upperMid", "}", ")", ";", "}" ]
Create the gradient to paint the frame interior. @param s the interior shape. @param titleHeight the height of the title bar, or 0 if none. @param defColors the color set to construct the gradient from. @return the gradient.
[ "Create", "the", "gradient", "to", "paint", "the", "frame", "interior", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/FrameAndRootPainter.java#L349-L357