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
sawano/java-commons
src/main/java/se/sawano/java/commons/lang/validate/Validate.java
Validate.notNull
public static <T> T notNull(final T object, final String message, final Object... values) { """ <p>Validate that the specified argument is not {@code null}; otherwise throwing an exception with the specified message. <pre>Validate.notNull(myObject, "The object must not be null");</pre> @param <T> the object type @param object the object to check @param message the {@link String#format(String, Object...)} exception message if invalid, not null @param values the optional values for the formatted exception message @return the validated object (never {@code null} for method chaining) @throws NullPointerValidationException if the object is {@code null} @see #notNull(Object) """ return INSTANCE.notNull(object, message, values); }
java
public static <T> T notNull(final T object, final String message, final Object... values) { return INSTANCE.notNull(object, message, values); }
[ "public", "static", "<", "T", ">", "T", "notNull", "(", "final", "T", "object", ",", "final", "String", "message", ",", "final", "Object", "...", "values", ")", "{", "return", "INSTANCE", ".", "notNull", "(", "object", ",", "message", ",", "values", ")", ";", "}" ]
<p>Validate that the specified argument is not {@code null}; otherwise throwing an exception with the specified message. <pre>Validate.notNull(myObject, "The object must not be null");</pre> @param <T> the object type @param object the object to check @param message the {@link String#format(String, Object...)} exception message if invalid, not null @param values the optional values for the formatted exception message @return the validated object (never {@code null} for method chaining) @throws NullPointerValidationException if the object is {@code null} @see #notNull(Object)
[ "<p", ">", "Validate", "that", "the", "specified", "argument", "is", "not", "{", "@code", "null", "}", ";", "otherwise", "throwing", "an", "exception", "with", "the", "specified", "message", ".", "<pre", ">", "Validate", ".", "notNull", "(", "myObject", "The", "object", "must", "not", "be", "null", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L788-L790
spring-projects/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/approval/TokenApprovalStore.java
TokenApprovalStore.getApprovals
@Override public Collection<Approval> getApprovals(String userId, String clientId) { """ Extract the implied approvals from any tokens associated with the user and client id supplied. @see org.springframework.security.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String, java.lang.String) """ Collection<Approval> result = new HashSet<Approval>(); Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId); for (OAuth2AccessToken token : tokens) { OAuth2Authentication authentication = store.readAuthentication(token); if (authentication != null) { Date expiresAt = token.getExpiration(); for (String scope : token.getScope()) { result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED)); } } } return result; }
java
@Override public Collection<Approval> getApprovals(String userId, String clientId) { Collection<Approval> result = new HashSet<Approval>(); Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId); for (OAuth2AccessToken token : tokens) { OAuth2Authentication authentication = store.readAuthentication(token); if (authentication != null) { Date expiresAt = token.getExpiration(); for (String scope : token.getScope()) { result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED)); } } } return result; }
[ "@", "Override", "public", "Collection", "<", "Approval", ">", "getApprovals", "(", "String", "userId", ",", "String", "clientId", ")", "{", "Collection", "<", "Approval", ">", "result", "=", "new", "HashSet", "<", "Approval", ">", "(", ")", ";", "Collection", "<", "OAuth2AccessToken", ">", "tokens", "=", "store", ".", "findTokensByClientIdAndUserName", "(", "clientId", ",", "userId", ")", ";", "for", "(", "OAuth2AccessToken", "token", ":", "tokens", ")", "{", "OAuth2Authentication", "authentication", "=", "store", ".", "readAuthentication", "(", "token", ")", ";", "if", "(", "authentication", "!=", "null", ")", "{", "Date", "expiresAt", "=", "token", ".", "getExpiration", "(", ")", ";", "for", "(", "String", "scope", ":", "token", ".", "getScope", "(", ")", ")", "{", "result", ".", "add", "(", "new", "Approval", "(", "userId", ",", "clientId", ",", "scope", ",", "expiresAt", ",", "ApprovalStatus", ".", "APPROVED", ")", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Extract the implied approvals from any tokens associated with the user and client id supplied. @see org.springframework.security.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String, java.lang.String)
[ "Extract", "the", "implied", "approvals", "from", "any", "tokens", "associated", "with", "the", "user", "and", "client", "id", "supplied", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/approval/TokenApprovalStore.java#L88-L102
twitter/hraven
hraven-core/src/main/java/com/twitter/hraven/datasource/FlowQueueService.java
FlowQueueService.moveFlow
public void moveFlow(FlowQueueKey oldKey, FlowQueueKey newKey) throws DataException, IOException { """ Moves a flow_queue record from one row key to another. All Cells in the existing row will be written to the new row. This would primarily be used for transitioning a flow's data from one status to another. @param oldKey the existing row key to move @param newKey the new row key to move to @throws IOException """ byte[] oldRowKey = queueKeyConverter.toBytes(oldKey); Get get = new Get(oldRowKey); Table flowQueueTable = null; try { flowQueueTable = hbaseConnection .getTable(TableName.valueOf(Constants.FLOW_QUEUE_TABLE)); Result result = flowQueueTable.get(get); if (result == null || result.isEmpty()) { // no existing row throw new DataException( "No row for key " + Bytes.toStringBinary(oldRowKey)); } // copy the existing row to the new key Put p = new Put(queueKeyConverter.toBytes(newKey)); for (Cell c : result.rawCells()) { p.addColumn(CellUtil.cloneFamily(c), CellUtil.cloneQualifier(c), CellUtil.cloneValue(c)); } flowQueueTable.put(p); // delete the old row Delete d = new Delete(oldRowKey); flowQueueTable.delete(d); } finally { if (flowQueueTable != null) { flowQueueTable.close(); } } }
java
public void moveFlow(FlowQueueKey oldKey, FlowQueueKey newKey) throws DataException, IOException { byte[] oldRowKey = queueKeyConverter.toBytes(oldKey); Get get = new Get(oldRowKey); Table flowQueueTable = null; try { flowQueueTable = hbaseConnection .getTable(TableName.valueOf(Constants.FLOW_QUEUE_TABLE)); Result result = flowQueueTable.get(get); if (result == null || result.isEmpty()) { // no existing row throw new DataException( "No row for key " + Bytes.toStringBinary(oldRowKey)); } // copy the existing row to the new key Put p = new Put(queueKeyConverter.toBytes(newKey)); for (Cell c : result.rawCells()) { p.addColumn(CellUtil.cloneFamily(c), CellUtil.cloneQualifier(c), CellUtil.cloneValue(c)); } flowQueueTable.put(p); // delete the old row Delete d = new Delete(oldRowKey); flowQueueTable.delete(d); } finally { if (flowQueueTable != null) { flowQueueTable.close(); } } }
[ "public", "void", "moveFlow", "(", "FlowQueueKey", "oldKey", ",", "FlowQueueKey", "newKey", ")", "throws", "DataException", ",", "IOException", "{", "byte", "[", "]", "oldRowKey", "=", "queueKeyConverter", ".", "toBytes", "(", "oldKey", ")", ";", "Get", "get", "=", "new", "Get", "(", "oldRowKey", ")", ";", "Table", "flowQueueTable", "=", "null", ";", "try", "{", "flowQueueTable", "=", "hbaseConnection", ".", "getTable", "(", "TableName", ".", "valueOf", "(", "Constants", ".", "FLOW_QUEUE_TABLE", ")", ")", ";", "Result", "result", "=", "flowQueueTable", ".", "get", "(", "get", ")", ";", "if", "(", "result", "==", "null", "||", "result", ".", "isEmpty", "(", ")", ")", "{", "// no existing row", "throw", "new", "DataException", "(", "\"No row for key \"", "+", "Bytes", ".", "toStringBinary", "(", "oldRowKey", ")", ")", ";", "}", "// copy the existing row to the new key", "Put", "p", "=", "new", "Put", "(", "queueKeyConverter", ".", "toBytes", "(", "newKey", ")", ")", ";", "for", "(", "Cell", "c", ":", "result", ".", "rawCells", "(", ")", ")", "{", "p", ".", "addColumn", "(", "CellUtil", ".", "cloneFamily", "(", "c", ")", ",", "CellUtil", ".", "cloneQualifier", "(", "c", ")", ",", "CellUtil", ".", "cloneValue", "(", "c", ")", ")", ";", "}", "flowQueueTable", ".", "put", "(", "p", ")", ";", "// delete the old row", "Delete", "d", "=", "new", "Delete", "(", "oldRowKey", ")", ";", "flowQueueTable", ".", "delete", "(", "d", ")", ";", "}", "finally", "{", "if", "(", "flowQueueTable", "!=", "null", ")", "{", "flowQueueTable", ".", "close", "(", ")", ";", "}", "}", "}" ]
Moves a flow_queue record from one row key to another. All Cells in the existing row will be written to the new row. This would primarily be used for transitioning a flow's data from one status to another. @param oldKey the existing row key to move @param newKey the new row key to move to @throws IOException
[ "Moves", "a", "flow_queue", "record", "from", "one", "row", "key", "to", "another", ".", "All", "Cells", "in", "the", "existing", "row", "will", "be", "written", "to", "the", "new", "row", ".", "This", "would", "primarily", "be", "used", "for", "transitioning", "a", "flow", "s", "data", "from", "one", "status", "to", "another", "." ]
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/FlowQueueService.java#L96-L125
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/ModuleContentTypes.java
ModuleContentTypes.fetchAll
public CMAArray<CMAContentType> fetchAll(String spaceId, String environmentId) { """ Fetch all Content Types from an Environment, using default query parameter. <p> This fetch uses the default parameter defined in {@link DefaultQueryParameter#FETCH} <p> This method will override the configuration specified through {@link CMAClient.Builder#setSpaceId(String)} and {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId Space ID @param environmentId Environment ID @return {@link CMAArray} result instance @throws IllegalArgumentException if spaceId is null. """ return fetchAll(spaceId, environmentId, new HashMap<>()); }
java
public CMAArray<CMAContentType> fetchAll(String spaceId, String environmentId) { return fetchAll(spaceId, environmentId, new HashMap<>()); }
[ "public", "CMAArray", "<", "CMAContentType", ">", "fetchAll", "(", "String", "spaceId", ",", "String", "environmentId", ")", "{", "return", "fetchAll", "(", "spaceId", ",", "environmentId", ",", "new", "HashMap", "<>", "(", ")", ")", ";", "}" ]
Fetch all Content Types from an Environment, using default query parameter. <p> This fetch uses the default parameter defined in {@link DefaultQueryParameter#FETCH} <p> This method will override the configuration specified through {@link CMAClient.Builder#setSpaceId(String)} and {@link CMAClient.Builder#setEnvironmentId(String)}. @param spaceId Space ID @param environmentId Environment ID @return {@link CMAArray} result instance @throws IllegalArgumentException if spaceId is null.
[ "Fetch", "all", "Content", "Types", "from", "an", "Environment", "using", "default", "query", "parameter", ".", "<p", ">", "This", "fetch", "uses", "the", "default", "parameter", "defined", "in", "{", "@link", "DefaultQueryParameter#FETCH", "}", "<p", ">", "This", "method", "will", "override", "the", "configuration", "specified", "through", "{", "@link", "CMAClient", ".", "Builder#setSpaceId", "(", "String", ")", "}", "and", "{", "@link", "CMAClient", ".", "Builder#setEnvironmentId", "(", "String", ")", "}", "." ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/ModuleContentTypes.java#L186-L188
jcustenborder/connect-utils
connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java
ConfigUtils.keyManagerFactory
public static KeyManagerFactory keyManagerFactory(AbstractConfig config, String key) { """ Method will create a KeyManagerFactory based on the Algorithm type specified in the config. @param config Config to read from. @param key Key to read from @return KeyManagerFactory based on the type specified in the config. """ final String keyManagerFactoryType = config.getString(key); try { return KeyManagerFactory.getInstance(keyManagerFactoryType); } catch (NoSuchAlgorithmException e) { ConfigException exception = new ConfigException( key, keyManagerFactoryType, "Unknown Algorithm." ); exception.initCause(e); throw exception; } }
java
public static KeyManagerFactory keyManagerFactory(AbstractConfig config, String key) { final String keyManagerFactoryType = config.getString(key); try { return KeyManagerFactory.getInstance(keyManagerFactoryType); } catch (NoSuchAlgorithmException e) { ConfigException exception = new ConfigException( key, keyManagerFactoryType, "Unknown Algorithm." ); exception.initCause(e); throw exception; } }
[ "public", "static", "KeyManagerFactory", "keyManagerFactory", "(", "AbstractConfig", "config", ",", "String", "key", ")", "{", "final", "String", "keyManagerFactoryType", "=", "config", ".", "getString", "(", "key", ")", ";", "try", "{", "return", "KeyManagerFactory", ".", "getInstance", "(", "keyManagerFactoryType", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "ConfigException", "exception", "=", "new", "ConfigException", "(", "key", ",", "keyManagerFactoryType", ",", "\"Unknown Algorithm.\"", ")", ";", "exception", ".", "initCause", "(", "e", ")", ";", "throw", "exception", ";", "}", "}" ]
Method will create a KeyManagerFactory based on the Algorithm type specified in the config. @param config Config to read from. @param key Key to read from @return KeyManagerFactory based on the type specified in the config.
[ "Method", "will", "create", "a", "KeyManagerFactory", "based", "on", "the", "Algorithm", "type", "specified", "in", "the", "config", "." ]
train
https://github.com/jcustenborder/connect-utils/blob/19add138921f59ffcc85282d7aad551eeb582370/connect-utils/src/main/java/com/github/jcustenborder/kafka/connect/utils/config/ConfigUtils.java#L399-L412
oboehm/jfachwert
src/main/java/de/jfachwert/net/Domainname.java
Domainname.getLevelDomain
public Domainname getLevelDomain(int level) { """ Waehrend die Top-Level-Domain die oberste Ebende wie "de" ist, ist die 2nd-Level-Domain von "www.jfachwert.de" die Domain "jfachwert.de" und die 3rd-Level-Domain ist in diesem Beispiel die komplette Domain. @param level z.B. 2 fuer 2nd-Level-Domain @return z.B. "jfachwert.de" """ String[] parts = this.getCode().split("\\."); int firstPart = parts.length - level; if ((firstPart < 0) || (level < 1)) { throw new LocalizedIllegalArgumentException(level, "level", Range.between(1, parts.length)); } StringBuilder name = new StringBuilder(parts[firstPart]); for (int i = firstPart + 1; i < parts.length; i++) { name.append('.'); name.append(parts[i]); } return new Domainname(name.toString()); }
java
public Domainname getLevelDomain(int level) { String[] parts = this.getCode().split("\\."); int firstPart = parts.length - level; if ((firstPart < 0) || (level < 1)) { throw new LocalizedIllegalArgumentException(level, "level", Range.between(1, parts.length)); } StringBuilder name = new StringBuilder(parts[firstPart]); for (int i = firstPart + 1; i < parts.length; i++) { name.append('.'); name.append(parts[i]); } return new Domainname(name.toString()); }
[ "public", "Domainname", "getLevelDomain", "(", "int", "level", ")", "{", "String", "[", "]", "parts", "=", "this", ".", "getCode", "(", ")", ".", "split", "(", "\"\\\\.\"", ")", ";", "int", "firstPart", "=", "parts", ".", "length", "-", "level", ";", "if", "(", "(", "firstPart", "<", "0", ")", "||", "(", "level", "<", "1", ")", ")", "{", "throw", "new", "LocalizedIllegalArgumentException", "(", "level", ",", "\"level\"", ",", "Range", ".", "between", "(", "1", ",", "parts", ".", "length", ")", ")", ";", "}", "StringBuilder", "name", "=", "new", "StringBuilder", "(", "parts", "[", "firstPart", "]", ")", ";", "for", "(", "int", "i", "=", "firstPart", "+", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "name", ".", "append", "(", "'", "'", ")", ";", "name", ".", "append", "(", "parts", "[", "i", "]", ")", ";", "}", "return", "new", "Domainname", "(", "name", ".", "toString", "(", ")", ")", ";", "}" ]
Waehrend die Top-Level-Domain die oberste Ebende wie "de" ist, ist die 2nd-Level-Domain von "www.jfachwert.de" die Domain "jfachwert.de" und die 3rd-Level-Domain ist in diesem Beispiel die komplette Domain. @param level z.B. 2 fuer 2nd-Level-Domain @return z.B. "jfachwert.de"
[ "Waehrend", "die", "Top", "-", "Level", "-", "Domain", "die", "oberste", "Ebende", "wie", "de", "ist", "ist", "die", "2nd", "-", "Level", "-", "Domain", "von", "www", ".", "jfachwert", ".", "de", "die", "Domain", "jfachwert", ".", "de", "und", "die", "3rd", "-", "Level", "-", "Domain", "ist", "in", "diesem", "Beispiel", "die", "komplette", "Domain", "." ]
train
https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/net/Domainname.java#L107-L119
astefanutti/camel-cdi
maven/src/main/java/org/apache/camel/maven/RunMojo.java
RunMojo.addRelevantPluginDependenciesToClasspath
private void addRelevantPluginDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { """ Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and ExecutableDependency into consideration. @param path classpath of {@link java.net.URL} objects @throws MojoExecutionException """ if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator<Artifact> iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } }
java
private void addRelevantPluginDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { if (hasCommandlineArgs()) { arguments = parseCommandlineArgs(); } try { Iterator<Artifact> iter = this.determineRelevantPluginDependencies().iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); // we must skip org.osgi.core, otherwise we get a // java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set if (classPathElement.getArtifactId().equals("org.osgi.core")) { getLog().debug("Skipping org.osgi.core -> " + classPathElement.getGroupId() + "/" + classPathElement.getArtifactId() + "/" + classPathElement.getVersion()); continue; } getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); path.add(classPathElement.getFile().toURI().toURL()); } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } }
[ "private", "void", "addRelevantPluginDependenciesToClasspath", "(", "Set", "<", "URL", ">", "path", ")", "throws", "MojoExecutionException", "{", "if", "(", "hasCommandlineArgs", "(", ")", ")", "{", "arguments", "=", "parseCommandlineArgs", "(", ")", ";", "}", "try", "{", "Iterator", "<", "Artifact", ">", "iter", "=", "this", ".", "determineRelevantPluginDependencies", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Artifact", "classPathElement", "=", "iter", ".", "next", "(", ")", ";", "// we must skip org.osgi.core, otherwise we get a", "// java.lang.NoClassDefFoundError: org.osgi.vendor.framework property not set", "if", "(", "classPathElement", ".", "getArtifactId", "(", ")", ".", "equals", "(", "\"org.osgi.core\"", ")", ")", "{", "getLog", "(", ")", ".", "debug", "(", "\"Skipping org.osgi.core -> \"", "+", "classPathElement", ".", "getGroupId", "(", ")", "+", "\"/\"", "+", "classPathElement", ".", "getArtifactId", "(", ")", "+", "\"/\"", "+", "classPathElement", ".", "getVersion", "(", ")", ")", ";", "continue", ";", "}", "getLog", "(", ")", ".", "debug", "(", "\"Adding plugin dependency artifact: \"", "+", "classPathElement", ".", "getArtifactId", "(", ")", "+", "\" to classpath\"", ")", ";", "path", ".", "add", "(", "classPathElement", ".", "getFile", "(", ")", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ")", ";", "}", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Error during setting up classpath\"", ",", "e", ")", ";", "}", "}" ]
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and ExecutableDependency into consideration. @param path classpath of {@link java.net.URL} objects @throws MojoExecutionException
[ "Add", "any", "relevant", "project", "dependencies", "to", "the", "classpath", ".", "Indirectly", "takes", "includePluginDependencies", "and", "ExecutableDependency", "into", "consideration", "." ]
train
https://github.com/astefanutti/camel-cdi/blob/686c7f5fe3a706f47378e0c49c323040795ddff8/maven/src/main/java/org/apache/camel/maven/RunMojo.java#L735-L760
stevespringett/Alpine
alpine/src/main/java/alpine/auth/LdapConnectionWrapper.java
LdapConnectionWrapper.getAttribute
public String getAttribute(final SearchResult result, final String attributeName) throws NamingException { """ Retrieves an attribute by its name for the specified search result. @param result the search result of the entry to obtain the attribute value for @param attributeName the name of the attribute to return @return the value of the attribute, or null if not found @throws NamingException if an exception is thrown @since 1.4.0 """ return getAttribute(result.getAttributes(), attributeName); }
java
public String getAttribute(final SearchResult result, final String attributeName) throws NamingException { return getAttribute(result.getAttributes(), attributeName); }
[ "public", "String", "getAttribute", "(", "final", "SearchResult", "result", ",", "final", "String", "attributeName", ")", "throws", "NamingException", "{", "return", "getAttribute", "(", "result", ".", "getAttributes", "(", ")", ",", "attributeName", ")", ";", "}" ]
Retrieves an attribute by its name for the specified search result. @param result the search result of the entry to obtain the attribute value for @param attributeName the name of the attribute to return @return the value of the attribute, or null if not found @throws NamingException if an exception is thrown @since 1.4.0
[ "Retrieves", "an", "attribute", "by", "its", "name", "for", "the", "specified", "search", "result", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/LdapConnectionWrapper.java#L238-L240
cdk/cdk
tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java
NonplanarBonds.setWedge
private void setWedge(IBond bond, IAtom end, IBond.Stereo style) { """ Sets a wedge bond, because wedges are relative we may need to flip the storage order on the bond. @param bond the bond @param end the expected end atom (fat end of wedge) @param style the wedge style """ if (!bond.getEnd().equals(end)) bond.setAtoms(new IAtom[]{bond.getEnd(), bond.getBegin()}); bond.setStereo(style); }
java
private void setWedge(IBond bond, IAtom end, IBond.Stereo style) { if (!bond.getEnd().equals(end)) bond.setAtoms(new IAtom[]{bond.getEnd(), bond.getBegin()}); bond.setStereo(style); }
[ "private", "void", "setWedge", "(", "IBond", "bond", ",", "IAtom", "end", ",", "IBond", ".", "Stereo", "style", ")", "{", "if", "(", "!", "bond", ".", "getEnd", "(", ")", ".", "equals", "(", "end", ")", ")", "bond", ".", "setAtoms", "(", "new", "IAtom", "[", "]", "{", "bond", ".", "getEnd", "(", ")", ",", "bond", ".", "getBegin", "(", ")", "}", ")", ";", "bond", ".", "setStereo", "(", "style", ")", ";", "}" ]
Sets a wedge bond, because wedges are relative we may need to flip the storage order on the bond. @param bond the bond @param end the expected end atom (fat end of wedge) @param style the wedge style
[ "Sets", "a", "wedge", "bond", "because", "wedges", "are", "relative", "we", "may", "need", "to", "flip", "the", "storage", "order", "on", "the", "bond", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java#L416-L420
Azure/azure-sdk-for-java
common/azure-common/src/main/java/com/azure/common/implementation/RestProxy.java
RestProxy.handleRestReturnType
public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType) { """ Handle the provided asynchronous HTTP response and return the deserialized value. @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request @param methodParser the SwaggerMethodParser that the request originates from @param returnType the type of value that will be returned @return the deserialized result """ final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { // ProxyMethod ReturnType: Mono<Void> result = asyncExpectedResponse.then(); } else { // ProxyMethod ReturnType: Mono<? extends RestResponseBase<?, ?>> result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuf(returnType)) { // ProxyMethod ReturnType: Flux<ByteBuf> result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { // ProxyMethod ReturnType: Void asyncExpectedResponse.block(); result = null; } else { // ProxyMethod ReturnType: T where T != async (Mono, Flux) or sync Void // Block the deserialization until a value T is received result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; }
java
public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { // ProxyMethod ReturnType: Mono<Void> result = asyncExpectedResponse.then(); } else { // ProxyMethod ReturnType: Mono<? extends RestResponseBase<?, ?>> result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuf(returnType)) { // ProxyMethod ReturnType: Flux<ByteBuf> result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { // ProxyMethod ReturnType: Void asyncExpectedResponse.block(); result = null; } else { // ProxyMethod ReturnType: T where T != async (Mono, Flux) or sync Void // Block the deserialization until a value T is received result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; }
[ "public", "final", "Object", "handleRestReturnType", "(", "Mono", "<", "HttpDecodedResponse", ">", "asyncHttpDecodedResponse", ",", "final", "SwaggerMethodParser", "methodParser", ",", "final", "Type", "returnType", ")", "{", "final", "Mono", "<", "HttpDecodedResponse", ">", "asyncExpectedResponse", "=", "ensureExpectedStatus", "(", "asyncHttpDecodedResponse", ",", "methodParser", ")", ";", "final", "Object", "result", ";", "if", "(", "TypeUtil", ".", "isTypeOrSubTypeOf", "(", "returnType", ",", "Mono", ".", "class", ")", ")", "{", "final", "Type", "monoTypeParam", "=", "TypeUtil", ".", "getTypeArgument", "(", "returnType", ")", ";", "if", "(", "TypeUtil", ".", "isTypeOrSubTypeOf", "(", "monoTypeParam", ",", "Void", ".", "class", ")", ")", "{", "// ProxyMethod ReturnType: Mono<Void>", "result", "=", "asyncExpectedResponse", ".", "then", "(", ")", ";", "}", "else", "{", "// ProxyMethod ReturnType: Mono<? extends RestResponseBase<?, ?>>", "result", "=", "asyncExpectedResponse", ".", "flatMap", "(", "response", "->", "handleRestResponseReturnType", "(", "response", ",", "methodParser", ",", "monoTypeParam", ")", ")", ";", "}", "}", "else", "if", "(", "FluxUtil", ".", "isFluxByteBuf", "(", "returnType", ")", ")", "{", "// ProxyMethod ReturnType: Flux<ByteBuf>", "result", "=", "asyncExpectedResponse", ".", "flatMapMany", "(", "ar", "->", "ar", ".", "sourceResponse", "(", ")", ".", "body", "(", ")", ")", ";", "}", "else", "if", "(", "TypeUtil", ".", "isTypeOrSubTypeOf", "(", "returnType", ",", "void", ".", "class", ")", "||", "TypeUtil", ".", "isTypeOrSubTypeOf", "(", "returnType", ",", "Void", ".", "class", ")", ")", "{", "// ProxyMethod ReturnType: Void", "asyncExpectedResponse", ".", "block", "(", ")", ";", "result", "=", "null", ";", "}", "else", "{", "// ProxyMethod ReturnType: T where T != async (Mono, Flux) or sync Void", "// Block the deserialization until a value T is received", "result", "=", "asyncExpectedResponse", ".", "flatMap", "(", "httpResponse", "->", "handleRestResponseReturnType", "(", "httpResponse", ",", "methodParser", ",", "returnType", ")", ")", ".", "block", "(", ")", ";", "}", "return", "result", ";", "}" ]
Handle the provided asynchronous HTTP response and return the deserialized value. @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request @param methodParser the SwaggerMethodParser that the request originates from @param returnType the type of value that will be returned @return the deserialized result
[ "Handle", "the", "provided", "asynchronous", "HTTP", "response", "and", "return", "the", "deserialized", "value", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/common/azure-common/src/main/java/com/azure/common/implementation/RestProxy.java#L488-L516
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/labeled/textfield/LabeledPasswordTextFieldPanel.java
LabeledPasswordTextFieldPanel.newPasswordTextField
protected PasswordTextField newPasswordTextField(final String id, final IModel<M> model) { """ Factory method for create the new {@link PasswordTextField}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link PasswordTextField}. @param id the id @param model the model @return the new {@link PasswordTextField} """ return ComponentFactory.newPasswordTextField(id, new PropertyModel<String>(model.getObject(), getId())); }
java
protected PasswordTextField newPasswordTextField(final String id, final IModel<M> model) { return ComponentFactory.newPasswordTextField(id, new PropertyModel<String>(model.getObject(), getId())); }
[ "protected", "PasswordTextField", "newPasswordTextField", "(", "final", "String", "id", ",", "final", "IModel", "<", "M", ">", "model", ")", "{", "return", "ComponentFactory", ".", "newPasswordTextField", "(", "id", ",", "new", "PropertyModel", "<", "String", ">", "(", "model", ".", "getObject", "(", ")", ",", "getId", "(", ")", ")", ")", ";", "}" ]
Factory method for create the new {@link PasswordTextField}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link PasswordTextField}. @param id the id @param model the model @return the new {@link PasswordTextField}
[ "Factory", "method", "for", "create", "the", "new", "{", "@link", "PasswordTextField", "}", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridden", "so", "users", "can", "provide", "their", "own", "version", "of", "a", "new", "{", "@link", "PasswordTextField", "}", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/labeled/textfield/LabeledPasswordTextFieldPanel.java#L92-L96
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.listPrebuiltEntitiesAsync
public Observable<List<AvailablePrebuiltEntityModel>> listPrebuiltEntitiesAsync(UUID appId, String versionId) { """ Gets all the available prebuilt entity extractors for the application. @param appId The application ID. @param versionId The version ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;AvailablePrebuiltEntityModel&gt; object """ return listPrebuiltEntitiesWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<AvailablePrebuiltEntityModel>>, List<AvailablePrebuiltEntityModel>>() { @Override public List<AvailablePrebuiltEntityModel> call(ServiceResponse<List<AvailablePrebuiltEntityModel>> response) { return response.body(); } }); }
java
public Observable<List<AvailablePrebuiltEntityModel>> listPrebuiltEntitiesAsync(UUID appId, String versionId) { return listPrebuiltEntitiesWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<List<AvailablePrebuiltEntityModel>>, List<AvailablePrebuiltEntityModel>>() { @Override public List<AvailablePrebuiltEntityModel> call(ServiceResponse<List<AvailablePrebuiltEntityModel>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "AvailablePrebuiltEntityModel", ">", ">", "listPrebuiltEntitiesAsync", "(", "UUID", "appId", ",", "String", "versionId", ")", "{", "return", "listPrebuiltEntitiesWithServiceResponseAsync", "(", "appId", ",", "versionId", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "List", "<", "AvailablePrebuiltEntityModel", ">", ">", ",", "List", "<", "AvailablePrebuiltEntityModel", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "AvailablePrebuiltEntityModel", ">", "call", "(", "ServiceResponse", "<", "List", "<", "AvailablePrebuiltEntityModel", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets all the available prebuilt entity extractors for the application. @param appId The application ID. @param versionId The version ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;AvailablePrebuiltEntityModel&gt; object
[ "Gets", "all", "the", "available", "prebuilt", "entity", "extractors", "for", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L2384-L2391
davidmarquis/fluent-interface-proxy
src/main/java/com/fluentinterface/beans/ObjectWrapper.java
ObjectWrapper.getMappedValue
@SuppressWarnings("unchecked") private static Object getMappedValue(Object obj, Property property, Object key) { """ /* Internal: Static version of {@link ObjectWrapper#getMappedValue(Property, Object)}. """ if (property == null) { throw new IllegalArgumentException("Cannot get the mapped value from a 'null' property."); } if (property.getType().isAssignableFrom(Map.class)) { Map<Object, Object> map = (Map<Object, Object>) property.get(obj); if (map == null) { throw new NullPointerException("Invalid 'null' value found for mapped " + property + " in " + obj.getClass().getName() + "."); } return map.get(key); } else { throw new IllegalArgumentException("Cannot get a mapped value from the not mapped " + property + ". Only Map type is supported, but " + property.getType().getSimpleName() + " found."); } }
java
@SuppressWarnings("unchecked") private static Object getMappedValue(Object obj, Property property, Object key) { if (property == null) { throw new IllegalArgumentException("Cannot get the mapped value from a 'null' property."); } if (property.getType().isAssignableFrom(Map.class)) { Map<Object, Object> map = (Map<Object, Object>) property.get(obj); if (map == null) { throw new NullPointerException("Invalid 'null' value found for mapped " + property + " in " + obj.getClass().getName() + "."); } return map.get(key); } else { throw new IllegalArgumentException("Cannot get a mapped value from the not mapped " + property + ". Only Map type is supported, but " + property.getType().getSimpleName() + " found."); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "Object", "getMappedValue", "(", "Object", "obj", ",", "Property", "property", ",", "Object", "key", ")", "{", "if", "(", "property", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot get the mapped value from a 'null' property.\"", ")", ";", "}", "if", "(", "property", ".", "getType", "(", ")", ".", "isAssignableFrom", "(", "Map", ".", "class", ")", ")", "{", "Map", "<", "Object", ",", "Object", ">", "map", "=", "(", "Map", "<", "Object", ",", "Object", ">", ")", "property", ".", "get", "(", "obj", ")", ";", "if", "(", "map", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Invalid 'null' value found for mapped \"", "+", "property", "+", "\" in \"", "+", "obj", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", ")", ";", "}", "return", "map", ".", "get", "(", "key", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot get a mapped value from the not mapped \"", "+", "property", "+", "\". Only Map type is supported, but \"", "+", "property", ".", "getType", "(", ")", ".", "getSimpleName", "(", ")", "+", "\" found.\"", ")", ";", "}", "}" ]
/* Internal: Static version of {@link ObjectWrapper#getMappedValue(Property, Object)}.
[ "/", "*", "Internal", ":", "Static", "version", "of", "{" ]
train
https://github.com/davidmarquis/fluent-interface-proxy/blob/8e72fff6cd1f496c76a01773269caead994fea65/src/main/java/com/fluentinterface/beans/ObjectWrapper.java#L648-L668
bozaro/git-lfs-java
gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/internal/BatchWorker.java
BatchWorker.submitTask
private void submitTask(@NotNull State<T, R> state, @NotNull BatchItem item, @NotNull Link auth) { """ Submit object processing task. @param state Current object state @param item Metadata information with upload/download urls. @param auth Urls authentication state. """ // Submit task final StateHolder holder = new StateHolder(state); try { state.auth = auth; final Work<R> worker = objectTask(state, item); if (state.future.isDone()) { holder.close(); return; } if (worker == null) { throw new IllegalStateException("Uncompleted task worker is null: " + item); } executeInPool( "task: " + state.getMeta().getOid(), () -> processObject(state, auth, worker), holder::close, true ); } catch (Throwable e) { holder.close(); throw e; } }
java
private void submitTask(@NotNull State<T, R> state, @NotNull BatchItem item, @NotNull Link auth) { // Submit task final StateHolder holder = new StateHolder(state); try { state.auth = auth; final Work<R> worker = objectTask(state, item); if (state.future.isDone()) { holder.close(); return; } if (worker == null) { throw new IllegalStateException("Uncompleted task worker is null: " + item); } executeInPool( "task: " + state.getMeta().getOid(), () -> processObject(state, auth, worker), holder::close, true ); } catch (Throwable e) { holder.close(); throw e; } }
[ "private", "void", "submitTask", "(", "@", "NotNull", "State", "<", "T", ",", "R", ">", "state", ",", "@", "NotNull", "BatchItem", "item", ",", "@", "NotNull", "Link", "auth", ")", "{", "// Submit task", "final", "StateHolder", "holder", "=", "new", "StateHolder", "(", "state", ")", ";", "try", "{", "state", ".", "auth", "=", "auth", ";", "final", "Work", "<", "R", ">", "worker", "=", "objectTask", "(", "state", ",", "item", ")", ";", "if", "(", "state", ".", "future", ".", "isDone", "(", ")", ")", "{", "holder", ".", "close", "(", ")", ";", "return", ";", "}", "if", "(", "worker", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Uncompleted task worker is null: \"", "+", "item", ")", ";", "}", "executeInPool", "(", "\"task: \"", "+", "state", ".", "getMeta", "(", ")", ".", "getOid", "(", ")", ",", "(", ")", "->", "processObject", "(", "state", ",", "auth", ",", "worker", ")", ",", "holder", "::", "close", ",", "true", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "holder", ".", "close", "(", ")", ";", "throw", "e", ";", "}", "}" ]
Submit object processing task. @param state Current object state @param item Metadata information with upload/download urls. @param auth Urls authentication state.
[ "Submit", "object", "processing", "task", "." ]
train
https://github.com/bozaro/git-lfs-java/blob/ee05bf0472ee61bf362cf93d283e5ee5d44ef685/gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/internal/BatchWorker.java#L208-L231
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FastHessianFeatureDetector.java
FastHessianFeatureDetector.findLocalScaleSpaceMax
private void findLocalScaleSpaceMax(int []size, int level, int skip) { """ Looks for features which are local maximums in the image and scale-space. @param size Size of features in different scale-spaces. @param level Which level in the scale-space @param skip How many pixels are skipped over. """ int index0 = spaceIndex; int index1 = (spaceIndex + 1) % 3; int index2 = (spaceIndex + 2) % 3; ImageBorder_F32 inten0 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index0], 0); GrayF32 inten1 = intensity[index1]; ImageBorder_F32 inten2 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index2], 0); // find local maximums in image 2D space. Borders need to be ignored since // false positives are found around them as an artifact of pixels outside being // treated as being zero. foundFeatures.reset(); extractor.setIgnoreBorder(size[level] / (2 * skip)); extractor.process(intensity[index1],null,null,null,foundFeatures); // Can't consider feature which are right up against the border since they might not be a true local // maximum when you consider the features on the other side of the ignore border int ignoreRadius = extractor.getIgnoreBorder() + extractor.getSearchRadius(); int ignoreWidth = intensity[index1].width-ignoreRadius; int ignoreHeight = intensity[index1].height-ignoreRadius; // number of features which can be added int numberRemaining; // if configured to do so, only select the features with the highest intensity QueueCorner features; if( sortBest != null ) { sortBest.process(intensity[index1],foundFeatures,true); features = sortBest.getBestCorners(); numberRemaining = maxFeaturesPerScale; } else { features = foundFeatures; numberRemaining = Integer.MAX_VALUE; } int levelSize = size[level]; int sizeStep = levelSize-size[level-1]; // see if these local maximums are also a maximum in scale-space for( int i = 0; i < features.size && numberRemaining > 0; i++ ) { Point2D_I16 f = features.get(i); // avoid false positives. see above comment if( f.x < ignoreRadius || f.x >= ignoreWidth || f.y < ignoreRadius || f.y >= ignoreHeight ) continue; float val = inten1.get(f.x,f.y); // see if it is a max in scale-space too if( checkMax(inten0,val,f.x,f.y) && checkMax(inten2,val,f.x,f.y) ) { // find the feature's location to sub-pixel accuracy using a second order polynomial // NOTE: In the original paper this was done using a quadratic. See comments above. // NOTE: Using a 2D polynomial for x and y might produce better results. float peakX = polyPeak(inten1.get(f.x-1,f.y),inten1.get(f.x,f.y),inten1.get(f.x+1,f.y)); float peakY = polyPeak(inten1.get(f.x,f.y-1),inten1.get(f.x,f.y),inten1.get(f.x,f.y+1)); float peakS = polyPeak(inten0.get(f.x,f.y),inten1.get(f.x,f.y),inten2.get(f.x,f.y)); float interpX = (f.x+peakX)*skip; float interpY = (f.y+peakY)*skip; float interpS = levelSize+peakS*sizeStep; double scale = 1.2*interpS/9.0; foundPoints.grow().set(interpX,interpY,scale); numberRemaining--; } } }
java
private void findLocalScaleSpaceMax(int []size, int level, int skip) { int index0 = spaceIndex; int index1 = (spaceIndex + 1) % 3; int index2 = (spaceIndex + 2) % 3; ImageBorder_F32 inten0 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index0], 0); GrayF32 inten1 = intensity[index1]; ImageBorder_F32 inten2 = (ImageBorder_F32)FactoryImageBorderAlgs.value(intensity[index2], 0); // find local maximums in image 2D space. Borders need to be ignored since // false positives are found around them as an artifact of pixels outside being // treated as being zero. foundFeatures.reset(); extractor.setIgnoreBorder(size[level] / (2 * skip)); extractor.process(intensity[index1],null,null,null,foundFeatures); // Can't consider feature which are right up against the border since they might not be a true local // maximum when you consider the features on the other side of the ignore border int ignoreRadius = extractor.getIgnoreBorder() + extractor.getSearchRadius(); int ignoreWidth = intensity[index1].width-ignoreRadius; int ignoreHeight = intensity[index1].height-ignoreRadius; // number of features which can be added int numberRemaining; // if configured to do so, only select the features with the highest intensity QueueCorner features; if( sortBest != null ) { sortBest.process(intensity[index1],foundFeatures,true); features = sortBest.getBestCorners(); numberRemaining = maxFeaturesPerScale; } else { features = foundFeatures; numberRemaining = Integer.MAX_VALUE; } int levelSize = size[level]; int sizeStep = levelSize-size[level-1]; // see if these local maximums are also a maximum in scale-space for( int i = 0; i < features.size && numberRemaining > 0; i++ ) { Point2D_I16 f = features.get(i); // avoid false positives. see above comment if( f.x < ignoreRadius || f.x >= ignoreWidth || f.y < ignoreRadius || f.y >= ignoreHeight ) continue; float val = inten1.get(f.x,f.y); // see if it is a max in scale-space too if( checkMax(inten0,val,f.x,f.y) && checkMax(inten2,val,f.x,f.y) ) { // find the feature's location to sub-pixel accuracy using a second order polynomial // NOTE: In the original paper this was done using a quadratic. See comments above. // NOTE: Using a 2D polynomial for x and y might produce better results. float peakX = polyPeak(inten1.get(f.x-1,f.y),inten1.get(f.x,f.y),inten1.get(f.x+1,f.y)); float peakY = polyPeak(inten1.get(f.x,f.y-1),inten1.get(f.x,f.y),inten1.get(f.x,f.y+1)); float peakS = polyPeak(inten0.get(f.x,f.y),inten1.get(f.x,f.y),inten2.get(f.x,f.y)); float interpX = (f.x+peakX)*skip; float interpY = (f.y+peakY)*skip; float interpS = levelSize+peakS*sizeStep; double scale = 1.2*interpS/9.0; foundPoints.grow().set(interpX,interpY,scale); numberRemaining--; } } }
[ "private", "void", "findLocalScaleSpaceMax", "(", "int", "[", "]", "size", ",", "int", "level", ",", "int", "skip", ")", "{", "int", "index0", "=", "spaceIndex", ";", "int", "index1", "=", "(", "spaceIndex", "+", "1", ")", "%", "3", ";", "int", "index2", "=", "(", "spaceIndex", "+", "2", ")", "%", "3", ";", "ImageBorder_F32", "inten0", "=", "(", "ImageBorder_F32", ")", "FactoryImageBorderAlgs", ".", "value", "(", "intensity", "[", "index0", "]", ",", "0", ")", ";", "GrayF32", "inten1", "=", "intensity", "[", "index1", "]", ";", "ImageBorder_F32", "inten2", "=", "(", "ImageBorder_F32", ")", "FactoryImageBorderAlgs", ".", "value", "(", "intensity", "[", "index2", "]", ",", "0", ")", ";", "// find local maximums in image 2D space. Borders need to be ignored since", "// false positives are found around them as an artifact of pixels outside being", "// treated as being zero.", "foundFeatures", ".", "reset", "(", ")", ";", "extractor", ".", "setIgnoreBorder", "(", "size", "[", "level", "]", "/", "(", "2", "*", "skip", ")", ")", ";", "extractor", ".", "process", "(", "intensity", "[", "index1", "]", ",", "null", ",", "null", ",", "null", ",", "foundFeatures", ")", ";", "// Can't consider feature which are right up against the border since they might not be a true local", "// maximum when you consider the features on the other side of the ignore border", "int", "ignoreRadius", "=", "extractor", ".", "getIgnoreBorder", "(", ")", "+", "extractor", ".", "getSearchRadius", "(", ")", ";", "int", "ignoreWidth", "=", "intensity", "[", "index1", "]", ".", "width", "-", "ignoreRadius", ";", "int", "ignoreHeight", "=", "intensity", "[", "index1", "]", ".", "height", "-", "ignoreRadius", ";", "// number of features which can be added", "int", "numberRemaining", ";", "// if configured to do so, only select the features with the highest intensity", "QueueCorner", "features", ";", "if", "(", "sortBest", "!=", "null", ")", "{", "sortBest", ".", "process", "(", "intensity", "[", "index1", "]", ",", "foundFeatures", ",", "true", ")", ";", "features", "=", "sortBest", ".", "getBestCorners", "(", ")", ";", "numberRemaining", "=", "maxFeaturesPerScale", ";", "}", "else", "{", "features", "=", "foundFeatures", ";", "numberRemaining", "=", "Integer", ".", "MAX_VALUE", ";", "}", "int", "levelSize", "=", "size", "[", "level", "]", ";", "int", "sizeStep", "=", "levelSize", "-", "size", "[", "level", "-", "1", "]", ";", "// see if these local maximums are also a maximum in scale-space", "for", "(", "int", "i", "=", "0", ";", "i", "<", "features", ".", "size", "&&", "numberRemaining", ">", "0", ";", "i", "++", ")", "{", "Point2D_I16", "f", "=", "features", ".", "get", "(", "i", ")", ";", "// avoid false positives. see above comment", "if", "(", "f", ".", "x", "<", "ignoreRadius", "||", "f", ".", "x", ">=", "ignoreWidth", "||", "f", ".", "y", "<", "ignoreRadius", "||", "f", ".", "y", ">=", "ignoreHeight", ")", "continue", ";", "float", "val", "=", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ";", "// see if it is a max in scale-space too", "if", "(", "checkMax", "(", "inten0", ",", "val", ",", "f", ".", "x", ",", "f", ".", "y", ")", "&&", "checkMax", "(", "inten2", ",", "val", ",", "f", ".", "x", ",", "f", ".", "y", ")", ")", "{", "// find the feature's location to sub-pixel accuracy using a second order polynomial", "// NOTE: In the original paper this was done using a quadratic. See comments above.", "// NOTE: Using a 2D polynomial for x and y might produce better results.", "float", "peakX", "=", "polyPeak", "(", "inten1", ".", "get", "(", "f", ".", "x", "-", "1", ",", "f", ".", "y", ")", ",", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ",", "inten1", ".", "get", "(", "f", ".", "x", "+", "1", ",", "f", ".", "y", ")", ")", ";", "float", "peakY", "=", "polyPeak", "(", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", "-", "1", ")", ",", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ",", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", "+", "1", ")", ")", ";", "float", "peakS", "=", "polyPeak", "(", "inten0", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ",", "inten1", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ",", "inten2", ".", "get", "(", "f", ".", "x", ",", "f", ".", "y", ")", ")", ";", "float", "interpX", "=", "(", "f", ".", "x", "+", "peakX", ")", "*", "skip", ";", "float", "interpY", "=", "(", "f", ".", "y", "+", "peakY", ")", "*", "skip", ";", "float", "interpS", "=", "levelSize", "+", "peakS", "*", "sizeStep", ";", "double", "scale", "=", "1.2", "*", "interpS", "/", "9.0", ";", "foundPoints", ".", "grow", "(", ")", ".", "set", "(", "interpX", ",", "interpY", ",", "scale", ")", ";", "numberRemaining", "--", ";", "}", "}", "}" ]
Looks for features which are local maximums in the image and scale-space. @param size Size of features in different scale-spaces. @param level Which level in the scale-space @param skip How many pixels are skipped over.
[ "Looks", "for", "features", "which", "are", "local", "maximums", "in", "the", "image", "and", "scale", "-", "space", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FastHessianFeatureDetector.java#L230-L298
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java
MutateInBuilder.arrayAppend
public <T> MutateInBuilder arrayAppend(String path, T value) { """ Append to an existing array, pushing the value to the back/last position in the array. @param path the path of the array. @param value the value to insert at the back of the array. """ asyncBuilder.arrayAppend(path, value); return this; }
java
public <T> MutateInBuilder arrayAppend(String path, T value) { asyncBuilder.arrayAppend(path, value); return this; }
[ "public", "<", "T", ">", "MutateInBuilder", "arrayAppend", "(", "String", "path", ",", "T", "value", ")", "{", "asyncBuilder", ".", "arrayAppend", "(", "path", ",", "value", ")", ";", "return", "this", ";", "}" ]
Append to an existing array, pushing the value to the back/last position in the array. @param path the path of the array. @param value the value to insert at the back of the array.
[ "Append", "to", "an", "existing", "array", "pushing", "the", "value", "to", "the", "back", "/", "last", "position", "in", "the", "array", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L821-L824
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java
SSLAlpnNegotiator.tryToRemoveAlpnNegotiator
protected void tryToRemoveAlpnNegotiator(ThirdPartyAlpnNegotiator negotiator, SSLEngine engine, SSLConnectionLink link) { """ If ALPN is active, try to remove the ThirdPartyAlpnNegotiator from the map of active negotiators @param ThirdPartyAlpnNegotiator @param SSLEngine @param SSLConnectionLink """ // the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object if (negotiator == null && isNativeAlpnActive()) { getNativeAlpnChoice(engine, link); } else if (negotiator == null && isIbmAlpnActive()) { getAndRemoveIbmAlpnChoice(engine, link); } else if (negotiator != null && isJettyAlpnActive() && negotiator instanceof JettyServerNegotiator) { ((JettyServerNegotiator) negotiator).removeEngine(); } else if (negotiator != null && isGrizzlyAlpnActive() && negotiator instanceof GrizzlyAlpnNegotiator) { ((GrizzlyAlpnNegotiator) negotiator).removeServerNegotiatorEngine(); } }
java
protected void tryToRemoveAlpnNegotiator(ThirdPartyAlpnNegotiator negotiator, SSLEngine engine, SSLConnectionLink link) { // the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object if (negotiator == null && isNativeAlpnActive()) { getNativeAlpnChoice(engine, link); } else if (negotiator == null && isIbmAlpnActive()) { getAndRemoveIbmAlpnChoice(engine, link); } else if (negotiator != null && isJettyAlpnActive() && negotiator instanceof JettyServerNegotiator) { ((JettyServerNegotiator) negotiator).removeEngine(); } else if (negotiator != null && isGrizzlyAlpnActive() && negotiator instanceof GrizzlyAlpnNegotiator) { ((GrizzlyAlpnNegotiator) negotiator).removeServerNegotiatorEngine(); } }
[ "protected", "void", "tryToRemoveAlpnNegotiator", "(", "ThirdPartyAlpnNegotiator", "negotiator", ",", "SSLEngine", "engine", ",", "SSLConnectionLink", "link", ")", "{", "// the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object", "if", "(", "negotiator", "==", "null", "&&", "isNativeAlpnActive", "(", ")", ")", "{", "getNativeAlpnChoice", "(", "engine", ",", "link", ")", ";", "}", "else", "if", "(", "negotiator", "==", "null", "&&", "isIbmAlpnActive", "(", ")", ")", "{", "getAndRemoveIbmAlpnChoice", "(", "engine", ",", "link", ")", ";", "}", "else", "if", "(", "negotiator", "!=", "null", "&&", "isJettyAlpnActive", "(", ")", "&&", "negotiator", "instanceof", "JettyServerNegotiator", ")", "{", "(", "(", "JettyServerNegotiator", ")", "negotiator", ")", ".", "removeEngine", "(", ")", ";", "}", "else", "if", "(", "negotiator", "!=", "null", "&&", "isGrizzlyAlpnActive", "(", ")", "&&", "negotiator", "instanceof", "GrizzlyAlpnNegotiator", ")", "{", "(", "(", "GrizzlyAlpnNegotiator", ")", "negotiator", ")", ".", "removeServerNegotiatorEngine", "(", ")", ";", "}", "}" ]
If ALPN is active, try to remove the ThirdPartyAlpnNegotiator from the map of active negotiators @param ThirdPartyAlpnNegotiator @param SSLEngine @param SSLConnectionLink
[ "If", "ALPN", "is", "active", "try", "to", "remove", "the", "ThirdPartyAlpnNegotiator", "from", "the", "map", "of", "active", "negotiators" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLAlpnNegotiator.java#L224-L235
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java
CommerceSubscriptionEntryPersistenceImpl.removeByUuid_C
@Override public void removeByUuid_C(String uuid, long companyId) { """ Removes all the commerce subscription entries where uuid = &#63; and companyId = &#63; from the database. @param uuid the uuid @param companyId the company ID """ for (CommerceSubscriptionEntry commerceSubscriptionEntry : findByUuid_C( uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceSubscriptionEntry); } }
java
@Override public void removeByUuid_C(String uuid, long companyId) { for (CommerceSubscriptionEntry commerceSubscriptionEntry : findByUuid_C( uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceSubscriptionEntry); } }
[ "@", "Override", "public", "void", "removeByUuid_C", "(", "String", "uuid", ",", "long", "companyId", ")", "{", "for", "(", "CommerceSubscriptionEntry", "commerceSubscriptionEntry", ":", "findByUuid_C", "(", "uuid", ",", "companyId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "commerceSubscriptionEntry", ")", ";", "}", "}" ]
Removes all the commerce subscription entries where uuid = &#63; and companyId = &#63; from the database. @param uuid the uuid @param companyId the company ID
[ "Removes", "all", "the", "commerce", "subscription", "entries", "where", "uuid", "=", "&#63", ";", "and", "companyId", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceSubscriptionEntryPersistenceImpl.java#L1425-L1431
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/categories/image.java
image.storeImage
public static void storeImage(Bitmap image, File pictureFile) { """ Stores an image on the storage @param image the image to store. @param pictureFile the file in which it must be stored """ if (pictureFile == null) { QuickUtils.log.d("Error creating media file, check storage permissions: "); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); image.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { QuickUtils.log.d("File not found: " + e.getMessage()); } catch (IOException e) { QuickUtils.log.d("Error accessing file: " + e.getMessage()); } }
java
public static void storeImage(Bitmap image, File pictureFile) { if (pictureFile == null) { QuickUtils.log.d("Error creating media file, check storage permissions: "); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); image.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { QuickUtils.log.d("File not found: " + e.getMessage()); } catch (IOException e) { QuickUtils.log.d("Error accessing file: " + e.getMessage()); } }
[ "public", "static", "void", "storeImage", "(", "Bitmap", "image", ",", "File", "pictureFile", ")", "{", "if", "(", "pictureFile", "==", "null", ")", "{", "QuickUtils", ".", "log", ".", "d", "(", "\"Error creating media file, check storage permissions: \"", ")", ";", "return", ";", "}", "try", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "pictureFile", ")", ";", "image", ".", "compress", "(", "Bitmap", ".", "CompressFormat", ".", "PNG", ",", "90", ",", "fos", ")", ";", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "QuickUtils", ".", "log", ".", "d", "(", "\"File not found: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "QuickUtils", ".", "log", ".", "d", "(", "\"Error accessing file: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Stores an image on the storage @param image the image to store. @param pictureFile the file in which it must be stored
[ "Stores", "an", "image", "on", "the", "storage" ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/categories/image.java#L188-L202
tvesalainen/util
util/src/main/java/org/vesalainen/navi/AnchorageSimulator.java
AnchorageSimulator.simulate
public void simulate(LocationSource locationSource, long period, boolean isDaemon) throws IOException { """ Starts simulating anchorige. @param locationSource @param period Update rate in millis. @param isDaemon Sets timer thread. In single thread this should be false. This parament is used only if external Timer was not provided! @throws IOException """ this.locationSource = locationSource; dis = new DataInputStream(new BufferedInputStream(url.openStream())); if (timer == null) { timer = new Timer("AnchorageSimulator", isDaemon); } timer.scheduleAtFixedRate(this, 0, period); }
java
public void simulate(LocationSource locationSource, long period, boolean isDaemon) throws IOException { this.locationSource = locationSource; dis = new DataInputStream(new BufferedInputStream(url.openStream())); if (timer == null) { timer = new Timer("AnchorageSimulator", isDaemon); } timer.scheduleAtFixedRate(this, 0, period); }
[ "public", "void", "simulate", "(", "LocationSource", "locationSource", ",", "long", "period", ",", "boolean", "isDaemon", ")", "throws", "IOException", "{", "this", ".", "locationSource", "=", "locationSource", ";", "dis", "=", "new", "DataInputStream", "(", "new", "BufferedInputStream", "(", "url", ".", "openStream", "(", ")", ")", ")", ";", "if", "(", "timer", "==", "null", ")", "{", "timer", "=", "new", "Timer", "(", "\"AnchorageSimulator\"", ",", "isDaemon", ")", ";", "}", "timer", ".", "scheduleAtFixedRate", "(", "this", ",", "0", ",", "period", ")", ";", "}" ]
Starts simulating anchorige. @param locationSource @param period Update rate in millis. @param isDaemon Sets timer thread. In single thread this should be false. This parament is used only if external Timer was not provided! @throws IOException
[ "Starts", "simulating", "anchorige", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/navi/AnchorageSimulator.java#L61-L70
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java
PDLucene.readLockedAtomic
@Nullable public <T> T readLockedAtomic (@Nonnull final IThrowingSupplier <T, IOException> aRunnable) throws IOException { """ Run the provided action within a locked section.<br> Note: because of a problem with JDK 1.8.60 (+) command line compiler, this method uses type "Exception" instead of "IOException" in the parameter signature @param aRunnable Callback to be executed. @return <code>null</code> if the index is just closing @throws IOException may be thrown by the callback @param <T> Result type """ m_aRWLock.readLock ().lock (); try { if (isClosing ()) LOGGER.info ("Cannot executed something read locked, because Lucene is shutting down"); else return aRunnable.get (); } finally { m_aRWLock.readLock ().unlock (); } return null; }
java
@Nullable public <T> T readLockedAtomic (@Nonnull final IThrowingSupplier <T, IOException> aRunnable) throws IOException { m_aRWLock.readLock ().lock (); try { if (isClosing ()) LOGGER.info ("Cannot executed something read locked, because Lucene is shutting down"); else return aRunnable.get (); } finally { m_aRWLock.readLock ().unlock (); } return null; }
[ "@", "Nullable", "public", "<", "T", ">", "T", "readLockedAtomic", "(", "@", "Nonnull", "final", "IThrowingSupplier", "<", "T", ",", "IOException", ">", "aRunnable", ")", "throws", "IOException", "{", "m_aRWLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "isClosing", "(", ")", ")", "LOGGER", ".", "info", "(", "\"Cannot executed something read locked, because Lucene is shutting down\"", ")", ";", "else", "return", "aRunnable", ".", "get", "(", ")", ";", "}", "finally", "{", "m_aRWLock", ".", "readLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "return", "null", ";", "}" ]
Run the provided action within a locked section.<br> Note: because of a problem with JDK 1.8.60 (+) command line compiler, this method uses type "Exception" instead of "IOException" in the parameter signature @param aRunnable Callback to be executed. @return <code>null</code> if the index is just closing @throws IOException may be thrown by the callback @param <T> Result type
[ "Run", "the", "provided", "action", "within", "a", "locked", "section", ".", "<br", ">", "Note", ":", "because", "of", "a", "problem", "with", "JDK", "1", ".", "8", ".", "60", "(", "+", ")", "command", "line", "compiler", "this", "method", "uses", "type", "Exception", "instead", "of", "IOException", "in", "the", "parameter", "signature" ]
train
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java#L415-L431
lestard/advanced-bindings
src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java
MathBindings.addExact
public static IntegerBinding addExact(final ObservableIntegerValue x, final ObservableIntegerValue y) { """ Binding for {@link java.lang.Math#addExact(int, int)} @param x the first value @param y the second value @return the result @throws ArithmeticException if the result overflows an int """ return createIntegerBinding(() -> Math.addExact(x.get(), y.get()), x, y); }
java
public static IntegerBinding addExact(final ObservableIntegerValue x, final ObservableIntegerValue y) { return createIntegerBinding(() -> Math.addExact(x.get(), y.get()), x, y); }
[ "public", "static", "IntegerBinding", "addExact", "(", "final", "ObservableIntegerValue", "x", ",", "final", "ObservableIntegerValue", "y", ")", "{", "return", "createIntegerBinding", "(", "(", ")", "->", "Math", ".", "addExact", "(", "x", ".", "get", "(", ")", ",", "y", ".", "get", "(", ")", ")", ",", "x", ",", "y", ")", ";", "}" ]
Binding for {@link java.lang.Math#addExact(int, int)} @param x the first value @param y the second value @return the result @throws ArithmeticException if the result overflows an int
[ "Binding", "for", "{", "@link", "java", ".", "lang", ".", "Math#addExact", "(", "int", "int", ")", "}" ]
train
https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java#L92-L94
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
DMatrixUtils.roundDownTo
public static BigDecimal roundDownTo(double value, double steps) { """ Returns the DOWN rounded value of the given value for the given steps. @param value The original value to be rounded. @param steps The steps. @return The DOWN rounded value of the given value for the given steps. """ final BigDecimal bValue = BigDecimal.valueOf(value); final BigDecimal bSteps = BigDecimal.valueOf(steps); if (Objects.equals(bSteps, BigDecimal.ZERO)) { return bValue; } else { return bValue.divide(bSteps, 0, RoundingMode.FLOOR).multiply(bSteps); } }
java
public static BigDecimal roundDownTo(double value, double steps) { final BigDecimal bValue = BigDecimal.valueOf(value); final BigDecimal bSteps = BigDecimal.valueOf(steps); if (Objects.equals(bSteps, BigDecimal.ZERO)) { return bValue; } else { return bValue.divide(bSteps, 0, RoundingMode.FLOOR).multiply(bSteps); } }
[ "public", "static", "BigDecimal", "roundDownTo", "(", "double", "value", ",", "double", "steps", ")", "{", "final", "BigDecimal", "bValue", "=", "BigDecimal", ".", "valueOf", "(", "value", ")", ";", "final", "BigDecimal", "bSteps", "=", "BigDecimal", ".", "valueOf", "(", "steps", ")", ";", "if", "(", "Objects", ".", "equals", "(", "bSteps", ",", "BigDecimal", ".", "ZERO", ")", ")", "{", "return", "bValue", ";", "}", "else", "{", "return", "bValue", ".", "divide", "(", "bSteps", ",", "0", ",", "RoundingMode", ".", "FLOOR", ")", ".", "multiply", "(", "bSteps", ")", ";", "}", "}" ]
Returns the DOWN rounded value of the given value for the given steps. @param value The original value to be rounded. @param steps The steps. @return The DOWN rounded value of the given value for the given steps.
[ "Returns", "the", "DOWN", "rounded", "value", "of", "the", "given", "value", "for", "the", "given", "steps", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L311-L320
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ArabicShaping.java
ArabicShaping.shape
public void shape(char[] source, int start, int length) throws ArabicShapingException { """ Convert a range of text in place. This may only be used if the Length option does not grow or shrink the text. @param source An array containing the input text @param start The start of the range of text to convert @param length The length of the range of text to convert @throws ArabicShapingException if the text cannot be converted according to the options. """ if ((options & LAMALEF_MASK) == LAMALEF_RESIZE) { throw new ArabicShapingException("Cannot shape in place with length option resize."); } shape(source, start, length, source, start, length); }
java
public void shape(char[] source, int start, int length) throws ArabicShapingException { if ((options & LAMALEF_MASK) == LAMALEF_RESIZE) { throw new ArabicShapingException("Cannot shape in place with length option resize."); } shape(source, start, length, source, start, length); }
[ "public", "void", "shape", "(", "char", "[", "]", "source", ",", "int", "start", ",", "int", "length", ")", "throws", "ArabicShapingException", "{", "if", "(", "(", "options", "&", "LAMALEF_MASK", ")", "==", "LAMALEF_RESIZE", ")", "{", "throw", "new", "ArabicShapingException", "(", "\"Cannot shape in place with length option resize.\"", ")", ";", "}", "shape", "(", "source", ",", "start", ",", "length", ",", "source", ",", "start", ",", "length", ")", ";", "}" ]
Convert a range of text in place. This may only be used if the Length option does not grow or shrink the text. @param source An array containing the input text @param start The start of the range of text to convert @param length The length of the range of text to convert @throws ArabicShapingException if the text cannot be converted according to the options.
[ "Convert", "a", "range", "of", "text", "in", "place", ".", "This", "may", "only", "be", "used", "if", "the", "Length", "option", "does", "not", "grow", "or", "shrink", "the", "text", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ArabicShaping.java#L144-L149
wisdom-framework/wisdom
core/content-manager/src/main/java/org/wisdom/content/converters/ParamConverterEngine.java
ParamConverterEngine.convertValues
@Override public <T> T convertValues(Collection<String> input, Class<T> rawType, Type type, String defaultValue) throws IllegalArgumentException { """ Creates an instance of T from the given input. Unlike {@link #convertValue(String, Class, java.lang.reflect.Type, String)}, this method support multi-value parameters. @param input the input Strings, may be {@literal null} or empty @param rawType the target class @param type the type representation of the raw type, may contains metadata about generics @param defaultValue the default value if any @return the created object @throws IllegalArgumentException if there are no converter available from the type T at the moment """ if (rawType.isArray()) { if (input == null) { input = getMultipleValues(defaultValue, null); } return createArray(input, rawType.getComponentType()); } else if (Collection.class.isAssignableFrom(rawType)) { if (input == null) { input = getMultipleValues(defaultValue, null); } return createCollection(input, rawType, type); } else { return convertSingleValue(input, rawType, defaultValue); } }
java
@Override public <T> T convertValues(Collection<String> input, Class<T> rawType, Type type, String defaultValue) throws IllegalArgumentException { if (rawType.isArray()) { if (input == null) { input = getMultipleValues(defaultValue, null); } return createArray(input, rawType.getComponentType()); } else if (Collection.class.isAssignableFrom(rawType)) { if (input == null) { input = getMultipleValues(defaultValue, null); } return createCollection(input, rawType, type); } else { return convertSingleValue(input, rawType, defaultValue); } }
[ "@", "Override", "public", "<", "T", ">", "T", "convertValues", "(", "Collection", "<", "String", ">", "input", ",", "Class", "<", "T", ">", "rawType", ",", "Type", "type", ",", "String", "defaultValue", ")", "throws", "IllegalArgumentException", "{", "if", "(", "rawType", ".", "isArray", "(", ")", ")", "{", "if", "(", "input", "==", "null", ")", "{", "input", "=", "getMultipleValues", "(", "defaultValue", ",", "null", ")", ";", "}", "return", "createArray", "(", "input", ",", "rawType", ".", "getComponentType", "(", ")", ")", ";", "}", "else", "if", "(", "Collection", ".", "class", ".", "isAssignableFrom", "(", "rawType", ")", ")", "{", "if", "(", "input", "==", "null", ")", "{", "input", "=", "getMultipleValues", "(", "defaultValue", ",", "null", ")", ";", "}", "return", "createCollection", "(", "input", ",", "rawType", ",", "type", ")", ";", "}", "else", "{", "return", "convertSingleValue", "(", "input", ",", "rawType", ",", "defaultValue", ")", ";", "}", "}" ]
Creates an instance of T from the given input. Unlike {@link #convertValue(String, Class, java.lang.reflect.Type, String)}, this method support multi-value parameters. @param input the input Strings, may be {@literal null} or empty @param rawType the target class @param type the type representation of the raw type, may contains metadata about generics @param defaultValue the default value if any @return the created object @throws IllegalArgumentException if there are no converter available from the type T at the moment
[ "Creates", "an", "instance", "of", "T", "from", "the", "given", "input", ".", "Unlike", "{", "@link", "#convertValue", "(", "String", "Class", "java", ".", "lang", ".", "reflect", ".", "Type", "String", ")", "}", "this", "method", "support", "multi", "-", "value", "parameters", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/content-manager/src/main/java/org/wisdom/content/converters/ParamConverterEngine.java#L111-L126
fuinorg/utils4j
src/main/java/org/fuin/utils4j/filter/TokenFilter.java
TokenFilter.complies
protected final boolean complies(final String value, final String constValue, final String separators) { """ Helper method for subclasses to do the comparation. @param value Object that contains the property. @param constValue Value to compare with. @param separators Separators @return If object property contains the value as one of the tokens TRUE else FALSE. """ if (value == null) { return false; } else { final StringTokenizer tok = new StringTokenizer(value, separators); while (tok.hasMoreTokens()) { final String t = tok.nextToken(); if (t.equals(constValue)) { return true; } } return false; } }
java
protected final boolean complies(final String value, final String constValue, final String separators) { if (value == null) { return false; } else { final StringTokenizer tok = new StringTokenizer(value, separators); while (tok.hasMoreTokens()) { final String t = tok.nextToken(); if (t.equals(constValue)) { return true; } } return false; } }
[ "protected", "final", "boolean", "complies", "(", "final", "String", "value", ",", "final", "String", "constValue", ",", "final", "String", "separators", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "false", ";", "}", "else", "{", "final", "StringTokenizer", "tok", "=", "new", "StringTokenizer", "(", "value", ",", "separators", ")", ";", "while", "(", "tok", ".", "hasMoreTokens", "(", ")", ")", "{", "final", "String", "t", "=", "tok", ".", "nextToken", "(", ")", ";", "if", "(", "t", ".", "equals", "(", "constValue", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "}" ]
Helper method for subclasses to do the comparation. @param value Object that contains the property. @param constValue Value to compare with. @param separators Separators @return If object property contains the value as one of the tokens TRUE else FALSE.
[ "Helper", "method", "for", "subclasses", "to", "do", "the", "comparation", "." ]
train
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/filter/TokenFilter.java#L80-L94
apereo/cas
core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/MultifactorAuthenticationUtils.java
MultifactorAuthenticationUtils.resolveProvider
public static Optional<MultifactorAuthenticationProvider> resolveProvider(final Map<String, MultifactorAuthenticationProvider> providers, final String requestMfaMethod) { """ Resolve provider optional. @param providers the providers @param requestMfaMethod the request mfa method @return the optional """ return resolveProvider(providers, Stream.of(requestMfaMethod).collect(Collectors.toList())); }
java
public static Optional<MultifactorAuthenticationProvider> resolveProvider(final Map<String, MultifactorAuthenticationProvider> providers, final String requestMfaMethod) { return resolveProvider(providers, Stream.of(requestMfaMethod).collect(Collectors.toList())); }
[ "public", "static", "Optional", "<", "MultifactorAuthenticationProvider", ">", "resolveProvider", "(", "final", "Map", "<", "String", ",", "MultifactorAuthenticationProvider", ">", "providers", ",", "final", "String", "requestMfaMethod", ")", "{", "return", "resolveProvider", "(", "providers", ",", "Stream", ".", "of", "(", "requestMfaMethod", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}" ]
Resolve provider optional. @param providers the providers @param requestMfaMethod the request mfa method @return the optional
[ "Resolve", "provider", "optional", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-mfa-api/src/main/java/org/apereo/cas/authentication/MultifactorAuthenticationUtils.java#L139-L142
ModeShape/modeshape
sequencers/modeshape-sequencer-java/src/main/java/org/modeshape/sequencer/javafile/AbstractJavaMetadata.java
AbstractJavaMetadata.processParameterizedType
protected FieldMetadata processParameterizedType( FieldDeclaration fieldDeclaration ) { """ Process the parameterized type of a {@link FieldDeclaration}. @param fieldDeclaration - the field declaration. @return ParameterizedTypeFieldMetadata. """ ParameterizedType parameterizedType = (ParameterizedType)fieldDeclaration.getType(); Type typeOfParameterizedType = parameterizedType.getType(); // type may be a simple type or a qualified type. FieldMetadata referenceFieldMetadata = createParameterizedFieldMetadataFrom(typeOfParameterizedType); // modifiers processModifiersOfFieldDeclaration(fieldDeclaration, referenceFieldMetadata); // variables referenceFieldMetadata.setName(getFieldName(fieldDeclaration)); processVariablesOfVariableDeclarationFragment(fieldDeclaration, referenceFieldMetadata); return referenceFieldMetadata; }
java
protected FieldMetadata processParameterizedType( FieldDeclaration fieldDeclaration ) { ParameterizedType parameterizedType = (ParameterizedType)fieldDeclaration.getType(); Type typeOfParameterizedType = parameterizedType.getType(); // type may be a simple type or a qualified type. FieldMetadata referenceFieldMetadata = createParameterizedFieldMetadataFrom(typeOfParameterizedType); // modifiers processModifiersOfFieldDeclaration(fieldDeclaration, referenceFieldMetadata); // variables referenceFieldMetadata.setName(getFieldName(fieldDeclaration)); processVariablesOfVariableDeclarationFragment(fieldDeclaration, referenceFieldMetadata); return referenceFieldMetadata; }
[ "protected", "FieldMetadata", "processParameterizedType", "(", "FieldDeclaration", "fieldDeclaration", ")", "{", "ParameterizedType", "parameterizedType", "=", "(", "ParameterizedType", ")", "fieldDeclaration", ".", "getType", "(", ")", ";", "Type", "typeOfParameterizedType", "=", "parameterizedType", ".", "getType", "(", ")", ";", "// type may be a simple type or a qualified type.", "FieldMetadata", "referenceFieldMetadata", "=", "createParameterizedFieldMetadataFrom", "(", "typeOfParameterizedType", ")", ";", "// modifiers", "processModifiersOfFieldDeclaration", "(", "fieldDeclaration", ",", "referenceFieldMetadata", ")", ";", "// variables", "referenceFieldMetadata", ".", "setName", "(", "getFieldName", "(", "fieldDeclaration", ")", ")", ";", "processVariablesOfVariableDeclarationFragment", "(", "fieldDeclaration", ",", "referenceFieldMetadata", ")", ";", "return", "referenceFieldMetadata", ";", "}" ]
Process the parameterized type of a {@link FieldDeclaration}. @param fieldDeclaration - the field declaration. @return ParameterizedTypeFieldMetadata.
[ "Process", "the", "parameterized", "type", "of", "a", "{", "@link", "FieldDeclaration", "}", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-java/src/main/java/org/modeshape/sequencer/javafile/AbstractJavaMetadata.java#L606-L618
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java
SessionStoreInterceptor.restoreFields
protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException { """ Restore all fields from value stored in session except if they. @param fields Fields to restore from session. @param actionBean ActionBean. @param context ActionBeanContext. @throws IllegalAccessException Cannot get access to some fields. """ HttpSession session = context.getRequest().getSession(false); if (session != null) { Set<String> parameters = this.getParameters(context.getRequest()); for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } if (!parameters.contains(field.getName())) { // Replace value. Object value = session.getAttribute(getFieldKey(field, actionBean.getClass())); // If value is null and field is primitive, don't set value. if (!(value == null && field.getType().isPrimitive())) { field.set(actionBean, value); } } } } }
java
protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException { HttpSession session = context.getRequest().getSession(false); if (session != null) { Set<String> parameters = this.getParameters(context.getRequest()); for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } if (!parameters.contains(field.getName())) { // Replace value. Object value = session.getAttribute(getFieldKey(field, actionBean.getClass())); // If value is null and field is primitive, don't set value. if (!(value == null && field.getType().isPrimitive())) { field.set(actionBean, value); } } } } }
[ "protected", "void", "restoreFields", "(", "Collection", "<", "Field", ">", "fields", ",", "ActionBean", "actionBean", ",", "ActionBeanContext", "context", ")", "throws", "IllegalAccessException", "{", "HttpSession", "session", "=", "context", ".", "getRequest", "(", ")", ".", "getSession", "(", "false", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "Set", "<", "String", ">", "parameters", "=", "this", ".", "getParameters", "(", "context", ".", "getRequest", "(", ")", ")", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "if", "(", "!", "field", ".", "isAccessible", "(", ")", ")", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "}", "if", "(", "!", "parameters", ".", "contains", "(", "field", ".", "getName", "(", ")", ")", ")", "{", "// Replace value.\r", "Object", "value", "=", "session", ".", "getAttribute", "(", "getFieldKey", "(", "field", ",", "actionBean", ".", "getClass", "(", ")", ")", ")", ";", "// If value is null and field is primitive, don't set value.\r", "if", "(", "!", "(", "value", "==", "null", "&&", "field", ".", "getType", "(", ")", ".", "isPrimitive", "(", ")", ")", ")", "{", "field", ".", "set", "(", "actionBean", ",", "value", ")", ";", "}", "}", "}", "}", "}" ]
Restore all fields from value stored in session except if they. @param fields Fields to restore from session. @param actionBean ActionBean. @param context ActionBeanContext. @throws IllegalAccessException Cannot get access to some fields.
[ "Restore", "all", "fields", "from", "value", "stored", "in", "session", "except", "if", "they", "." ]
train
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L91-L109
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLReflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.java
OWLReflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLReflexiveObjectPropertyAxiomImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLReflexiveObjectPropertyAxiomImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLReflexiveObjectPropertyAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLReflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.java#L74-L77
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java
OmemoService.fetchDeviceList
private static OmemoDeviceListElement fetchDeviceList(XMPPConnection connection, BareJid contact) throws InterruptedException, PubSubException.NotALeafNodeException, SmackException.NoResponseException, SmackException.NotConnectedException, XMPPException.XMPPErrorException, PubSubException.NotAPubSubNodeException { """ Retrieve the OMEMO device list of a contact. @param connection authenticated XMPP connection. @param contact BareJid of the contact of which we want to retrieve the device list from. @return @throws InterruptedException @throws PubSubException.NotALeafNodeException @throws SmackException.NoResponseException @throws SmackException.NotConnectedException @throws XMPPException.XMPPErrorException @throws PubSubException.NotAPubSubNodeException """ PubSubManager pm = PubSubManager.getInstanceFor(connection, contact); String nodeName = OmemoConstants.PEP_NODE_DEVICE_LIST; LeafNode node = pm.getLeafNode(nodeName); if (node == null) { return null; } List<PayloadItem<OmemoDeviceListElement>> items = node.getItems(); if (items.isEmpty()) { return null; } return items.get(items.size() - 1).getPayload(); }
java
private static OmemoDeviceListElement fetchDeviceList(XMPPConnection connection, BareJid contact) throws InterruptedException, PubSubException.NotALeafNodeException, SmackException.NoResponseException, SmackException.NotConnectedException, XMPPException.XMPPErrorException, PubSubException.NotAPubSubNodeException { PubSubManager pm = PubSubManager.getInstanceFor(connection, contact); String nodeName = OmemoConstants.PEP_NODE_DEVICE_LIST; LeafNode node = pm.getLeafNode(nodeName); if (node == null) { return null; } List<PayloadItem<OmemoDeviceListElement>> items = node.getItems(); if (items.isEmpty()) { return null; } return items.get(items.size() - 1).getPayload(); }
[ "private", "static", "OmemoDeviceListElement", "fetchDeviceList", "(", "XMPPConnection", "connection", ",", "BareJid", "contact", ")", "throws", "InterruptedException", ",", "PubSubException", ".", "NotALeafNodeException", ",", "SmackException", ".", "NoResponseException", ",", "SmackException", ".", "NotConnectedException", ",", "XMPPException", ".", "XMPPErrorException", ",", "PubSubException", ".", "NotAPubSubNodeException", "{", "PubSubManager", "pm", "=", "PubSubManager", ".", "getInstanceFor", "(", "connection", ",", "contact", ")", ";", "String", "nodeName", "=", "OmemoConstants", ".", "PEP_NODE_DEVICE_LIST", ";", "LeafNode", "node", "=", "pm", ".", "getLeafNode", "(", "nodeName", ")", ";", "if", "(", "node", "==", "null", ")", "{", "return", "null", ";", "}", "List", "<", "PayloadItem", "<", "OmemoDeviceListElement", ">", ">", "items", "=", "node", ".", "getItems", "(", ")", ";", "if", "(", "items", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "items", ".", "get", "(", "items", ".", "size", "(", ")", "-", "1", ")", ".", "getPayload", "(", ")", ";", "}" ]
Retrieve the OMEMO device list of a contact. @param connection authenticated XMPP connection. @param contact BareJid of the contact of which we want to retrieve the device list from. @return @throws InterruptedException @throws PubSubException.NotALeafNodeException @throws SmackException.NoResponseException @throws SmackException.NotConnectedException @throws XMPPException.XMPPErrorException @throws PubSubException.NotAPubSubNodeException
[ "Retrieve", "the", "OMEMO", "device", "list", "of", "a", "contact", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoService.java#L604-L623
BlueBrain/bluima
modules/bluima_scripting/src/main/java/ch/epfl/bbp/uima/laucher/PipelineScriptParser.java
PipelineScriptParser.parseJava
private static void parseJava(IteratorWithPrevious<String> it, Pipeline pipeline) throws ParseException { """ Parses inline, raw java code and executes it with Beanshell @return """ String script = ""; while (it.hasNext()) { String current = it.next(); if (isBlank(current)) break; script += current + "\n"; } if (script.length() < 3) throw new ParseException("empty script", -1); try { pipeline.aeds.add(createEngineDescription(BeanshellAnnotator.class, SCRIPT_STRING, script)); } catch (ResourceInitializationException e) { throw new ParseException("could not create aed with script " + script, -1); } }
java
private static void parseJava(IteratorWithPrevious<String> it, Pipeline pipeline) throws ParseException { String script = ""; while (it.hasNext()) { String current = it.next(); if (isBlank(current)) break; script += current + "\n"; } if (script.length() < 3) throw new ParseException("empty script", -1); try { pipeline.aeds.add(createEngineDescription(BeanshellAnnotator.class, SCRIPT_STRING, script)); } catch (ResourceInitializationException e) { throw new ParseException("could not create aed with script " + script, -1); } }
[ "private", "static", "void", "parseJava", "(", "IteratorWithPrevious", "<", "String", ">", "it", ",", "Pipeline", "pipeline", ")", "throws", "ParseException", "{", "String", "script", "=", "\"\"", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "String", "current", "=", "it", ".", "next", "(", ")", ";", "if", "(", "isBlank", "(", "current", ")", ")", "break", ";", "script", "+=", "current", "+", "\"\\n\"", ";", "}", "if", "(", "script", ".", "length", "(", ")", "<", "3", ")", "throw", "new", "ParseException", "(", "\"empty script\"", ",", "-", "1", ")", ";", "try", "{", "pipeline", ".", "aeds", ".", "add", "(", "createEngineDescription", "(", "BeanshellAnnotator", ".", "class", ",", "SCRIPT_STRING", ",", "script", ")", ")", ";", "}", "catch", "(", "ResourceInitializationException", "e", ")", "{", "throw", "new", "ParseException", "(", "\"could not create aed with script \"", "+", "script", ",", "-", "1", ")", ";", "}", "}" ]
Parses inline, raw java code and executes it with Beanshell @return
[ "Parses", "inline", "raw", "java", "code", "and", "executes", "it", "with", "Beanshell" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_scripting/src/main/java/ch/epfl/bbp/uima/laucher/PipelineScriptParser.java#L240-L260
Coveros/selenified
src/main/java/com/coveros/selenified/element/Element.java
Element.isNotInput
private boolean isNotInput(String action, String expected, String extra) { """ Determines if the element is an input. @param action - what action is occurring @param expected - what is the expected result @param extra - what actually is occurring @return Boolean: is the element enabled? """ // wait for element to be displayed if (!is.input()) { reporter.fail(action, expected, extra + prettyOutput() + NOT_AN_INPUT); // indicates element not an input return true; } return false; }
java
private boolean isNotInput(String action, String expected, String extra) { // wait for element to be displayed if (!is.input()) { reporter.fail(action, expected, extra + prettyOutput() + NOT_AN_INPUT); // indicates element not an input return true; } return false; }
[ "private", "boolean", "isNotInput", "(", "String", "action", ",", "String", "expected", ",", "String", "extra", ")", "{", "// wait for element to be displayed", "if", "(", "!", "is", ".", "input", "(", ")", ")", "{", "reporter", ".", "fail", "(", "action", ",", "expected", ",", "extra", "+", "prettyOutput", "(", ")", "+", "NOT_AN_INPUT", ")", ";", "// indicates element not an input", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determines if the element is an input. @param action - what action is occurring @param expected - what is the expected result @param extra - what actually is occurring @return Boolean: is the element enabled?
[ "Determines", "if", "the", "element", "is", "an", "input", "." ]
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L658-L666
Red5/red5-server-common
src/main/java/org/red5/server/messaging/AbstractPipe.java
AbstractPipe.subscribe
public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { """ Connect provider to this pipe. Doesn't allow to connect one provider twice. Does register event listeners if instance of IPipeConnectionListener is given. @param provider Provider @param paramMap Parameters passed with connection, used in concrete pipe implementations @return true if provider was added, false otherwise """ boolean success = providers.addIfAbsent(provider); // register event listener if given and just added if (success && provider instanceof IPipeConnectionListener) { listeners.addIfAbsent((IPipeConnectionListener) provider); } return success; }
java
public boolean subscribe(IProvider provider, Map<String, Object> paramMap) { boolean success = providers.addIfAbsent(provider); // register event listener if given and just added if (success && provider instanceof IPipeConnectionListener) { listeners.addIfAbsent((IPipeConnectionListener) provider); } return success; }
[ "public", "boolean", "subscribe", "(", "IProvider", "provider", ",", "Map", "<", "String", ",", "Object", ">", "paramMap", ")", "{", "boolean", "success", "=", "providers", ".", "addIfAbsent", "(", "provider", ")", ";", "// register event listener if given and just added", "if", "(", "success", "&&", "provider", "instanceof", "IPipeConnectionListener", ")", "{", "listeners", ".", "addIfAbsent", "(", "(", "IPipeConnectionListener", ")", "provider", ")", ";", "}", "return", "success", ";", "}" ]
Connect provider to this pipe. Doesn't allow to connect one provider twice. Does register event listeners if instance of IPipeConnectionListener is given. @param provider Provider @param paramMap Parameters passed with connection, used in concrete pipe implementations @return true if provider was added, false otherwise
[ "Connect", "provider", "to", "this", "pipe", ".", "Doesn", "t", "allow", "to", "connect", "one", "provider", "twice", ".", "Does", "register", "event", "listeners", "if", "instance", "of", "IPipeConnectionListener", "is", "given", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/messaging/AbstractPipe.java#L92-L99
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/FaultManager.java
FaultManager.isBlacklisted
public boolean isBlacklisted(String nodeName, ResourceType type) { """ Check if a resource on a node is blacklisted. @param nodeName The node name. @param type The type of resource to check for blacklisting. @return A boolean value that is true if blacklisted, false if not. """ List<ResourceType> blacklistedResourceTypes = blacklistedNodes.get(nodeName); if (blacklistedResourceTypes != null) { synchronized (blacklistedResourceTypes) { return blacklistedResourceTypes.contains(type); } } else { return false; } }
java
public boolean isBlacklisted(String nodeName, ResourceType type) { List<ResourceType> blacklistedResourceTypes = blacklistedNodes.get(nodeName); if (blacklistedResourceTypes != null) { synchronized (blacklistedResourceTypes) { return blacklistedResourceTypes.contains(type); } } else { return false; } }
[ "public", "boolean", "isBlacklisted", "(", "String", "nodeName", ",", "ResourceType", "type", ")", "{", "List", "<", "ResourceType", ">", "blacklistedResourceTypes", "=", "blacklistedNodes", ".", "get", "(", "nodeName", ")", ";", "if", "(", "blacklistedResourceTypes", "!=", "null", ")", "{", "synchronized", "(", "blacklistedResourceTypes", ")", "{", "return", "blacklistedResourceTypes", ".", "contains", "(", "type", ")", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check if a resource on a node is blacklisted. @param nodeName The node name. @param type The type of resource to check for blacklisting. @return A boolean value that is true if blacklisted, false if not.
[ "Check", "if", "a", "resource", "on", "a", "node", "is", "blacklisted", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/FaultManager.java#L191-L201
protostuff/protostuff
protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java
XmlIOUtil.mergeFrom
public static <T> void mergeFrom(byte[] data, int offset, int len, T message, Schema<T> schema, XMLInputFactory inFactory) { """ Merges the {@code message} with the byte array using the given {@code schema}. """ final ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len); try { mergeFrom(in, message, schema, inFactory); } catch (IOException e) { throw new RuntimeException(e); } }
java
public static <T> void mergeFrom(byte[] data, int offset, int len, T message, Schema<T> schema, XMLInputFactory inFactory) { final ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len); try { mergeFrom(in, message, schema, inFactory); } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "<", "T", ">", "void", "mergeFrom", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "len", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ",", "XMLInputFactory", "inFactory", ")", "{", "final", "ByteArrayInputStream", "in", "=", "new", "ByteArrayInputStream", "(", "data", ",", "offset", ",", "len", ")", ";", "try", "{", "mergeFrom", "(", "in", ",", "message", ",", "schema", ",", "inFactory", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Merges the {@code message} with the byte array using the given {@code schema}.
[ "Merges", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java#L198-L210
Erudika/para
para-server/src/main/java/com/erudika/para/utils/GZipResponseUtil.java
GZipResponseUtil.shouldBodyBeZero
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) { """ Performs a number of checks to ensure response saneness according to the rules of RFC2616: <ol> <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5 <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 </ol> @param request the client HTTP request @param responseStatus the responseStatus @return true if the response should be 0, even if it is isn't. """ //Check for NO_CONTENT if (responseStatus == HttpServletResponse.SC_NO_CONTENT) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT); } return true; } //Check for NOT_MODIFIED if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED); } return true; } return false; }
java
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) { //Check for NO_CONTENT if (responseStatus == HttpServletResponse.SC_NO_CONTENT) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT); } return true; } //Check for NOT_MODIFIED if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.", request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED); } return true; } return false; }
[ "public", "static", "boolean", "shouldBodyBeZero", "(", "HttpServletRequest", "request", ",", "int", "responseStatus", ")", "{", "//Check for NO_CONTENT", "if", "(", "responseStatus", "==", "HttpServletResponse", ".", "SC_NO_CONTENT", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"{} resulted in a {} response. Removing message body in accordance with RFC2616.\"", ",", "request", ".", "getRequestURL", "(", ")", ",", "HttpServletResponse", ".", "SC_NO_CONTENT", ")", ";", "}", "return", "true", ";", "}", "//Check for NOT_MODIFIED", "if", "(", "responseStatus", "==", "HttpServletResponse", ".", "SC_NOT_MODIFIED", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"{} resulted in a {} response. Removing message body in accordance with RFC2616.\"", ",", "request", ".", "getRequestURL", "(", ")", ",", "HttpServletResponse", ".", "SC_NOT_MODIFIED", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Performs a number of checks to ensure response saneness according to the rules of RFC2616: <ol> <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5 <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 </ol> @param request the client HTTP request @param responseStatus the responseStatus @return true if the response should be 0, even if it is isn't.
[ "Performs", "a", "number", "of", "checks", "to", "ensure", "response", "saneness", "according", "to", "the", "rules", "of", "RFC2616", ":", "<ol", ">", "<li", ">", "If", "the", "response", "code", "is", "{" ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/utils/GZipResponseUtil.java#L81-L101
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java
DefaultHttp2Connection.removeStream
void removeStream(DefaultStream stream, Iterator<?> itr) { """ Remove a stream from the {@link #streamMap}. @param stream the stream to remove. @param itr an iterator that may be pointing to the stream during iteration and {@link Iterator#remove()} will be used if non-{@code null}. """ final boolean removed; if (itr == null) { removed = streamMap.remove(stream.id()) != null; } else { itr.remove(); removed = true; } if (removed) { for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamRemoved(stream); } catch (Throwable cause) { logger.error("Caught Throwable from listener onStreamRemoved.", cause); } } if (closePromise != null && isStreamMapEmpty()) { closePromise.trySuccess(null); } } }
java
void removeStream(DefaultStream stream, Iterator<?> itr) { final boolean removed; if (itr == null) { removed = streamMap.remove(stream.id()) != null; } else { itr.remove(); removed = true; } if (removed) { for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamRemoved(stream); } catch (Throwable cause) { logger.error("Caught Throwable from listener onStreamRemoved.", cause); } } if (closePromise != null && isStreamMapEmpty()) { closePromise.trySuccess(null); } } }
[ "void", "removeStream", "(", "DefaultStream", "stream", ",", "Iterator", "<", "?", ">", "itr", ")", "{", "final", "boolean", "removed", ";", "if", "(", "itr", "==", "null", ")", "{", "removed", "=", "streamMap", ".", "remove", "(", "stream", ".", "id", "(", ")", ")", "!=", "null", ";", "}", "else", "{", "itr", ".", "remove", "(", ")", ";", "removed", "=", "true", ";", "}", "if", "(", "removed", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "listeners", ".", "size", "(", ")", ";", "i", "++", ")", "{", "try", "{", "listeners", ".", "get", "(", "i", ")", ".", "onStreamRemoved", "(", "stream", ")", ";", "}", "catch", "(", "Throwable", "cause", ")", "{", "logger", ".", "error", "(", "\"Caught Throwable from listener onStreamRemoved.\"", ",", "cause", ")", ";", "}", "}", "if", "(", "closePromise", "!=", "null", "&&", "isStreamMapEmpty", "(", ")", ")", "{", "closePromise", ".", "trySuccess", "(", "null", ")", ";", "}", "}", "}" ]
Remove a stream from the {@link #streamMap}. @param stream the stream to remove. @param itr an iterator that may be pointing to the stream during iteration and {@link Iterator#remove()} will be used if non-{@code null}.
[ "Remove", "a", "stream", "from", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java#L304-L326
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_service_serviceName_directory_getDirectoryServiceCode_GET
public ArrayList<OvhDirectoryHeadingPJ> billingAccount_service_serviceName_directory_getDirectoryServiceCode_GET(String billingAccount, String serviceName, String apeCode) throws IOException { """ Get directory service code from an APE code ( principal activity of the firm code ) REST: GET /telephony/{billingAccount}/service/{serviceName}/directory/getDirectoryServiceCode @param apeCode [required] @param billingAccount [required] The name of your billingAccount @param serviceName [required] """ String qPath = "/telephony/{billingAccount}/service/{serviceName}/directory/getDirectoryServiceCode"; StringBuilder sb = path(qPath, billingAccount, serviceName); query(sb, "apeCode", apeCode); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t13); }
java
public ArrayList<OvhDirectoryHeadingPJ> billingAccount_service_serviceName_directory_getDirectoryServiceCode_GET(String billingAccount, String serviceName, String apeCode) throws IOException { String qPath = "/telephony/{billingAccount}/service/{serviceName}/directory/getDirectoryServiceCode"; StringBuilder sb = path(qPath, billingAccount, serviceName); query(sb, "apeCode", apeCode); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t13); }
[ "public", "ArrayList", "<", "OvhDirectoryHeadingPJ", ">", "billingAccount_service_serviceName_directory_getDirectoryServiceCode_GET", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "apeCode", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/service/{serviceName}/directory/getDirectoryServiceCode\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "billingAccount", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"apeCode\"", ",", "apeCode", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t13", ")", ";", "}" ]
Get directory service code from an APE code ( principal activity of the firm code ) REST: GET /telephony/{billingAccount}/service/{serviceName}/directory/getDirectoryServiceCode @param apeCode [required] @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Get", "directory", "service", "code", "from", "an", "APE", "code", "(", "principal", "activity", "of", "the", "firm", "code", ")" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3961-L3967
fabric8io/fabric8-forge
addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelCatalogHelper.java
CamelCatalogHelper.isMultiValue
public static boolean isMultiValue(CamelCatalog camelCatalog, String scheme, String key) { """ Checks whether the given key is a multi valued option @param scheme the component name @param key the option key @return <tt>true</tt> if the key is multi valued, <tt>false</tt> otherwise """ // use the camel catalog String json = camelCatalog.componentJSonSchema(scheme); if (json == null) { throw new IllegalArgumentException("Could not find catalog entry for component name: " + scheme); } List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("properties", json, true); if (data != null) { for (Map<String, String> propertyMap : data) { String name = propertyMap.get("name"); String multiValue = propertyMap.get("multiValue"); if (key.equals(name)) { return "true".equals(multiValue); } } } return false; }
java
public static boolean isMultiValue(CamelCatalog camelCatalog, String scheme, String key) { // use the camel catalog String json = camelCatalog.componentJSonSchema(scheme); if (json == null) { throw new IllegalArgumentException("Could not find catalog entry for component name: " + scheme); } List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("properties", json, true); if (data != null) { for (Map<String, String> propertyMap : data) { String name = propertyMap.get("name"); String multiValue = propertyMap.get("multiValue"); if (key.equals(name)) { return "true".equals(multiValue); } } } return false; }
[ "public", "static", "boolean", "isMultiValue", "(", "CamelCatalog", "camelCatalog", ",", "String", "scheme", ",", "String", "key", ")", "{", "// use the camel catalog", "String", "json", "=", "camelCatalog", ".", "componentJSonSchema", "(", "scheme", ")", ";", "if", "(", "json", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Could not find catalog entry for component name: \"", "+", "scheme", ")", ";", "}", "List", "<", "Map", "<", "String", ",", "String", ">", ">", "data", "=", "JSonSchemaHelper", ".", "parseJsonSchema", "(", "\"properties\"", ",", "json", ",", "true", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "for", "(", "Map", "<", "String", ",", "String", ">", "propertyMap", ":", "data", ")", "{", "String", "name", "=", "propertyMap", ".", "get", "(", "\"name\"", ")", ";", "String", "multiValue", "=", "propertyMap", ".", "get", "(", "\"multiValue\"", ")", ";", "if", "(", "key", ".", "equals", "(", "name", ")", ")", "{", "return", "\"true\"", ".", "equals", "(", "multiValue", ")", ";", "}", "}", "}", "return", "false", ";", "}" ]
Checks whether the given key is a multi valued option @param scheme the component name @param key the option key @return <tt>true</tt> if the key is multi valued, <tt>false</tt> otherwise
[ "Checks", "whether", "the", "given", "key", "is", "a", "multi", "valued", "option" ]
train
https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelCatalogHelper.java#L207-L225
greatman/GreatmancodeTools
src/main/java/com/greatmancode/tools/utils/Metrics.java
Metrics.appendJSONPair
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { """ Appends a json encoded key/value pair to the given string builder. @param json @param key @param value @throws UnsupportedEncodingException """ boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
java
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
[ "private", "static", "void", "appendJSONPair", "(", "StringBuilder", "json", ",", "String", "key", ",", "String", "value", ")", "throws", "UnsupportedEncodingException", "{", "boolean", "isValueNumeric", "=", "false", ";", "try", "{", "if", "(", "value", ".", "equals", "(", "\"0\"", ")", "||", "!", "value", ".", "endsWith", "(", "\"0\"", ")", ")", "{", "Double", ".", "parseDouble", "(", "value", ")", ";", "isValueNumeric", "=", "true", ";", "}", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "isValueNumeric", "=", "false", ";", "}", "if", "(", "json", ".", "charAt", "(", "json", ".", "length", "(", ")", "-", "1", ")", "!=", "'", "'", ")", "{", "json", ".", "append", "(", "'", "'", ")", ";", "}", "json", ".", "append", "(", "escapeJSON", "(", "key", ")", ")", ";", "json", ".", "append", "(", "'", "'", ")", ";", "if", "(", "isValueNumeric", ")", "{", "json", ".", "append", "(", "value", ")", ";", "}", "else", "{", "json", ".", "append", "(", "escapeJSON", "(", "value", ")", ")", ";", "}", "}" ]
Appends a json encoded key/value pair to the given string builder. @param json @param key @param value @throws UnsupportedEncodingException
[ "Appends", "a", "json", "encoded", "key", "/", "value", "pair", "to", "the", "given", "string", "builder", "." ]
train
https://github.com/greatman/GreatmancodeTools/blob/4c9d2656c5c8298ff9e1f235c9be8b148e43c9f1/src/main/java/com/greatmancode/tools/utils/Metrics.java#L547-L571
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java
CmsContainerpageHandler.decorateMenuEntry
protected void decorateMenuEntry(CmsContextMenuEntry entry, String name, boolean checked) { """ Fills in label and checkbox of a menu entry.<p> @param entry the menu entry @param name the label @param checked true if checkbox should be shown """ CmsContextMenuEntryBean bean = new CmsContextMenuEntryBean(); bean.setLabel(name); bean.setActive(true); bean.setVisible(true); I_CmsInputCss inputCss = I_CmsInputLayoutBundle.INSTANCE.inputCss(); bean.setIconClass(checked ? inputCss.checkBoxImageChecked() : ""); entry.setBean(bean); }
java
protected void decorateMenuEntry(CmsContextMenuEntry entry, String name, boolean checked) { CmsContextMenuEntryBean bean = new CmsContextMenuEntryBean(); bean.setLabel(name); bean.setActive(true); bean.setVisible(true); I_CmsInputCss inputCss = I_CmsInputLayoutBundle.INSTANCE.inputCss(); bean.setIconClass(checked ? inputCss.checkBoxImageChecked() : ""); entry.setBean(bean); }
[ "protected", "void", "decorateMenuEntry", "(", "CmsContextMenuEntry", "entry", ",", "String", "name", ",", "boolean", "checked", ")", "{", "CmsContextMenuEntryBean", "bean", "=", "new", "CmsContextMenuEntryBean", "(", ")", ";", "bean", ".", "setLabel", "(", "name", ")", ";", "bean", ".", "setActive", "(", "true", ")", ";", "bean", ".", "setVisible", "(", "true", ")", ";", "I_CmsInputCss", "inputCss", "=", "I_CmsInputLayoutBundle", ".", "INSTANCE", ".", "inputCss", "(", ")", ";", "bean", ".", "setIconClass", "(", "checked", "?", "inputCss", ".", "checkBoxImageChecked", "(", ")", ":", "\"\"", ")", ";", "entry", ".", "setBean", "(", "bean", ")", ";", "}" ]
Fills in label and checkbox of a menu entry.<p> @param entry the menu entry @param name the label @param checked true if checkbox should be shown
[ "Fills", "in", "label", "and", "checkbox", "of", "a", "menu", "entry", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L1496-L1505
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java
JvmTypesBuilder.setExtension
public void setExtension(/* @Nullable */ JvmField field, EObject sourceElement, boolean value) { """ Adds or removes the annotation {@link Extension @Extension} from the given field. If the annotation is already present, nothing is done if {@code value} is {@code true}. If it is not present and {@code value} is {@code false}, this is a no-op, too. @param field the field that will be processed @param sourceElement the context that shall be used to lookup the {@link Extension annotation type}. @param value <code>true</code> if the parameter shall be marked as extension, <code>false</code> if it should be unmarked. """ if (field == null) return; internalSetExtension(field, sourceElement, value); }
java
public void setExtension(/* @Nullable */ JvmField field, EObject sourceElement, boolean value) { if (field == null) return; internalSetExtension(field, sourceElement, value); }
[ "public", "void", "setExtension", "(", "/* @Nullable */", "JvmField", "field", ",", "EObject", "sourceElement", ",", "boolean", "value", ")", "{", "if", "(", "field", "==", "null", ")", "return", ";", "internalSetExtension", "(", "field", ",", "sourceElement", ",", "value", ")", ";", "}" ]
Adds or removes the annotation {@link Extension @Extension} from the given field. If the annotation is already present, nothing is done if {@code value} is {@code true}. If it is not present and {@code value} is {@code false}, this is a no-op, too. @param field the field that will be processed @param sourceElement the context that shall be used to lookup the {@link Extension annotation type}. @param value <code>true</code> if the parameter shall be marked as extension, <code>false</code> if it should be unmarked.
[ "Adds", "or", "removes", "the", "annotation", "{", "@link", "Extension", "@Extension", "}", "from", "the", "given", "field", ".", "If", "the", "annotation", "is", "already", "present", "nothing", "is", "done", "if", "{", "@code", "value", "}", "is", "{", "@code", "true", "}", ".", "If", "it", "is", "not", "present", "and", "{", "@code", "value", "}", "is", "{", "@code", "false", "}", "this", "is", "a", "no", "-", "op", "too", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java#L605-L609
dnsjava/dnsjava
org/xbill/DNS/ZoneTransferIn.java
ZoneTransferIn.newAXFR
public static ZoneTransferIn newAXFR(Name zone, SocketAddress address, TSIG key) { """ Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer). @param zone The zone to transfer. @param address The host/port from which to transfer the zone. @param key The TSIG key used to authenticate the transfer, or null. @return The ZoneTransferIn object. """ return new ZoneTransferIn(zone, Type.AXFR, 0, false, address, key); }
java
public static ZoneTransferIn newAXFR(Name zone, SocketAddress address, TSIG key) { return new ZoneTransferIn(zone, Type.AXFR, 0, false, address, key); }
[ "public", "static", "ZoneTransferIn", "newAXFR", "(", "Name", "zone", ",", "SocketAddress", "address", ",", "TSIG", "key", ")", "{", "return", "new", "ZoneTransferIn", "(", "zone", ",", "Type", ".", "AXFR", ",", "0", ",", "false", ",", "address", ",", "key", ")", ";", "}" ]
Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer). @param zone The zone to transfer. @param address The host/port from which to transfer the zone. @param key The TSIG key used to authenticate the transfer, or null. @return The ZoneTransferIn object.
[ "Instantiates", "a", "ZoneTransferIn", "object", "to", "do", "an", "AXFR", "(", "full", "zone", "transfer", ")", "." ]
train
https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/ZoneTransferIn.java#L200-L203
couchbase/java-dcp-client
src/main/java/com/couchbase/client/dcp/Client.java
Client.initializeState
public Completable initializeState(final StreamFrom from, final StreamTo to) { """ Initialize the {@link SessionState} based on arbitrary time points. <p> The following combinations are supported and make sense: <p> - {@link StreamFrom#BEGINNING} to {@link StreamTo#NOW} - {@link StreamFrom#BEGINNING} to {@link StreamTo#INFINITY} - {@link StreamFrom#NOW} to {@link StreamTo#INFINITY} <p> If you already have state captured and you want to resume from this position, use {@link #recoverState(StateFormat, byte[])} or {@link #recoverOrInitializeState(StateFormat, byte[], StreamFrom, StreamTo)} instead. @param from where to start streaming from. @param to when to stop streaming. @return A {@link Completable} indicating the success or failure of the state init. """ if (from == StreamFrom.BEGINNING && to == StreamTo.INFINITY) { buzzMe(); return initFromBeginningToInfinity(); } else if (from == StreamFrom.BEGINNING && to == StreamTo.NOW) { return initFromBeginningToNow(); } else if (from == StreamFrom.NOW && to == StreamTo.INFINITY) { buzzMe(); return initFromNowToInfinity(); } else { throw new IllegalStateException("Unsupported FROM/TO combination: " + from + " -> " + to); } }
java
public Completable initializeState(final StreamFrom from, final StreamTo to) { if (from == StreamFrom.BEGINNING && to == StreamTo.INFINITY) { buzzMe(); return initFromBeginningToInfinity(); } else if (from == StreamFrom.BEGINNING && to == StreamTo.NOW) { return initFromBeginningToNow(); } else if (from == StreamFrom.NOW && to == StreamTo.INFINITY) { buzzMe(); return initFromNowToInfinity(); } else { throw new IllegalStateException("Unsupported FROM/TO combination: " + from + " -> " + to); } }
[ "public", "Completable", "initializeState", "(", "final", "StreamFrom", "from", ",", "final", "StreamTo", "to", ")", "{", "if", "(", "from", "==", "StreamFrom", ".", "BEGINNING", "&&", "to", "==", "StreamTo", ".", "INFINITY", ")", "{", "buzzMe", "(", ")", ";", "return", "initFromBeginningToInfinity", "(", ")", ";", "}", "else", "if", "(", "from", "==", "StreamFrom", ".", "BEGINNING", "&&", "to", "==", "StreamTo", ".", "NOW", ")", "{", "return", "initFromBeginningToNow", "(", ")", ";", "}", "else", "if", "(", "from", "==", "StreamFrom", ".", "NOW", "&&", "to", "==", "StreamTo", ".", "INFINITY", ")", "{", "buzzMe", "(", ")", ";", "return", "initFromNowToInfinity", "(", ")", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Unsupported FROM/TO combination: \"", "+", "from", "+", "\" -> \"", "+", "to", ")", ";", "}", "}" ]
Initialize the {@link SessionState} based on arbitrary time points. <p> The following combinations are supported and make sense: <p> - {@link StreamFrom#BEGINNING} to {@link StreamTo#NOW} - {@link StreamFrom#BEGINNING} to {@link StreamTo#INFINITY} - {@link StreamFrom#NOW} to {@link StreamTo#INFINITY} <p> If you already have state captured and you want to resume from this position, use {@link #recoverState(StateFormat, byte[])} or {@link #recoverOrInitializeState(StateFormat, byte[], StreamFrom, StreamTo)} instead. @param from where to start streaming from. @param to when to stop streaming. @return A {@link Completable} indicating the success or failure of the state init.
[ "Initialize", "the", "{", "@link", "SessionState", "}", "based", "on", "arbitrary", "time", "points", ".", "<p", ">", "The", "following", "combinations", "are", "supported", "and", "make", "sense", ":", "<p", ">", "-", "{", "@link", "StreamFrom#BEGINNING", "}", "to", "{", "@link", "StreamTo#NOW", "}", "-", "{", "@link", "StreamFrom#BEGINNING", "}", "to", "{", "@link", "StreamTo#INFINITY", "}", "-", "{", "@link", "StreamFrom#NOW", "}", "to", "{", "@link", "StreamTo#INFINITY", "}", "<p", ">", "If", "you", "already", "have", "state", "captured", "and", "you", "want", "to", "resume", "from", "this", "position", "use", "{", "@link", "#recoverState", "(", "StateFormat", "byte", "[]", ")", "}", "or", "{", "@link", "#recoverOrInitializeState", "(", "StateFormat", "byte", "[]", "StreamFrom", "StreamTo", ")", "}", "instead", "." ]
train
https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/Client.java#L575-L587
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/api/common/io/FileInputFormat.java
FileInputFormat.getStatistics
@Override public FileBaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException { """ Obtains basic file statistics containing only file size. If the input is a directory, then the size is the sum of all contained files. @see eu.stratosphere.api.common.io.InputFormat#getStatistics(eu.stratosphere.api.common.io.statistics.BaseStatistics) """ final FileBaseStatistics cachedFileStats = (cachedStats != null && cachedStats instanceof FileBaseStatistics) ? (FileBaseStatistics) cachedStats : null; try { final Path path = this.filePath; final FileSystem fs = FileSystem.get(path.toUri()); return getFileStats(cachedFileStats, path, fs, new ArrayList<FileStatus>(1)); } catch (IOException ioex) { if (LOG.isWarnEnabled()) { LOG.warn("Could not determine statistics for file '" + this.filePath + "' due to an io error: " + ioex.getMessage()); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected problen while getting the file statistics for file '" + this.filePath + "': " + t.getMessage(), t); } } // no statistics available return null; }
java
@Override public FileBaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException { final FileBaseStatistics cachedFileStats = (cachedStats != null && cachedStats instanceof FileBaseStatistics) ? (FileBaseStatistics) cachedStats : null; try { final Path path = this.filePath; final FileSystem fs = FileSystem.get(path.toUri()); return getFileStats(cachedFileStats, path, fs, new ArrayList<FileStatus>(1)); } catch (IOException ioex) { if (LOG.isWarnEnabled()) { LOG.warn("Could not determine statistics for file '" + this.filePath + "' due to an io error: " + ioex.getMessage()); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected problen while getting the file statistics for file '" + this.filePath + "': " + t.getMessage(), t); } } // no statistics available return null; }
[ "@", "Override", "public", "FileBaseStatistics", "getStatistics", "(", "BaseStatistics", "cachedStats", ")", "throws", "IOException", "{", "final", "FileBaseStatistics", "cachedFileStats", "=", "(", "cachedStats", "!=", "null", "&&", "cachedStats", "instanceof", "FileBaseStatistics", ")", "?", "(", "FileBaseStatistics", ")", "cachedStats", ":", "null", ";", "try", "{", "final", "Path", "path", "=", "this", ".", "filePath", ";", "final", "FileSystem", "fs", "=", "FileSystem", ".", "get", "(", "path", ".", "toUri", "(", ")", ")", ";", "return", "getFileStats", "(", "cachedFileStats", ",", "path", ",", "fs", ",", "new", "ArrayList", "<", "FileStatus", ">", "(", "1", ")", ")", ";", "}", "catch", "(", "IOException", "ioex", ")", "{", "if", "(", "LOG", ".", "isWarnEnabled", "(", ")", ")", "{", "LOG", ".", "warn", "(", "\"Could not determine statistics for file '\"", "+", "this", ".", "filePath", "+", "\"' due to an io error: \"", "+", "ioex", ".", "getMessage", "(", ")", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "if", "(", "LOG", ".", "isErrorEnabled", "(", ")", ")", "{", "LOG", ".", "error", "(", "\"Unexpected problen while getting the file statistics for file '\"", "+", "this", ".", "filePath", "+", "\"': \"", "+", "t", ".", "getMessage", "(", ")", ",", "t", ")", ";", "}", "}", "// no statistics available", "return", "null", ";", "}" ]
Obtains basic file statistics containing only file size. If the input is a directory, then the size is the sum of all contained files. @see eu.stratosphere.api.common.io.InputFormat#getStatistics(eu.stratosphere.api.common.io.statistics.BaseStatistics)
[ "Obtains", "basic", "file", "statistics", "containing", "only", "file", "size", ".", "If", "the", "input", "is", "a", "directory", "then", "the", "size", "is", "the", "sum", "of", "all", "contained", "files", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/api/common/io/FileInputFormat.java#L307-L333
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java
EncodingUtils.encryptValueAsJwtDirectAes128Sha256
public static String encryptValueAsJwtDirectAes128Sha256(final Key key, final Serializable value) { """ Encrypt value as jwt with direct algorithm and encryption content alg aes-128-sha-256. @param key the key @param value the value @return the string """ return encryptValueAsJwt(key, value, KeyManagementAlgorithmIdentifiers.DIRECT, CipherExecutor.DEFAULT_CONTENT_ENCRYPTION_ALGORITHM); }
java
public static String encryptValueAsJwtDirectAes128Sha256(final Key key, final Serializable value) { return encryptValueAsJwt(key, value, KeyManagementAlgorithmIdentifiers.DIRECT, CipherExecutor.DEFAULT_CONTENT_ENCRYPTION_ALGORITHM); }
[ "public", "static", "String", "encryptValueAsJwtDirectAes128Sha256", "(", "final", "Key", "key", ",", "final", "Serializable", "value", ")", "{", "return", "encryptValueAsJwt", "(", "key", ",", "value", ",", "KeyManagementAlgorithmIdentifiers", ".", "DIRECT", ",", "CipherExecutor", ".", "DEFAULT_CONTENT_ENCRYPTION_ALGORITHM", ")", ";", "}" ]
Encrypt value as jwt with direct algorithm and encryption content alg aes-128-sha-256. @param key the key @param value the value @return the string
[ "Encrypt", "value", "as", "jwt", "with", "direct", "algorithm", "and", "encryption", "content", "alg", "aes", "-", "128", "-", "sha", "-", "256", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/EncodingUtils.java#L378-L381
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/JavaBean.java
JavaBean.acceptVisitor
public static void acceptVisitor(Object bean, JavaBeanVisitor visitor) { """ * Given a given object, use reflection to determine qualities. Call the appropriate visitor method to provide the given attributes @param bean the object to derive information @param visitor object/operation that will be provided the needed information """ if(bean == null) return; Class<?> beanClass = bean.getClass(); if(ClassPath.isPrimitive(beanClass)) { visitor.visitClass(beanClass, bean); return; //no properties } PropertyDescriptor descriptors[] = getPropertyDescriptors(bean); Object value = null; for(int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if("class".equals(name)) { visitor.visitClass((Class<?>)getProperty(bean, name),bean); continue; } if(descriptors[i].getReadMethod() != null) { value = getProperty(bean, name); visitor.visitProperty(name, value,bean); } } }
java
public static void acceptVisitor(Object bean, JavaBeanVisitor visitor) { if(bean == null) return; Class<?> beanClass = bean.getClass(); if(ClassPath.isPrimitive(beanClass)) { visitor.visitClass(beanClass, bean); return; //no properties } PropertyDescriptor descriptors[] = getPropertyDescriptors(bean); Object value = null; for(int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if("class".equals(name)) { visitor.visitClass((Class<?>)getProperty(bean, name),bean); continue; } if(descriptors[i].getReadMethod() != null) { value = getProperty(bean, name); visitor.visitProperty(name, value,bean); } } }
[ "public", "static", "void", "acceptVisitor", "(", "Object", "bean", ",", "JavaBeanVisitor", "visitor", ")", "{", "if", "(", "bean", "==", "null", ")", "return", ";", "Class", "<", "?", ">", "beanClass", "=", "bean", ".", "getClass", "(", ")", ";", "if", "(", "ClassPath", ".", "isPrimitive", "(", "beanClass", ")", ")", "{", "visitor", ".", "visitClass", "(", "beanClass", ",", "bean", ")", ";", "return", ";", "//no properties\r", "}", "PropertyDescriptor", "descriptors", "[", "]", "=", "getPropertyDescriptors", "(", "bean", ")", ";", "Object", "value", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "descriptors", ".", "length", ";", "i", "++", ")", "{", "String", "name", "=", "descriptors", "[", "i", "]", ".", "getName", "(", ")", ";", "if", "(", "\"class\"", ".", "equals", "(", "name", ")", ")", "{", "visitor", ".", "visitClass", "(", "(", "Class", "<", "?", ">", ")", "getProperty", "(", "bean", ",", "name", ")", ",", "bean", ")", ";", "continue", ";", "}", "if", "(", "descriptors", "[", "i", "]", ".", "getReadMethod", "(", ")", "!=", "null", ")", "{", "value", "=", "getProperty", "(", "bean", ",", "name", ")", ";", "visitor", ".", "visitProperty", "(", "name", ",", "value", ",", "bean", ")", ";", "}", "}", "}" ]
* Given a given object, use reflection to determine qualities. Call the appropriate visitor method to provide the given attributes @param bean the object to derive information @param visitor object/operation that will be provided the needed information
[ "*", "Given", "a", "given", "object", "use", "reflection", "to", "determine", "qualities", ".", "Call", "the", "appropriate", "visitor", "method", "to", "provide", "the", "given", "attributes" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/JavaBean.java#L140-L177
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java
CPDefinitionOptionRelPersistenceImpl.findByCompanyId
@Override public List<CPDefinitionOptionRel> findByCompanyId(long companyId, int start, int end) { """ Returns a range of all the cp definition option rels where companyId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionOptionRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param companyId the company ID @param start the lower bound of the range of cp definition option rels @param end the upper bound of the range of cp definition option rels (not inclusive) @return the range of matching cp definition option rels """ return findByCompanyId(companyId, start, end, null); }
java
@Override public List<CPDefinitionOptionRel> findByCompanyId(long companyId, int start, int end) { return findByCompanyId(companyId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CPDefinitionOptionRel", ">", "findByCompanyId", "(", "long", "companyId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByCompanyId", "(", "companyId", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp definition option rels where companyId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionOptionRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param companyId the company ID @param start the lower bound of the range of cp definition option rels @param end the upper bound of the range of cp definition option rels (not inclusive) @return the range of matching cp definition option rels
[ "Returns", "a", "range", "of", "all", "the", "cp", "definition", "option", "rels", "where", "companyId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java#L2052-L2056
b3log/latke
latke-core/src/main/java/org/b3log/latke/util/Times.java
Times.isSameMonth
public static boolean isSameMonth(final Date date1, final Date date2) { """ Determines whether the specified date1 is the same month with the specified date2. @param date1 the specified date1 @param date2 the specified date2 @return {@code true} if it is the same month, returns {@code false} otherwise """ final Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH); }
java
public static boolean isSameMonth(final Date date1, final Date date2) { final Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH); }
[ "public", "static", "boolean", "isSameMonth", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ")", "{", "final", "Calendar", "cal1", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal1", ".", "setTime", "(", "date1", ")", ";", "final", "Calendar", "cal2", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal2", ".", "setTime", "(", "date2", ")", ";", "return", "cal1", ".", "get", "(", "Calendar", ".", "ERA", ")", "==", "cal2", ".", "get", "(", "Calendar", ".", "ERA", ")", "&&", "cal1", ".", "get", "(", "Calendar", ".", "YEAR", ")", "==", "cal2", ".", "get", "(", "Calendar", ".", "YEAR", ")", "&&", "cal1", ".", "get", "(", "Calendar", ".", "MONTH", ")", "==", "cal2", ".", "get", "(", "Calendar", ".", "MONTH", ")", ";", "}" ]
Determines whether the specified date1 is the same month with the specified date2. @param date1 the specified date1 @param date2 the specified date2 @return {@code true} if it is the same month, returns {@code false} otherwise
[ "Determines", "whether", "the", "specified", "date1", "is", "the", "same", "month", "with", "the", "specified", "date2", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Times.java#L163-L173
twotoasters/JazzyListView
library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java
JazzyHelper.notifyAdditionalOnScrollListener
private void notifyAdditionalOnScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { """ Notifies the OnScrollListener of an onScroll event, since JazzyListView is the primary listener for onScroll events. """ if (mAdditionalOnScrollListener != null) { mAdditionalOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }
java
private void notifyAdditionalOnScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mAdditionalOnScrollListener != null) { mAdditionalOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }
[ "private", "void", "notifyAdditionalOnScrollListener", "(", "AbsListView", "view", ",", "int", "firstVisibleItem", ",", "int", "visibleItemCount", ",", "int", "totalItemCount", ")", "{", "if", "(", "mAdditionalOnScrollListener", "!=", "null", ")", "{", "mAdditionalOnScrollListener", ".", "onScroll", "(", "view", ",", "firstVisibleItem", ",", "visibleItemCount", ",", "totalItemCount", ")", ";", "}", "}" ]
Notifies the OnScrollListener of an onScroll event, since JazzyListView is the primary listener for onScroll events.
[ "Notifies", "the", "OnScrollListener", "of", "an", "onScroll", "event", "since", "JazzyListView", "is", "the", "primary", "listener", "for", "onScroll", "events", "." ]
train
https://github.com/twotoasters/JazzyListView/blob/4a69239f90374a71e7d4073448ca049bd074f7fe/library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java#L296-L300
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/impl/ClassPathBuilder.java
ClassPathBuilder.addToWorkList
private void addToWorkList(LinkedList<WorkListItem> workList, WorkListItem itemToAdd) { """ Add a worklist item to the worklist. This method maintains the invariant that all of the worklist items representing application codebases appear <em>before</em> all of the worklist items representing auxiliary codebases. @param projectWorkList the worklist @param itemToAdd the worklist item to add """ if (DEBUG) { new RuntimeException("Adding work list item " + itemToAdd).printStackTrace(System.out); } if (!itemToAdd.isAppCodeBase()) { // Auxiliary codebases are always added at the end workList.addLast(itemToAdd); return; } // Adding an application codebase: position a ListIterator // just before first auxiliary codebase (or at the end of the list // if there are no auxiliary codebases) ListIterator<WorkListItem> i = workList.listIterator(); while (i.hasNext()) { WorkListItem listItem = i.next(); if (!listItem.isAppCodeBase()) { i.previous(); break; } } // Add the codebase to the worklist i.add(itemToAdd); }
java
private void addToWorkList(LinkedList<WorkListItem> workList, WorkListItem itemToAdd) { if (DEBUG) { new RuntimeException("Adding work list item " + itemToAdd).printStackTrace(System.out); } if (!itemToAdd.isAppCodeBase()) { // Auxiliary codebases are always added at the end workList.addLast(itemToAdd); return; } // Adding an application codebase: position a ListIterator // just before first auxiliary codebase (or at the end of the list // if there are no auxiliary codebases) ListIterator<WorkListItem> i = workList.listIterator(); while (i.hasNext()) { WorkListItem listItem = i.next(); if (!listItem.isAppCodeBase()) { i.previous(); break; } } // Add the codebase to the worklist i.add(itemToAdd); }
[ "private", "void", "addToWorkList", "(", "LinkedList", "<", "WorkListItem", ">", "workList", ",", "WorkListItem", "itemToAdd", ")", "{", "if", "(", "DEBUG", ")", "{", "new", "RuntimeException", "(", "\"Adding work list item \"", "+", "itemToAdd", ")", ".", "printStackTrace", "(", "System", ".", "out", ")", ";", "}", "if", "(", "!", "itemToAdd", ".", "isAppCodeBase", "(", ")", ")", "{", "// Auxiliary codebases are always added at the end", "workList", ".", "addLast", "(", "itemToAdd", ")", ";", "return", ";", "}", "// Adding an application codebase: position a ListIterator", "// just before first auxiliary codebase (or at the end of the list", "// if there are no auxiliary codebases)", "ListIterator", "<", "WorkListItem", ">", "i", "=", "workList", ".", "listIterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "WorkListItem", "listItem", "=", "i", ".", "next", "(", ")", ";", "if", "(", "!", "listItem", ".", "isAppCodeBase", "(", ")", ")", "{", "i", ".", "previous", "(", ")", ";", "break", ";", "}", "}", "// Add the codebase to the worklist", "i", ".", "add", "(", "itemToAdd", ")", ";", "}" ]
Add a worklist item to the worklist. This method maintains the invariant that all of the worklist items representing application codebases appear <em>before</em> all of the worklist items representing auxiliary codebases. @param projectWorkList the worklist @param itemToAdd the worklist item to add
[ "Add", "a", "worklist", "item", "to", "the", "worklist", ".", "This", "method", "maintains", "the", "invariant", "that", "all", "of", "the", "worklist", "items", "representing", "application", "codebases", "appear", "<em", ">", "before<", "/", "em", ">", "all", "of", "the", "worklist", "items", "representing", "auxiliary", "codebases", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/impl/ClassPathBuilder.java#L805-L829
santhosh-tekuri/jlibs
xsd/src/main/java/jlibs/xml/xsd/XSParser.java
XSParser.parseString
public XSModel parseString(String schema, String baseURI) { """ Parse an XML Schema document from String specified @param schema String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters). If an XML declaration is present, the value of the encoding attribute will be ignored. @param baseURI The base URI to be used for resolving relative URIs to absolute URIs. """ return xsLoader.load(new DOMInputImpl(null, null, baseURI, schema, null)); }
java
public XSModel parseString(String schema, String baseURI){ return xsLoader.load(new DOMInputImpl(null, null, baseURI, schema, null)); }
[ "public", "XSModel", "parseString", "(", "String", "schema", ",", "String", "baseURI", ")", "{", "return", "xsLoader", ".", "load", "(", "new", "DOMInputImpl", "(", "null", ",", "null", ",", "baseURI", ",", "schema", ",", "null", ")", ")", ";", "}" ]
Parse an XML Schema document from String specified @param schema String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters). If an XML declaration is present, the value of the encoding attribute will be ignored. @param baseURI The base URI to be used for resolving relative URIs to absolute URIs.
[ "Parse", "an", "XML", "Schema", "document", "from", "String", "specified" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/xsd/src/main/java/jlibs/xml/xsd/XSParser.java#L121-L123
joniles/mpxj
src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java
PrimaveraConvert.process
public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception { """ Extract Primavera project data and export in another format. @param driverClass JDBC driver class name @param connectionString JDBC connection string @param projectID project ID @param outputFile output file @throws Exception """ System.out.println("Reading Primavera database started."); Class.forName(driverClass); Properties props = new Properties(); // // This is not a very robust way to detect that we're working with SQLlite... // If you are trying to grab data from // a standalone P6 using SQLite, the SQLite JDBC driver needs this property // in order to correctly parse timestamps. // if (driverClass.equals("org.sqlite.JDBC")) { props.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss"); } Connection c = DriverManager.getConnection(connectionString, props); PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader(); reader.setConnection(c); processProject(reader, Integer.parseInt(projectID), outputFile); }
java
public void process(String driverClass, String connectionString, String projectID, String outputFile) throws Exception { System.out.println("Reading Primavera database started."); Class.forName(driverClass); Properties props = new Properties(); // // This is not a very robust way to detect that we're working with SQLlite... // If you are trying to grab data from // a standalone P6 using SQLite, the SQLite JDBC driver needs this property // in order to correctly parse timestamps. // if (driverClass.equals("org.sqlite.JDBC")) { props.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss"); } Connection c = DriverManager.getConnection(connectionString, props); PrimaveraDatabaseReader reader = new PrimaveraDatabaseReader(); reader.setConnection(c); processProject(reader, Integer.parseInt(projectID), outputFile); }
[ "public", "void", "process", "(", "String", "driverClass", ",", "String", "connectionString", ",", "String", "projectID", ",", "String", "outputFile", ")", "throws", "Exception", "{", "System", ".", "out", ".", "println", "(", "\"Reading Primavera database started.\"", ")", ";", "Class", ".", "forName", "(", "driverClass", ")", ";", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "//", "// This is not a very robust way to detect that we're working with SQLlite...", "// If you are trying to grab data from", "// a standalone P6 using SQLite, the SQLite JDBC driver needs this property", "// in order to correctly parse timestamps.", "//", "if", "(", "driverClass", ".", "equals", "(", "\"org.sqlite.JDBC\"", ")", ")", "{", "props", ".", "setProperty", "(", "\"date_string_format\"", ",", "\"yyyy-MM-dd HH:mm:ss\"", ")", ";", "}", "Connection", "c", "=", "DriverManager", ".", "getConnection", "(", "connectionString", ",", "props", ")", ";", "PrimaveraDatabaseReader", "reader", "=", "new", "PrimaveraDatabaseReader", "(", ")", ";", "reader", ".", "setConnection", "(", "c", ")", ";", "processProject", "(", "reader", ",", "Integer", ".", "parseInt", "(", "projectID", ")", ",", "outputFile", ")", ";", "}" ]
Extract Primavera project data and export in another format. @param driverClass JDBC driver class name @param connectionString JDBC connection string @param projectID project ID @param outputFile output file @throws Exception
[ "Extract", "Primavera", "project", "data", "and", "export", "in", "another", "format", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sample/PrimaveraConvert.java#L82-L105
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/KeyUpdateCollection.java
KeyUpdateCollection.add
void add(BucketUpdate.KeyUpdate update, int entryLength, long originalOffset) { """ Includes the given {@link BucketUpdate.KeyUpdate} into this collection. If we get multiple updates for the same key, only the one with highest version will be kept. Due to compaction, it is possible that a lower version of a Key will end up after a higher version of the same Key, in which case the higher version should take precedence. @param update The {@link BucketUpdate.KeyUpdate} to include. @param entryLength The total length of the given update, as serialized in the Segment. @param originalOffset If this update was a result of a compaction copy, then this should be the original offset where it was copied from (as serialized in the Segment). If no such information exists, then {@link TableKey#NO_VERSION} should be used. """ val existing = this.updates.get(update.getKey()); if (existing == null || update.supersedes(existing)) { this.updates.put(update.getKey(), update); } // Update remaining counters, regardless of whether we considered this update or not. this.totalUpdateCount.incrementAndGet(); long lastOffset = update.getOffset() + entryLength; this.lastIndexedOffset.updateAndGet(e -> Math.max(lastOffset, e)); if (originalOffset >= 0) { this.highestCopiedOffset.updateAndGet(e -> Math.max(e, originalOffset + entryLength)); } }
java
void add(BucketUpdate.KeyUpdate update, int entryLength, long originalOffset) { val existing = this.updates.get(update.getKey()); if (existing == null || update.supersedes(existing)) { this.updates.put(update.getKey(), update); } // Update remaining counters, regardless of whether we considered this update or not. this.totalUpdateCount.incrementAndGet(); long lastOffset = update.getOffset() + entryLength; this.lastIndexedOffset.updateAndGet(e -> Math.max(lastOffset, e)); if (originalOffset >= 0) { this.highestCopiedOffset.updateAndGet(e -> Math.max(e, originalOffset + entryLength)); } }
[ "void", "add", "(", "BucketUpdate", ".", "KeyUpdate", "update", ",", "int", "entryLength", ",", "long", "originalOffset", ")", "{", "val", "existing", "=", "this", ".", "updates", ".", "get", "(", "update", ".", "getKey", "(", ")", ")", ";", "if", "(", "existing", "==", "null", "||", "update", ".", "supersedes", "(", "existing", ")", ")", "{", "this", ".", "updates", ".", "put", "(", "update", ".", "getKey", "(", ")", ",", "update", ")", ";", "}", "// Update remaining counters, regardless of whether we considered this update or not.", "this", ".", "totalUpdateCount", ".", "incrementAndGet", "(", ")", ";", "long", "lastOffset", "=", "update", ".", "getOffset", "(", ")", "+", "entryLength", ";", "this", ".", "lastIndexedOffset", ".", "updateAndGet", "(", "e", "->", "Math", ".", "max", "(", "lastOffset", ",", "e", ")", ")", ";", "if", "(", "originalOffset", ">=", "0", ")", "{", "this", ".", "highestCopiedOffset", ".", "updateAndGet", "(", "e", "->", "Math", ".", "max", "(", "e", ",", "originalOffset", "+", "entryLength", ")", ")", ";", "}", "}" ]
Includes the given {@link BucketUpdate.KeyUpdate} into this collection. If we get multiple updates for the same key, only the one with highest version will be kept. Due to compaction, it is possible that a lower version of a Key will end up after a higher version of the same Key, in which case the higher version should take precedence. @param update The {@link BucketUpdate.KeyUpdate} to include. @param entryLength The total length of the given update, as serialized in the Segment. @param originalOffset If this update was a result of a compaction copy, then this should be the original offset where it was copied from (as serialized in the Segment). If no such information exists, then {@link TableKey#NO_VERSION} should be used.
[ "Includes", "the", "given", "{", "@link", "BucketUpdate", ".", "KeyUpdate", "}", "into", "this", "collection", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/KeyUpdateCollection.java#L72-L85
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java
ApiOvhDedicatedhousing.serviceName_task_taskId_cancel_POST
public void serviceName_task_taskId_cancel_POST(String serviceName, Long taskId) throws IOException { """ this action stop the task progression if it's possible REST: POST /dedicated/housing/{serviceName}/task/{taskId}/cancel @param serviceName [required] The internal name of your Housing bay @param taskId [required] the id of the task """ String qPath = "/dedicated/housing/{serviceName}/task/{taskId}/cancel"; StringBuilder sb = path(qPath, serviceName, taskId); exec(qPath, "POST", sb.toString(), null); }
java
public void serviceName_task_taskId_cancel_POST(String serviceName, Long taskId) throws IOException { String qPath = "/dedicated/housing/{serviceName}/task/{taskId}/cancel"; StringBuilder sb = path(qPath, serviceName, taskId); exec(qPath, "POST", sb.toString(), null); }
[ "public", "void", "serviceName_task_taskId_cancel_POST", "(", "String", "serviceName", ",", "Long", "taskId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/housing/{serviceName}/task/{taskId}/cancel\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "taskId", ")", ";", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
this action stop the task progression if it's possible REST: POST /dedicated/housing/{serviceName}/task/{taskId}/cancel @param serviceName [required] The internal name of your Housing bay @param taskId [required] the id of the task
[ "this", "action", "stop", "the", "task", "progression", "if", "it", "s", "possible" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java#L80-L84
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/transport/ClientTransportFactory.java
ClientTransportFactory.getReverseClientTransport
public static ClientTransport getReverseClientTransport(String container, AbstractChannel channel) { """ 构建反向的(服务端到客户端)虚拟长连接 @param container Container of client transport @param channel Exists channel from client @return reverse client transport of exists channel """ if (REVERSE_CLIENT_TRANSPORT_MAP == null) { // 初始化 synchronized (ClientTransportFactory.class) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { REVERSE_CLIENT_TRANSPORT_MAP = new ConcurrentHashMap<String, ClientTransport>(); } } } String key = NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()); ClientTransport transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { synchronized (ClientTransportFactory.class) { transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { ClientTransportConfig config = new ClientTransportConfig() .setProviderInfo(new ProviderInfo().setHost(channel.remoteAddress().getHostName()) .setPort(channel.remoteAddress().getPort())) .setContainer(container); transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class) .getExtension(config.getContainer(), new Class[] { ClientTransportConfig.class }, new Object[] { config }); transport.setChannel(channel); REVERSE_CLIENT_TRANSPORT_MAP.put(key, transport); // 保存唯一长连接 } } } return transport; }
java
public static ClientTransport getReverseClientTransport(String container, AbstractChannel channel) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { // 初始化 synchronized (ClientTransportFactory.class) { if (REVERSE_CLIENT_TRANSPORT_MAP == null) { REVERSE_CLIENT_TRANSPORT_MAP = new ConcurrentHashMap<String, ClientTransport>(); } } } String key = NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()); ClientTransport transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { synchronized (ClientTransportFactory.class) { transport = REVERSE_CLIENT_TRANSPORT_MAP.get(key); if (transport == null) { ClientTransportConfig config = new ClientTransportConfig() .setProviderInfo(new ProviderInfo().setHost(channel.remoteAddress().getHostName()) .setPort(channel.remoteAddress().getPort())) .setContainer(container); transport = ExtensionLoaderFactory.getExtensionLoader(ClientTransport.class) .getExtension(config.getContainer(), new Class[] { ClientTransportConfig.class }, new Object[] { config }); transport.setChannel(channel); REVERSE_CLIENT_TRANSPORT_MAP.put(key, transport); // 保存唯一长连接 } } } return transport; }
[ "public", "static", "ClientTransport", "getReverseClientTransport", "(", "String", "container", ",", "AbstractChannel", "channel", ")", "{", "if", "(", "REVERSE_CLIENT_TRANSPORT_MAP", "==", "null", ")", "{", "// 初始化", "synchronized", "(", "ClientTransportFactory", ".", "class", ")", "{", "if", "(", "REVERSE_CLIENT_TRANSPORT_MAP", "==", "null", ")", "{", "REVERSE_CLIENT_TRANSPORT_MAP", "=", "new", "ConcurrentHashMap", "<", "String", ",", "ClientTransport", ">", "(", ")", ";", "}", "}", "}", "String", "key", "=", "NetUtils", ".", "channelToString", "(", "channel", ".", "remoteAddress", "(", ")", ",", "channel", ".", "localAddress", "(", ")", ")", ";", "ClientTransport", "transport", "=", "REVERSE_CLIENT_TRANSPORT_MAP", ".", "get", "(", "key", ")", ";", "if", "(", "transport", "==", "null", ")", "{", "synchronized", "(", "ClientTransportFactory", ".", "class", ")", "{", "transport", "=", "REVERSE_CLIENT_TRANSPORT_MAP", ".", "get", "(", "key", ")", ";", "if", "(", "transport", "==", "null", ")", "{", "ClientTransportConfig", "config", "=", "new", "ClientTransportConfig", "(", ")", ".", "setProviderInfo", "(", "new", "ProviderInfo", "(", ")", ".", "setHost", "(", "channel", ".", "remoteAddress", "(", ")", ".", "getHostName", "(", ")", ")", ".", "setPort", "(", "channel", ".", "remoteAddress", "(", ")", ".", "getPort", "(", ")", ")", ")", ".", "setContainer", "(", "container", ")", ";", "transport", "=", "ExtensionLoaderFactory", ".", "getExtensionLoader", "(", "ClientTransport", ".", "class", ")", ".", "getExtension", "(", "config", ".", "getContainer", "(", ")", ",", "new", "Class", "[", "]", "{", "ClientTransportConfig", ".", "class", "}", ",", "new", "Object", "[", "]", "{", "config", "}", ")", ";", "transport", ".", "setChannel", "(", "channel", ")", ";", "REVERSE_CLIENT_TRANSPORT_MAP", ".", "put", "(", "key", ",", "transport", ")", ";", "// 保存唯一长连接", "}", "}", "}", "return", "transport", ";", "}" ]
构建反向的(服务端到客户端)虚拟长连接 @param container Container of client transport @param channel Exists channel from client @return reverse client transport of exists channel
[ "构建反向的(服务端到客户端)虚拟长连接" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/transport/ClientTransportFactory.java#L135-L163
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java
DateFunctions.dateAddMillis
public static Expression dateAddMillis(String expression, int n, DatePart part) { """ Returned expression performs Date arithmetic, and returns result of computation. n and part are used to define an interval or duration, which is then added (or subtracted) to the UNIX timestamp, returning the result. """ return dateAddMillis(x(expression), n, part); }
java
public static Expression dateAddMillis(String expression, int n, DatePart part) { return dateAddMillis(x(expression), n, part); }
[ "public", "static", "Expression", "dateAddMillis", "(", "String", "expression", ",", "int", "n", ",", "DatePart", "part", ")", "{", "return", "dateAddMillis", "(", "x", "(", "expression", ")", ",", "n", ",", "part", ")", ";", "}" ]
Returned expression performs Date arithmetic, and returns result of computation. n and part are used to define an interval or duration, which is then added (or subtracted) to the UNIX timestamp, returning the result.
[ "Returned", "expression", "performs", "Date", "arithmetic", "and", "returns", "result", "of", "computation", ".", "n", "and", "part", "are", "used", "to", "define", "an", "interval", "or", "duration", "which", "is", "then", "added", "(", "or", "subtracted", ")", "to", "the", "UNIX", "timestamp", "returning", "the", "result", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L82-L84
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/api/KickflipApiClient.java
KickflipApiClient.stopStream
public void stopStream(Stream stream, final KickflipCallback cb) { """ Stop a Stream. Must be called after {@link io.kickflip.sdk.api.KickflipApiClient#createNewUser(KickflipCallback)} and {@link io.kickflip.sdk.api.KickflipApiClient#startStream(io.kickflip.sdk.api.json.Stream, KickflipCallback)} @param cb This callback will receive a Stream subclass in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)} depending on the Kickflip account type. Implementors should check if the response is instanceof HlsStream, etc. """ if (!assertActiveUserAvailable(cb)) return; stopStream(getActiveUser(), stream, cb); }
java
public void stopStream(Stream stream, final KickflipCallback cb) { if (!assertActiveUserAvailable(cb)) return; stopStream(getActiveUser(), stream, cb); }
[ "public", "void", "stopStream", "(", "Stream", "stream", ",", "final", "KickflipCallback", "cb", ")", "{", "if", "(", "!", "assertActiveUserAvailable", "(", "cb", ")", ")", "return", ";", "stopStream", "(", "getActiveUser", "(", ")", ",", "stream", ",", "cb", ")", ";", "}" ]
Stop a Stream. Must be called after {@link io.kickflip.sdk.api.KickflipApiClient#createNewUser(KickflipCallback)} and {@link io.kickflip.sdk.api.KickflipApiClient#startStream(io.kickflip.sdk.api.json.Stream, KickflipCallback)} @param cb This callback will receive a Stream subclass in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)} depending on the Kickflip account type. Implementors should check if the response is instanceof HlsStream, etc.
[ "Stop", "a", "Stream", ".", "Must", "be", "called", "after", "{", "@link", "io", ".", "kickflip", ".", "sdk", ".", "api", ".", "KickflipApiClient#createNewUser", "(", "KickflipCallback", ")", "}", "and", "{", "@link", "io", ".", "kickflip", ".", "sdk", ".", "api", ".", "KickflipApiClient#startStream", "(", "io", ".", "kickflip", ".", "sdk", ".", "api", ".", "json", ".", "Stream", "KickflipCallback", ")", "}" ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/api/KickflipApiClient.java#L358-L361
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/transform/StaxUnmarshallerContext.java
StaxUnmarshallerContext.registerMetadataExpression
public void registerMetadataExpression(String expression, int targetDepth, String storageKey) { """ Registers an expression, which if matched, will cause the data for the matching element to be stored in the metadata map under the specified key. @param expression The expression an element must match in order for it's data to be pulled out and stored in the metadata map. @param targetDepth The depth in the XML document where the expression match must start. @param storageKey The key under which to store the matching element's data. """ metadataExpressions.add(new MetadataExpression(expression, targetDepth, storageKey)); }
java
public void registerMetadataExpression(String expression, int targetDepth, String storageKey) { metadataExpressions.add(new MetadataExpression(expression, targetDepth, storageKey)); }
[ "public", "void", "registerMetadataExpression", "(", "String", "expression", ",", "int", "targetDepth", ",", "String", "storageKey", ")", "{", "metadataExpressions", ".", "add", "(", "new", "MetadataExpression", "(", "expression", ",", "targetDepth", ",", "storageKey", ")", ")", ";", "}" ]
Registers an expression, which if matched, will cause the data for the matching element to be stored in the metadata map under the specified key. @param expression The expression an element must match in order for it's data to be pulled out and stored in the metadata map. @param targetDepth The depth in the XML document where the expression match must start. @param storageKey The key under which to store the matching element's data.
[ "Registers", "an", "expression", "which", "if", "matched", "will", "cause", "the", "data", "for", "the", "matching", "element", "to", "be", "stored", "in", "the", "metadata", "map", "under", "the", "specified", "key", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/transform/StaxUnmarshallerContext.java#L258-L260
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java
HullWhiteModel.getA
private RandomVariable getA(double time, double maturity) { """ Returns A(t,T) where \( A(t,T) = P(T)/P(t) \cdot exp(B(t,T) \cdot f(0,t) - \frac{1}{2} \phi(0,t) * B(t,T)^{2} ) \) and \( \phi(t,T) \) is the value calculated from integrating \( ( \sigma(s) exp(-\int_{s}^{T} a(\tau) \mathrm{d}\tau ) )^{2} \) with respect to s from t to T in <code>getShortRateConditionalVariance</code>. @param time The parameter t. @param maturity The parameter T. @return The value A(t,T). """ int timeIndex = getProcess().getTimeIndex(time); double timeStep = getProcess().getTimeDiscretization().getTimeStep(timeIndex); RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time); RandomVariable forwardBond = getDiscountFactorFromForwardCurve(maturity).div(getDiscountFactorFromForwardCurve(time)).log(); RandomVariable B = getB(time,maturity); RandomVariable lnA = B.mult(zeroRate).sub(B.squared().mult(getShortRateConditionalVariance(0,time).div(2))).add(forwardBond); return lnA.exp(); }
java
private RandomVariable getA(double time, double maturity) { int timeIndex = getProcess().getTimeIndex(time); double timeStep = getProcess().getTimeDiscretization().getTimeStep(timeIndex); RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time); RandomVariable forwardBond = getDiscountFactorFromForwardCurve(maturity).div(getDiscountFactorFromForwardCurve(time)).log(); RandomVariable B = getB(time,maturity); RandomVariable lnA = B.mult(zeroRate).sub(B.squared().mult(getShortRateConditionalVariance(0,time).div(2))).add(forwardBond); return lnA.exp(); }
[ "private", "RandomVariable", "getA", "(", "double", "time", ",", "double", "maturity", ")", "{", "int", "timeIndex", "=", "getProcess", "(", ")", ".", "getTimeIndex", "(", "time", ")", ";", "double", "timeStep", "=", "getProcess", "(", ")", ".", "getTimeDiscretization", "(", ")", ".", "getTimeStep", "(", "timeIndex", ")", ";", "RandomVariable", "zeroRate", "=", "getZeroRateFromForwardCurve", "(", "time", ")", ";", "//getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time);", "RandomVariable", "forwardBond", "=", "getDiscountFactorFromForwardCurve", "(", "maturity", ")", ".", "div", "(", "getDiscountFactorFromForwardCurve", "(", "time", ")", ")", ".", "log", "(", ")", ";", "RandomVariable", "B", "=", "getB", "(", "time", ",", "maturity", ")", ";", "RandomVariable", "lnA", "=", "B", ".", "mult", "(", "zeroRate", ")", ".", "sub", "(", "B", ".", "squared", "(", ")", ".", "mult", "(", "getShortRateConditionalVariance", "(", "0", ",", "time", ")", ".", "div", "(", "2", ")", ")", ")", ".", "add", "(", "forwardBond", ")", ";", "return", "lnA", ".", "exp", "(", ")", ";", "}" ]
Returns A(t,T) where \( A(t,T) = P(T)/P(t) \cdot exp(B(t,T) \cdot f(0,t) - \frac{1}{2} \phi(0,t) * B(t,T)^{2} ) \) and \( \phi(t,T) \) is the value calculated from integrating \( ( \sigma(s) exp(-\int_{s}^{T} a(\tau) \mathrm{d}\tau ) )^{2} \) with respect to s from t to T in <code>getShortRateConditionalVariance</code>. @param time The parameter t. @param maturity The parameter T. @return The value A(t,T).
[ "Returns", "A", "(", "t", "T", ")", "where", "\\", "(", "A", "(", "t", "T", ")", "=", "P", "(", "T", ")", "/", "P", "(", "t", ")", "\\", "cdot", "exp", "(", "B", "(", "t", "T", ")", "\\", "cdot", "f", "(", "0", "t", ")", "-", "\\", "frac", "{", "1", "}", "{", "2", "}", "\\", "phi", "(", "0", "t", ")", "*", "B", "(", "t", "T", ")", "^", "{", "2", "}", ")", "\\", ")", "and", "\\", "(", "\\", "phi", "(", "t", "T", ")", "\\", ")", "is", "the", "value", "calculated", "from", "integrating", "\\", "(", "(", "\\", "sigma", "(", "s", ")", "exp", "(", "-", "\\", "int_", "{", "s", "}", "^", "{", "T", "}", "a", "(", "\\", "tau", ")", "\\", "mathrm", "{", "d", "}", "\\", "tau", ")", ")", "^", "{", "2", "}", "\\", ")", "with", "respect", "to", "s", "from", "t", "to", "T", "in", "<code", ">", "getShortRateConditionalVariance<", "/", "code", ">", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java#L558-L571
voldemort/voldemort
src/java/voldemort/utils/UpdateClusterUtils.java
UpdateClusterUtils.removePartitionFromNode
public static Node removePartitionFromNode(final Node node, Integer donatedPartition) { """ Remove a partition from the node provided @param node The node from which we're removing the partition @param donatedPartition The partitions to remove @return The new node without the partition """ return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition)); }
java
public static Node removePartitionFromNode(final Node node, Integer donatedPartition) { return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition)); }
[ "public", "static", "Node", "removePartitionFromNode", "(", "final", "Node", "node", ",", "Integer", "donatedPartition", ")", "{", "return", "UpdateClusterUtils", ".", "removePartitionsFromNode", "(", "node", ",", "Sets", ".", "newHashSet", "(", "donatedPartition", ")", ")", ";", "}" ]
Remove a partition from the node provided @param node The node from which we're removing the partition @param donatedPartition The partitions to remove @return The new node without the partition
[ "Remove", "a", "partition", "from", "the", "node", "provided" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L78-L80
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java
PerspectiveOps.convertNormToPixel
public static Point2D_F64 convertNormToPixel( DMatrixRMaj K, Point2D_F64 norm , Point2D_F64 pixel ) { """ <p> Convenient function for converting from normalized image coordinates to the original image pixel coordinate. If speed is a concern then {@link PinholeNtoP_F64} should be used instead. </p> NOTE: norm and pixel can be the same instance. @param K Intrinsic camera calibration matrix @param norm Normalized image coordinate. @param pixel Optional storage for output. If null a new instance will be declared. @return pixel image coordinate """ return ImplPerspectiveOps_F64.convertNormToPixel(K, norm, pixel); }
java
public static Point2D_F64 convertNormToPixel( DMatrixRMaj K, Point2D_F64 norm , Point2D_F64 pixel ) { return ImplPerspectiveOps_F64.convertNormToPixel(K, norm, pixel); }
[ "public", "static", "Point2D_F64", "convertNormToPixel", "(", "DMatrixRMaj", "K", ",", "Point2D_F64", "norm", ",", "Point2D_F64", "pixel", ")", "{", "return", "ImplPerspectiveOps_F64", ".", "convertNormToPixel", "(", "K", ",", "norm", ",", "pixel", ")", ";", "}" ]
<p> Convenient function for converting from normalized image coordinates to the original image pixel coordinate. If speed is a concern then {@link PinholeNtoP_F64} should be used instead. </p> NOTE: norm and pixel can be the same instance. @param K Intrinsic camera calibration matrix @param norm Normalized image coordinate. @param pixel Optional storage for output. If null a new instance will be declared. @return pixel image coordinate
[ "<p", ">", "Convenient", "function", "for", "converting", "from", "normalized", "image", "coordinates", "to", "the", "original", "image", "pixel", "coordinate", ".", "If", "speed", "is", "a", "concern", "then", "{", "@link", "PinholeNtoP_F64", "}", "should", "be", "used", "instead", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L427-L430
xmlunit/xmlunit
xmlunit-matchers/src/main/java/org/xmlunit/matchers/EvaluateXPathMatcher.java
EvaluateXPathMatcher.hasXPath
@Factory public static EvaluateXPathMatcher hasXPath(String xPath, Matcher<String> valueMatcher) { """ Creates a matcher that matches when the examined XML input has a value at the specified <code>xPath</code> that satisfies the specified <code>valueMatcher</code>. <p>For example:</p> <pre>assertThat(xml, hasXPath(&quot;//fruits/fruit/@name&quot;, equalTo(&quot;apple&quot;))</pre> @param xPath the target xpath @param valueMatcher matcher for the value at the specified xpath @return the xpath matcher """ return new EvaluateXPathMatcher(xPath, valueMatcher); }
java
@Factory public static EvaluateXPathMatcher hasXPath(String xPath, Matcher<String> valueMatcher) { return new EvaluateXPathMatcher(xPath, valueMatcher); }
[ "@", "Factory", "public", "static", "EvaluateXPathMatcher", "hasXPath", "(", "String", "xPath", ",", "Matcher", "<", "String", ">", "valueMatcher", ")", "{", "return", "new", "EvaluateXPathMatcher", "(", "xPath", ",", "valueMatcher", ")", ";", "}" ]
Creates a matcher that matches when the examined XML input has a value at the specified <code>xPath</code> that satisfies the specified <code>valueMatcher</code>. <p>For example:</p> <pre>assertThat(xml, hasXPath(&quot;//fruits/fruit/@name&quot;, equalTo(&quot;apple&quot;))</pre> @param xPath the target xpath @param valueMatcher matcher for the value at the specified xpath @return the xpath matcher
[ "Creates", "a", "matcher", "that", "matches", "when", "the", "examined", "XML", "input", "has", "a", "value", "at", "the", "specified", "<code", ">", "xPath<", "/", "code", ">", "that", "satisfies", "the", "specified", "<code", ">", "valueMatcher<", "/", "code", ">", "." ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-matchers/src/main/java/org/xmlunit/matchers/EvaluateXPathMatcher.java#L96-L99
jMetal/jMetal
jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/UniformMutation.java
UniformMutation.doMutation
public void doMutation(double probability, DoubleSolution solution) { """ Perform the operation @param probability Mutation setProbability @param solution The solution to mutate """ for (int i = 0; i < solution.getNumberOfVariables(); i++) { if (randomGenenerator.getRandomValue() < probability) { double rand = randomGenenerator.getRandomValue(); double tmp = (rand - 0.5) * perturbation; tmp += solution.getVariableValue(i); if (tmp < solution.getLowerBound(i)) { tmp = solution.getLowerBound(i); } else if (tmp > solution.getUpperBound(i)) { tmp = solution.getUpperBound(i); } solution.setVariableValue(i, tmp); } } }
java
public void doMutation(double probability, DoubleSolution solution) { for (int i = 0; i < solution.getNumberOfVariables(); i++) { if (randomGenenerator.getRandomValue() < probability) { double rand = randomGenenerator.getRandomValue(); double tmp = (rand - 0.5) * perturbation; tmp += solution.getVariableValue(i); if (tmp < solution.getLowerBound(i)) { tmp = solution.getLowerBound(i); } else if (tmp > solution.getUpperBound(i)) { tmp = solution.getUpperBound(i); } solution.setVariableValue(i, tmp); } } }
[ "public", "void", "doMutation", "(", "double", "probability", ",", "DoubleSolution", "solution", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "solution", ".", "getNumberOfVariables", "(", ")", ";", "i", "++", ")", "{", "if", "(", "randomGenenerator", ".", "getRandomValue", "(", ")", "<", "probability", ")", "{", "double", "rand", "=", "randomGenenerator", ".", "getRandomValue", "(", ")", ";", "double", "tmp", "=", "(", "rand", "-", "0.5", ")", "*", "perturbation", ";", "tmp", "+=", "solution", ".", "getVariableValue", "(", "i", ")", ";", "if", "(", "tmp", "<", "solution", ".", "getLowerBound", "(", "i", ")", ")", "{", "tmp", "=", "solution", ".", "getLowerBound", "(", "i", ")", ";", "}", "else", "if", "(", "tmp", ">", "solution", ".", "getUpperBound", "(", "i", ")", ")", "{", "tmp", "=", "solution", ".", "getUpperBound", "(", "i", ")", ";", "}", "solution", ".", "setVariableValue", "(", "i", ",", "tmp", ")", ";", "}", "}", "}" ]
Perform the operation @param probability Mutation setProbability @param solution The solution to mutate
[ "Perform", "the", "operation" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/operator/impl/mutation/UniformMutation.java#L57-L74
prestodb/presto
presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/IndexLookup.java
IndexLookup.applyIndex
public boolean applyIndex( String schema, String table, ConnectorSession session, Collection<AccumuloColumnConstraint> constraints, Collection<Range> rowIdRanges, List<TabletSplitMetadata> tabletSplits, AccumuloRowSerializer serializer, Authorizations auths) throws Exception { """ Scans the index table, applying the index based on the given column constraints to return a set of tablet splits. <p> If this function returns true, the output parameter tabletSplits contains a list of TabletSplitMetadata objects. These in turn contain a collection of Ranges containing the exact row IDs determined using the index. <p> If this function returns false, the secondary index should not be used. In this case, either the accumulo session has disabled secondary indexing, or the number of row IDs that would be used by the secondary index is greater than the configured threshold (again retrieved from the session). @param schema Schema name @param table Table name @param session Current client session @param constraints All column constraints (this method will filter for if the column is indexed) @param rowIdRanges Collection of Accumulo ranges based on any predicate against a record key @param tabletSplits Output parameter containing the bundles of row IDs determined by the use of the index. @param serializer Instance of a row serializer @param auths Scan-time authorizations @return True if the tablet splits are valid and should be used, false otherwise @throws Exception If something bad happens. What are the odds? """ // Early out if index is disabled if (!isOptimizeIndexEnabled(session)) { LOG.debug("Secondary index is disabled"); return false; } LOG.debug("Secondary index is enabled"); // Collect Accumulo ranges for each indexed column constraint Multimap<AccumuloColumnConstraint, Range> constraintRanges = getIndexedConstraintRanges(constraints, serializer); // If there is no constraints on an index column, we again will bail out if (constraintRanges.isEmpty()) { LOG.debug("Query contains no constraints on indexed columns, skipping secondary index"); return false; } // If metrics are not enabled if (!isIndexMetricsEnabled(session)) { LOG.debug("Use of index metrics is disabled"); // Get the ranges via the index table List<Range> indexRanges = getIndexRanges(getIndexTableName(schema, table), constraintRanges, rowIdRanges, auths); if (!indexRanges.isEmpty()) { // Bin the ranges into TabletMetadataSplits and return true to use the tablet splits binRanges(getNumIndexRowsPerSplit(session), indexRanges, tabletSplits); LOG.debug("Number of splits for %s.%s is %d with %d ranges", schema, table, tabletSplits.size(), indexRanges.size()); } else { LOG.debug("Query would return no results, returning empty list of splits"); } return true; } else { LOG.debug("Use of index metrics is enabled"); // Get ranges using the metrics return getRangesWithMetrics(session, schema, table, constraintRanges, rowIdRanges, tabletSplits, auths); } }
java
public boolean applyIndex( String schema, String table, ConnectorSession session, Collection<AccumuloColumnConstraint> constraints, Collection<Range> rowIdRanges, List<TabletSplitMetadata> tabletSplits, AccumuloRowSerializer serializer, Authorizations auths) throws Exception { // Early out if index is disabled if (!isOptimizeIndexEnabled(session)) { LOG.debug("Secondary index is disabled"); return false; } LOG.debug("Secondary index is enabled"); // Collect Accumulo ranges for each indexed column constraint Multimap<AccumuloColumnConstraint, Range> constraintRanges = getIndexedConstraintRanges(constraints, serializer); // If there is no constraints on an index column, we again will bail out if (constraintRanges.isEmpty()) { LOG.debug("Query contains no constraints on indexed columns, skipping secondary index"); return false; } // If metrics are not enabled if (!isIndexMetricsEnabled(session)) { LOG.debug("Use of index metrics is disabled"); // Get the ranges via the index table List<Range> indexRanges = getIndexRanges(getIndexTableName(schema, table), constraintRanges, rowIdRanges, auths); if (!indexRanges.isEmpty()) { // Bin the ranges into TabletMetadataSplits and return true to use the tablet splits binRanges(getNumIndexRowsPerSplit(session), indexRanges, tabletSplits); LOG.debug("Number of splits for %s.%s is %d with %d ranges", schema, table, tabletSplits.size(), indexRanges.size()); } else { LOG.debug("Query would return no results, returning empty list of splits"); } return true; } else { LOG.debug("Use of index metrics is enabled"); // Get ranges using the metrics return getRangesWithMetrics(session, schema, table, constraintRanges, rowIdRanges, tabletSplits, auths); } }
[ "public", "boolean", "applyIndex", "(", "String", "schema", ",", "String", "table", ",", "ConnectorSession", "session", ",", "Collection", "<", "AccumuloColumnConstraint", ">", "constraints", ",", "Collection", "<", "Range", ">", "rowIdRanges", ",", "List", "<", "TabletSplitMetadata", ">", "tabletSplits", ",", "AccumuloRowSerializer", "serializer", ",", "Authorizations", "auths", ")", "throws", "Exception", "{", "// Early out if index is disabled", "if", "(", "!", "isOptimizeIndexEnabled", "(", "session", ")", ")", "{", "LOG", ".", "debug", "(", "\"Secondary index is disabled\"", ")", ";", "return", "false", ";", "}", "LOG", ".", "debug", "(", "\"Secondary index is enabled\"", ")", ";", "// Collect Accumulo ranges for each indexed column constraint", "Multimap", "<", "AccumuloColumnConstraint", ",", "Range", ">", "constraintRanges", "=", "getIndexedConstraintRanges", "(", "constraints", ",", "serializer", ")", ";", "// If there is no constraints on an index column, we again will bail out", "if", "(", "constraintRanges", ".", "isEmpty", "(", ")", ")", "{", "LOG", ".", "debug", "(", "\"Query contains no constraints on indexed columns, skipping secondary index\"", ")", ";", "return", "false", ";", "}", "// If metrics are not enabled", "if", "(", "!", "isIndexMetricsEnabled", "(", "session", ")", ")", "{", "LOG", ".", "debug", "(", "\"Use of index metrics is disabled\"", ")", ";", "// Get the ranges via the index table", "List", "<", "Range", ">", "indexRanges", "=", "getIndexRanges", "(", "getIndexTableName", "(", "schema", ",", "table", ")", ",", "constraintRanges", ",", "rowIdRanges", ",", "auths", ")", ";", "if", "(", "!", "indexRanges", ".", "isEmpty", "(", ")", ")", "{", "// Bin the ranges into TabletMetadataSplits and return true to use the tablet splits", "binRanges", "(", "getNumIndexRowsPerSplit", "(", "session", ")", ",", "indexRanges", ",", "tabletSplits", ")", ";", "LOG", ".", "debug", "(", "\"Number of splits for %s.%s is %d with %d ranges\"", ",", "schema", ",", "table", ",", "tabletSplits", ".", "size", "(", ")", ",", "indexRanges", ".", "size", "(", ")", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Query would return no results, returning empty list of splits\"", ")", ";", "}", "return", "true", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Use of index metrics is enabled\"", ")", ";", "// Get ranges using the metrics", "return", "getRangesWithMetrics", "(", "session", ",", "schema", ",", "table", ",", "constraintRanges", ",", "rowIdRanges", ",", "tabletSplits", ",", "auths", ")", ";", "}", "}" ]
Scans the index table, applying the index based on the given column constraints to return a set of tablet splits. <p> If this function returns true, the output parameter tabletSplits contains a list of TabletSplitMetadata objects. These in turn contain a collection of Ranges containing the exact row IDs determined using the index. <p> If this function returns false, the secondary index should not be used. In this case, either the accumulo session has disabled secondary indexing, or the number of row IDs that would be used by the secondary index is greater than the configured threshold (again retrieved from the session). @param schema Schema name @param table Table name @param session Current client session @param constraints All column constraints (this method will filter for if the column is indexed) @param rowIdRanges Collection of Accumulo ranges based on any predicate against a record key @param tabletSplits Output parameter containing the bundles of row IDs determined by the use of the index. @param serializer Instance of a row serializer @param auths Scan-time authorizations @return True if the tablet splits are valid and should be used, false otherwise @throws Exception If something bad happens. What are the odds?
[ "Scans", "the", "index", "table", "applying", "the", "index", "based", "on", "the", "given", "column", "constraints", "to", "return", "a", "set", "of", "tablet", "splits", ".", "<p", ">", "If", "this", "function", "returns", "true", "the", "output", "parameter", "tabletSplits", "contains", "a", "list", "of", "TabletSplitMetadata", "objects", ".", "These", "in", "turn", "contain", "a", "collection", "of", "Ranges", "containing", "the", "exact", "row", "IDs", "determined", "using", "the", "index", ".", "<p", ">", "If", "this", "function", "returns", "false", "the", "secondary", "index", "should", "not", "be", "used", ".", "In", "this", "case", "either", "the", "accumulo", "session", "has", "disabled", "secondary", "indexing", "or", "the", "number", "of", "row", "IDs", "that", "would", "be", "used", "by", "the", "secondary", "index", "is", "greater", "than", "the", "configured", "threshold", "(", "again", "retrieved", "from", "the", "session", ")", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/IndexLookup.java#L129-L179
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java
DCacheBase.setValue
public void setValue(EntryInfo entryInfo, Object value) { """ This sets the actual value (JSP or command) of an entry in the cache. @param entryInfo The cache entry @param value The value to cache in the entry """ setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), DynaCacheConstants.VBC_CACHE_NEW_CONTENT); }
java
public void setValue(EntryInfo entryInfo, Object value) { setValue(entryInfo, value, !shouldPull(entryInfo.getSharingPolicy(), entryInfo.id), DynaCacheConstants.VBC_CACHE_NEW_CONTENT); }
[ "public", "void", "setValue", "(", "EntryInfo", "entryInfo", ",", "Object", "value", ")", "{", "setValue", "(", "entryInfo", ",", "value", ",", "!", "shouldPull", "(", "entryInfo", ".", "getSharingPolicy", "(", ")", ",", "entryInfo", ".", "id", ")", ",", "DynaCacheConstants", ".", "VBC_CACHE_NEW_CONTENT", ")", ";", "}" ]
This sets the actual value (JSP or command) of an entry in the cache. @param entryInfo The cache entry @param value The value to cache in the entry
[ "This", "sets", "the", "actual", "value", "(", "JSP", "or", "command", ")", "of", "an", "entry", "in", "the", "cache", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java#L521-L523
foundation-runtime/service-directory
1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java
DirectoryRegistrationService.registerService
public void registerService(ProvidedServiceInstance serviceInstance, ServiceInstanceHealth registryHealth) { """ Register a ProvidedServiceInstance with the ServiceInstanceHealth callback. @param serviceInstance the ProvidedServiceInstance. @param registryHealth the ServiceInstanceHealth callback. """ // Monitor disabled ProvidedServiceInstance should not have the ServiceInstanceHealth. if(serviceInstance.isMonitorEnabled()== false){ throw new ServiceException(ErrorCode.SERVICE_INSTANCE_HEALTH_ERROR); } registerService(serviceInstance); }
java
public void registerService(ProvidedServiceInstance serviceInstance, ServiceInstanceHealth registryHealth) { // Monitor disabled ProvidedServiceInstance should not have the ServiceInstanceHealth. if(serviceInstance.isMonitorEnabled()== false){ throw new ServiceException(ErrorCode.SERVICE_INSTANCE_HEALTH_ERROR); } registerService(serviceInstance); }
[ "public", "void", "registerService", "(", "ProvidedServiceInstance", "serviceInstance", ",", "ServiceInstanceHealth", "registryHealth", ")", "{", "// Monitor disabled ProvidedServiceInstance should not have the ServiceInstanceHealth.", "if", "(", "serviceInstance", ".", "isMonitorEnabled", "(", ")", "==", "false", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_INSTANCE_HEALTH_ERROR", ")", ";", "}", "registerService", "(", "serviceInstance", ")", ";", "}" ]
Register a ProvidedServiceInstance with the ServiceInstanceHealth callback. @param serviceInstance the ProvidedServiceInstance. @param registryHealth the ServiceInstanceHealth callback.
[ "Register", "a", "ProvidedServiceInstance", "with", "the", "ServiceInstanceHealth", "callback", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryRegistrationService.java#L102-L108
jbundle/jbundle
base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/report/HHeadingScreen.java
HHeadingScreen.printDataEndForm
public void printDataEndForm(PrintWriter out, int iPrintOptions) { """ Output this screen using HTML. @exception DBException File exception. """ out.println("</tr>\n</table>"); if ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) != 0) out.println("</td>\n</tr>"); }
java
public void printDataEndForm(PrintWriter out, int iPrintOptions) { out.println("</tr>\n</table>"); if ((iPrintOptions & HtmlConstants.DETAIL_SCREEN) != 0) out.println("</td>\n</tr>"); }
[ "public", "void", "printDataEndForm", "(", "PrintWriter", "out", ",", "int", "iPrintOptions", ")", "{", "out", ".", "println", "(", "\"</tr>\\n</table>\"", ")", ";", "if", "(", "(", "iPrintOptions", "&", "HtmlConstants", ".", "DETAIL_SCREEN", ")", "!=", "0", ")", "out", ".", "println", "(", "\"</td>\\n</tr>\"", ")", ";", "}" ]
Output this screen using HTML. @exception DBException File exception.
[ "Output", "this", "screen", "using", "HTML", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/report/HHeadingScreen.java#L88-L93
shinesolutions/swagger-aem
java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java
SlingApi.postAuthorizableKeystoreAsync
public com.squareup.okhttp.Call postAuthorizableKeystoreAsync(String intermediatePath, String authorizableId, String operation, String currentPassword, String newPassword, String rePassword, String keyPassword, String keyStorePass, String operation2, String alias, String newAlias, String removeAlias, File certChain, File pk, File keyStore, final ApiCallback<KeystoreInformations> callback) throws ApiException { """ (asynchronously) @param intermediatePath (required) @param authorizableId (required) @param operation (optional) @param currentPassword (optional) @param newPassword (optional) @param rePassword (optional) @param keyPassword (optional) @param keyStorePass (optional) @param operation2 (optional) @param alias (optional) @param newAlias (optional) @param removeAlias (optional) @param certChain (optional) @param pk (optional) @param keyStore (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object """ ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postAuthorizableKeystoreValidateBeforeCall(intermediatePath, authorizableId, operation, currentPassword, newPassword, rePassword, keyPassword, keyStorePass, operation2, alias, newAlias, removeAlias, certChain, pk, keyStore, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<KeystoreInformations>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call postAuthorizableKeystoreAsync(String intermediatePath, String authorizableId, String operation, String currentPassword, String newPassword, String rePassword, String keyPassword, String keyStorePass, String operation2, String alias, String newAlias, String removeAlias, File certChain, File pk, File keyStore, final ApiCallback<KeystoreInformations> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postAuthorizableKeystoreValidateBeforeCall(intermediatePath, authorizableId, operation, currentPassword, newPassword, rePassword, keyPassword, keyStorePass, operation2, alias, newAlias, removeAlias, certChain, pk, keyStore, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<KeystoreInformations>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "postAuthorizableKeystoreAsync", "(", "String", "intermediatePath", ",", "String", "authorizableId", ",", "String", "operation", ",", "String", "currentPassword", ",", "String", "newPassword", ",", "String", "rePassword", ",", "String", "keyPassword", ",", "String", "keyStorePass", ",", "String", "operation2", ",", "String", "alias", ",", "String", "newAlias", ",", "String", "removeAlias", ",", "File", "certChain", ",", "File", "pk", ",", "File", "keyStore", ",", "final", "ApiCallback", "<", "KeystoreInformations", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "postAuthorizableKeystoreValidateBeforeCall", "(", "intermediatePath", ",", "authorizableId", ",", "operation", ",", "currentPassword", ",", "newPassword", ",", "rePassword", ",", "keyPassword", ",", "keyStorePass", ",", "operation2", ",", "alias", ",", "newAlias", ",", "removeAlias", ",", "certChain", ",", "pk", ",", "keyStore", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "KeystoreInformations", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
(asynchronously) @param intermediatePath (required) @param authorizableId (required) @param operation (optional) @param currentPassword (optional) @param newPassword (optional) @param rePassword (optional) @param keyPassword (optional) @param keyStorePass (optional) @param operation2 (optional) @param alias (optional) @param newAlias (optional) @param removeAlias (optional) @param certChain (optional) @param pk (optional) @param keyStore (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "(", "asynchronously", ")" ]
train
https://github.com/shinesolutions/swagger-aem/blob/ae7da4df93e817dc2bad843779b2069d9c4e7c6b/java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java#L2304-L2329
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/wsspi/kernel/embeddable/ServerBuilder.java
ServerBuilder.addProductExtension
public ServerBuilder addProductExtension(String name, Properties props) { """ Add a product extension. <p> The addProductExtension method can be called multiple times to add multiple extensions. <p> When the server is started, any product extension files added by this method will be combined with the product extension files found in other source locations. Any duplicate product names will invoke the following override logic: product extensions defined through this SPI will override product extensions defined by the Environment variable <code>WLP_PRODUCT_EXT_DIR</code> which in turn would override product extensions found in <code>$WLP_INSTALL_DIR/etc/extensions</code> to constitute the full set of product extensions for this instance of the running server. @param name The name of the product extension. @param props A properties file containing com.ibm.websphere.productId and com.ibm.websphere.productInstall. @return a reference to this object. """ if ((name != null) && (props != null)) { if (productExtensions == null) { productExtensions = new HashMap<String, Properties>(); } this.productExtensions.put(name, props); } return this; }
java
public ServerBuilder addProductExtension(String name, Properties props) { if ((name != null) && (props != null)) { if (productExtensions == null) { productExtensions = new HashMap<String, Properties>(); } this.productExtensions.put(name, props); } return this; }
[ "public", "ServerBuilder", "addProductExtension", "(", "String", "name", ",", "Properties", "props", ")", "{", "if", "(", "(", "name", "!=", "null", ")", "&&", "(", "props", "!=", "null", ")", ")", "{", "if", "(", "productExtensions", "==", "null", ")", "{", "productExtensions", "=", "new", "HashMap", "<", "String", ",", "Properties", ">", "(", ")", ";", "}", "this", ".", "productExtensions", ".", "put", "(", "name", ",", "props", ")", ";", "}", "return", "this", ";", "}" ]
Add a product extension. <p> The addProductExtension method can be called multiple times to add multiple extensions. <p> When the server is started, any product extension files added by this method will be combined with the product extension files found in other source locations. Any duplicate product names will invoke the following override logic: product extensions defined through this SPI will override product extensions defined by the Environment variable <code>WLP_PRODUCT_EXT_DIR</code> which in turn would override product extensions found in <code>$WLP_INSTALL_DIR/etc/extensions</code> to constitute the full set of product extensions for this instance of the running server. @param name The name of the product extension. @param props A properties file containing com.ibm.websphere.productId and com.ibm.websphere.productInstall. @return a reference to this object.
[ "Add", "a", "product", "extension", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/wsspi/kernel/embeddable/ServerBuilder.java#L214-L222
box/box-java-sdk
src/main/java/com/box/sdk/BoxFile.java
BoxFile.downloadRange
public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) { """ Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, while reporting the progress to a ProgressListener. @param output the stream to where the file will be written. @param rangeStart the byte offset at which to start the download. @param rangeEnd the byte offset at which to stop the download. @param listener a listener for monitoring the download's progress. """ URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); if (rangeEnd > 0) { request.addHeader("Range", String.format("bytes=%s-%s", Long.toString(rangeStart), Long.toString(rangeEnd))); } else { request.addHeader("Range", String.format("bytes=%s-", Long.toString(rangeStart))); } BoxAPIResponse response = request.send(); InputStream input = response.getBody(listener); byte[] buffer = new byte[BUFFER_SIZE]; try { int n = input.read(buffer); while (n != -1) { output.write(buffer, 0, n); n = input.read(buffer); } } catch (IOException e) { throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); } finally { response.disconnect(); } }
java
public void downloadRange(OutputStream output, long rangeStart, long rangeEnd, ProgressListener listener) { URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); if (rangeEnd > 0) { request.addHeader("Range", String.format("bytes=%s-%s", Long.toString(rangeStart), Long.toString(rangeEnd))); } else { request.addHeader("Range", String.format("bytes=%s-", Long.toString(rangeStart))); } BoxAPIResponse response = request.send(); InputStream input = response.getBody(listener); byte[] buffer = new byte[BUFFER_SIZE]; try { int n = input.read(buffer); while (n != -1) { output.write(buffer, 0, n); n = input.read(buffer); } } catch (IOException e) { throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); } finally { response.disconnect(); } }
[ "public", "void", "downloadRange", "(", "OutputStream", "output", ",", "long", "rangeStart", ",", "long", "rangeEnd", ",", "ProgressListener", "listener", ")", "{", "URL", "url", "=", "CONTENT_URL_TEMPLATE", ".", "build", "(", "this", ".", "getAPI", "(", ")", ".", "getBaseURL", "(", ")", ",", "this", ".", "getID", "(", ")", ")", ";", "BoxAPIRequest", "request", "=", "new", "BoxAPIRequest", "(", "this", ".", "getAPI", "(", ")", ",", "url", ",", "\"GET\"", ")", ";", "if", "(", "rangeEnd", ">", "0", ")", "{", "request", ".", "addHeader", "(", "\"Range\"", ",", "String", ".", "format", "(", "\"bytes=%s-%s\"", ",", "Long", ".", "toString", "(", "rangeStart", ")", ",", "Long", ".", "toString", "(", "rangeEnd", ")", ")", ")", ";", "}", "else", "{", "request", ".", "addHeader", "(", "\"Range\"", ",", "String", ".", "format", "(", "\"bytes=%s-\"", ",", "Long", ".", "toString", "(", "rangeStart", ")", ")", ")", ";", "}", "BoxAPIResponse", "response", "=", "request", ".", "send", "(", ")", ";", "InputStream", "input", "=", "response", ".", "getBody", "(", "listener", ")", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "try", "{", "int", "n", "=", "input", ".", "read", "(", "buffer", ")", ";", "while", "(", "n", "!=", "-", "1", ")", "{", "output", ".", "write", "(", "buffer", ",", "0", ",", "n", ")", ";", "n", "=", "input", ".", "read", "(", "buffer", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "BoxAPIException", "(", "\"Couldn't connect to the Box API due to a network error.\"", ",", "e", ")", ";", "}", "finally", "{", "response", ".", "disconnect", "(", ")", ";", "}", "}" ]
Downloads a part of this file's contents, starting at rangeStart and stopping at rangeEnd, while reporting the progress to a ProgressListener. @param output the stream to where the file will be written. @param rangeStart the byte offset at which to start the download. @param rangeEnd the byte offset at which to stop the download. @param listener a listener for monitoring the download's progress.
[ "Downloads", "a", "part", "of", "this", "file", "s", "contents", "starting", "at", "rangeStart", "and", "stopping", "at", "rangeEnd", "while", "reporting", "the", "progress", "to", "a", "ProgressListener", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFile.java#L342-L367
broadinstitute/barclay
src/main/java/org/broadinstitute/barclay/argparser/NamedArgumentDefinition.java
NamedArgumentDefinition.getValuePopulatedWithTags
private Object getValuePopulatedWithTags(final String originalTag, final String stringValue) { """ populated with the actual value and tags and attributes provided by the user for that argument. """ // See if the value is a surrogate key in the tag parser's map that was placed there during preprocessing, // and if so, unpack the values retrieved via the key and use those to populate the field final Object value = constructFromString(stringValue, getLongName()); if (TaggedArgument.class.isAssignableFrom(getUnderlyingFieldClass())) { // NOTE: this propagates the tag name/attributes to the field BEFORE the value is set TaggedArgument taggedArgument = (TaggedArgument) value; TaggedArgumentParser.populateArgumentTags( taggedArgument, getLongName(), originalTag); } else if (originalTag != null) { // a tag was found for a non-taggable argument throw new CommandLineException( String.format("The argument: \"%s/%s\" does not accept tags: \"%s\"", getShortName(), getFullName(), originalTag)); } return value; }
java
private Object getValuePopulatedWithTags(final String originalTag, final String stringValue) { // See if the value is a surrogate key in the tag parser's map that was placed there during preprocessing, // and if so, unpack the values retrieved via the key and use those to populate the field final Object value = constructFromString(stringValue, getLongName()); if (TaggedArgument.class.isAssignableFrom(getUnderlyingFieldClass())) { // NOTE: this propagates the tag name/attributes to the field BEFORE the value is set TaggedArgument taggedArgument = (TaggedArgument) value; TaggedArgumentParser.populateArgumentTags( taggedArgument, getLongName(), originalTag); } else if (originalTag != null) { // a tag was found for a non-taggable argument throw new CommandLineException( String.format("The argument: \"%s/%s\" does not accept tags: \"%s\"", getShortName(), getFullName(), originalTag)); } return value; }
[ "private", "Object", "getValuePopulatedWithTags", "(", "final", "String", "originalTag", ",", "final", "String", "stringValue", ")", "{", "// See if the value is a surrogate key in the tag parser's map that was placed there during preprocessing,", "// and if so, unpack the values retrieved via the key and use those to populate the field", "final", "Object", "value", "=", "constructFromString", "(", "stringValue", ",", "getLongName", "(", ")", ")", ";", "if", "(", "TaggedArgument", ".", "class", ".", "isAssignableFrom", "(", "getUnderlyingFieldClass", "(", ")", ")", ")", "{", "// NOTE: this propagates the tag name/attributes to the field BEFORE the value is set", "TaggedArgument", "taggedArgument", "=", "(", "TaggedArgument", ")", "value", ";", "TaggedArgumentParser", ".", "populateArgumentTags", "(", "taggedArgument", ",", "getLongName", "(", ")", ",", "originalTag", ")", ";", "}", "else", "if", "(", "originalTag", "!=", "null", ")", "{", "// a tag was found for a non-taggable argument", "throw", "new", "CommandLineException", "(", "String", ".", "format", "(", "\"The argument: \\\"%s/%s\\\" does not accept tags: \\\"%s\\\"\"", ",", "getShortName", "(", ")", ",", "getFullName", "(", ")", ",", "originalTag", ")", ")", ";", "}", "return", "value", ";", "}" ]
populated with the actual value and tags and attributes provided by the user for that argument.
[ "populated", "with", "the", "actual", "value", "and", "tags", "and", "attributes", "provided", "by", "the", "user", "for", "that", "argument", "." ]
train
https://github.com/broadinstitute/barclay/blob/7e56d725766b0da3baff23e79a31c3d01c3589c2/src/main/java/org/broadinstitute/barclay/argparser/NamedArgumentDefinition.java#L532-L554
alkacon/opencms-core
src/org/opencms/xml/types/CmsXmlCategoryValue.java
CmsXmlCategoryValue.fillEntry
public static void fillEntry(Element element, CmsUUID id, String rootPath, CmsRelationType type) { """ Fills the given element with a {@link CmsXmlCategoryValue} for the given data.<p> @param element the element to fill @param id the id to use @param rootPath the path to use @param type the relation type to use """ CmsLink link = new CmsLink(CmsXmlCategoryValue.TYPE_VFS_LINK, type, id, rootPath, true); // get xml node Element linkElement = element.element(CmsXmlPage.NODE_LINK); if (linkElement == null) { // create xml node if needed linkElement = element.addElement(CmsXmlPage.NODE_LINK); } // update xml node CmsLinkUpdateUtil.updateXmlForVfsFile(link, linkElement); }
java
public static void fillEntry(Element element, CmsUUID id, String rootPath, CmsRelationType type) { CmsLink link = new CmsLink(CmsXmlCategoryValue.TYPE_VFS_LINK, type, id, rootPath, true); // get xml node Element linkElement = element.element(CmsXmlPage.NODE_LINK); if (linkElement == null) { // create xml node if needed linkElement = element.addElement(CmsXmlPage.NODE_LINK); } // update xml node CmsLinkUpdateUtil.updateXmlForVfsFile(link, linkElement); }
[ "public", "static", "void", "fillEntry", "(", "Element", "element", ",", "CmsUUID", "id", ",", "String", "rootPath", ",", "CmsRelationType", "type", ")", "{", "CmsLink", "link", "=", "new", "CmsLink", "(", "CmsXmlCategoryValue", ".", "TYPE_VFS_LINK", ",", "type", ",", "id", ",", "rootPath", ",", "true", ")", ";", "// get xml node", "Element", "linkElement", "=", "element", ".", "element", "(", "CmsXmlPage", ".", "NODE_LINK", ")", ";", "if", "(", "linkElement", "==", "null", ")", "{", "// create xml node if needed", "linkElement", "=", "element", ".", "addElement", "(", "CmsXmlPage", ".", "NODE_LINK", ")", ";", "}", "// update xml node", "CmsLinkUpdateUtil", ".", "updateXmlForVfsFile", "(", "link", ",", "linkElement", ")", ";", "}" ]
Fills the given element with a {@link CmsXmlCategoryValue} for the given data.<p> @param element the element to fill @param id the id to use @param rootPath the path to use @param type the relation type to use
[ "Fills", "the", "given", "element", "with", "a", "{", "@link", "CmsXmlCategoryValue", "}", "for", "the", "given", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/types/CmsXmlCategoryValue.java#L115-L126
tvesalainen/util
util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java
ChannelHelper.readAll
public static final int readAll(ReadableByteChannel ch, ByteBuffer dst) throws IOException { """ Read channel until dst has remaining or eof. @param ch @param dst @return Returns number of bytes or -1 if no bytes were read and eof reached. @throws IOException """ int count = 0; while (dst.hasRemaining()) { int rc = ch.read(dst); if (rc == -1) { if (count > 0) { return count; } return -1; } count += rc; } return count; }
java
public static final int readAll(ReadableByteChannel ch, ByteBuffer dst) throws IOException { int count = 0; while (dst.hasRemaining()) { int rc = ch.read(dst); if (rc == -1) { if (count > 0) { return count; } return -1; } count += rc; } return count; }
[ "public", "static", "final", "int", "readAll", "(", "ReadableByteChannel", "ch", ",", "ByteBuffer", "dst", ")", "throws", "IOException", "{", "int", "count", "=", "0", ";", "while", "(", "dst", ".", "hasRemaining", "(", ")", ")", "{", "int", "rc", "=", "ch", ".", "read", "(", "dst", ")", ";", "if", "(", "rc", "==", "-", "1", ")", "{", "if", "(", "count", ">", "0", ")", "{", "return", "count", ";", "}", "return", "-", "1", ";", "}", "count", "+=", "rc", ";", "}", "return", "count", ";", "}" ]
Read channel until dst has remaining or eof. @param ch @param dst @return Returns number of bytes or -1 if no bytes were read and eof reached. @throws IOException
[ "Read", "channel", "until", "dst", "has", "remaining", "or", "eof", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/channels/ChannelHelper.java#L118-L135
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java
DockerFileUtil.createInterpolator
public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) { """ Create an interpolator for the given maven parameters and filter configuration. @param params The maven parameters. @param filter The filter configuration. @return An interpolator for replacing maven properties. """ String[] delimiters = extractDelimiters(filter); if (delimiters == null) { // Don't interpolate anything return FixedStringSearchInterpolator.create(); } DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null); // Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator return AssemblyInterpolator .fullInterpolator(params.getProject(), DefaultAssemblyReader.createProjectInterpolator(params.getProject()) .withExpressionMarkers(delimiters[0], delimiters[1]), configSource) .withExpressionMarkers(delimiters[0], delimiters[1]); }
java
public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) { String[] delimiters = extractDelimiters(filter); if (delimiters == null) { // Don't interpolate anything return FixedStringSearchInterpolator.create(); } DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null); // Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator return AssemblyInterpolator .fullInterpolator(params.getProject(), DefaultAssemblyReader.createProjectInterpolator(params.getProject()) .withExpressionMarkers(delimiters[0], delimiters[1]), configSource) .withExpressionMarkers(delimiters[0], delimiters[1]); }
[ "public", "static", "FixedStringSearchInterpolator", "createInterpolator", "(", "MojoParameters", "params", ",", "String", "filter", ")", "{", "String", "[", "]", "delimiters", "=", "extractDelimiters", "(", "filter", ")", ";", "if", "(", "delimiters", "==", "null", ")", "{", "// Don't interpolate anything", "return", "FixedStringSearchInterpolator", ".", "create", "(", ")", ";", "}", "DockerAssemblyConfigurationSource", "configSource", "=", "new", "DockerAssemblyConfigurationSource", "(", "params", ",", "null", ",", "null", ")", ";", "// Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator", "return", "AssemblyInterpolator", ".", "fullInterpolator", "(", "params", ".", "getProject", "(", ")", ",", "DefaultAssemblyReader", ".", "createProjectInterpolator", "(", "params", ".", "getProject", "(", ")", ")", ".", "withExpressionMarkers", "(", "delimiters", "[", "0", "]", ",", "delimiters", "[", "1", "]", ")", ",", "configSource", ")", ".", "withExpressionMarkers", "(", "delimiters", "[", "0", "]", ",", "delimiters", "[", "1", "]", ")", ";", "}" ]
Create an interpolator for the given maven parameters and filter configuration. @param params The maven parameters. @param filter The filter configuration. @return An interpolator for replacing maven properties.
[ "Create", "an", "interpolator", "for", "the", "given", "maven", "parameters", "and", "filter", "configuration", "." ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java#L113-L127
lucee/Lucee
core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java
XMLConfigAdmin.updateJDBCDriver
public void updateJDBCDriver(String label, String id, ClassDefinition cd) throws PageException { """ /* public static void updateJDBCDriver(ConfigImpl config, String label, ClassDefinition cd, boolean reload) throws IOException, SAXException, PageException, BundleException { ConfigWebAdmin admin = new ConfigWebAdmin(config, null); admin._updateJDBCDriver(label,cd); admin._store(); // store is necessary, otherwise it get lost if(reload)admin._reload(); } """ checkWriteAccess(); _updateJDBCDriver(label, id, cd); }
java
public void updateJDBCDriver(String label, String id, ClassDefinition cd) throws PageException { checkWriteAccess(); _updateJDBCDriver(label, id, cd); }
[ "public", "void", "updateJDBCDriver", "(", "String", "label", ",", "String", "id", ",", "ClassDefinition", "cd", ")", "throws", "PageException", "{", "checkWriteAccess", "(", ")", ";", "_updateJDBCDriver", "(", "label", ",", "id", ",", "cd", ")", ";", "}" ]
/* public static void updateJDBCDriver(ConfigImpl config, String label, ClassDefinition cd, boolean reload) throws IOException, SAXException, PageException, BundleException { ConfigWebAdmin admin = new ConfigWebAdmin(config, null); admin._updateJDBCDriver(label,cd); admin._store(); // store is necessary, otherwise it get lost if(reload)admin._reload(); }
[ "/", "*", "public", "static", "void", "updateJDBCDriver", "(", "ConfigImpl", "config", "String", "label", "ClassDefinition", "cd", "boolean", "reload", ")", "throws", "IOException", "SAXException", "PageException", "BundleException", "{", "ConfigWebAdmin", "admin", "=", "new", "ConfigWebAdmin", "(", "config", "null", ")", ";", "admin", ".", "_updateJDBCDriver", "(", "label", "cd", ")", ";", "admin", ".", "_store", "()", ";", "//", "store", "is", "necessary", "otherwise", "it", "get", "lost", "if", "(", "reload", ")", "admin", ".", "_reload", "()", ";", "}" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/XMLConfigAdmin.java#L1677-L1680
doanduyhai/Achilles
achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java
AbstractManagerFactoryBuilder.withDefaultReadConsistencyMap
public T withDefaultReadConsistencyMap(Map<String, ConsistencyLevel> readConsistencyMap) { """ Define the default Consistency level map to be used for all READ operations The map keys represent table names and values represent the corresponding consistency level @return ManagerFactoryBuilder @see <a href="https://github.com/doanduyhai/Achilles/wiki/Configuration-Parameters#consistency-level" target="_blank">Consistency configuration</a> """ configMap.put(CONSISTENCY_LEVEL_READ_MAP, readConsistencyMap); return getThis(); }
java
public T withDefaultReadConsistencyMap(Map<String, ConsistencyLevel> readConsistencyMap) { configMap.put(CONSISTENCY_LEVEL_READ_MAP, readConsistencyMap); return getThis(); }
[ "public", "T", "withDefaultReadConsistencyMap", "(", "Map", "<", "String", ",", "ConsistencyLevel", ">", "readConsistencyMap", ")", "{", "configMap", ".", "put", "(", "CONSISTENCY_LEVEL_READ_MAP", ",", "readConsistencyMap", ")", ";", "return", "getThis", "(", ")", ";", "}" ]
Define the default Consistency level map to be used for all READ operations The map keys represent table names and values represent the corresponding consistency level @return ManagerFactoryBuilder @see <a href="https://github.com/doanduyhai/Achilles/wiki/Configuration-Parameters#consistency-level" target="_blank">Consistency configuration</a>
[ "Define", "the", "default", "Consistency", "level", "map", "to", "be", "used", "for", "all", "READ", "operations", "The", "map", "keys", "represent", "table", "names", "and", "values", "represent", "the", "corresponding", "consistency", "level" ]
train
https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java#L135-L138
alipay/sofa-hessian
src/main/java/com/caucho/hessian/io/HessianOutput.java
HessianOutput.writeBytes
public void writeBytes(byte[] buffer) throws IOException { """ Writes a byte array to the stream. The array will be written with the following syntax: <code><pre> B b16 b18 bytes </pre></code> If the value is null, it will be written as <code><pre> N </pre></code> @param value the string value to write. """ if (buffer == null) os.write('N'); else writeBytes(buffer, 0, buffer.length); }
java
public void writeBytes(byte[] buffer) throws IOException { if (buffer == null) os.write('N'); else writeBytes(buffer, 0, buffer.length); }
[ "public", "void", "writeBytes", "(", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "if", "(", "buffer", "==", "null", ")", "os", ".", "write", "(", "'", "'", ")", ";", "else", "writeBytes", "(", "buffer", ",", "0", ",", "buffer", ".", "length", ")", ";", "}" ]
Writes a byte array to the stream. The array will be written with the following syntax: <code><pre> B b16 b18 bytes </pre></code> If the value is null, it will be written as <code><pre> N </pre></code> @param value the string value to write.
[ "Writes", "a", "byte", "array", "to", "the", "stream", ".", "The", "array", "will", "be", "written", "with", "the", "following", "syntax", ":" ]
train
https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/caucho/hessian/io/HessianOutput.java#L660-L667
cdk/cdk
legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
GeometryTools.findClosestInSpace
public static List<IAtom> findClosestInSpace(IAtomContainer container, IAtom startAtom, int max) throws CDKException { """ Returns the atoms which are closes to an atom in an AtomContainer by distance in 3d. @param container The AtomContainer to examine @param startAtom the atom to start from @param max the number of neighbours to return @return the average bond length @exception CDKException Description of the Exception """ Point3d originalPoint = startAtom.getPoint3d(); if (originalPoint == null) { throw new CDKException("No point3d, but findClosestInSpace is working on point3ds"); } Map<Double, IAtom> atomsByDistance = new TreeMap<Double, IAtom>(); for (IAtom atom : container.atoms()) { if (!atom.equals(startAtom)) { if (atom.getPoint3d() == null) { throw new CDKException("No point3d, but findClosestInSpace is working on point3ds"); } double distance = atom.getPoint3d().distance(originalPoint); atomsByDistance.put(distance, atom); } } // FIXME: should there not be some sort here?? Set<Double> keySet = atomsByDistance.keySet(); Iterator<Double> keyIter = keySet.iterator(); List<IAtom> returnValue = new ArrayList<IAtom>(); int i = 0; while (keyIter.hasNext() && i < max) { returnValue.add(atomsByDistance.get(keyIter.next())); i++; } return (returnValue); }
java
public static List<IAtom> findClosestInSpace(IAtomContainer container, IAtom startAtom, int max) throws CDKException { Point3d originalPoint = startAtom.getPoint3d(); if (originalPoint == null) { throw new CDKException("No point3d, but findClosestInSpace is working on point3ds"); } Map<Double, IAtom> atomsByDistance = new TreeMap<Double, IAtom>(); for (IAtom atom : container.atoms()) { if (!atom.equals(startAtom)) { if (atom.getPoint3d() == null) { throw new CDKException("No point3d, but findClosestInSpace is working on point3ds"); } double distance = atom.getPoint3d().distance(originalPoint); atomsByDistance.put(distance, atom); } } // FIXME: should there not be some sort here?? Set<Double> keySet = atomsByDistance.keySet(); Iterator<Double> keyIter = keySet.iterator(); List<IAtom> returnValue = new ArrayList<IAtom>(); int i = 0; while (keyIter.hasNext() && i < max) { returnValue.add(atomsByDistance.get(keyIter.next())); i++; } return (returnValue); }
[ "public", "static", "List", "<", "IAtom", ">", "findClosestInSpace", "(", "IAtomContainer", "container", ",", "IAtom", "startAtom", ",", "int", "max", ")", "throws", "CDKException", "{", "Point3d", "originalPoint", "=", "startAtom", ".", "getPoint3d", "(", ")", ";", "if", "(", "originalPoint", "==", "null", ")", "{", "throw", "new", "CDKException", "(", "\"No point3d, but findClosestInSpace is working on point3ds\"", ")", ";", "}", "Map", "<", "Double", ",", "IAtom", ">", "atomsByDistance", "=", "new", "TreeMap", "<", "Double", ",", "IAtom", ">", "(", ")", ";", "for", "(", "IAtom", "atom", ":", "container", ".", "atoms", "(", ")", ")", "{", "if", "(", "!", "atom", ".", "equals", "(", "startAtom", ")", ")", "{", "if", "(", "atom", ".", "getPoint3d", "(", ")", "==", "null", ")", "{", "throw", "new", "CDKException", "(", "\"No point3d, but findClosestInSpace is working on point3ds\"", ")", ";", "}", "double", "distance", "=", "atom", ".", "getPoint3d", "(", ")", ".", "distance", "(", "originalPoint", ")", ";", "atomsByDistance", ".", "put", "(", "distance", ",", "atom", ")", ";", "}", "}", "// FIXME: should there not be some sort here??", "Set", "<", "Double", ">", "keySet", "=", "atomsByDistance", ".", "keySet", "(", ")", ";", "Iterator", "<", "Double", ">", "keyIter", "=", "keySet", ".", "iterator", "(", ")", ";", "List", "<", "IAtom", ">", "returnValue", "=", "new", "ArrayList", "<", "IAtom", ">", "(", ")", ";", "int", "i", "=", "0", ";", "while", "(", "keyIter", ".", "hasNext", "(", ")", "&&", "i", "<", "max", ")", "{", "returnValue", ".", "add", "(", "atomsByDistance", ".", "get", "(", "keyIter", ".", "next", "(", ")", ")", ")", ";", "i", "++", ";", "}", "return", "(", "returnValue", ")", ";", "}" ]
Returns the atoms which are closes to an atom in an AtomContainer by distance in 3d. @param container The AtomContainer to examine @param startAtom the atom to start from @param max the number of neighbours to return @return the average bond length @exception CDKException Description of the Exception
[ "Returns", "the", "atoms", "which", "are", "closes", "to", "an", "atom", "in", "an", "AtomContainer", "by", "distance", "in", "3d", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L1248-L1274
alibaba/Virtualview-Android
virtualview/src/main/java/com/tmall/wireless/vaf/virtualview/Helper/RtlHelper.java
RtlHelper.getRealLeft
public static int getRealLeft(boolean isRtl, int parentLeft, int parentWidth, int left, int width) { """ Convert left to RTL left if need. @param parentLeft parent's left @param parentWidth parent's width @param left self's left @param width self's width @return """ if (isRtl) { // 1, trim the parent's left. left -= parentLeft; // 2, calculate the RTL left. left = parentWidth - width - left; // 3, add the parent's left. left += parentLeft; } return left; }
java
public static int getRealLeft(boolean isRtl, int parentLeft, int parentWidth, int left, int width) { if (isRtl) { // 1, trim the parent's left. left -= parentLeft; // 2, calculate the RTL left. left = parentWidth - width - left; // 3, add the parent's left. left += parentLeft; } return left; }
[ "public", "static", "int", "getRealLeft", "(", "boolean", "isRtl", ",", "int", "parentLeft", ",", "int", "parentWidth", ",", "int", "left", ",", "int", "width", ")", "{", "if", "(", "isRtl", ")", "{", "// 1, trim the parent's left.", "left", "-=", "parentLeft", ";", "// 2, calculate the RTL left.", "left", "=", "parentWidth", "-", "width", "-", "left", ";", "// 3, add the parent's left.", "left", "+=", "parentLeft", ";", "}", "return", "left", ";", "}" ]
Convert left to RTL left if need. @param parentLeft parent's left @param parentWidth parent's width @param left self's left @param width self's width @return
[ "Convert", "left", "to", "RTL", "left", "if", "need", "." ]
train
https://github.com/alibaba/Virtualview-Android/blob/30c65791f34458ec840e00d2b84ab2912ea102f0/virtualview/src/main/java/com/tmall/wireless/vaf/virtualview/Helper/RtlHelper.java#L49-L59
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemNumber.java
ElemNumber.getLocale
Locale getLocale(TransformerImpl transformer, int contextNode) throws TransformerException { """ Get the locale we should be using. @param transformer non-null reference to the the current transform-time state. @param contextNode The node that "." expresses. @return The locale to use. May be specified by "lang" attribute, but if not, use default locale on the system. @throws TransformerException """ Locale locale = null; if (null != m_lang_avt) { XPathContext xctxt = transformer.getXPathContext(); String langValue = m_lang_avt.evaluate(xctxt, contextNode, this); if (null != langValue) { // Not really sure what to do about the country code, so I use the // default from the system. // TODO: fix xml:lang handling. locale = new Locale(langValue.toUpperCase(), ""); //Locale.getDefault().getDisplayCountry()); if (null == locale) { transformer.getMsgMgr().warn(this, null, xctxt.getDTM(contextNode).getNode(contextNode), XSLTErrorResources.WG_LOCALE_NOT_FOUND, new Object[]{ langValue }); //"Warning: Could not find locale for xml:lang="+langValue); locale = Locale.getDefault(); } } } else { locale = Locale.getDefault(); } return locale; }
java
Locale getLocale(TransformerImpl transformer, int contextNode) throws TransformerException { Locale locale = null; if (null != m_lang_avt) { XPathContext xctxt = transformer.getXPathContext(); String langValue = m_lang_avt.evaluate(xctxt, contextNode, this); if (null != langValue) { // Not really sure what to do about the country code, so I use the // default from the system. // TODO: fix xml:lang handling. locale = new Locale(langValue.toUpperCase(), ""); //Locale.getDefault().getDisplayCountry()); if (null == locale) { transformer.getMsgMgr().warn(this, null, xctxt.getDTM(contextNode).getNode(contextNode), XSLTErrorResources.WG_LOCALE_NOT_FOUND, new Object[]{ langValue }); //"Warning: Could not find locale for xml:lang="+langValue); locale = Locale.getDefault(); } } } else { locale = Locale.getDefault(); } return locale; }
[ "Locale", "getLocale", "(", "TransformerImpl", "transformer", ",", "int", "contextNode", ")", "throws", "TransformerException", "{", "Locale", "locale", "=", "null", ";", "if", "(", "null", "!=", "m_lang_avt", ")", "{", "XPathContext", "xctxt", "=", "transformer", ".", "getXPathContext", "(", ")", ";", "String", "langValue", "=", "m_lang_avt", ".", "evaluate", "(", "xctxt", ",", "contextNode", ",", "this", ")", ";", "if", "(", "null", "!=", "langValue", ")", "{", "// Not really sure what to do about the country code, so I use the", "// default from the system.", "// TODO: fix xml:lang handling.", "locale", "=", "new", "Locale", "(", "langValue", ".", "toUpperCase", "(", ")", ",", "\"\"", ")", ";", "//Locale.getDefault().getDisplayCountry());", "if", "(", "null", "==", "locale", ")", "{", "transformer", ".", "getMsgMgr", "(", ")", ".", "warn", "(", "this", ",", "null", ",", "xctxt", ".", "getDTM", "(", "contextNode", ")", ".", "getNode", "(", "contextNode", ")", ",", "XSLTErrorResources", ".", "WG_LOCALE_NOT_FOUND", ",", "new", "Object", "[", "]", "{", "langValue", "}", ")", ";", "//\"Warning: Could not find locale for xml:lang=\"+langValue);", "locale", "=", "Locale", ".", "getDefault", "(", ")", ";", "}", "}", "}", "else", "{", "locale", "=", "Locale", ".", "getDefault", "(", ")", ";", "}", "return", "locale", ";", "}" ]
Get the locale we should be using. @param transformer non-null reference to the the current transform-time state. @param contextNode The node that "." expresses. @return The locale to use. May be specified by "lang" attribute, but if not, use default locale on the system. @throws TransformerException
[ "Get", "the", "locale", "we", "should", "be", "using", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemNumber.java#L1033-L1069
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedCollator.java
RuleBasedCollator.internalAddContractions
void internalAddContractions(int c, UnicodeSet set) { """ Adds the contractions that start with character c to the set. Ignores prefixes. Used by AlphabeticIndex. @deprecated This API is ICU internal only. @hide draft / provisional / internal are hidden on Android """ new ContractionsAndExpansions(set, null, null, false).forCodePoint(data, c); }
java
void internalAddContractions(int c, UnicodeSet set) { new ContractionsAndExpansions(set, null, null, false).forCodePoint(data, c); }
[ "void", "internalAddContractions", "(", "int", "c", ",", "UnicodeSet", "set", ")", "{", "new", "ContractionsAndExpansions", "(", "set", ",", "null", ",", "null", ",", "false", ")", ".", "forCodePoint", "(", "data", ",", "c", ")", ";", "}" ]
Adds the contractions that start with character c to the set. Ignores prefixes. Used by AlphabeticIndex. @deprecated This API is ICU internal only. @hide draft / provisional / internal are hidden on Android
[ "Adds", "the", "contractions", "that", "start", "with", "character", "c", "to", "the", "set", ".", "Ignores", "prefixes", ".", "Used", "by", "AlphabeticIndex", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RuleBasedCollator.java#L1006-L1008
microfocus-idol/java-idol-indexing-api
src/main/java/com/autonomy/nonaci/indexing/impl/IndexingServiceImpl.java
IndexingServiceImpl.executeCommand
@Override public int executeCommand(final IndexCommand command) throws IndexingException { """ Executes an index command @param command The index command to execute @return the index queue id for the command @throws com.autonomy.nonaci.indexing.IndexingException if an error response was detected """ LOGGER.trace("executeCommand() called..."); // Execute and return the result... return executeCommand(serverDetails, command); }
java
@Override public int executeCommand(final IndexCommand command) throws IndexingException { LOGGER.trace("executeCommand() called..."); // Execute and return the result... return executeCommand(serverDetails, command); }
[ "@", "Override", "public", "int", "executeCommand", "(", "final", "IndexCommand", "command", ")", "throws", "IndexingException", "{", "LOGGER", ".", "trace", "(", "\"executeCommand() called...\"", ")", ";", "// Execute and return the result...", "return", "executeCommand", "(", "serverDetails", ",", "command", ")", ";", "}" ]
Executes an index command @param command The index command to execute @return the index queue id for the command @throws com.autonomy.nonaci.indexing.IndexingException if an error response was detected
[ "Executes", "an", "index", "command" ]
train
https://github.com/microfocus-idol/java-idol-indexing-api/blob/178ea844da501318d8d797a35b2f72ff40786b8c/src/main/java/com/autonomy/nonaci/indexing/impl/IndexingServiceImpl.java#L123-L129
biezhi/webp-io
src/main/java/io/github/biezhi/webp/WebpIO.java
WebpIO.toNormalImage
public void toNormalImage(String src, String dest) { """ Converter webp file to normal image @param src webp file path @param dest normal image path """ toNormalImage(new File(src), new File(dest)); }
java
public void toNormalImage(String src, String dest) { toNormalImage(new File(src), new File(dest)); }
[ "public", "void", "toNormalImage", "(", "String", "src", ",", "String", "dest", ")", "{", "toNormalImage", "(", "new", "File", "(", "src", ")", ",", "new", "File", "(", "dest", ")", ")", ";", "}" ]
Converter webp file to normal image @param src webp file path @param dest normal image path
[ "Converter", "webp", "file", "to", "normal", "image" ]
train
https://github.com/biezhi/webp-io/blob/8eefe535087b3abccacff76de2b6e27bb7301bcc/src/main/java/io/github/biezhi/webp/WebpIO.java#L76-L78
inkstand-io/scribble
scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java
XMLContentHandler.startElementNode
private void startElementNode(final Attributes attributes) { """ Invoked on node element. @param attributes the DOM attributes of the node element @throws SAXException if the node for the new element can not be added """ LOG.debug("Found node"); try { this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes)); } catch (final RepositoryException e) { throw new AssertionError("Could not create node", e); } }
java
private void startElementNode(final Attributes attributes) { LOG.debug("Found node"); try { this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes)); } catch (final RepositoryException e) { throw new AssertionError("Could not create node", e); } }
[ "private", "void", "startElementNode", "(", "final", "Attributes", "attributes", ")", "{", "LOG", ".", "debug", "(", "\"Found node\"", ")", ";", "try", "{", "this", ".", "nodeStack", ".", "push", "(", "this", ".", "newNode", "(", "this", ".", "nodeStack", ".", "peek", "(", ")", ",", "attributes", ")", ")", ";", "}", "catch", "(", "final", "RepositoryException", "e", ")", "{", "throw", "new", "AssertionError", "(", "\"Could not create node\"", ",", "e", ")", ";", "}", "}" ]
Invoked on node element. @param attributes the DOM attributes of the node element @throws SAXException if the node for the new element can not be added
[ "Invoked", "on", "node", "element", "." ]
train
https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java#L354-L362
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApiClient.java
GitLabApiClient.getWithAccepts
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, String accepts, Object... pathArgs) throws IOException { """ Perform an HTTP GET call with the specified query parameters and path objects, returning a ClientResponse instance with the data returned from the endpoint. @param queryParams multivalue map of request parameters @param accepts if non-empty will set the Accepts header to this value @param pathArgs variable list of arguments used to build the URI @return a ClientResponse instance with the data returned from the endpoint @throws IOException if an error occurs while constructing the URL """ URL url = getApiUrl(pathArgs); return (getWithAccepts(queryParams, url, accepts)); }
java
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, String accepts, Object... pathArgs) throws IOException { URL url = getApiUrl(pathArgs); return (getWithAccepts(queryParams, url, accepts)); }
[ "protected", "Response", "getWithAccepts", "(", "MultivaluedMap", "<", "String", ",", "String", ">", "queryParams", ",", "String", "accepts", ",", "Object", "...", "pathArgs", ")", "throws", "IOException", "{", "URL", "url", "=", "getApiUrl", "(", "pathArgs", ")", ";", "return", "(", "getWithAccepts", "(", "queryParams", ",", "url", ",", "accepts", ")", ")", ";", "}" ]
Perform an HTTP GET call with the specified query parameters and path objects, returning a ClientResponse instance with the data returned from the endpoint. @param queryParams multivalue map of request parameters @param accepts if non-empty will set the Accepts header to this value @param pathArgs variable list of arguments used to build the URI @return a ClientResponse instance with the data returned from the endpoint @throws IOException if an error occurs while constructing the URL
[ "Perform", "an", "HTTP", "GET", "call", "with", "the", "specified", "query", "parameters", "and", "path", "objects", "returning", "a", "ClientResponse", "instance", "with", "the", "data", "returned", "from", "the", "endpoint", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApiClient.java#L399-L402
landawn/AbacusUtil
src/com/landawn/abacus/util/StringUtil.java
StringUtil.toLowerCase
public static String toLowerCase(final String str, final Locale locale) { """ <p> Converts a String to lower case as per {@link String#toLowerCase(Locale)} . </p> <p> A {@code null} input String returns {@code null}. </p> <pre> StrUtil.toLowerCase(null, Locale.ENGLISH) = null StrUtil.toLowerCase("", Locale.ENGLISH) = "" StrUtil.toLowerCase("aBc", Locale.ENGLISH) = "abc" </pre> @param str the String to lower case, may be null @param locale the locale that defines the case transformation rules, must not be null @return the lower cased String, {@code null} if null String input @since 2.5 """ if (N.isNullOrEmpty(str)) { return str; } return str.toLowerCase(locale); }
java
public static String toLowerCase(final String str, final Locale locale) { if (N.isNullOrEmpty(str)) { return str; } return str.toLowerCase(locale); }
[ "public", "static", "String", "toLowerCase", "(", "final", "String", "str", ",", "final", "Locale", "locale", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "str", ")", ")", "{", "return", "str", ";", "}", "return", "str", ".", "toLowerCase", "(", "locale", ")", ";", "}" ]
<p> Converts a String to lower case as per {@link String#toLowerCase(Locale)} . </p> <p> A {@code null} input String returns {@code null}. </p> <pre> StrUtil.toLowerCase(null, Locale.ENGLISH) = null StrUtil.toLowerCase("", Locale.ENGLISH) = "" StrUtil.toLowerCase("aBc", Locale.ENGLISH) = "abc" </pre> @param str the String to lower case, may be null @param locale the locale that defines the case transformation rules, must not be null @return the lower cased String, {@code null} if null String input @since 2.5
[ "<p", ">", "Converts", "a", "String", "to", "lower", "case", "as", "per", "{", "@link", "String#toLowerCase", "(", "Locale", ")", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L523-L529
codelibs/minhash
src/main/java/org/codelibs/minhash/MinHash.java
MinHash.createAnalyzer
public static Analyzer createAnalyzer(final int hashBit, final int seed, final int num) { """ <p>Create an analyzer to calculate a minhash.</p> <p>Uses {@link WhitespaceTokenizer} as {@link Tokenizer}</p> @param hashBit the number of hash bits @param seed a base seed for hash function @param num the number of hash functions @return analyzer used by {@link MinHash#calculate(Analyzer, String)} """ return createAnalyzer(new WhitespaceTokenizer(), hashBit, seed, num); }
java
public static Analyzer createAnalyzer(final int hashBit, final int seed, final int num) { return createAnalyzer(new WhitespaceTokenizer(), hashBit, seed, num); }
[ "public", "static", "Analyzer", "createAnalyzer", "(", "final", "int", "hashBit", ",", "final", "int", "seed", ",", "final", "int", "num", ")", "{", "return", "createAnalyzer", "(", "new", "WhitespaceTokenizer", "(", ")", ",", "hashBit", ",", "seed", ",", "num", ")", ";", "}" ]
<p>Create an analyzer to calculate a minhash.</p> <p>Uses {@link WhitespaceTokenizer} as {@link Tokenizer}</p> @param hashBit the number of hash bits @param seed a base seed for hash function @param num the number of hash functions @return analyzer used by {@link MinHash#calculate(Analyzer, String)}
[ "<p", ">", "Create", "an", "analyzer", "to", "calculate", "a", "minhash", ".", "<", "/", "p", ">", "<p", ">", "Uses", "{", "@link", "WhitespaceTokenizer", "}", "as", "{", "@link", "Tokenizer", "}", "<", "/", "p", ">" ]
train
https://github.com/codelibs/minhash/blob/2aaa16e3096461c0f550d0eb462ae9e69d1b7749/src/main/java/org/codelibs/minhash/MinHash.java#L236-L238
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.getAttributes
public static BasicFileAttributes getAttributes(Path path, boolean isFollowLinks) throws IORuntimeException { """ 获取文件属性 @param path 文件路径{@link Path} @param isFollowLinks 是否跟踪到软链对应的真实路径 @return {@link BasicFileAttributes} @throws IORuntimeException IO异常 @since 3.1.0 """ if (null == path) { return null; } final LinkOption[] options = isFollowLinks ? new LinkOption[0] : new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; try { return Files.readAttributes(path, BasicFileAttributes.class, options); } catch (IOException e) { throw new IORuntimeException(e); } }
java
public static BasicFileAttributes getAttributes(Path path, boolean isFollowLinks) throws IORuntimeException { if (null == path) { return null; } final LinkOption[] options = isFollowLinks ? new LinkOption[0] : new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; try { return Files.readAttributes(path, BasicFileAttributes.class, options); } catch (IOException e) { throw new IORuntimeException(e); } }
[ "public", "static", "BasicFileAttributes", "getAttributes", "(", "Path", "path", ",", "boolean", "isFollowLinks", ")", "throws", "IORuntimeException", "{", "if", "(", "null", "==", "path", ")", "{", "return", "null", ";", "}", "final", "LinkOption", "[", "]", "options", "=", "isFollowLinks", "?", "new", "LinkOption", "[", "0", "]", ":", "new", "LinkOption", "[", "]", "{", "LinkOption", ".", "NOFOLLOW_LINKS", "}", ";", "try", "{", "return", "Files", ".", "readAttributes", "(", "path", ",", "BasicFileAttributes", ".", "class", ",", "options", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IORuntimeException", "(", "e", ")", ";", "}", "}" ]
获取文件属性 @param path 文件路径{@link Path} @param isFollowLinks 是否跟踪到软链对应的真实路径 @return {@link BasicFileAttributes} @throws IORuntimeException IO异常 @since 3.1.0
[ "获取文件属性" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L1871-L1882
alkacon/opencms-core
src/org/opencms/jsp/CmsJspNavBuilder.java
CmsJspNavBuilder.isNavLevelFolder
public static boolean isNavLevelFolder(CmsObject cms, CmsResource resource) { """ Returns whether the given resource is a folder and is marked to be a navigation level folder.<p> @param cms the cms context @param resource the resource @return <code>true</code> if the resource is marked to be a navigation level folder """ if (resource.isFolder()) { I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource); if (CmsResourceTypeFolder.RESOURCE_TYPE_NAME.equals(type.getTypeName())) { try { CmsProperty prop = cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_DEFAULT_FILE, false); return !prop.isNullProperty() && NAVIGATION_LEVEL_FOLDER.equals(prop.getValue()); } catch (CmsException e) { LOG.debug(e.getMessage(), e); } } } return false; }
java
public static boolean isNavLevelFolder(CmsObject cms, CmsResource resource) { if (resource.isFolder()) { I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource); if (CmsResourceTypeFolder.RESOURCE_TYPE_NAME.equals(type.getTypeName())) { try { CmsProperty prop = cms.readPropertyObject( resource, CmsPropertyDefinition.PROPERTY_DEFAULT_FILE, false); return !prop.isNullProperty() && NAVIGATION_LEVEL_FOLDER.equals(prop.getValue()); } catch (CmsException e) { LOG.debug(e.getMessage(), e); } } } return false; }
[ "public", "static", "boolean", "isNavLevelFolder", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "{", "if", "(", "resource", ".", "isFolder", "(", ")", ")", "{", "I_CmsResourceType", "type", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "resource", ")", ";", "if", "(", "CmsResourceTypeFolder", ".", "RESOURCE_TYPE_NAME", ".", "equals", "(", "type", ".", "getTypeName", "(", ")", ")", ")", "{", "try", "{", "CmsProperty", "prop", "=", "cms", ".", "readPropertyObject", "(", "resource", ",", "CmsPropertyDefinition", ".", "PROPERTY_DEFAULT_FILE", ",", "false", ")", ";", "return", "!", "prop", ".", "isNullProperty", "(", ")", "&&", "NAVIGATION_LEVEL_FOLDER", ".", "equals", "(", "prop", ".", "getValue", "(", ")", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "debug", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "return", "false", ";", "}" ]
Returns whether the given resource is a folder and is marked to be a navigation level folder.<p> @param cms the cms context @param resource the resource @return <code>true</code> if the resource is marked to be a navigation level folder
[ "Returns", "whether", "the", "given", "resource", "is", "a", "folder", "and", "is", "marked", "to", "be", "a", "navigation", "level", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspNavBuilder.java#L332-L349
RestComm/jss7
isup/isup-impl/src/main/java/org/restcomm/protocols/ss7/isup/impl/message/ISUPMessageImpl.java
ISUPMessageImpl.decodeMandatoryVariableParameters
protected int decodeMandatoryVariableParameters(ISUPParameterFactory parameterFactory, byte[] b, int index) throws ParameterException { """ decodes ptrs and returns offset from passed index value to first optional parameter parameter @param b @param index @return @throws ParameterException """ // FIXME: possibly this should also be per msg, since if msg lacks // proper parameter, decoding wotn pick this up and will throw // some bad output, which wont give a clue about reason... int readCount = 0; // int optionalOffset = 0; if (b.length - index > 0) { byte extPIndex = -1; try { int count = getNumberOfMandatoryVariableLengthParameters(); readCount = count; for (int parameterIndex = 0; parameterIndex < count; parameterIndex++) { int lengthPointerIndex = index + parameterIndex; int parameterLengthIndex = b[lengthPointerIndex] + lengthPointerIndex; int parameterLength = b[parameterLengthIndex]; byte[] parameterBody = new byte[parameterLength]; System.arraycopy(b, parameterLengthIndex + 1, parameterBody, 0, parameterLength); decodeMandatoryVariableBody(parameterFactory, parameterBody, parameterIndex); } // optionalOffset = b[index + readCount]; } catch (ArrayIndexOutOfBoundsException aioobe) { throw new ParameterException( "Failed to read parameter, to few octets in buffer, parameter index: " + extPIndex, aioobe); } catch (IllegalArgumentException e) { throw new ParameterException("Failed to parse, paramet index: " + extPIndex, e); } } else { throw new ParameterException( "To few bytes to decode mandatory variable part. There should be atleast on byte to indicate optional part."); } // return readCount + optionalOffset; return readCount; }
java
protected int decodeMandatoryVariableParameters(ISUPParameterFactory parameterFactory, byte[] b, int index) throws ParameterException { // FIXME: possibly this should also be per msg, since if msg lacks // proper parameter, decoding wotn pick this up and will throw // some bad output, which wont give a clue about reason... int readCount = 0; // int optionalOffset = 0; if (b.length - index > 0) { byte extPIndex = -1; try { int count = getNumberOfMandatoryVariableLengthParameters(); readCount = count; for (int parameterIndex = 0; parameterIndex < count; parameterIndex++) { int lengthPointerIndex = index + parameterIndex; int parameterLengthIndex = b[lengthPointerIndex] + lengthPointerIndex; int parameterLength = b[parameterLengthIndex]; byte[] parameterBody = new byte[parameterLength]; System.arraycopy(b, parameterLengthIndex + 1, parameterBody, 0, parameterLength); decodeMandatoryVariableBody(parameterFactory, parameterBody, parameterIndex); } // optionalOffset = b[index + readCount]; } catch (ArrayIndexOutOfBoundsException aioobe) { throw new ParameterException( "Failed to read parameter, to few octets in buffer, parameter index: " + extPIndex, aioobe); } catch (IllegalArgumentException e) { throw new ParameterException("Failed to parse, paramet index: " + extPIndex, e); } } else { throw new ParameterException( "To few bytes to decode mandatory variable part. There should be atleast on byte to indicate optional part."); } // return readCount + optionalOffset; return readCount; }
[ "protected", "int", "decodeMandatoryVariableParameters", "(", "ISUPParameterFactory", "parameterFactory", ",", "byte", "[", "]", "b", ",", "int", "index", ")", "throws", "ParameterException", "{", "// FIXME: possibly this should also be per msg, since if msg lacks", "// proper parameter, decoding wotn pick this up and will throw", "// some bad output, which wont give a clue about reason...", "int", "readCount", "=", "0", ";", "// int optionalOffset = 0;", "if", "(", "b", ".", "length", "-", "index", ">", "0", ")", "{", "byte", "extPIndex", "=", "-", "1", ";", "try", "{", "int", "count", "=", "getNumberOfMandatoryVariableLengthParameters", "(", ")", ";", "readCount", "=", "count", ";", "for", "(", "int", "parameterIndex", "=", "0", ";", "parameterIndex", "<", "count", ";", "parameterIndex", "++", ")", "{", "int", "lengthPointerIndex", "=", "index", "+", "parameterIndex", ";", "int", "parameterLengthIndex", "=", "b", "[", "lengthPointerIndex", "]", "+", "lengthPointerIndex", ";", "int", "parameterLength", "=", "b", "[", "parameterLengthIndex", "]", ";", "byte", "[", "]", "parameterBody", "=", "new", "byte", "[", "parameterLength", "]", ";", "System", ".", "arraycopy", "(", "b", ",", "parameterLengthIndex", "+", "1", ",", "parameterBody", ",", "0", ",", "parameterLength", ")", ";", "decodeMandatoryVariableBody", "(", "parameterFactory", ",", "parameterBody", ",", "parameterIndex", ")", ";", "}", "// optionalOffset = b[index + readCount];", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "aioobe", ")", "{", "throw", "new", "ParameterException", "(", "\"Failed to read parameter, to few octets in buffer, parameter index: \"", "+", "extPIndex", ",", "aioobe", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "ParameterException", "(", "\"Failed to parse, paramet index: \"", "+", "extPIndex", ",", "e", ")", ";", "}", "}", "else", "{", "throw", "new", "ParameterException", "(", "\"To few bytes to decode mandatory variable part. There should be atleast on byte to indicate optional part.\"", ")", ";", "}", "// return readCount + optionalOffset;", "return", "readCount", ";", "}" ]
decodes ptrs and returns offset from passed index value to first optional parameter parameter @param b @param index @return @throws ParameterException
[ "decodes", "ptrs", "and", "returns", "offset", "from", "passed", "index", "value", "to", "first", "optional", "parameter", "parameter" ]
train
https://github.com/RestComm/jss7/blob/402b4b3984e581c581e309cb5f6a858fde6dbc33/isup/isup-impl/src/main/java/org/restcomm/protocols/ss7/isup/impl/message/ISUPMessageImpl.java#L375-L414
elki-project/elki
addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/UKMeans.java
UKMeans.logVarstat
protected void logVarstat(DoubleStatistic varstat, double[] varsum) { """ Log statistics on the variance sum. @param varstat Statistics log instance @param varsum Variance sum per cluster """ if(varstat != null) { double s = sum(varsum); getLogger().statistics(varstat.setDouble(s)); } }
java
protected void logVarstat(DoubleStatistic varstat, double[] varsum) { if(varstat != null) { double s = sum(varsum); getLogger().statistics(varstat.setDouble(s)); } }
[ "protected", "void", "logVarstat", "(", "DoubleStatistic", "varstat", ",", "double", "[", "]", "varsum", ")", "{", "if", "(", "varstat", "!=", "null", ")", "{", "double", "s", "=", "sum", "(", "varsum", ")", ";", "getLogger", "(", ")", ".", "statistics", "(", "varstat", ".", "setDouble", "(", "s", ")", ")", ";", "}", "}" ]
Log statistics on the variance sum. @param varstat Statistics log instance @param varsum Variance sum per cluster
[ "Log", "statistics", "on", "the", "variance", "sum", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/UKMeans.java#L306-L311
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
FormLayout.setConstraints
public void setConstraints(Component component, CellConstraints constraints) { """ Sets the constraints for the specified component in this layout. @param component the component to be modified @param constraints the constraints to be applied @throws NullPointerException if {@code component} or {@code constraints} is {@code null} """ checkNotNull(component, "The component must not be null."); checkNotNull(constraints, "The constraints must not be null."); constraints.ensureValidGridBounds(getColumnCount(), getRowCount()); constraintMap.put(component, (CellConstraints) constraints.clone()); }
java
public void setConstraints(Component component, CellConstraints constraints) { checkNotNull(component, "The component must not be null."); checkNotNull(constraints, "The constraints must not be null."); constraints.ensureValidGridBounds(getColumnCount(), getRowCount()); constraintMap.put(component, (CellConstraints) constraints.clone()); }
[ "public", "void", "setConstraints", "(", "Component", "component", ",", "CellConstraints", "constraints", ")", "{", "checkNotNull", "(", "component", ",", "\"The component must not be null.\"", ")", ";", "checkNotNull", "(", "constraints", ",", "\"The constraints must not be null.\"", ")", ";", "constraints", ".", "ensureValidGridBounds", "(", "getColumnCount", "(", ")", ",", "getRowCount", "(", ")", ")", ";", "constraintMap", ".", "put", "(", "component", ",", "(", "CellConstraints", ")", "constraints", ".", "clone", "(", ")", ")", ";", "}" ]
Sets the constraints for the specified component in this layout. @param component the component to be modified @param constraints the constraints to be applied @throws NullPointerException if {@code component} or {@code constraints} is {@code null}
[ "Sets", "the", "constraints", "for", "the", "specified", "component", "in", "this", "layout", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L756-L761
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbAuthentication.java
TmdbAuthentication.getAuthorisationToken
public TokenAuthorisation getAuthorisationToken() throws MovieDbException { """ This method is used to generate a valid request token for user based authentication. A request token is required in order to request a session id. You can generate any number of request tokens but they will expire after 60 minutes. As soon as a valid session id has been created the token will be destroyed. @return @throws MovieDbException """ TmdbParameters parameters = new TmdbParameters(); URL url = new ApiUrl(apiKey, MethodBase.AUTH).subMethod(MethodSub.TOKEN_NEW).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, TokenAuthorisation.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Failed to get Authorisation Token", url, ex); } }
java
public TokenAuthorisation getAuthorisationToken() throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); URL url = new ApiUrl(apiKey, MethodBase.AUTH).subMethod(MethodSub.TOKEN_NEW).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, TokenAuthorisation.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.AUTH_FAILURE, "Failed to get Authorisation Token", url, ex); } }
[ "public", "TokenAuthorisation", "getAuthorisationToken", "(", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "AUTH", ")", ".", "subMethod", "(", "MethodSub", ".", "TOKEN_NEW", ")", ".", "buildUrl", "(", "parameters", ")", ";", "String", "webpage", "=", "httpTools", ".", "getRequest", "(", "url", ")", ";", "try", "{", "return", "MAPPER", ".", "readValue", "(", "webpage", ",", "TokenAuthorisation", ".", "class", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MovieDbException", "(", "ApiExceptionType", ".", "AUTH_FAILURE", ",", "\"Failed to get Authorisation Token\"", ",", "url", ",", "ex", ")", ";", "}", "}" ]
This method is used to generate a valid request token for user based authentication. A request token is required in order to request a session id. You can generate any number of request tokens but they will expire after 60 minutes. As soon as a valid session id has been created the token will be destroyed. @return @throws MovieDbException
[ "This", "method", "is", "used", "to", "generate", "a", "valid", "request", "token", "for", "user", "based", "authentication", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbAuthentication.java#L67-L78
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.plusRetainScale
public BigMoney plusRetainScale(BigMoneyProvider moneyToAdd, RoundingMode roundingMode) { """ Returns a copy of this monetary value with the amount in the same currency added retaining the scale by rounding the result. <p> The scale of the result will be the same as the scale of this instance. For example,'USD 25.95' plus 'USD 3.021' gives 'USD 28.97' with most rounding modes. <p> This instance is immutable and unaffected by this method. @param moneyToAdd the monetary value to add, not null @param roundingMode the rounding mode to use to adjust the scale, not null @return the new instance with the input amount added, never null """ BigMoney toAdd = checkCurrencyEqual(moneyToAdd); return plusRetainScale(toAdd.getAmount(), roundingMode); }
java
public BigMoney plusRetainScale(BigMoneyProvider moneyToAdd, RoundingMode roundingMode) { BigMoney toAdd = checkCurrencyEqual(moneyToAdd); return plusRetainScale(toAdd.getAmount(), roundingMode); }
[ "public", "BigMoney", "plusRetainScale", "(", "BigMoneyProvider", "moneyToAdd", ",", "RoundingMode", "roundingMode", ")", "{", "BigMoney", "toAdd", "=", "checkCurrencyEqual", "(", "moneyToAdd", ")", ";", "return", "plusRetainScale", "(", "toAdd", ".", "getAmount", "(", ")", ",", "roundingMode", ")", ";", "}" ]
Returns a copy of this monetary value with the amount in the same currency added retaining the scale by rounding the result. <p> The scale of the result will be the same as the scale of this instance. For example,'USD 25.95' plus 'USD 3.021' gives 'USD 28.97' with most rounding modes. <p> This instance is immutable and unaffected by this method. @param moneyToAdd the monetary value to add, not null @param roundingMode the rounding mode to use to adjust the scale, not null @return the new instance with the input amount added, never null
[ "Returns", "a", "copy", "of", "this", "monetary", "value", "with", "the", "amount", "in", "the", "same", "currency", "added", "retaining", "the", "scale", "by", "rounding", "the", "result", ".", "<p", ">", "The", "scale", "of", "the", "result", "will", "be", "the", "same", "as", "the", "scale", "of", "this", "instance", ".", "For", "example", "USD", "25", ".", "95", "plus", "USD", "3", ".", "021", "gives", "USD", "28", ".", "97", "with", "most", "rounding", "modes", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "." ]
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L967-L970
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.scaleAround
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz, Matrix4f dest) { """ /* (non-Javadoc) @see org.joml.Matrix4fc#scaleAround(float, float, float, float, float, float, org.joml.Matrix4f) """ float nm30 = m00 * ox + m10 * oy + m20 * oz + m30; float nm31 = m01 * ox + m11 * oy + m21 * oz + m31; float nm32 = m02 * ox + m12 * oy + m22 * oz + m32; float nm33 = m03 * ox + m13 * oy + m23 * oz + m33; dest._m00(m00 * sx); dest._m01(m01 * sx); dest._m02(m02 * sx); dest._m03(m03 * sx); dest._m10(m10 * sy); dest._m11(m11 * sy); dest._m12(m12 * sy); dest._m13(m13 * sy); dest._m20(m20 * sz); dest._m21(m21 * sz); dest._m22(m22 * sz); dest._m23(m23 * sz); dest._m30(-m00 * ox - m10 * oy - m20 * oz + nm30); dest._m31(-m01 * ox - m11 * oy - m21 * oz + nm31); dest._m32(-m02 * ox - m12 * oy - m22 * oz + nm32); dest._m33(-m03 * ox - m13 * oy - m23 * oz + nm33); boolean one = Math.abs(sx) == 1.0f && Math.abs(sy) == 1.0f && Math.abs(sz) == 1.0f; dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION | (one ? 0 : PROPERTY_ORTHONORMAL))); return dest; }
java
public Matrix4f scaleAround(float sx, float sy, float sz, float ox, float oy, float oz, Matrix4f dest) { float nm30 = m00 * ox + m10 * oy + m20 * oz + m30; float nm31 = m01 * ox + m11 * oy + m21 * oz + m31; float nm32 = m02 * ox + m12 * oy + m22 * oz + m32; float nm33 = m03 * ox + m13 * oy + m23 * oz + m33; dest._m00(m00 * sx); dest._m01(m01 * sx); dest._m02(m02 * sx); dest._m03(m03 * sx); dest._m10(m10 * sy); dest._m11(m11 * sy); dest._m12(m12 * sy); dest._m13(m13 * sy); dest._m20(m20 * sz); dest._m21(m21 * sz); dest._m22(m22 * sz); dest._m23(m23 * sz); dest._m30(-m00 * ox - m10 * oy - m20 * oz + nm30); dest._m31(-m01 * ox - m11 * oy - m21 * oz + nm31); dest._m32(-m02 * ox - m12 * oy - m22 * oz + nm32); dest._m33(-m03 * ox - m13 * oy - m23 * oz + nm33); boolean one = Math.abs(sx) == 1.0f && Math.abs(sy) == 1.0f && Math.abs(sz) == 1.0f; dest._properties(properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION | (one ? 0 : PROPERTY_ORTHONORMAL))); return dest; }
[ "public", "Matrix4f", "scaleAround", "(", "float", "sx", ",", "float", "sy", ",", "float", "sz", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ",", "Matrix4f", "dest", ")", "{", "float", "nm30", "=", "m00", "*", "ox", "+", "m10", "*", "oy", "+", "m20", "*", "oz", "+", "m30", ";", "float", "nm31", "=", "m01", "*", "ox", "+", "m11", "*", "oy", "+", "m21", "*", "oz", "+", "m31", ";", "float", "nm32", "=", "m02", "*", "ox", "+", "m12", "*", "oy", "+", "m22", "*", "oz", "+", "m32", ";", "float", "nm33", "=", "m03", "*", "ox", "+", "m13", "*", "oy", "+", "m23", "*", "oz", "+", "m33", ";", "dest", ".", "_m00", "(", "m00", "*", "sx", ")", ";", "dest", ".", "_m01", "(", "m01", "*", "sx", ")", ";", "dest", ".", "_m02", "(", "m02", "*", "sx", ")", ";", "dest", ".", "_m03", "(", "m03", "*", "sx", ")", ";", "dest", ".", "_m10", "(", "m10", "*", "sy", ")", ";", "dest", ".", "_m11", "(", "m11", "*", "sy", ")", ";", "dest", ".", "_m12", "(", "m12", "*", "sy", ")", ";", "dest", ".", "_m13", "(", "m13", "*", "sy", ")", ";", "dest", ".", "_m20", "(", "m20", "*", "sz", ")", ";", "dest", ".", "_m21", "(", "m21", "*", "sz", ")", ";", "dest", ".", "_m22", "(", "m22", "*", "sz", ")", ";", "dest", ".", "_m23", "(", "m23", "*", "sz", ")", ";", "dest", ".", "_m30", "(", "-", "m00", "*", "ox", "-", "m10", "*", "oy", "-", "m20", "*", "oz", "+", "nm30", ")", ";", "dest", ".", "_m31", "(", "-", "m01", "*", "ox", "-", "m11", "*", "oy", "-", "m21", "*", "oz", "+", "nm31", ")", ";", "dest", ".", "_m32", "(", "-", "m02", "*", "ox", "-", "m12", "*", "oy", "-", "m22", "*", "oz", "+", "nm32", ")", ";", "dest", ".", "_m33", "(", "-", "m03", "*", "ox", "-", "m13", "*", "oy", "-", "m23", "*", "oz", "+", "nm33", ")", ";", "boolean", "one", "=", "Math", ".", "abs", "(", "sx", ")", "==", "1.0f", "&&", "Math", ".", "abs", "(", "sy", ")", "==", "1.0f", "&&", "Math", ".", "abs", "(", "sz", ")", "==", "1.0f", ";", "dest", ".", "_properties", "(", "properties", "&", "~", "(", "PROPERTY_PERSPECTIVE", "|", "PROPERTY_IDENTITY", "|", "PROPERTY_TRANSLATION", "|", "(", "one", "?", "0", ":", "PROPERTY_ORTHONORMAL", ")", ")", ")", ";", "return", "dest", ";", "}" ]
/* (non-Javadoc) @see org.joml.Matrix4fc#scaleAround(float, float, float, float, float, float, org.joml.Matrix4f)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4789-L4814
dmak/jaxb-xew-plugin
src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java
XmlElementWrapperPlugin.deleteSettersGetters
private boolean deleteSettersGetters(JDefinedClass clazz, String fieldPublicName) { """ Returns {@code true} if setter/getter with given public name was successfully removed from given class/interface. """ boolean result = false; for (Iterator<JMethod> iter = clazz.methods().iterator(); iter.hasNext();) { JMethod m = iter.next(); if (m.name().equals("set" + fieldPublicName) || m.name().equals("get" + fieldPublicName)) { iter.remove(); result = true; } } return result; }
java
private boolean deleteSettersGetters(JDefinedClass clazz, String fieldPublicName) { boolean result = false; for (Iterator<JMethod> iter = clazz.methods().iterator(); iter.hasNext();) { JMethod m = iter.next(); if (m.name().equals("set" + fieldPublicName) || m.name().equals("get" + fieldPublicName)) { iter.remove(); result = true; } } return result; }
[ "private", "boolean", "deleteSettersGetters", "(", "JDefinedClass", "clazz", ",", "String", "fieldPublicName", ")", "{", "boolean", "result", "=", "false", ";", "for", "(", "Iterator", "<", "JMethod", ">", "iter", "=", "clazz", ".", "methods", "(", ")", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "JMethod", "m", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "m", ".", "name", "(", ")", ".", "equals", "(", "\"set\"", "+", "fieldPublicName", ")", "||", "m", ".", "name", "(", ")", ".", "equals", "(", "\"get\"", "+", "fieldPublicName", ")", ")", "{", "iter", ".", "remove", "(", ")", ";", "result", "=", "true", ";", "}", "}", "return", "result", ";", "}" ]
Returns {@code true} if setter/getter with given public name was successfully removed from given class/interface.
[ "Returns", "{" ]
train
https://github.com/dmak/jaxb-xew-plugin/blob/d564d6bf8e50c46b056cdb4b46d1d4bee4adfbe3/src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java#L857-L870
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java
ApiOvhHostingweb.serviceName_localSeo_location_id_serviceInfosUpdate_POST
public void serviceName_localSeo_location_id_serviceInfosUpdate_POST(String serviceName, Long id, OvhRenewType renew) throws IOException { """ Alter this object properties REST: POST /hosting/web/{serviceName}/localSeo/location/{id}/serviceInfosUpdate @param renew [required] Renew type @param serviceName [required] The internal name of your hosting @param id [required] Location id """ String qPath = "/hosting/web/{serviceName}/localSeo/location/{id}/serviceInfosUpdate"; StringBuilder sb = path(qPath, serviceName, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "renew", renew); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_localSeo_location_id_serviceInfosUpdate_POST(String serviceName, Long id, OvhRenewType renew) throws IOException { String qPath = "/hosting/web/{serviceName}/localSeo/location/{id}/serviceInfosUpdate"; StringBuilder sb = path(qPath, serviceName, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "renew", renew); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_localSeo_location_id_serviceInfosUpdate_POST", "(", "String", "serviceName", ",", "Long", "id", ",", "OvhRenewType", "renew", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/web/{serviceName}/localSeo/location/{id}/serviceInfosUpdate\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "id", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"renew\"", ",", "renew", ")", ";", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "}" ]
Alter this object properties REST: POST /hosting/web/{serviceName}/localSeo/location/{id}/serviceInfosUpdate @param renew [required] Renew type @param serviceName [required] The internal name of your hosting @param id [required] Location id
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/ApiOvhHostingweb.java#L837-L843
paypal/SeLion
dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/JsonDataProviderImpl.java
JsonDataProviderImpl.getDataAsHashtable
@Override public Hashtable<String, Object> getDataAsHashtable() { """ A utility method to give out JSON data as HashTable. Please note this method works on the rule that the json object that needs to be parsed MUST contain a key named "id". <pre> [ { <b>"id":</b>"test1", "password":123456, "accountNumber":9999999999, "amount":80000, "areaCode":[{ "areaCode" :"area3"}, { "areaCode" :"area4"}], "bank":{ "name" : "Bank1", "type" : "Current", "address" : { "street":"1234 dark St" } } } ] Here the key to the data in the hashtable will be "test1" </pre> @return The JSON data as a {@link Hashtable} """ Preconditions.checkArgument(resource != null, "File resource cannot be null"); logger.entering(); // Over-writing the resource because there is a possibility that a user // can give a type resource.setCls(Hashtable[].class); Hashtable<String, Object> dataAsHashTable = null; JsonReader reader = null; try { reader = new JsonReader(getReader(resource)); Object[][] dataObject = mapJsonData(reader, resource.getCls()); dataAsHashTable = new Hashtable<>(); for (Object[] currentData : dataObject) { // Its pretty safe to cast to array and its also known that a 1D // array is packed Hashtable<?, ?> value = (Hashtable<?, ?>) currentData[0]; /* * As per the json specification a Json Object is a unordered collection of name value pairs. To give * out the json data as hash table , a key needs to be figured out. To keep things clear and easy the * .json file must have all the objects with a key "id" whose value can be used as the key in the * hashtable.Users can directly access the data from the hash table using the value. * * Note: The id is harcoded purposefully here because to enforce the contract between data providers to * have common methods. */ dataAsHashTable.put((String) value.get("id"), currentData); } } catch (NullPointerException n) { // NOSONAR throw new DataProviderException( "Error while parsing Json Data as a Hash table. Root cause: Unable to find a key named id. Please refer Javadoc", n); } catch (Exception e) { throw new DataProviderException("Error while parsing Json Data as a Hash table", e); } finally { IOUtils.closeQuietly(reader); } logger.exiting(dataAsHashTable); return dataAsHashTable; }
java
@Override public Hashtable<String, Object> getDataAsHashtable() { Preconditions.checkArgument(resource != null, "File resource cannot be null"); logger.entering(); // Over-writing the resource because there is a possibility that a user // can give a type resource.setCls(Hashtable[].class); Hashtable<String, Object> dataAsHashTable = null; JsonReader reader = null; try { reader = new JsonReader(getReader(resource)); Object[][] dataObject = mapJsonData(reader, resource.getCls()); dataAsHashTable = new Hashtable<>(); for (Object[] currentData : dataObject) { // Its pretty safe to cast to array and its also known that a 1D // array is packed Hashtable<?, ?> value = (Hashtable<?, ?>) currentData[0]; /* * As per the json specification a Json Object is a unordered collection of name value pairs. To give * out the json data as hash table , a key needs to be figured out. To keep things clear and easy the * .json file must have all the objects with a key "id" whose value can be used as the key in the * hashtable.Users can directly access the data from the hash table using the value. * * Note: The id is harcoded purposefully here because to enforce the contract between data providers to * have common methods. */ dataAsHashTable.put((String) value.get("id"), currentData); } } catch (NullPointerException n) { // NOSONAR throw new DataProviderException( "Error while parsing Json Data as a Hash table. Root cause: Unable to find a key named id. Please refer Javadoc", n); } catch (Exception e) { throw new DataProviderException("Error while parsing Json Data as a Hash table", e); } finally { IOUtils.closeQuietly(reader); } logger.exiting(dataAsHashTable); return dataAsHashTable; }
[ "@", "Override", "public", "Hashtable", "<", "String", ",", "Object", ">", "getDataAsHashtable", "(", ")", "{", "Preconditions", ".", "checkArgument", "(", "resource", "!=", "null", ",", "\"File resource cannot be null\"", ")", ";", "logger", ".", "entering", "(", ")", ";", "// Over-writing the resource because there is a possibility that a user", "// can give a type", "resource", ".", "setCls", "(", "Hashtable", "[", "]", ".", "class", ")", ";", "Hashtable", "<", "String", ",", "Object", ">", "dataAsHashTable", "=", "null", ";", "JsonReader", "reader", "=", "null", ";", "try", "{", "reader", "=", "new", "JsonReader", "(", "getReader", "(", "resource", ")", ")", ";", "Object", "[", "]", "[", "]", "dataObject", "=", "mapJsonData", "(", "reader", ",", "resource", ".", "getCls", "(", ")", ")", ";", "dataAsHashTable", "=", "new", "Hashtable", "<>", "(", ")", ";", "for", "(", "Object", "[", "]", "currentData", ":", "dataObject", ")", "{", "// Its pretty safe to cast to array and its also known that a 1D", "// array is packed", "Hashtable", "<", "?", ",", "?", ">", "value", "=", "(", "Hashtable", "<", "?", ",", "?", ">", ")", "currentData", "[", "0", "]", ";", "/*\n * As per the json specification a Json Object is a unordered collection of name value pairs. To give\n * out the json data as hash table , a key needs to be figured out. To keep things clear and easy the\n * .json file must have all the objects with a key \"id\" whose value can be used as the key in the\n * hashtable.Users can directly access the data from the hash table using the value.\n *\n * Note: The id is harcoded purposefully here because to enforce the contract between data providers to\n * have common methods.\n */", "dataAsHashTable", ".", "put", "(", "(", "String", ")", "value", ".", "get", "(", "\"id\"", ")", ",", "currentData", ")", ";", "}", "}", "catch", "(", "NullPointerException", "n", ")", "{", "// NOSONAR", "throw", "new", "DataProviderException", "(", "\"Error while parsing Json Data as a Hash table. Root cause: Unable to find a key named id. Please refer Javadoc\"", ",", "n", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DataProviderException", "(", "\"Error while parsing Json Data as a Hash table\"", ",", "e", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "reader", ")", ";", "}", "logger", ".", "exiting", "(", "dataAsHashTable", ")", ";", "return", "dataAsHashTable", ";", "}" ]
A utility method to give out JSON data as HashTable. Please note this method works on the rule that the json object that needs to be parsed MUST contain a key named "id". <pre> [ { <b>"id":</b>"test1", "password":123456, "accountNumber":9999999999, "amount":80000, "areaCode":[{ "areaCode" :"area3"}, { "areaCode" :"area4"}], "bank":{ "name" : "Bank1", "type" : "Current", "address" : { "street":"1234 dark St" } } } ] Here the key to the data in the hashtable will be "test1" </pre> @return The JSON data as a {@link Hashtable}
[ "A", "utility", "method", "to", "give", "out", "JSON", "data", "as", "HashTable", ".", "Please", "note", "this", "method", "works", "on", "the", "rule", "that", "the", "json", "object", "that", "needs", "to", "be", "parsed", "MUST", "contain", "a", "key", "named", "id", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/JsonDataProviderImpl.java#L230-L270