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
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/compiler/JBBPCompilerUtils.java
JBBPCompilerUtils.findIndexForFieldPath
public static int findIndexForFieldPath(final String fieldPath, final List<JBBPNamedFieldInfo> namedFields) { """ Find a named field info index in a list for its path. @param fieldPath a field path, it must not be null. @param namedFields a list contains named field info items. @return the index of a field for the path if found one, -1 otherwise """ final String normalized = JBBPUtils.normalizeFieldNameOrPath(fieldPath); int result = -1; for (int i = namedFields.size() - 1; i >= 0; i--) { final JBBPNamedFieldInfo f = namedFields.get(i); if (normalized.equals(f.getFieldPath())) { result = i; break; } } return result; }
java
public static int findIndexForFieldPath(final String fieldPath, final List<JBBPNamedFieldInfo> namedFields) { final String normalized = JBBPUtils.normalizeFieldNameOrPath(fieldPath); int result = -1; for (int i = namedFields.size() - 1; i >= 0; i--) { final JBBPNamedFieldInfo f = namedFields.get(i); if (normalized.equals(f.getFieldPath())) { result = i; break; } } return result; }
[ "public", "static", "int", "findIndexForFieldPath", "(", "final", "String", "fieldPath", ",", "final", "List", "<", "JBBPNamedFieldInfo", ">", "namedFields", ")", "{", "final", "String", "normalized", "=", "JBBPUtils", ".", "normalizeFieldNameOrPath", "(", "fieldPath", ")", ";", "int", "result", "=", "-", "1", ";", "for", "(", "int", "i", "=", "namedFields", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "final", "JBBPNamedFieldInfo", "f", "=", "namedFields", ".", "get", "(", "i", ")", ";", "if", "(", "normalized", ".", "equals", "(", "f", ".", "getFieldPath", "(", ")", ")", ")", "{", "result", "=", "i", ";", "break", ";", "}", "}", "return", "result", ";", "}" ]
Find a named field info index in a list for its path. @param fieldPath a field path, it must not be null. @param namedFields a list contains named field info items. @return the index of a field for the path if found one, -1 otherwise
[ "Find", "a", "named", "field", "info", "index", "in", "a", "list", "for", "its", "path", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/compiler/JBBPCompilerUtils.java#L42-L53
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/builder/Swagger2MarkupConfigBuilder.java
Swagger2MarkupConfigBuilder.getDefaultConfiguration
private Configuration getDefaultConfiguration() { """ Loads the default properties from the classpath. @return the default properties """ Configurations configs = new Configurations(); try { return configs.properties(PROPERTIES_DEFAULT); } catch (ConfigurationException e) { throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT), e); } }
java
private Configuration getDefaultConfiguration() { Configurations configs = new Configurations(); try { return configs.properties(PROPERTIES_DEFAULT); } catch (ConfigurationException e) { throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT), e); } }
[ "private", "Configuration", "getDefaultConfiguration", "(", ")", "{", "Configurations", "configs", "=", "new", "Configurations", "(", ")", ";", "try", "{", "return", "configs", ".", "properties", "(", "PROPERTIES_DEFAULT", ")", ";", "}", "catch", "(", "ConfigurationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Can't load default properties '%s'\"", ",", "PROPERTIES_DEFAULT", ")", ",", "e", ")", ";", "}", "}" ]
Loads the default properties from the classpath. @return the default properties
[ "Loads", "the", "default", "properties", "from", "the", "classpath", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/builder/Swagger2MarkupConfigBuilder.java#L134-L141
gliga/ekstazi
org.ekstazi.core/src/main/java/org/ekstazi/dynamic/JarXtractor.java
JarXtractor.startsWith
private static boolean startsWith(String str, String... prefixes) { """ Checks if the given string starts with any of the given prefixes. @param str String to check for prefix. @param prefixes Potential prefixes of the string. @return True if the string starts with any of the prefixes. """ for (String prefix : prefixes) { if (str.startsWith(prefix)) return true; } return false; }
java
private static boolean startsWith(String str, String... prefixes) { for (String prefix : prefixes) { if (str.startsWith(prefix)) return true; } return false; }
[ "private", "static", "boolean", "startsWith", "(", "String", "str", ",", "String", "...", "prefixes", ")", "{", "for", "(", "String", "prefix", ":", "prefixes", ")", "{", "if", "(", "str", ".", "startsWith", "(", "prefix", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if the given string starts with any of the given prefixes. @param str String to check for prefix. @param prefixes Potential prefixes of the string. @return True if the string starts with any of the prefixes.
[ "Checks", "if", "the", "given", "string", "starts", "with", "any", "of", "the", "given", "prefixes", "." ]
train
https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/dynamic/JarXtractor.java#L99-L104
JosePaumard/streams-utils
src/main/java/org/paumard/streams/StreamsUtils.java
StreamsUtils.shiftingWindowAveragingInt
public static <E> DoubleStream shiftingWindowAveragingInt(Stream<E> stream, int rollingFactor, ToIntFunction<? super E> mapper) { """ <p>Generates a stream that is computed from a provided stream following two steps.</p> <p>The first steps maps this stream to an <code>IntStream</code> that is then rolled following the same principle as the <code>roll()</code> method. This steps builds a <code>Stream&lt;IntStream&gt;</code>. </p> <p>Then the <code>average()</code> method is called on each <code>IntStream</code> using a mapper, and a <code>DoubleStream</code> of averages is returned.</p> <p>The resulting stream has the same number of elements as the provided stream, minus the size of the window width, to preserve consistency of each collection. </p> <p>A <code>NullPointerException</code> will be thrown if the provided stream or the mapper is null.</p> @param stream the processed stream @param rollingFactor the size of the window to apply the collector on @param mapper the mapper applied @param <E> the type of the provided stream @return a stream in which each value is the average of the provided stream """ Objects.requireNonNull(stream); Objects.requireNonNull(mapper); IntStream intStream = stream.mapToInt(mapper); return shiftingWindowAveragingInt(intStream, rollingFactor); }
java
public static <E> DoubleStream shiftingWindowAveragingInt(Stream<E> stream, int rollingFactor, ToIntFunction<? super E> mapper) { Objects.requireNonNull(stream); Objects.requireNonNull(mapper); IntStream intStream = stream.mapToInt(mapper); return shiftingWindowAveragingInt(intStream, rollingFactor); }
[ "public", "static", "<", "E", ">", "DoubleStream", "shiftingWindowAveragingInt", "(", "Stream", "<", "E", ">", "stream", ",", "int", "rollingFactor", ",", "ToIntFunction", "<", "?", "super", "E", ">", "mapper", ")", "{", "Objects", ".", "requireNonNull", "(", "stream", ")", ";", "Objects", ".", "requireNonNull", "(", "mapper", ")", ";", "IntStream", "intStream", "=", "stream", ".", "mapToInt", "(", "mapper", ")", ";", "return", "shiftingWindowAveragingInt", "(", "intStream", ",", "rollingFactor", ")", ";", "}" ]
<p>Generates a stream that is computed from a provided stream following two steps.</p> <p>The first steps maps this stream to an <code>IntStream</code> that is then rolled following the same principle as the <code>roll()</code> method. This steps builds a <code>Stream&lt;IntStream&gt;</code>. </p> <p>Then the <code>average()</code> method is called on each <code>IntStream</code> using a mapper, and a <code>DoubleStream</code> of averages is returned.</p> <p>The resulting stream has the same number of elements as the provided stream, minus the size of the window width, to preserve consistency of each collection. </p> <p>A <code>NullPointerException</code> will be thrown if the provided stream or the mapper is null.</p> @param stream the processed stream @param rollingFactor the size of the window to apply the collector on @param mapper the mapper applied @param <E> the type of the provided stream @return a stream in which each value is the average of the provided stream
[ "<p", ">", "Generates", "a", "stream", "that", "is", "computed", "from", "a", "provided", "stream", "following", "two", "steps", ".", "<", "/", "p", ">", "<p", ">", "The", "first", "steps", "maps", "this", "stream", "to", "an", "<code", ">", "IntStream<", "/", "code", ">", "that", "is", "then", "rolled", "following", "the", "same", "principle", "as", "the", "<code", ">", "roll", "()", "<", "/", "code", ">", "method", ".", "This", "steps", "builds", "a", "<code", ">", "Stream&lt", ";", "IntStream&gt", ";", "<", "/", "code", ">", ".", "<", "/", "p", ">", "<p", ">", "Then", "the", "<code", ">", "average", "()", "<", "/", "code", ">", "method", "is", "called", "on", "each", "<code", ">", "IntStream<", "/", "code", ">", "using", "a", "mapper", "and", "a", "<code", ">", "DoubleStream<", "/", "code", ">", "of", "averages", "is", "returned", ".", "<", "/", "p", ">", "<p", ">", "The", "resulting", "stream", "has", "the", "same", "number", "of", "elements", "as", "the", "provided", "stream", "minus", "the", "size", "of", "the", "window", "width", "to", "preserve", "consistency", "of", "each", "collection", ".", "<", "/", "p", ">", "<p", ">", "A", "<code", ">", "NullPointerException<", "/", "code", ">", "will", "be", "thrown", "if", "the", "provided", "stream", "or", "the", "mapper", "is", "null", ".", "<", "/", "p", ">" ]
train
https://github.com/JosePaumard/streams-utils/blob/56152574af0aca44c5f679761202a8f90984ab73/src/main/java/org/paumard/streams/StreamsUtils.java#L560-L566
spring-projects/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/DefaultTokenServices.java
DefaultTokenServices.createRefreshedAuthentication
private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { """ Create a refreshed authentication. @param authentication The authentication. @param request The scope for the refreshed token. @return The refreshed authentication. @throws InvalidScopeException If the scope requested is invalid or wider than the original scope. """ OAuth2Authentication narrowed = authentication; Set<String> scope = request.getScope(); OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); if (scope != null && !scope.isEmpty()) { Set<String> originalScope = clientAuth.getScope(); if (originalScope == null || !originalScope.containsAll(scope)) { throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope + ".", originalScope); } else { clientAuth = clientAuth.narrowScope(scope); } } narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); return narrowed; }
java
private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { OAuth2Authentication narrowed = authentication; Set<String> scope = request.getScope(); OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); if (scope != null && !scope.isEmpty()) { Set<String> originalScope = clientAuth.getScope(); if (originalScope == null || !originalScope.containsAll(scope)) { throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope + ".", originalScope); } else { clientAuth = clientAuth.narrowScope(scope); } } narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); return narrowed; }
[ "private", "OAuth2Authentication", "createRefreshedAuthentication", "(", "OAuth2Authentication", "authentication", ",", "TokenRequest", "request", ")", "{", "OAuth2Authentication", "narrowed", "=", "authentication", ";", "Set", "<", "String", ">", "scope", "=", "request", ".", "getScope", "(", ")", ";", "OAuth2Request", "clientAuth", "=", "authentication", ".", "getOAuth2Request", "(", ")", ".", "refresh", "(", "request", ")", ";", "if", "(", "scope", "!=", "null", "&&", "!", "scope", ".", "isEmpty", "(", ")", ")", "{", "Set", "<", "String", ">", "originalScope", "=", "clientAuth", ".", "getScope", "(", ")", ";", "if", "(", "originalScope", "==", "null", "||", "!", "originalScope", ".", "containsAll", "(", "scope", ")", ")", "{", "throw", "new", "InvalidScopeException", "(", "\"Unable to narrow the scope of the client authentication to \"", "+", "scope", "+", "\".\"", ",", "originalScope", ")", ";", "}", "else", "{", "clientAuth", "=", "clientAuth", ".", "narrowScope", "(", "scope", ")", ";", "}", "}", "narrowed", "=", "new", "OAuth2Authentication", "(", "clientAuth", ",", "authentication", ".", "getUserAuthentication", "(", ")", ")", ";", "return", "narrowed", ";", "}" ]
Create a refreshed authentication. @param authentication The authentication. @param request The scope for the refreshed token. @return The refreshed authentication. @throws InvalidScopeException If the scope requested is invalid or wider than the original scope.
[ "Create", "a", "refreshed", "authentication", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/DefaultTokenServices.java#L196-L212
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/interpreter/collection/CollectionInterpreter.java
CollectionInterpreter.executeRow
private void executeRow(Example valuesRow, Example headers, Fixture rowFixtureAdapter) { """ <p>executeRow.</p> @param valuesRow a {@link com.greenpepper.Example} object. @param headers a {@link com.greenpepper.Example} object. @param rowFixtureAdapter a {@link com.greenpepper.reflect.Fixture} object. """ valuesRow.annotate( Annotations.right() ); Statistics rowStats = new Statistics(); for (int i = 0; i != valuesRow.remainings(); ++i) { Example cell = valuesRow.at( i ); if (i < headers.remainings()) { // We can do the cast because #parseColumn returns an ExpectedColumn ExpectedColumn column = (ExpectedColumn) columns[i]; try { chekOneCell(rowFixtureAdapter, rowStats, cell, column); } catch (Exception e) { cell.annotate( exception( e ) ); stats.exception(); } } else { cell.annotate( ignored( cell.getContent() ) ); } } applyRowStatistic(rowStats); }
java
private void executeRow(Example valuesRow, Example headers, Fixture rowFixtureAdapter) { valuesRow.annotate( Annotations.right() ); Statistics rowStats = new Statistics(); for (int i = 0; i != valuesRow.remainings(); ++i) { Example cell = valuesRow.at( i ); if (i < headers.remainings()) { // We can do the cast because #parseColumn returns an ExpectedColumn ExpectedColumn column = (ExpectedColumn) columns[i]; try { chekOneCell(rowFixtureAdapter, rowStats, cell, column); } catch (Exception e) { cell.annotate( exception( e ) ); stats.exception(); } } else { cell.annotate( ignored( cell.getContent() ) ); } } applyRowStatistic(rowStats); }
[ "private", "void", "executeRow", "(", "Example", "valuesRow", ",", "Example", "headers", ",", "Fixture", "rowFixtureAdapter", ")", "{", "valuesRow", ".", "annotate", "(", "Annotations", ".", "right", "(", ")", ")", ";", "Statistics", "rowStats", "=", "new", "Statistics", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "valuesRow", ".", "remainings", "(", ")", ";", "++", "i", ")", "{", "Example", "cell", "=", "valuesRow", ".", "at", "(", "i", ")", ";", "if", "(", "i", "<", "headers", ".", "remainings", "(", ")", ")", "{", "// We can do the cast because #parseColumn returns an ExpectedColumn", "ExpectedColumn", "column", "=", "(", "ExpectedColumn", ")", "columns", "[", "i", "]", ";", "try", "{", "chekOneCell", "(", "rowFixtureAdapter", ",", "rowStats", ",", "cell", ",", "column", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "cell", ".", "annotate", "(", "exception", "(", "e", ")", ")", ";", "stats", ".", "exception", "(", ")", ";", "}", "}", "else", "{", "cell", ".", "annotate", "(", "ignored", "(", "cell", ".", "getContent", "(", ")", ")", ")", ";", "}", "}", "applyRowStatistic", "(", "rowStats", ")", ";", "}" ]
<p>executeRow.</p> @param valuesRow a {@link com.greenpepper.Example} object. @param headers a {@link com.greenpepper.Example} object. @param rowFixtureAdapter a {@link com.greenpepper.reflect.Fixture} object.
[ "<p", ">", "executeRow", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/interpreter/collection/CollectionInterpreter.java#L118-L149
cverges/expect4j
src/main/java/expect4j/ExpectUtils.java
ExpectUtils.SSH
public static Expect4j SSH(String hostname, String username, String password, int port) throws Exception { """ Creates an SSH session to the given server on a custom TCP port using the provided credentials. This is equivalent to Expect's <code>spawn ssh $hostname</code>. @param hostname the DNS or IP address of the remote server @param username the account name to use when authenticating @param password the account password to use when authenticating @param port the TCP port for the SSH service @return the controlling Expect4j instance @throws Exception on a variety of errors """ logger.debug("Creating SSH session with " + hostname + ":" + port + " as " + username); JSch jsch = new JSch(); //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); final Session session = jsch.getSession(username, hostname, port); if (password != null) { logger.trace("Setting the Jsch password to the one provided (not shown)"); session.setPassword(password); } java.util.Hashtable<String, String> config = new java.util.Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setDaemonThread(true); session.connect(3 * 1000); // making a connection with timeout. ChannelShell channel = (ChannelShell) session.openChannel("shell"); //channel.setInputStream(System.in); //channel.setOutputStream(System.out); channel.setPtyType("vt102"); //channel.setEnv("LANG", "ja_JP.eucJP"); Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()) { public void close() { super.close(); session.disconnect(); } }; channel.connect(5 * 1000); return expect; }
java
public static Expect4j SSH(String hostname, String username, String password, int port) throws Exception { logger.debug("Creating SSH session with " + hostname + ":" + port + " as " + username); JSch jsch = new JSch(); //jsch.setKnownHosts("/home/foo/.ssh/known_hosts"); final Session session = jsch.getSession(username, hostname, port); if (password != null) { logger.trace("Setting the Jsch password to the one provided (not shown)"); session.setPassword(password); } java.util.Hashtable<String, String> config = new java.util.Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setDaemonThread(true); session.connect(3 * 1000); // making a connection with timeout. ChannelShell channel = (ChannelShell) session.openChannel("shell"); //channel.setInputStream(System.in); //channel.setOutputStream(System.out); channel.setPtyType("vt102"); //channel.setEnv("LANG", "ja_JP.eucJP"); Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()) { public void close() { super.close(); session.disconnect(); } }; channel.connect(5 * 1000); return expect; }
[ "public", "static", "Expect4j", "SSH", "(", "String", "hostname", ",", "String", "username", ",", "String", "password", ",", "int", "port", ")", "throws", "Exception", "{", "logger", ".", "debug", "(", "\"Creating SSH session with \"", "+", "hostname", "+", "\":\"", "+", "port", "+", "\" as \"", "+", "username", ")", ";", "JSch", "jsch", "=", "new", "JSch", "(", ")", ";", "//jsch.setKnownHosts(\"/home/foo/.ssh/known_hosts\");", "final", "Session", "session", "=", "jsch", ".", "getSession", "(", "username", ",", "hostname", ",", "port", ")", ";", "if", "(", "password", "!=", "null", ")", "{", "logger", ".", "trace", "(", "\"Setting the Jsch password to the one provided (not shown)\"", ")", ";", "session", ".", "setPassword", "(", "password", ")", ";", "}", "java", ".", "util", ".", "Hashtable", "<", "String", ",", "String", ">", "config", "=", "new", "java", ".", "util", ".", "Hashtable", "<>", "(", ")", ";", "config", ".", "put", "(", "\"StrictHostKeyChecking\"", ",", "\"no\"", ")", ";", "session", ".", "setConfig", "(", "config", ")", ";", "session", ".", "setDaemonThread", "(", "true", ")", ";", "session", ".", "connect", "(", "3", "*", "1000", ")", ";", "// making a connection with timeout.", "ChannelShell", "channel", "=", "(", "ChannelShell", ")", "session", ".", "openChannel", "(", "\"shell\"", ")", ";", "//channel.setInputStream(System.in);", "//channel.setOutputStream(System.out);", "channel", ".", "setPtyType", "(", "\"vt102\"", ")", ";", "//channel.setEnv(\"LANG\", \"ja_JP.eucJP\");", "Expect4j", "expect", "=", "new", "Expect4j", "(", "channel", ".", "getInputStream", "(", ")", ",", "channel", ".", "getOutputStream", "(", ")", ")", "{", "public", "void", "close", "(", ")", "{", "super", ".", "close", "(", ")", ";", "session", ".", "disconnect", "(", ")", ";", "}", "}", ";", "channel", ".", "connect", "(", "5", "*", "1000", ")", ";", "return", "expect", ";", "}" ]
Creates an SSH session to the given server on a custom TCP port using the provided credentials. This is equivalent to Expect's <code>spawn ssh $hostname</code>. @param hostname the DNS or IP address of the remote server @param username the account name to use when authenticating @param password the account password to use when authenticating @param port the TCP port for the SSH service @return the controlling Expect4j instance @throws Exception on a variety of errors
[ "Creates", "an", "SSH", "session", "to", "the", "given", "server", "on", "a", "custom", "TCP", "port", "using", "the", "provided", "credentials", ".", "This", "is", "equivalent", "to", "Expect", "s", "<code", ">", "spawn", "ssh", "$hostname<", "/", "code", ">", "." ]
train
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/ExpectUtils.java#L180-L218
SUSE/salt-netapi-client
src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java
WebSocketEventStream.onClose
@OnClose public void onClose(Session session, CloseReason closeReason) { """ On closing the websocket, refresh the session and notify all subscribed listeners. Upon exit from this method, all subscribed listeners will be removed. @param session the websocket {@link Session} @param closeReason the {@link CloseReason} for the websocket closure """ this.session = session; clearListeners(closeReason.getCloseCode().getCode(), closeReason.getReasonPhrase()); }
java
@OnClose public void onClose(Session session, CloseReason closeReason) { this.session = session; clearListeners(closeReason.getCloseCode().getCode(), closeReason.getReasonPhrase()); }
[ "@", "OnClose", "public", "void", "onClose", "(", "Session", "session", ",", "CloseReason", "closeReason", ")", "{", "this", ".", "session", "=", "session", ";", "clearListeners", "(", "closeReason", ".", "getCloseCode", "(", ")", ".", "getCode", "(", ")", ",", "closeReason", ".", "getReasonPhrase", "(", ")", ")", ";", "}" ]
On closing the websocket, refresh the session and notify all subscribed listeners. Upon exit from this method, all subscribed listeners will be removed. @param session the websocket {@link Session} @param closeReason the {@link CloseReason} for the websocket closure
[ "On", "closing", "the", "websocket", "refresh", "the", "session", "and", "notify", "all", "subscribed", "listeners", ".", "Upon", "exit", "from", "this", "method", "all", "subscribed", "listeners", "will", "be", "removed", "." ]
train
https://github.com/SUSE/salt-netapi-client/blob/a0bdf643c8e34fa4def4b915366594c1491fdad5/src/main/java/com/suse/salt/netapi/event/WebSocketEventStream.java#L208-L213
haraldk/TwelveMonkeys
common/common-lang/src/main/java/com/twelvemonkeys/lang/SystemUtil.java
SystemUtil.getResourceAsStream
private static InputStream getResourceAsStream(ClassLoader pClassLoader, String pName, boolean pGuessSuffix) { """ Gets the named resource as a stream from the given Class' Classoader. If the pGuessSuffix parameter is true, the method will try to append typical properties file suffixes, such as ".properties" or ".xml". @param pClassLoader the class loader to use @param pName name of the resource @param pGuessSuffix guess suffix @return an input stream reading from the resource """ InputStream is; if (!pGuessSuffix) { is = pClassLoader.getResourceAsStream(pName); // If XML, wrap stream if (is != null && pName.endsWith(XML_PROPERTIES)) { is = new XMLPropertiesInputStream(is); } } else { // Try normal properties is = pClassLoader.getResourceAsStream(pName + STD_PROPERTIES); // Try XML if (is == null) { is = pClassLoader.getResourceAsStream(pName + XML_PROPERTIES); // Wrap stream if (is != null) { is = new XMLPropertiesInputStream(is); } } } // Return stream return is; }
java
private static InputStream getResourceAsStream(ClassLoader pClassLoader, String pName, boolean pGuessSuffix) { InputStream is; if (!pGuessSuffix) { is = pClassLoader.getResourceAsStream(pName); // If XML, wrap stream if (is != null && pName.endsWith(XML_PROPERTIES)) { is = new XMLPropertiesInputStream(is); } } else { // Try normal properties is = pClassLoader.getResourceAsStream(pName + STD_PROPERTIES); // Try XML if (is == null) { is = pClassLoader.getResourceAsStream(pName + XML_PROPERTIES); // Wrap stream if (is != null) { is = new XMLPropertiesInputStream(is); } } } // Return stream return is; }
[ "private", "static", "InputStream", "getResourceAsStream", "(", "ClassLoader", "pClassLoader", ",", "String", "pName", ",", "boolean", "pGuessSuffix", ")", "{", "InputStream", "is", ";", "if", "(", "!", "pGuessSuffix", ")", "{", "is", "=", "pClassLoader", ".", "getResourceAsStream", "(", "pName", ")", ";", "// If XML, wrap stream\r", "if", "(", "is", "!=", "null", "&&", "pName", ".", "endsWith", "(", "XML_PROPERTIES", ")", ")", "{", "is", "=", "new", "XMLPropertiesInputStream", "(", "is", ")", ";", "}", "}", "else", "{", "// Try normal properties\r", "is", "=", "pClassLoader", ".", "getResourceAsStream", "(", "pName", "+", "STD_PROPERTIES", ")", ";", "// Try XML\r", "if", "(", "is", "==", "null", ")", "{", "is", "=", "pClassLoader", ".", "getResourceAsStream", "(", "pName", "+", "XML_PROPERTIES", ")", ";", "// Wrap stream\r", "if", "(", "is", "!=", "null", ")", "{", "is", "=", "new", "XMLPropertiesInputStream", "(", "is", ")", ";", "}", "}", "}", "// Return stream \r", "return", "is", ";", "}" ]
Gets the named resource as a stream from the given Class' Classoader. If the pGuessSuffix parameter is true, the method will try to append typical properties file suffixes, such as ".properties" or ".xml". @param pClassLoader the class loader to use @param pName name of the resource @param pGuessSuffix guess suffix @return an input stream reading from the resource
[ "Gets", "the", "named", "resource", "as", "a", "stream", "from", "the", "given", "Class", "Classoader", ".", "If", "the", "pGuessSuffix", "parameter", "is", "true", "the", "method", "will", "try", "to", "append", "typical", "properties", "file", "suffixes", "such", "as", ".", "properties", "or", ".", "xml", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/SystemUtil.java#L84-L112
aws/aws-sdk-java
aws-java-sdk-pi/src/main/java/com/amazonaws/services/pi/model/DimensionKeyDescription.java
DimensionKeyDescription.withDimensions
public DimensionKeyDescription withDimensions(java.util.Map<String, String> dimensions) { """ <p> A map of name-value pairs for the dimensions in the group. </p> @param dimensions A map of name-value pairs for the dimensions in the group. @return Returns a reference to this object so that method calls can be chained together. """ setDimensions(dimensions); return this; }
java
public DimensionKeyDescription withDimensions(java.util.Map<String, String> dimensions) { setDimensions(dimensions); return this; }
[ "public", "DimensionKeyDescription", "withDimensions", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "dimensions", ")", "{", "setDimensions", "(", "dimensions", ")", ";", "return", "this", ";", "}" ]
<p> A map of name-value pairs for the dimensions in the group. </p> @param dimensions A map of name-value pairs for the dimensions in the group. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "name", "-", "value", "pairs", "for", "the", "dimensions", "in", "the", "group", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pi/src/main/java/com/amazonaws/services/pi/model/DimensionKeyDescription.java#L85-L88
ZenHarbinger/l2fprod-properties-editor
src/main/java/com/l2fprod/common/swing/StatusBar.java
StatusBar.setZones
public void setZones(String[] ids, Component[] zones, String[] constraints) { """ For example: <code> setZones(new String[]{"A","B"}, new JComponent[]{new JLabel(), new JLabel()}, new String[]{"33%","*"}); </code> would construct a new status bar with two zones (two JLabels) named A and B, the first zone A will occupy 33 percents of the overall size of the status bar and B the left space. @param ids a value of type 'String[]' @param zones a value of type 'JComponent[]' @param constraints a value of type 'String[]' """ removeAll(); idToZones.clear(); for (int i = 0, c = zones.length; i < c; i++) { addZone(ids[i], zones[i], constraints[i]); } }
java
public void setZones(String[] ids, Component[] zones, String[] constraints) { removeAll(); idToZones.clear(); for (int i = 0, c = zones.length; i < c; i++) { addZone(ids[i], zones[i], constraints[i]); } }
[ "public", "void", "setZones", "(", "String", "[", "]", "ids", ",", "Component", "[", "]", "zones", ",", "String", "[", "]", "constraints", ")", "{", "removeAll", "(", ")", ";", "idToZones", ".", "clear", "(", ")", ";", "for", "(", "int", "i", "=", "0", ",", "c", "=", "zones", ".", "length", ";", "i", "<", "c", ";", "i", "++", ")", "{", "addZone", "(", "ids", "[", "i", "]", ",", "zones", "[", "i", "]", ",", "constraints", "[", "i", "]", ")", ";", "}", "}" ]
For example: <code> setZones(new String[]{"A","B"}, new JComponent[]{new JLabel(), new JLabel()}, new String[]{"33%","*"}); </code> would construct a new status bar with two zones (two JLabels) named A and B, the first zone A will occupy 33 percents of the overall size of the status bar and B the left space. @param ids a value of type 'String[]' @param zones a value of type 'JComponent[]' @param constraints a value of type 'String[]'
[ "For", "example", ":" ]
train
https://github.com/ZenHarbinger/l2fprod-properties-editor/blob/d9b15c3f0b6ac1d9a2a9d315be073d2a4a419c32/src/main/java/com/l2fprod/common/swing/StatusBar.java#L113-L119
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java
DataFormatHelper.formatTime
public static final String formatTime(long timestamp, boolean useIsoDateFormat) { """ Return the given time formatted, based on the provided format structure @param timestamp A timestamp as a long, e.g. what would be returned from <code>System.currentTimeMillis()</code> @param useIsoDateFormat A boolean, if true, the given date and time will be formatted in ISO-8601, e.g. yyyy-MM-dd'T'HH:mm:ss.SSSZ if false, the date and time will be formatted as the current locale, @return formated date string """ DateFormat df = dateformats.get(); if (df == null) { df = getDateFormat(); dateformats.set(df); } try { // Get and store the locale Date pattern that was retrieved from getDateTimeInstance, to be used later. // This is to prevent creating multiple new instances of SimpleDateFormat, which is expensive. String ddp = localeDatePattern.get(); if (ddp == null) { ddp = ((SimpleDateFormat) df).toPattern(); localeDatePattern.set(ddp); } if (useIsoDateFormat) { ((SimpleDateFormat) df).applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } else { ((SimpleDateFormat) df).applyPattern(ddp); } } catch (Exception e) { // Use the default pattern, instead. } return df.format(timestamp); }
java
public static final String formatTime(long timestamp, boolean useIsoDateFormat) { DateFormat df = dateformats.get(); if (df == null) { df = getDateFormat(); dateformats.set(df); } try { // Get and store the locale Date pattern that was retrieved from getDateTimeInstance, to be used later. // This is to prevent creating multiple new instances of SimpleDateFormat, which is expensive. String ddp = localeDatePattern.get(); if (ddp == null) { ddp = ((SimpleDateFormat) df).toPattern(); localeDatePattern.set(ddp); } if (useIsoDateFormat) { ((SimpleDateFormat) df).applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } else { ((SimpleDateFormat) df).applyPattern(ddp); } } catch (Exception e) { // Use the default pattern, instead. } return df.format(timestamp); }
[ "public", "static", "final", "String", "formatTime", "(", "long", "timestamp", ",", "boolean", "useIsoDateFormat", ")", "{", "DateFormat", "df", "=", "dateformats", ".", "get", "(", ")", ";", "if", "(", "df", "==", "null", ")", "{", "df", "=", "getDateFormat", "(", ")", ";", "dateformats", ".", "set", "(", "df", ")", ";", "}", "try", "{", "// Get and store the locale Date pattern that was retrieved from getDateTimeInstance, to be used later.", "// This is to prevent creating multiple new instances of SimpleDateFormat, which is expensive.", "String", "ddp", "=", "localeDatePattern", ".", "get", "(", ")", ";", "if", "(", "ddp", "==", "null", ")", "{", "ddp", "=", "(", "(", "SimpleDateFormat", ")", "df", ")", ".", "toPattern", "(", ")", ";", "localeDatePattern", ".", "set", "(", "ddp", ")", ";", "}", "if", "(", "useIsoDateFormat", ")", "{", "(", "(", "SimpleDateFormat", ")", "df", ")", ".", "applyPattern", "(", "\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\"", ")", ";", "}", "else", "{", "(", "(", "SimpleDateFormat", ")", "df", ")", ".", "applyPattern", "(", "ddp", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// Use the default pattern, instead.", "}", "return", "df", ".", "format", "(", "timestamp", ")", ";", "}" ]
Return the given time formatted, based on the provided format structure @param timestamp A timestamp as a long, e.g. what would be returned from <code>System.currentTimeMillis()</code> @param useIsoDateFormat A boolean, if true, the given date and time will be formatted in ISO-8601, e.g. yyyy-MM-dd'T'HH:mm:ss.SSSZ if false, the date and time will be formatted as the current locale, @return formated date string
[ "Return", "the", "given", "time", "formatted", "based", "on", "the", "provided", "format", "structure" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/DataFormatHelper.java#L103-L129
OpenTSDB/opentsdb
src/query/QueryUtil.java
QueryUtil.getRowKeyUIDRegex
public static String getRowKeyUIDRegex(final List<byte[]> group_bys, final ByteMap<byte[][]> row_key_literals) { """ Crafts a regular expression for scanning over data table rows and filtering time series that the user doesn't want. At least one of the parameters must be set and have values. NOTE: This method will sort the group bys. @param group_bys An optional list of tag keys that we want to group on. May be null. @param row_key_literals An optional list of key value pairs to filter on. May be null. @return A regular expression string to pass to the storage layer. """ return getRowKeyUIDRegex(group_bys, row_key_literals, false, null, null); }
java
public static String getRowKeyUIDRegex(final List<byte[]> group_bys, final ByteMap<byte[][]> row_key_literals) { return getRowKeyUIDRegex(group_bys, row_key_literals, false, null, null); }
[ "public", "static", "String", "getRowKeyUIDRegex", "(", "final", "List", "<", "byte", "[", "]", ">", "group_bys", ",", "final", "ByteMap", "<", "byte", "[", "]", "[", "]", ">", "row_key_literals", ")", "{", "return", "getRowKeyUIDRegex", "(", "group_bys", ",", "row_key_literals", ",", "false", ",", "null", ",", "null", ")", ";", "}" ]
Crafts a regular expression for scanning over data table rows and filtering time series that the user doesn't want. At least one of the parameters must be set and have values. NOTE: This method will sort the group bys. @param group_bys An optional list of tag keys that we want to group on. May be null. @param row_key_literals An optional list of key value pairs to filter on. May be null. @return A regular expression string to pass to the storage layer.
[ "Crafts", "a", "regular", "expression", "for", "scanning", "over", "data", "table", "rows", "and", "filtering", "time", "series", "that", "the", "user", "doesn", "t", "want", ".", "At", "least", "one", "of", "the", "parameters", "must", "be", "set", "and", "have", "values", ".", "NOTE", ":", "This", "method", "will", "sort", "the", "group", "bys", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/query/QueryUtil.java#L57-L60
appium/java-client
src/main/java/io/appium/java_client/MobileCommand.java
MobileCommand.compareImagesCommand
public static Map.Entry<String, Map<String, ?>> compareImagesCommand(ComparisonMode mode, byte[] img1Data, byte[] img2Data, @Nullable BaseComparisonOptions options) { """ Forms a {@link java.util.Map} of parameters for images comparison. @param mode one of possible comparison modes @param img1Data base64-encoded data of the first image @param img2Data base64-encoded data of the second image @param options comparison options @return key-value pairs """ String[] parameters = options == null ? new String[]{"mode", "firstImage", "secondImage"} : new String[]{"mode", "firstImage", "secondImage", "options"}; Object[] values = options == null ? new Object[]{mode.toString(), new String(img1Data, StandardCharsets.UTF_8), new String(img2Data, StandardCharsets.UTF_8)} : new Object[]{mode.toString(), new String(img1Data, StandardCharsets.UTF_8), new String(img2Data, StandardCharsets.UTF_8), options.build()}; return new AbstractMap.SimpleEntry<>(COMPARE_IMAGES, prepareArguments(parameters, values)); }
java
public static Map.Entry<String, Map<String, ?>> compareImagesCommand(ComparisonMode mode, byte[] img1Data, byte[] img2Data, @Nullable BaseComparisonOptions options) { String[] parameters = options == null ? new String[]{"mode", "firstImage", "secondImage"} : new String[]{"mode", "firstImage", "secondImage", "options"}; Object[] values = options == null ? new Object[]{mode.toString(), new String(img1Data, StandardCharsets.UTF_8), new String(img2Data, StandardCharsets.UTF_8)} : new Object[]{mode.toString(), new String(img1Data, StandardCharsets.UTF_8), new String(img2Data, StandardCharsets.UTF_8), options.build()}; return new AbstractMap.SimpleEntry<>(COMPARE_IMAGES, prepareArguments(parameters, values)); }
[ "public", "static", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "String", ",", "?", ">", ">", "compareImagesCommand", "(", "ComparisonMode", "mode", ",", "byte", "[", "]", "img1Data", ",", "byte", "[", "]", "img2Data", ",", "@", "Nullable", "BaseComparisonOptions", "options", ")", "{", "String", "[", "]", "parameters", "=", "options", "==", "null", "?", "new", "String", "[", "]", "{", "\"mode\"", ",", "\"firstImage\"", ",", "\"secondImage\"", "}", ":", "new", "String", "[", "]", "{", "\"mode\"", ",", "\"firstImage\"", ",", "\"secondImage\"", ",", "\"options\"", "}", ";", "Object", "[", "]", "values", "=", "options", "==", "null", "?", "new", "Object", "[", "]", "{", "mode", ".", "toString", "(", ")", ",", "new", "String", "(", "img1Data", ",", "StandardCharsets", ".", "UTF_8", ")", ",", "new", "String", "(", "img2Data", ",", "StandardCharsets", ".", "UTF_8", ")", "}", ":", "new", "Object", "[", "]", "{", "mode", ".", "toString", "(", ")", ",", "new", "String", "(", "img1Data", ",", "StandardCharsets", ".", "UTF_8", ")", ",", "new", "String", "(", "img2Data", ",", "StandardCharsets", ".", "UTF_8", ")", ",", "options", ".", "build", "(", ")", "}", ";", "return", "new", "AbstractMap", ".", "SimpleEntry", "<>", "(", "COMPARE_IMAGES", ",", "prepareArguments", "(", "parameters", ",", "values", ")", ")", ";", "}" ]
Forms a {@link java.util.Map} of parameters for images comparison. @param mode one of possible comparison modes @param img1Data base64-encoded data of the first image @param img2Data base64-encoded data of the second image @param options comparison options @return key-value pairs
[ "Forms", "a", "{", "@link", "java", ".", "util", ".", "Map", "}", "of", "parameters", "for", "images", "comparison", "." ]
train
https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/MobileCommand.java#L505-L517
spring-projects/spring-data-solr
src/main/java/org/springframework/data/solr/core/query/Criteria.java
Criteria.is
public Criteria is(@Nullable Object o) { """ Crates new {@link Predicate} without any wildcards. Strings with blanks will be escaped {@code "string\ with\ blank"} @param o @return """ if (o == null) { return isNull(); } predicates.add(new Predicate(OperationKey.EQUALS, o)); return this; }
java
public Criteria is(@Nullable Object o) { if (o == null) { return isNull(); } predicates.add(new Predicate(OperationKey.EQUALS, o)); return this; }
[ "public", "Criteria", "is", "(", "@", "Nullable", "Object", "o", ")", "{", "if", "(", "o", "==", "null", ")", "{", "return", "isNull", "(", ")", ";", "}", "predicates", ".", "add", "(", "new", "Predicate", "(", "OperationKey", ".", "EQUALS", ",", "o", ")", ")", ";", "return", "this", ";", "}" ]
Crates new {@link Predicate} without any wildcards. Strings with blanks will be escaped {@code "string\ with\ blank"} @param o @return
[ "Crates", "new", "{", "@link", "Predicate", "}", "without", "any", "wildcards", ".", "Strings", "with", "blanks", "will", "be", "escaped", "{", "@code", "string", "\\", "with", "\\", "blank", "}" ]
train
https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/query/Criteria.java#L121-L127
alkacon/opencms-core
src/org/opencms/main/CmsShellCommands.java
CmsShellCommands.setLoginMessage
public void setLoginMessage(String messageText, boolean loginDisabled) throws CmsRoleViolationException { """ Sets the login message.<p> @param messageText the message text @param loginDisabled true if login should be disabled @throws CmsRoleViolationException when this is not called with the correct privileges """ CmsLoginMessage message = new CmsLoginMessage(0, 0, messageText, loginDisabled); OpenCms.getLoginManager().setLoginMessage(m_cms, message); OpenCms.writeConfiguration(CmsVariablesConfiguration.class); }
java
public void setLoginMessage(String messageText, boolean loginDisabled) throws CmsRoleViolationException { CmsLoginMessage message = new CmsLoginMessage(0, 0, messageText, loginDisabled); OpenCms.getLoginManager().setLoginMessage(m_cms, message); OpenCms.writeConfiguration(CmsVariablesConfiguration.class); }
[ "public", "void", "setLoginMessage", "(", "String", "messageText", ",", "boolean", "loginDisabled", ")", "throws", "CmsRoleViolationException", "{", "CmsLoginMessage", "message", "=", "new", "CmsLoginMessage", "(", "0", ",", "0", ",", "messageText", ",", "loginDisabled", ")", ";", "OpenCms", ".", "getLoginManager", "(", ")", ".", "setLoginMessage", "(", "m_cms", ",", "message", ")", ";", "OpenCms", ".", "writeConfiguration", "(", "CmsVariablesConfiguration", ".", "class", ")", ";", "}" ]
Sets the login message.<p> @param messageText the message text @param loginDisabled true if login should be disabled @throws CmsRoleViolationException when this is not called with the correct privileges
[ "Sets", "the", "login", "message", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L1554-L1559
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/AbstractApi.java
AbstractApi.addFormParam
protected void addFormParam(Form formData, String name, Object value) throws IllegalArgumentException { """ Convenience method for adding query and form parameters to a get() or post() call. @param formData the Form containing the name/value pairs @param name the name of the field/attribute to add @param value the value of the field/attribute to add """ addFormParam(formData, name, value, false); }
java
protected void addFormParam(Form formData, String name, Object value) throws IllegalArgumentException { addFormParam(formData, name, value, false); }
[ "protected", "void", "addFormParam", "(", "Form", "formData", ",", "String", "name", ",", "Object", "value", ")", "throws", "IllegalArgumentException", "{", "addFormParam", "(", "formData", ",", "name", ",", "value", ",", "false", ")", ";", "}" ]
Convenience method for adding query and form parameters to a get() or post() call. @param formData the Form containing the name/value pairs @param name the name of the field/attribute to add @param value the value of the field/attribute to add
[ "Convenience", "method", "for", "adding", "query", "and", "form", "parameters", "to", "a", "get", "()", "or", "post", "()", "call", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/AbstractApi.java#L541-L543
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/ui/SeaGlassTabbedPaneUI.java
SeaGlassTabbedPaneUI.isOverCloseButton
protected boolean isOverCloseButton(int x, int y) { """ Determine whether the mouse is over a tab close button, and if so, set the hover index. @param x the current mouse x coordinate. @param y the current mouse y coordinate. @return {@code true} if the mouse is over a close button, {@code false} otherwise. """ if (tabCloseButtonPlacement != CENTER) { int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (getCloseButtonBounds(i).contains(x, y)) { closeButtonHoverIndex = i; return true; } } } closeButtonHoverIndex = -1; return false; }
java
protected boolean isOverCloseButton(int x, int y) { if (tabCloseButtonPlacement != CENTER) { int tabCount = tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (getCloseButtonBounds(i).contains(x, y)) { closeButtonHoverIndex = i; return true; } } } closeButtonHoverIndex = -1; return false; }
[ "protected", "boolean", "isOverCloseButton", "(", "int", "x", ",", "int", "y", ")", "{", "if", "(", "tabCloseButtonPlacement", "!=", "CENTER", ")", "{", "int", "tabCount", "=", "tabPane", ".", "getTabCount", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tabCount", ";", "i", "++", ")", "{", "if", "(", "getCloseButtonBounds", "(", "i", ")", ".", "contains", "(", "x", ",", "y", ")", ")", "{", "closeButtonHoverIndex", "=", "i", ";", "return", "true", ";", "}", "}", "}", "closeButtonHoverIndex", "=", "-", "1", ";", "return", "false", ";", "}" ]
Determine whether the mouse is over a tab close button, and if so, set the hover index. @param x the current mouse x coordinate. @param y the current mouse y coordinate. @return {@code true} if the mouse is over a close button, {@code false} otherwise.
[ "Determine", "whether", "the", "mouse", "is", "over", "a", "tab", "close", "button", "and", "if", "so", "set", "the", "hover", "index", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassTabbedPaneUI.java#L1121-L1135
groupon/robo-remote
RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/logging/LogEvent.java
LogEvent.parseTime
private long parseTime(String day, String hours) { """ Time comes in following format: 08-11 20:03:17.182: Parse into milliseconds @param day string of format 08-11 @param hours string of format 20:03:17.182: @return """ DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date utcDate = new Date(); try { utcDate = format.parse(day.concat(" " + hours)); } catch (Exception e) { } return utcDate.getTime(); }
java
private long parseTime(String day, String hours) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date utcDate = new Date(); try { utcDate = format.parse(day.concat(" " + hours)); } catch (Exception e) { } return utcDate.getTime(); }
[ "private", "long", "parseTime", "(", "String", "day", ",", "String", "hours", ")", "{", "DateFormat", "format", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd HH:mm:ss.SSS\"", ")", ";", "Date", "utcDate", "=", "new", "Date", "(", ")", ";", "try", "{", "utcDate", "=", "format", ".", "parse", "(", "day", ".", "concat", "(", "\" \"", "+", "hours", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "return", "utcDate", ".", "getTime", "(", ")", ";", "}" ]
Time comes in following format: 08-11 20:03:17.182: Parse into milliseconds @param day string of format 08-11 @param hours string of format 20:03:17.182: @return
[ "Time", "comes", "in", "following", "format", ":", "08", "-", "11", "20", ":", "03", ":", "17", ".", "182", ":", "Parse", "into", "milliseconds" ]
train
https://github.com/groupon/robo-remote/blob/12d242faad50bf90f98657ca9a0c0c3ae1993f07/RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/logging/LogEvent.java#L160-L170
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java
ArrayFunctions.arrayAppend
public static Expression arrayAppend(JsonArray array, Expression value) { """ Returned expression results in new array with value appended. """ return arrayAppend(x(array), value); }
java
public static Expression arrayAppend(JsonArray array, Expression value) { return arrayAppend(x(array), value); }
[ "public", "static", "Expression", "arrayAppend", "(", "JsonArray", "array", ",", "Expression", "value", ")", "{", "return", "arrayAppend", "(", "x", "(", "array", ")", ",", "value", ")", ";", "}" ]
Returned expression results in new array with value appended.
[ "Returned", "expression", "results", "in", "new", "array", "with", "value", "appended", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L59-L61
opsmatters/newrelic-api
src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java
HttpContext.applyHeaders
private void applyHeaders(Invocation.Builder builder, Map<String, Object> headers) { """ Add the given set of headers to the web target. @param builder The invocation to add the headers to @param headers The headers to add """ if(headers != null) { for (Map.Entry<String, Object> e : headers.entrySet()) { builder.header(e.getKey(), e.getValue()); } } }
java
private void applyHeaders(Invocation.Builder builder, Map<String, Object> headers) { if(headers != null) { for (Map.Entry<String, Object> e : headers.entrySet()) { builder.header(e.getKey(), e.getValue()); } } }
[ "private", "void", "applyHeaders", "(", "Invocation", ".", "Builder", "builder", ",", "Map", "<", "String", ",", "Object", ">", "headers", ")", "{", "if", "(", "headers", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "e", ":", "headers", ".", "entrySet", "(", ")", ")", "{", "builder", ".", "header", "(", "e", ".", "getKey", "(", ")", ",", "e", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Add the given set of headers to the web target. @param builder The invocation to add the headers to @param headers The headers to add
[ "Add", "the", "given", "set", "of", "headers", "to", "the", "web", "target", "." ]
train
https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L573-L582
RestComm/sipunit
src/main/java/org/cafesip/sipunit/SipAssert.java
SipAssert.assertRequestReceived
public static void assertRequestReceived(String method, long sequenceNumber, MessageListener obj) { """ Asserts that the given message listener object received a request with the indicated CSeq method and CSeq sequence number. @param method The CSeq method to look for (SipRequest.REGISTER, etc.) @param sequenceNumber The CSeq sequence number to look for @param obj The MessageListener object (ie, SipCall, Subscription, etc.). """ assertRequestReceived(null, method, sequenceNumber, obj); }
java
public static void assertRequestReceived(String method, long sequenceNumber, MessageListener obj) { assertRequestReceived(null, method, sequenceNumber, obj); }
[ "public", "static", "void", "assertRequestReceived", "(", "String", "method", ",", "long", "sequenceNumber", ",", "MessageListener", "obj", ")", "{", "assertRequestReceived", "(", "null", ",", "method", ",", "sequenceNumber", ",", "obj", ")", ";", "}" ]
Asserts that the given message listener object received a request with the indicated CSeq method and CSeq sequence number. @param method The CSeq method to look for (SipRequest.REGISTER, etc.) @param sequenceNumber The CSeq sequence number to look for @param obj The MessageListener object (ie, SipCall, Subscription, etc.).
[ "Asserts", "that", "the", "given", "message", "listener", "object", "received", "a", "request", "with", "the", "indicated", "CSeq", "method", "and", "CSeq", "sequence", "number", "." ]
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/SipAssert.java#L430-L432
mgormley/pacaya
src/main/java/edu/jhu/pacaya/parse/dep/ProjectiveDependencyParser.java
ProjectiveDependencyParser.parseSingleRoot
public static double parseSingleRoot(double[] fracRoot, double[][] fracChild, int[] parents) { """ This gives the maximum projective dependency tree using the algorithm of (Eisner, 2000) as described in McDonald (2006). In the resulting tree, the wall node (denoted as the parent -1) will be the root, and will have exactly one child. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @param parents Output: The parent index of each node or -1 if its parent is the wall node. @return The score of the parse. """ assert (parents.length == fracRoot.length); assert (fracChild.length == fracRoot.length); final int n = parents.length; final ProjTreeChart c = new ProjTreeChart(n+1, DepParseType.VITERBI); insideAlgorithm(EdgeScores.combine(fracRoot, fracChild), c, true); // Trace the backpointers to extract the parents. Arrays.fill(parents, -2); // Get the head of the sentence. int head = c.getBp(0, n, RIGHT, COMPLETE); parents[head-1] = -1; // The wall (-1) is its parent. // Extract parents left of the head. extractParentsComp(1, head, LEFT, c, parents); // Extract parents right of the head. extractParentsComp(head, n, RIGHT, c, parents); return c.getScore(0, n, RIGHT, COMPLETE); }
java
public static double parseSingleRoot(double[] fracRoot, double[][] fracChild, int[] parents) { assert (parents.length == fracRoot.length); assert (fracChild.length == fracRoot.length); final int n = parents.length; final ProjTreeChart c = new ProjTreeChart(n+1, DepParseType.VITERBI); insideAlgorithm(EdgeScores.combine(fracRoot, fracChild), c, true); // Trace the backpointers to extract the parents. Arrays.fill(parents, -2); // Get the head of the sentence. int head = c.getBp(0, n, RIGHT, COMPLETE); parents[head-1] = -1; // The wall (-1) is its parent. // Extract parents left of the head. extractParentsComp(1, head, LEFT, c, parents); // Extract parents right of the head. extractParentsComp(head, n, RIGHT, c, parents); return c.getScore(0, n, RIGHT, COMPLETE); }
[ "public", "static", "double", "parseSingleRoot", "(", "double", "[", "]", "fracRoot", ",", "double", "[", "]", "[", "]", "fracChild", ",", "int", "[", "]", "parents", ")", "{", "assert", "(", "parents", ".", "length", "==", "fracRoot", ".", "length", ")", ";", "assert", "(", "fracChild", ".", "length", "==", "fracRoot", ".", "length", ")", ";", "final", "int", "n", "=", "parents", ".", "length", ";", "final", "ProjTreeChart", "c", "=", "new", "ProjTreeChart", "(", "n", "+", "1", ",", "DepParseType", ".", "VITERBI", ")", ";", "insideAlgorithm", "(", "EdgeScores", ".", "combine", "(", "fracRoot", ",", "fracChild", ")", ",", "c", ",", "true", ")", ";", "// Trace the backpointers to extract the parents. ", "Arrays", ".", "fill", "(", "parents", ",", "-", "2", ")", ";", "// Get the head of the sentence.", "int", "head", "=", "c", ".", "getBp", "(", "0", ",", "n", ",", "RIGHT", ",", "COMPLETE", ")", ";", "parents", "[", "head", "-", "1", "]", "=", "-", "1", ";", "// The wall (-1) is its parent.", "// Extract parents left of the head.", "extractParentsComp", "(", "1", ",", "head", ",", "LEFT", ",", "c", ",", "parents", ")", ";", "// Extract parents right of the head.", "extractParentsComp", "(", "head", ",", "n", ",", "RIGHT", ",", "c", ",", "parents", ")", ";", "return", "c", ".", "getScore", "(", "0", ",", "n", ",", "RIGHT", ",", "COMPLETE", ")", ";", "}" ]
This gives the maximum projective dependency tree using the algorithm of (Eisner, 2000) as described in McDonald (2006). In the resulting tree, the wall node (denoted as the parent -1) will be the root, and will have exactly one child. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @param parents Output: The parent index of each node or -1 if its parent is the wall node. @return The score of the parse.
[ "This", "gives", "the", "maximum", "projective", "dependency", "tree", "using", "the", "algorithm", "of", "(", "Eisner", "2000", ")", "as", "described", "in", "McDonald", "(", "2006", ")", ".", "In", "the", "resulting", "tree", "the", "wall", "node", "(", "denoted", "as", "the", "parent", "-", "1", ")", "will", "be", "the", "root", "and", "will", "have", "exactly", "one", "child", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/parse/dep/ProjectiveDependencyParser.java#L57-L76
graphql-java/graphql-java
src/main/java/graphql/execution/ExecutionStrategy.java
ExecutionStrategy.getFieldDef
protected GraphQLFieldDefinition getFieldDef(GraphQLSchema schema, GraphQLObjectType parentType, Field field) { """ Called to discover the field definition give the current parameters and the AST {@link Field} @param schema the schema in play @param parentType the parent type of the field @param field the field to find the definition of @return a {@link GraphQLFieldDefinition} """ return Introspection.getFieldDef(schema, parentType, field.getName()); }
java
protected GraphQLFieldDefinition getFieldDef(GraphQLSchema schema, GraphQLObjectType parentType, Field field) { return Introspection.getFieldDef(schema, parentType, field.getName()); }
[ "protected", "GraphQLFieldDefinition", "getFieldDef", "(", "GraphQLSchema", "schema", ",", "GraphQLObjectType", "parentType", ",", "Field", "field", ")", "{", "return", "Introspection", ".", "getFieldDef", "(", "schema", ",", "parentType", ",", "field", ".", "getName", "(", ")", ")", ";", "}" ]
Called to discover the field definition give the current parameters and the AST {@link Field} @param schema the schema in play @param parentType the parent type of the field @param field the field to find the definition of @return a {@link GraphQLFieldDefinition}
[ "Called", "to", "discover", "the", "field", "definition", "give", "the", "current", "parameters", "and", "the", "AST", "{", "@link", "Field", "}" ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/execution/ExecutionStrategy.java#L713-L715
google/closure-templates
java/src/com/google/template/soy/internal/i18n/BidiFormatter.java
BidiFormatter.estimateDirection
@VisibleForTesting static Dir estimateDirection(String str, boolean isHtml) { """ Estimates the directionality of a string using the best known general-purpose method, i.e. using relative word counts. Dir.NEUTRAL return value indicates completely neutral input. @param str String whose directionality is to be estimated @param isHtml Whether {@code str} is HTML / HTML-escaped @return {@code str}'s estimated overall directionality """ return BidiUtils.estimateDirection(str, isHtml); }
java
@VisibleForTesting static Dir estimateDirection(String str, boolean isHtml) { return BidiUtils.estimateDirection(str, isHtml); }
[ "@", "VisibleForTesting", "static", "Dir", "estimateDirection", "(", "String", "str", ",", "boolean", "isHtml", ")", "{", "return", "BidiUtils", ".", "estimateDirection", "(", "str", ",", "isHtml", ")", ";", "}" ]
Estimates the directionality of a string using the best known general-purpose method, i.e. using relative word counts. Dir.NEUTRAL return value indicates completely neutral input. @param str String whose directionality is to be estimated @param isHtml Whether {@code str} is HTML / HTML-escaped @return {@code str}'s estimated overall directionality
[ "Estimates", "the", "directionality", "of", "a", "string", "using", "the", "best", "known", "general", "-", "purpose", "method", "i", ".", "e", ".", "using", "relative", "word", "counts", ".", "Dir", ".", "NEUTRAL", "return", "value", "indicates", "completely", "neutral", "input", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/i18n/BidiFormatter.java#L245-L248
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java
StreamSegmentReadIndex.checkReadAvailability
private ReadAvailability checkReadAvailability(long offset, boolean lastOffsetInclusive) { """ Determines the availability of reading at a particular offset, given the state of a segment. @param offset The offset to check. @param lastOffsetInclusive If true, it will consider the last offset of the segment as a valid offset, otherwise it will only validate offsets before the last offset in the segment. @return A ReadAvailability based on the Segment's current state and the given offset. This will return Available unless the given offset is before the Segment's StartOffset or beyond its Length and the Segment is Sealed. """ // We can only read at a particular offset if: // * The offset is not before the Segment's StartOffset // AND // * The segment is not sealed (we are allowed to do a future read) OR // * The segment is sealed and we are not trying to read at or beyond the last offset (based on input). if (offset < this.metadata.getStartOffset()) { return ReadAvailability.BeforeStartOffset; } else if (this.metadata.isSealed()) { return offset < (this.metadata.getLength() + (lastOffsetInclusive ? 1 : 0)) ? ReadAvailability.Available : ReadAvailability.BeyondLastOffset; } // Offset is in a valid range. return ReadAvailability.Available; }
java
private ReadAvailability checkReadAvailability(long offset, boolean lastOffsetInclusive) { // We can only read at a particular offset if: // * The offset is not before the Segment's StartOffset // AND // * The segment is not sealed (we are allowed to do a future read) OR // * The segment is sealed and we are not trying to read at or beyond the last offset (based on input). if (offset < this.metadata.getStartOffset()) { return ReadAvailability.BeforeStartOffset; } else if (this.metadata.isSealed()) { return offset < (this.metadata.getLength() + (lastOffsetInclusive ? 1 : 0)) ? ReadAvailability.Available : ReadAvailability.BeyondLastOffset; } // Offset is in a valid range. return ReadAvailability.Available; }
[ "private", "ReadAvailability", "checkReadAvailability", "(", "long", "offset", ",", "boolean", "lastOffsetInclusive", ")", "{", "// We can only read at a particular offset if:", "// * The offset is not before the Segment's StartOffset", "// AND", "// * The segment is not sealed (we are allowed to do a future read) OR", "// * The segment is sealed and we are not trying to read at or beyond the last offset (based on input).", "if", "(", "offset", "<", "this", ".", "metadata", ".", "getStartOffset", "(", ")", ")", "{", "return", "ReadAvailability", ".", "BeforeStartOffset", ";", "}", "else", "if", "(", "this", ".", "metadata", ".", "isSealed", "(", ")", ")", "{", "return", "offset", "<", "(", "this", ".", "metadata", ".", "getLength", "(", ")", "+", "(", "lastOffsetInclusive", "?", "1", ":", "0", ")", ")", "?", "ReadAvailability", ".", "Available", ":", "ReadAvailability", ".", "BeyondLastOffset", ";", "}", "// Offset is in a valid range.", "return", "ReadAvailability", ".", "Available", ";", "}" ]
Determines the availability of reading at a particular offset, given the state of a segment. @param offset The offset to check. @param lastOffsetInclusive If true, it will consider the last offset of the segment as a valid offset, otherwise it will only validate offsets before the last offset in the segment. @return A ReadAvailability based on the Segment's current state and the given offset. This will return Available unless the given offset is before the Segment's StartOffset or beyond its Length and the Segment is Sealed.
[ "Determines", "the", "availability", "of", "reading", "at", "a", "particular", "offset", "given", "the", "state", "of", "a", "segment", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/reading/StreamSegmentReadIndex.java#L707-L723
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/exception/fault/FaultFormatTextDecorator.java
FaultFormatTextDecorator.getText
@Override public String getText() { """ Converts the target fault into a formatted text. @see nyla.solutions.core.data.Textable#getText() """ if(this.target == null) return null; try { //Check if load of template needed if((this.template == null || this.template.length() == 0) && this.templateName != null) { try { this.template = Text.loadTemplate(templateName); } catch(Exception e) { throw new SetupException("Cannot load template:"+templateName,e); } } Map<Object,Object> faultMap = JavaBean.toMap(this.target); if(this.argumentTextDecorator != null) { this.argumentTextDecorator.setTarget(this.target.getArgument()); faultMap.put(this.argumentKeyName, this.argumentTextDecorator.getText()); } return Text.format(this.template, faultMap); } catch (FormatException e) { throw new FormatFaultException(this.template, e); } }
java
@Override public String getText() { if(this.target == null) return null; try { //Check if load of template needed if((this.template == null || this.template.length() == 0) && this.templateName != null) { try { this.template = Text.loadTemplate(templateName); } catch(Exception e) { throw new SetupException("Cannot load template:"+templateName,e); } } Map<Object,Object> faultMap = JavaBean.toMap(this.target); if(this.argumentTextDecorator != null) { this.argumentTextDecorator.setTarget(this.target.getArgument()); faultMap.put(this.argumentKeyName, this.argumentTextDecorator.getText()); } return Text.format(this.template, faultMap); } catch (FormatException e) { throw new FormatFaultException(this.template, e); } }
[ "@", "Override", "public", "String", "getText", "(", ")", "{", "if", "(", "this", ".", "target", "==", "null", ")", "return", "null", ";", "try", "{", "//Check if load of template needed", "if", "(", "(", "this", ".", "template", "==", "null", "||", "this", ".", "template", ".", "length", "(", ")", "==", "0", ")", "&&", "this", ".", "templateName", "!=", "null", ")", "{", "try", "{", "this", ".", "template", "=", "Text", ".", "loadTemplate", "(", "templateName", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SetupException", "(", "\"Cannot load template:\"", "+", "templateName", ",", "e", ")", ";", "}", "}", "Map", "<", "Object", ",", "Object", ">", "faultMap", "=", "JavaBean", ".", "toMap", "(", "this", ".", "target", ")", ";", "if", "(", "this", ".", "argumentTextDecorator", "!=", "null", ")", "{", "this", ".", "argumentTextDecorator", ".", "setTarget", "(", "this", ".", "target", ".", "getArgument", "(", ")", ")", ";", "faultMap", ".", "put", "(", "this", ".", "argumentKeyName", ",", "this", ".", "argumentTextDecorator", ".", "getText", "(", ")", ")", ";", "}", "return", "Text", ".", "format", "(", "this", ".", "template", ",", "faultMap", ")", ";", "}", "catch", "(", "FormatException", "e", ")", "{", "throw", "new", "FormatFaultException", "(", "this", ".", "template", ",", "e", ")", ";", "}", "}" ]
Converts the target fault into a formatted text. @see nyla.solutions.core.data.Textable#getText()
[ "Converts", "the", "target", "fault", "into", "a", "formatted", "text", "." ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/exception/fault/FaultFormatTextDecorator.java#L40-L80
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/eventbus/BusSupport.java
BusSupport.wrapEventHandler
public static EventHandlerWrapper wrapEventHandler(@NonNull Object subscriber, @NonNull JSONObject jsonObject) { """ This performs the same feature as {@link #wrapEventHandler(String, String, Object, String)}, just parse the params from jsonObject. @param subscriber Original subscriber object @param jsonObject Json params @return An EventHandlerWrapper wrapping a subscriber and used to registered into event bus. """ String type = jsonObject.optString("type"); if (TextUtils.isEmpty(type)) { return null; } String producer = jsonObject.optString("producer"); // String subscriber = jsonObject.optString("subscriber"); String action = jsonObject.optString("action"); return new EventHandlerWrapper(type, producer, subscriber, action); }
java
public static EventHandlerWrapper wrapEventHandler(@NonNull Object subscriber, @NonNull JSONObject jsonObject) { String type = jsonObject.optString("type"); if (TextUtils.isEmpty(type)) { return null; } String producer = jsonObject.optString("producer"); // String subscriber = jsonObject.optString("subscriber"); String action = jsonObject.optString("action"); return new EventHandlerWrapper(type, producer, subscriber, action); }
[ "public", "static", "EventHandlerWrapper", "wrapEventHandler", "(", "@", "NonNull", "Object", "subscriber", ",", "@", "NonNull", "JSONObject", "jsonObject", ")", "{", "String", "type", "=", "jsonObject", ".", "optString", "(", "\"type\"", ")", ";", "if", "(", "TextUtils", ".", "isEmpty", "(", "type", ")", ")", "{", "return", "null", ";", "}", "String", "producer", "=", "jsonObject", ".", "optString", "(", "\"producer\"", ")", ";", "// String subscriber = jsonObject.optString(\"subscriber\");", "String", "action", "=", "jsonObject", ".", "optString", "(", "\"action\"", ")", ";", "return", "new", "EventHandlerWrapper", "(", "type", ",", "producer", ",", "subscriber", ",", "action", ")", ";", "}" ]
This performs the same feature as {@link #wrapEventHandler(String, String, Object, String)}, just parse the params from jsonObject. @param subscriber Original subscriber object @param jsonObject Json params @return An EventHandlerWrapper wrapping a subscriber and used to registered into event bus.
[ "This", "performs", "the", "same", "feature", "as", "{" ]
train
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/eventbus/BusSupport.java#L179-L188
killbill/killbill
entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/EventsStreamBuilder.java
EventsStreamBuilder.buildForEntitlement
public EventsStream buildForEntitlement(final Collection<BlockingState> blockingStatesForAccount, final ImmutableAccountData account, final SubscriptionBaseBundle bundle, final SubscriptionBase baseSubscription, final Collection<SubscriptionBase> allSubscriptionsForBundle, final int accountBCD, final Catalog catalog, final InternalTenantContext internalTenantContext) throws EntitlementApiException { """ Special signature for OptimizedProxyBlockingStateDao to save some DAO calls """ final Map<UUID, Integer> bcdCache = new HashMap<UUID, Integer>(); return buildForEntitlement(blockingStatesForAccount, account, bundle, baseSubscription, baseSubscription, allSubscriptionsForBundle, accountBCD, bcdCache, catalog, internalTenantContext); }
java
public EventsStream buildForEntitlement(final Collection<BlockingState> blockingStatesForAccount, final ImmutableAccountData account, final SubscriptionBaseBundle bundle, final SubscriptionBase baseSubscription, final Collection<SubscriptionBase> allSubscriptionsForBundle, final int accountBCD, final Catalog catalog, final InternalTenantContext internalTenantContext) throws EntitlementApiException { final Map<UUID, Integer> bcdCache = new HashMap<UUID, Integer>(); return buildForEntitlement(blockingStatesForAccount, account, bundle, baseSubscription, baseSubscription, allSubscriptionsForBundle, accountBCD, bcdCache, catalog, internalTenantContext); }
[ "public", "EventsStream", "buildForEntitlement", "(", "final", "Collection", "<", "BlockingState", ">", "blockingStatesForAccount", ",", "final", "ImmutableAccountData", "account", ",", "final", "SubscriptionBaseBundle", "bundle", ",", "final", "SubscriptionBase", "baseSubscription", ",", "final", "Collection", "<", "SubscriptionBase", ">", "allSubscriptionsForBundle", ",", "final", "int", "accountBCD", ",", "final", "Catalog", "catalog", ",", "final", "InternalTenantContext", "internalTenantContext", ")", "throws", "EntitlementApiException", "{", "final", "Map", "<", "UUID", ",", "Integer", ">", "bcdCache", "=", "new", "HashMap", "<", "UUID", ",", "Integer", ">", "(", ")", ";", "return", "buildForEntitlement", "(", "blockingStatesForAccount", ",", "account", ",", "bundle", ",", "baseSubscription", ",", "baseSubscription", ",", "allSubscriptionsForBundle", ",", "accountBCD", ",", "bcdCache", ",", "catalog", ",", "internalTenantContext", ")", ";", "}" ]
Special signature for OptimizedProxyBlockingStateDao to save some DAO calls
[ "Special", "signature", "for", "OptimizedProxyBlockingStateDao", "to", "save", "some", "DAO", "calls" ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/EventsStreamBuilder.java#L313-L323
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java
Log.getLocalizedString
public static String getLocalizedString(String key, Object ... args) { """ Find a localized string in the resource bundle. Because this method is static, it ignores the locale. Use localize(key, args) when possible. @param key The key for the localized string. @param args Fields to substitute into the string. """ return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args); }
java
public static String getLocalizedString(String key, Object ... args) { return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args); }
[ "public", "static", "String", "getLocalizedString", "(", "String", "key", ",", "Object", "...", "args", ")", "{", "return", "JavacMessages", ".", "getDefaultLocalizedString", "(", "PrefixKind", ".", "COMPILER_MISC", ".", "key", "(", "key", ")", ",", "args", ")", ";", "}" ]
Find a localized string in the resource bundle. Because this method is static, it ignores the locale. Use localize(key, args) when possible. @param key The key for the localized string. @param args Fields to substitute into the string.
[ "Find", "a", "localized", "string", "in", "the", "resource", "bundle", ".", "Because", "this", "method", "is", "static", "it", "ignores", "the", "locale", ".", "Use", "localize", "(", "key", "args", ")", "when", "possible", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java#L760-L762
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java
ST_Drape.drapeMultiLineString
public static Geometry drapeMultiLineString(MultiLineString lines, Geometry triangles, STRtree sTRtree) { """ Drape a multilinestring to a set of triangles @param lines @param triangles @param sTRtree @return """ GeometryFactory factory = lines.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); int nbLines = lines.getNumGeometries(); LineString[] lineStrings = new LineString[nbLines]; for (int i = 0; i < nbLines; i++) { lineStrings[i] = (LineString) lineMerge(lines.getGeometryN(i).difference(triangleLines), factory); } Geometry diffExt = factory.createMultiLineString(lineStrings); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); diffExt.apply(drapeFilter); return diffExt; }
java
public static Geometry drapeMultiLineString(MultiLineString lines, Geometry triangles, STRtree sTRtree) { GeometryFactory factory = lines.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); int nbLines = lines.getNumGeometries(); LineString[] lineStrings = new LineString[nbLines]; for (int i = 0; i < nbLines; i++) { lineStrings[i] = (LineString) lineMerge(lines.getGeometryN(i).difference(triangleLines), factory); } Geometry diffExt = factory.createMultiLineString(lineStrings); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); diffExt.apply(drapeFilter); return diffExt; }
[ "public", "static", "Geometry", "drapeMultiLineString", "(", "MultiLineString", "lines", ",", "Geometry", "triangles", ",", "STRtree", "sTRtree", ")", "{", "GeometryFactory", "factory", "=", "lines", ".", "getFactory", "(", ")", ";", "//Split the triangles in lines to perform all intersections", "Geometry", "triangleLines", "=", "LinearComponentExtracter", ".", "getGeometry", "(", "triangles", ",", "true", ")", ";", "int", "nbLines", "=", "lines", ".", "getNumGeometries", "(", ")", ";", "LineString", "[", "]", "lineStrings", "=", "new", "LineString", "[", "nbLines", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nbLines", ";", "i", "++", ")", "{", "lineStrings", "[", "i", "]", "=", "(", "LineString", ")", "lineMerge", "(", "lines", ".", "getGeometryN", "(", "i", ")", ".", "difference", "(", "triangleLines", ")", ",", "factory", ")", ";", "}", "Geometry", "diffExt", "=", "factory", ".", "createMultiLineString", "(", "lineStrings", ")", ";", "CoordinateSequenceFilter", "drapeFilter", "=", "new", "DrapeFilter", "(", "sTRtree", ")", ";", "diffExt", ".", "apply", "(", "drapeFilter", ")", ";", "return", "diffExt", ";", "}" ]
Drape a multilinestring to a set of triangles @param lines @param triangles @param sTRtree @return
[ "Drape", "a", "multilinestring", "to", "a", "set", "of", "triangles" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java#L128-L141
geomajas/geomajas-project-client-gwt2
plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java
TileBasedLayerClient.createOsmLayer
public OsmLayer createOsmLayer(String id, int nrOfLevels, String... urls) { """ Create a new OSM layer with URLs to OSM tile services. <p/> The URLs should have placeholders for the x- and y-coordinate and tile level in the form of {x}, {y}, {z}. The file extension of the tiles should be part of the URL. @param id The unique ID of the layer. @param conf The tile configuration. @param urls The URL to the tile services. @return A new OSM layer. @since 2.2.1 """ OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels)); layer.addUrls(Arrays.asList(urls)); return layer; }
java
public OsmLayer createOsmLayer(String id, int nrOfLevels, String... urls) { OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels)); layer.addUrls(Arrays.asList(urls)); return layer; }
[ "public", "OsmLayer", "createOsmLayer", "(", "String", "id", ",", "int", "nrOfLevels", ",", "String", "...", "urls", ")", "{", "OsmLayer", "layer", "=", "new", "OsmLayer", "(", "id", ",", "createOsmTileConfiguration", "(", "nrOfLevels", ")", ")", ";", "layer", ".", "addUrls", "(", "Arrays", ".", "asList", "(", "urls", ")", ")", ";", "return", "layer", ";", "}" ]
Create a new OSM layer with URLs to OSM tile services. <p/> The URLs should have placeholders for the x- and y-coordinate and tile level in the form of {x}, {y}, {z}. The file extension of the tiles should be part of the URL. @param id The unique ID of the layer. @param conf The tile configuration. @param urls The URL to the tile services. @return A new OSM layer. @since 2.2.1
[ "Create", "a", "new", "OSM", "layer", "with", "URLs", "to", "OSM", "tile", "services", ".", "<p", "/", ">", "The", "URLs", "should", "have", "placeholders", "for", "the", "x", "-", "and", "y", "-", "coordinate", "and", "tile", "level", "in", "the", "form", "of", "{", "x", "}", "{", "y", "}", "{", "z", "}", ".", "The", "file", "extension", "of", "the", "tiles", "should", "be", "part", "of", "the", "URL", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L188-L192
katjahahn/PortEx
src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java
Visualizer.drawPixels
private void drawPixels(Color color, long fileOffset, long length) { """ Draws a square pixels at fileOffset with color. Height and width of the drawn area are based on the number of bytes that it represents given by the length. Square pixels are drawn without visible gap. @param color of the square pixels @param fileOffset file location that the square pixels represent @param length number of bytes that are colored by the square pixels. """ assert color != null; drawPixels(color, fileOffset, length, 0); }
java
private void drawPixels(Color color, long fileOffset, long length) { assert color != null; drawPixels(color, fileOffset, length, 0); }
[ "private", "void", "drawPixels", "(", "Color", "color", ",", "long", "fileOffset", ",", "long", "length", ")", "{", "assert", "color", "!=", "null", ";", "drawPixels", "(", "color", ",", "fileOffset", ",", "length", ",", "0", ")", ";", "}" ]
Draws a square pixels at fileOffset with color. Height and width of the drawn area are based on the number of bytes that it represents given by the length. Square pixels are drawn without visible gap. @param color of the square pixels @param fileOffset file location that the square pixels represent @param length number of bytes that are colored by the square pixels.
[ "Draws", "a", "square", "pixels", "at", "fileOffset", "with", "color", ".", "Height", "and", "width", "of", "the", "drawn", "area", "are", "based", "on", "the", "number", "of", "bytes", "that", "it", "represents", "given", "by", "the", "length", "." ]
train
https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java#L935-L938
UrielCh/ovh-java-sdk
ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java
ApiOvhDbaaslogs.serviceName_role_roleId_PUT
public OvhOperation serviceName_role_roleId_PUT(String serviceName, String roleId, String description, String name, String optionId) throws IOException { """ Update information of specified role REST: PUT /dbaas/logs/{serviceName}/role/{roleId} @param serviceName [required] Service name @param roleId [required] Role ID @param optionId [required] Option ID @param name [required] Name @param description [required] Description """ String qPath = "/dbaas/logs/{serviceName}/role/{roleId}"; StringBuilder sb = path(qPath, serviceName, roleId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "name", name); addBody(o, "optionId", optionId); String resp = exec(qPath, "PUT", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
java
public OvhOperation serviceName_role_roleId_PUT(String serviceName, String roleId, String description, String name, String optionId) throws IOException { String qPath = "/dbaas/logs/{serviceName}/role/{roleId}"; StringBuilder sb = path(qPath, serviceName, roleId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "name", name); addBody(o, "optionId", optionId); String resp = exec(qPath, "PUT", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
[ "public", "OvhOperation", "serviceName_role_roleId_PUT", "(", "String", "serviceName", ",", "String", "roleId", ",", "String", "description", ",", "String", "name", ",", "String", "optionId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dbaas/logs/{serviceName}/role/{roleId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "roleId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"name\"", ",", "name", ")", ";", "addBody", "(", "o", ",", "\"optionId\"", ",", "optionId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOperation", ".", "class", ")", ";", "}" ]
Update information of specified role REST: PUT /dbaas/logs/{serviceName}/role/{roleId} @param serviceName [required] Service name @param roleId [required] Role ID @param optionId [required] Option ID @param name [required] Name @param description [required] Description
[ "Update", "information", "of", "specified", "role" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L750-L759
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/GeometryDeserializer.java
GeometryDeserializer.asMultiPoint
private MultiPoint asMultiPoint(List<List> coords, CrsId crsId) throws IOException { """ Parses the JSON as a linestring geometry @param coords A list of coordinates of points. @param crsId @return An instance of linestring @throws IOException if the given json does not correspond to a linestring or can be parsed as such. """ if (coords == null || coords.isEmpty()) { throw new IOException("A multipoint contains at least one point"); } Point[] points = new Point[coords.size()]; for (int i = 0; i < coords.size(); i++) { points[i] = asPoint(coords.get(i), crsId); } return new MultiPoint(points); }
java
private MultiPoint asMultiPoint(List<List> coords, CrsId crsId) throws IOException { if (coords == null || coords.isEmpty()) { throw new IOException("A multipoint contains at least one point"); } Point[] points = new Point[coords.size()]; for (int i = 0; i < coords.size(); i++) { points[i] = asPoint(coords.get(i), crsId); } return new MultiPoint(points); }
[ "private", "MultiPoint", "asMultiPoint", "(", "List", "<", "List", ">", "coords", ",", "CrsId", "crsId", ")", "throws", "IOException", "{", "if", "(", "coords", "==", "null", "||", "coords", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"A multipoint contains at least one point\"", ")", ";", "}", "Point", "[", "]", "points", "=", "new", "Point", "[", "coords", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "coords", ".", "size", "(", ")", ";", "i", "++", ")", "{", "points", "[", "i", "]", "=", "asPoint", "(", "coords", ".", "get", "(", "i", ")", ",", "crsId", ")", ";", "}", "return", "new", "MultiPoint", "(", "points", ")", ";", "}" ]
Parses the JSON as a linestring geometry @param coords A list of coordinates of points. @param crsId @return An instance of linestring @throws IOException if the given json does not correspond to a linestring or can be parsed as such.
[ "Parses", "the", "JSON", "as", "a", "linestring", "geometry" ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/GeometryDeserializer.java#L320-L329
sarxos/webcam-capture
webcam-capture/src/main/java/com/github/sarxos/webcam/Webcam.java
Webcam.getImage
public BufferedImage getImage() { """ Capture image from webcam and return it. Will return image object or null if webcam is closed or has been already disposed by JVM.<br> <br> <b>IMPORTANT NOTE!!!</b><br> <br> There are two possible behaviors of what webcam should do when you try to get image and webcam is actually closed. Normally it will return null, but there is a special flag which can be statically set to switch all webcams to auto open mode. In this mode, webcam will be automatically open, when you try to get image from closed webcam. Please be aware of some side effects! In case of multi-threaded applications, there is no guarantee that one thread will not try to open webcam even if it was manually closed in different thread. @return Captured image or null if webcam is closed or disposed by JVM """ if (!isReady()) { return null; } long t1 = 0; long t2 = 0; if (asynchronous) { return updater.getImage(); } else { // get image t1 = System.currentTimeMillis(); BufferedImage image = transform(new WebcamGetImageTask(driver, device).getImage()); t2 = System.currentTimeMillis(); if (image == null) { return null; } // get FPS if (device instanceof WebcamDevice.FPSSource) { fps = ((WebcamDevice.FPSSource) device).getFPS(); } else { // +1 to avoid division by zero fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5; } // notify webcam listeners about new image available notifyWebcamImageAcquired(image); return image; } }
java
public BufferedImage getImage() { if (!isReady()) { return null; } long t1 = 0; long t2 = 0; if (asynchronous) { return updater.getImage(); } else { // get image t1 = System.currentTimeMillis(); BufferedImage image = transform(new WebcamGetImageTask(driver, device).getImage()); t2 = System.currentTimeMillis(); if (image == null) { return null; } // get FPS if (device instanceof WebcamDevice.FPSSource) { fps = ((WebcamDevice.FPSSource) device).getFPS(); } else { // +1 to avoid division by zero fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5; } // notify webcam listeners about new image available notifyWebcamImageAcquired(image); return image; } }
[ "public", "BufferedImage", "getImage", "(", ")", "{", "if", "(", "!", "isReady", "(", ")", ")", "{", "return", "null", ";", "}", "long", "t1", "=", "0", ";", "long", "t2", "=", "0", ";", "if", "(", "asynchronous", ")", "{", "return", "updater", ".", "getImage", "(", ")", ";", "}", "else", "{", "// get image\r", "t1", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "BufferedImage", "image", "=", "transform", "(", "new", "WebcamGetImageTask", "(", "driver", ",", "device", ")", ".", "getImage", "(", ")", ")", ";", "t2", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "image", "==", "null", ")", "{", "return", "null", ";", "}", "// get FPS\r", "if", "(", "device", "instanceof", "WebcamDevice", ".", "FPSSource", ")", "{", "fps", "=", "(", "(", "WebcamDevice", ".", "FPSSource", ")", "device", ")", ".", "getFPS", "(", ")", ";", "}", "else", "{", "// +1 to avoid division by zero\r", "fps", "=", "(", "4", "*", "fps", "+", "1000", "/", "(", "t2", "-", "t1", "+", "1", ")", ")", "/", "5", ";", "}", "// notify webcam listeners about new image available\r", "notifyWebcamImageAcquired", "(", "image", ")", ";", "return", "image", ";", "}", "}" ]
Capture image from webcam and return it. Will return image object or null if webcam is closed or has been already disposed by JVM.<br> <br> <b>IMPORTANT NOTE!!!</b><br> <br> There are two possible behaviors of what webcam should do when you try to get image and webcam is actually closed. Normally it will return null, but there is a special flag which can be statically set to switch all webcams to auto open mode. In this mode, webcam will be automatically open, when you try to get image from closed webcam. Please be aware of some side effects! In case of multi-threaded applications, there is no guarantee that one thread will not try to open webcam even if it was manually closed in different thread. @return Captured image or null if webcam is closed or disposed by JVM
[ "Capture", "image", "from", "webcam", "and", "return", "it", ".", "Will", "return", "image", "object", "or", "null", "if", "webcam", "is", "closed", "or", "has", "been", "already", "disposed", "by", "JVM", ".", "<br", ">", "<br", ">", "<b", ">", "IMPORTANT", "NOTE!!!<", "/", "b", ">", "<br", ">", "<br", ">", "There", "are", "two", "possible", "behaviors", "of", "what", "webcam", "should", "do", "when", "you", "try", "to", "get", "image", "and", "webcam", "is", "actually", "closed", ".", "Normally", "it", "will", "return", "null", "but", "there", "is", "a", "special", "flag", "which", "can", "be", "statically", "set", "to", "switch", "all", "webcams", "to", "auto", "open", "mode", ".", "In", "this", "mode", "webcam", "will", "be", "automatically", "open", "when", "you", "try", "to", "get", "image", "from", "closed", "webcam", ".", "Please", "be", "aware", "of", "some", "side", "effects!", "In", "case", "of", "multi", "-", "threaded", "applications", "there", "is", "no", "guarantee", "that", "one", "thread", "will", "not", "try", "to", "open", "webcam", "even", "if", "it", "was", "manually", "closed", "in", "different", "thread", "." ]
train
https://github.com/sarxos/webcam-capture/blob/efbdae04f9ba48db9ec621e94a9bcd6f031882c8/webcam-capture/src/main/java/com/github/sarxos/webcam/Webcam.java#L645-L683
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java
ChocoViews.resolveDependencies
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { """ Flatten the views while considering their dependencies. Operations over the views that respect the iteration order, satisfies the dependencies. @param mo the model @param views the associated solver views @return the list of views, dependency-free @throws SchedulerException if there is a cyclic dependency """ Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
java
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
[ "public", "static", "List", "<", "ChocoView", ">", "resolveDependencies", "(", "Model", "mo", ",", "List", "<", "ChocoView", ">", "views", ",", "Collection", "<", "String", ">", "base", ")", "throws", "SchedulerException", "{", "Set", "<", "String", ">", "done", "=", "new", "HashSet", "<>", "(", "base", ")", ";", "List", "<", "ChocoView", ">", "remaining", "=", "new", "ArrayList", "<>", "(", "views", ")", ";", "List", "<", "ChocoView", ">", "solved", "=", "new", "ArrayList", "<>", "(", ")", ";", "while", "(", "!", "remaining", ".", "isEmpty", "(", ")", ")", "{", "ListIterator", "<", "ChocoView", ">", "ite", "=", "remaining", ".", "listIterator", "(", ")", ";", "boolean", "blocked", "=", "true", ";", "while", "(", "ite", ".", "hasNext", "(", ")", ")", "{", "ChocoView", "s", "=", "ite", ".", "next", "(", ")", ";", "if", "(", "done", ".", "containsAll", "(", "s", ".", "getDependencies", "(", ")", ")", ")", "{", "ite", ".", "remove", "(", ")", ";", "done", ".", "add", "(", "s", ".", "getIdentifier", "(", ")", ")", ";", "solved", ".", "add", "(", "s", ")", ";", "blocked", "=", "false", ";", "}", "}", "if", "(", "blocked", ")", "{", "throw", "new", "SchedulerModelingException", "(", "mo", ",", "\"Missing dependencies or cyclic dependencies prevent from using: \"", "+", "remaining", ")", ";", "}", "}", "return", "solved", ";", "}" ]
Flatten the views while considering their dependencies. Operations over the views that respect the iteration order, satisfies the dependencies. @param mo the model @param views the associated solver views @return the list of views, dependency-free @throws SchedulerException if there is a cyclic dependency
[ "Flatten", "the", "views", "while", "considering", "their", "dependencies", ".", "Operations", "over", "the", "views", "that", "respect", "the", "iteration", "order", "satisfies", "the", "dependencies", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java#L52-L73
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/matching/ConsumerMonitorRegistrar.java
ConsumerMonitorRegistrar.addCallbackToConnectionIndex
public void addCallbackToConnectionIndex( ConnectionImpl connection, String topicExpression, boolean isWildcarded, ConsumerSetChangeCallback callback) { """ Method addCallbackToConnectionIndex Adds a new callback to the callback index. @param topicExpression @param isWildcarded @param callback @return """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "addCallbackToConnectionIndex", new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback }); // Map of callbacks-to-expressions for a connection Map connMap = null; if(_callbackIndex.containsKey(connection)) { // Already have registered callbacks for this connection connMap = (HashMap)_callbackIndex.get(connection); } else { // No registered callbacks for this connection connMap = new HashMap(); _callbackIndex.put(connection,connMap); } // Add the new callback to the index, so we can find it when we deregister TopicRecord tRecord = new TopicRecord(topicExpression, isWildcarded); connMap.put(callback, tRecord); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addCallbackToConnectionIndex"); }
java
public void addCallbackToConnectionIndex( ConnectionImpl connection, String topicExpression, boolean isWildcarded, ConsumerSetChangeCallback callback) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "addCallbackToConnectionIndex", new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback }); // Map of callbacks-to-expressions for a connection Map connMap = null; if(_callbackIndex.containsKey(connection)) { // Already have registered callbacks for this connection connMap = (HashMap)_callbackIndex.get(connection); } else { // No registered callbacks for this connection connMap = new HashMap(); _callbackIndex.put(connection,connMap); } // Add the new callback to the index, so we can find it when we deregister TopicRecord tRecord = new TopicRecord(topicExpression, isWildcarded); connMap.put(callback, tRecord); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addCallbackToConnectionIndex"); }
[ "public", "void", "addCallbackToConnectionIndex", "(", "ConnectionImpl", "connection", ",", "String", "topicExpression", ",", "boolean", "isWildcarded", ",", "ConsumerSetChangeCallback", "callback", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"addCallbackToConnectionIndex\"", ",", "new", "Object", "[", "]", "{", "connection", ",", "topicExpression", ",", "new", "Boolean", "(", "isWildcarded", ")", ",", "callback", "}", ")", ";", "// Map of callbacks-to-expressions for a connection", "Map", "connMap", "=", "null", ";", "if", "(", "_callbackIndex", ".", "containsKey", "(", "connection", ")", ")", "{", "// Already have registered callbacks for this connection", "connMap", "=", "(", "HashMap", ")", "_callbackIndex", ".", "get", "(", "connection", ")", ";", "}", "else", "{", "// No registered callbacks for this connection", "connMap", "=", "new", "HashMap", "(", ")", ";", "_callbackIndex", ".", "put", "(", "connection", ",", "connMap", ")", ";", "}", "// Add the new callback to the index, so we can find it when we deregister", "TopicRecord", "tRecord", "=", "new", "TopicRecord", "(", "topicExpression", ",", "isWildcarded", ")", ";", "connMap", ".", "put", "(", "callback", ",", "tRecord", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"addCallbackToConnectionIndex\"", ")", ";", "}" ]
Method addCallbackToConnectionIndex Adds a new callback to the callback index. @param topicExpression @param isWildcarded @param callback @return
[ "Method", "addCallbackToConnectionIndex" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/matching/ConsumerMonitorRegistrar.java#L1140-L1173
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.mdb/src/com/ibm/ws/ejbcontainer/mdb/internal/MessageEndpointFactoryImpl.java
MessageEndpointFactoryImpl.setJCAVersion
@Override public void setJCAVersion(int majorJCAVer, int minorJCAVer) { """ Indicates what version of JCA specification the RA using this MessageEndpointFactory requires compliance with. @see com.ibm.ws.jca.service.WSMessageEndpointFactory#setJCAVersion(int, int) """ majorJCAVersion = majorJCAVer; minorJCAVersion = minorJCAVer; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "MessageEndpointFactoryImpl.setJCAVersionJCA: Version " + majorJCAVersion + "." + minorJCAVersion + " is set"); } }
java
@Override public void setJCAVersion(int majorJCAVer, int minorJCAVer) { majorJCAVersion = majorJCAVer; minorJCAVersion = minorJCAVer; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "MessageEndpointFactoryImpl.setJCAVersionJCA: Version " + majorJCAVersion + "." + minorJCAVersion + " is set"); } }
[ "@", "Override", "public", "void", "setJCAVersion", "(", "int", "majorJCAVer", ",", "int", "minorJCAVer", ")", "{", "majorJCAVersion", "=", "majorJCAVer", ";", "minorJCAVersion", "=", "minorJCAVer", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"MessageEndpointFactoryImpl.setJCAVersionJCA: Version \"", "+", "majorJCAVersion", "+", "\".\"", "+", "minorJCAVersion", "+", "\" is set\"", ")", ";", "}", "}" ]
Indicates what version of JCA specification the RA using this MessageEndpointFactory requires compliance with. @see com.ibm.ws.jca.service.WSMessageEndpointFactory#setJCAVersion(int, int)
[ "Indicates", "what", "version", "of", "JCA", "specification", "the", "RA", "using", "this", "MessageEndpointFactory", "requires", "compliance", "with", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.mdb/src/com/ibm/ws/ejbcontainer/mdb/internal/MessageEndpointFactoryImpl.java#L394-L401
aws/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetGatewayResponseResult.java
GetGatewayResponseResult.withResponseTemplates
public GetGatewayResponseResult withResponseTemplates(java.util.Map<String, String> responseTemplates) { """ <p> Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs. </p> @param responseTemplates Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs. @return Returns a reference to this object so that method calls can be chained together. """ setResponseTemplates(responseTemplates); return this; }
java
public GetGatewayResponseResult withResponseTemplates(java.util.Map<String, String> responseTemplates) { setResponseTemplates(responseTemplates); return this; }
[ "public", "GetGatewayResponseResult", "withResponseTemplates", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseTemplates", ")", "{", "setResponseTemplates", "(", "responseTemplates", ")", ";", "return", "this", ";", "}" ]
<p> Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs. </p> @param responseTemplates Response templates of the <a>GatewayResponse</a> as a string-to-string map of key-value pairs. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Response", "templates", "of", "the", "<a", ">", "GatewayResponse<", "/", "a", ">", "as", "a", "string", "-", "to", "-", "string", "map", "of", "key", "-", "value", "pairs", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/GetGatewayResponseResult.java#L544-L547
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/newproject/BuildSettingWizardPage.java
BuildSettingWizardPage.updateStatus
private void updateStatus(Throwable event) { """ Update the status of this page according to the given exception. @param event the exception. """ Throwable cause = event; while (cause != null && (!(cause instanceof CoreException)) && cause.getCause() != null && cause.getCause() != cause) { cause = cause.getCause(); } if (cause instanceof CoreException) { updateStatus(((CoreException) cause).getStatus()); } else { final String message; if (cause != null) { message = cause.getLocalizedMessage(); } else { message = event.getLocalizedMessage(); } final IStatus status = new StatusInfo(IStatus.ERROR, message); updateStatus(status); } }
java
private void updateStatus(Throwable event) { Throwable cause = event; while (cause != null && (!(cause instanceof CoreException)) && cause.getCause() != null && cause.getCause() != cause) { cause = cause.getCause(); } if (cause instanceof CoreException) { updateStatus(((CoreException) cause).getStatus()); } else { final String message; if (cause != null) { message = cause.getLocalizedMessage(); } else { message = event.getLocalizedMessage(); } final IStatus status = new StatusInfo(IStatus.ERROR, message); updateStatus(status); } }
[ "private", "void", "updateStatus", "(", "Throwable", "event", ")", "{", "Throwable", "cause", "=", "event", ";", "while", "(", "cause", "!=", "null", "&&", "(", "!", "(", "cause", "instanceof", "CoreException", ")", ")", "&&", "cause", ".", "getCause", "(", ")", "!=", "null", "&&", "cause", ".", "getCause", "(", ")", "!=", "cause", ")", "{", "cause", "=", "cause", ".", "getCause", "(", ")", ";", "}", "if", "(", "cause", "instanceof", "CoreException", ")", "{", "updateStatus", "(", "(", "(", "CoreException", ")", "cause", ")", ".", "getStatus", "(", ")", ")", ";", "}", "else", "{", "final", "String", "message", ";", "if", "(", "cause", "!=", "null", ")", "{", "message", "=", "cause", ".", "getLocalizedMessage", "(", ")", ";", "}", "else", "{", "message", "=", "event", ".", "getLocalizedMessage", "(", ")", ";", "}", "final", "IStatus", "status", "=", "new", "StatusInfo", "(", "IStatus", ".", "ERROR", ",", "message", ")", ";", "updateStatus", "(", "status", ")", ";", "}", "}" ]
Update the status of this page according to the given exception. @param event the exception.
[ "Update", "the", "status", "of", "this", "page", "according", "to", "the", "given", "exception", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/wizards/newproject/BuildSettingWizardPage.java#L193-L213
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/clustering/SpectralClustering.java
SpectralClustering.scaleMatrix
private Matrix scaleMatrix(Matrix matrix) { """ Returns a scaled {@link Matrix}, where each row is the unit magnitude version of the corresponding row vector in {@link matrix}. This is required so that dot product computations over a large number of data points can be distributed, wherease the cosine similarity cannot be. """ // Scale every data point such that it has a dot product of 1 with // itself. This will make further calculations easier since the dot // product distrubutes when the cosine similarity does not. if (matrix instanceof SparseMatrix) { List<SparseDoubleVector> scaledVectors = new ArrayList<SparseDoubleVector>(matrix.rows()); SparseMatrix sm = (SparseMatrix) matrix; for (int r = 0; r < matrix.rows(); ++r) { SparseDoubleVector v = sm.getRowVector(r); scaledVectors.add(new ScaledSparseDoubleVector( v, 1/v.magnitude())); } return Matrices.asSparseMatrix(scaledVectors); } else { List<DoubleVector> scaledVectors = new ArrayList<DoubleVector>(matrix.rows()); for (int r = 0; r < matrix.rows(); ++r) { DoubleVector v = matrix.getRowVector(r); scaledVectors.add(new ScaledDoubleVector(v, 1/v.magnitude())); } return Matrices.asMatrix(scaledVectors); } }
java
private Matrix scaleMatrix(Matrix matrix) { // Scale every data point such that it has a dot product of 1 with // itself. This will make further calculations easier since the dot // product distrubutes when the cosine similarity does not. if (matrix instanceof SparseMatrix) { List<SparseDoubleVector> scaledVectors = new ArrayList<SparseDoubleVector>(matrix.rows()); SparseMatrix sm = (SparseMatrix) matrix; for (int r = 0; r < matrix.rows(); ++r) { SparseDoubleVector v = sm.getRowVector(r); scaledVectors.add(new ScaledSparseDoubleVector( v, 1/v.magnitude())); } return Matrices.asSparseMatrix(scaledVectors); } else { List<DoubleVector> scaledVectors = new ArrayList<DoubleVector>(matrix.rows()); for (int r = 0; r < matrix.rows(); ++r) { DoubleVector v = matrix.getRowVector(r); scaledVectors.add(new ScaledDoubleVector(v, 1/v.magnitude())); } return Matrices.asMatrix(scaledVectors); } }
[ "private", "Matrix", "scaleMatrix", "(", "Matrix", "matrix", ")", "{", "// Scale every data point such that it has a dot product of 1 with", "// itself. This will make further calculations easier since the dot", "// product distrubutes when the cosine similarity does not.", "if", "(", "matrix", "instanceof", "SparseMatrix", ")", "{", "List", "<", "SparseDoubleVector", ">", "scaledVectors", "=", "new", "ArrayList", "<", "SparseDoubleVector", ">", "(", "matrix", ".", "rows", "(", ")", ")", ";", "SparseMatrix", "sm", "=", "(", "SparseMatrix", ")", "matrix", ";", "for", "(", "int", "r", "=", "0", ";", "r", "<", "matrix", ".", "rows", "(", ")", ";", "++", "r", ")", "{", "SparseDoubleVector", "v", "=", "sm", ".", "getRowVector", "(", "r", ")", ";", "scaledVectors", ".", "add", "(", "new", "ScaledSparseDoubleVector", "(", "v", ",", "1", "/", "v", ".", "magnitude", "(", ")", ")", ")", ";", "}", "return", "Matrices", ".", "asSparseMatrix", "(", "scaledVectors", ")", ";", "}", "else", "{", "List", "<", "DoubleVector", ">", "scaledVectors", "=", "new", "ArrayList", "<", "DoubleVector", ">", "(", "matrix", ".", "rows", "(", ")", ")", ";", "for", "(", "int", "r", "=", "0", ";", "r", "<", "matrix", ".", "rows", "(", ")", ";", "++", "r", ")", "{", "DoubleVector", "v", "=", "matrix", ".", "getRowVector", "(", "r", ")", ";", "scaledVectors", ".", "add", "(", "new", "ScaledDoubleVector", "(", "v", ",", "1", "/", "v", ".", "magnitude", "(", ")", ")", ")", ";", "}", "return", "Matrices", ".", "asMatrix", "(", "scaledVectors", ")", ";", "}", "}" ]
Returns a scaled {@link Matrix}, where each row is the unit magnitude version of the corresponding row vector in {@link matrix}. This is required so that dot product computations over a large number of data points can be distributed, wherease the cosine similarity cannot be.
[ "Returns", "a", "scaled", "{" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/clustering/SpectralClustering.java#L178-L201
pwall567/jsonutil
src/main/java/net/pwall/json/JSON.java
JSON.parseArray
public static JSONArray parseArray(InputStream is, String csName) throws IOException { """ Parse a sequence of characters from an {@link InputStream} as a JSON array, specifying the character set by name. @param is the {@link InputStream} @param csName the character set name @return the JSON array @throws JSONException if the stream does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an array """ return (JSONArray)parse(is, csName); }
java
public static JSONArray parseArray(InputStream is, String csName) throws IOException { return (JSONArray)parse(is, csName); }
[ "public", "static", "JSONArray", "parseArray", "(", "InputStream", "is", ",", "String", "csName", ")", "throws", "IOException", "{", "return", "(", "JSONArray", ")", "parse", "(", "is", ",", "csName", ")", ";", "}" ]
Parse a sequence of characters from an {@link InputStream} as a JSON array, specifying the character set by name. @param is the {@link InputStream} @param csName the character set name @return the JSON array @throws JSONException if the stream does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an array
[ "Parse", "a", "sequence", "of", "characters", "from", "an", "{", "@link", "InputStream", "}", "as", "a", "JSON", "array", "specifying", "the", "character", "set", "by", "name", "." ]
train
https://github.com/pwall567/jsonutil/blob/dd5960b9b0bcc9acfe6c52b884fffd9ee5f422fe/src/main/java/net/pwall/json/JSON.java#L423-L425
apache/groovy
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.callWithRows
public List<GroovyRowResult> callWithRows(String sql, List<Object> params, Closure closure) throws SQLException { """ Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning the rows of the ResultSet. <p> Use this when calling a stored procedure that utilizes both output parameters and returns a single ResultSet. <p> Once created, the stored procedure can be called like this: <pre> def rows = sql.callWithRows '{call Hemisphere2(?, ?, ?)}', ['Guillaume', 'Laforge', Sql.VARCHAR], { dwells {@code ->} println dwells } </pre> <p> Resource handling is performed automatically where appropriate. @param sql the sql statement @param params a list of parameters @param closure called once with all out parameter results @return a list of GroovyRowResult objects @throws SQLException if a database access error occurs @see #callWithRows(GString, Closure) """ return callWithRows(sql, params, FIRST_RESULT_SET, closure).get(0); }
java
public List<GroovyRowResult> callWithRows(String sql, List<Object> params, Closure closure) throws SQLException { return callWithRows(sql, params, FIRST_RESULT_SET, closure).get(0); }
[ "public", "List", "<", "GroovyRowResult", ">", "callWithRows", "(", "String", "sql", ",", "List", "<", "Object", ">", "params", ",", "Closure", "closure", ")", "throws", "SQLException", "{", "return", "callWithRows", "(", "sql", ",", "params", ",", "FIRST_RESULT_SET", ",", "closure", ")", ".", "get", "(", "0", ")", ";", "}" ]
Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning the rows of the ResultSet. <p> Use this when calling a stored procedure that utilizes both output parameters and returns a single ResultSet. <p> Once created, the stored procedure can be called like this: <pre> def rows = sql.callWithRows '{call Hemisphere2(?, ?, ?)}', ['Guillaume', 'Laforge', Sql.VARCHAR], { dwells {@code ->} println dwells } </pre> <p> Resource handling is performed automatically where appropriate. @param sql the sql statement @param params a list of parameters @param closure called once with all out parameter results @return a list of GroovyRowResult objects @throws SQLException if a database access error occurs @see #callWithRows(GString, Closure)
[ "Performs", "a", "stored", "procedure", "call", "with", "the", "given", "parameters", "calling", "the", "closure", "once", "with", "all", "result", "objects", "and", "also", "returning", "the", "rows", "of", "the", "ResultSet", ".", "<p", ">", "Use", "this", "when", "calling", "a", "stored", "procedure", "that", "utilizes", "both", "output", "parameters", "and", "returns", "a", "single", "ResultSet", ".", "<p", ">", "Once", "created", "the", "stored", "procedure", "can", "be", "called", "like", "this", ":", "<pre", ">", "def", "rows", "=", "sql", ".", "callWithRows", "{", "call", "Hemisphere2", "(", "?", "?", "?", ")", "}", "[", "Guillaume", "Laforge", "Sql", ".", "VARCHAR", "]", "{", "dwells", "{", "@code", "-", ">", "}", "println", "dwells", "}", "<", "/", "pre", ">", "<p", ">", "Resource", "handling", "is", "performed", "automatically", "where", "appropriate", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L3266-L3268
mangstadt/biweekly
src/main/java/biweekly/io/scribe/property/ICalPropertyScribe.java
ICalPropertyScribe.parseJson
public final T parseJson(JCalValue value, ICalDataType dataType, ICalParameters parameters, ParseContext context) { """ Unmarshals a property's value from a JSON data stream (jCal). @param value the property's JSON value @param dataType the data type @param parameters the parsed parameters @param context the context @return the unmarshalled property @throws CannotParseException if the scribe could not parse the property's value @throws SkipMeException if the property should not be added to the final {@link ICalendar} object """ T property = _parseJson(value, dataType, parameters, context); property.setParameters(parameters); return property; }
java
public final T parseJson(JCalValue value, ICalDataType dataType, ICalParameters parameters, ParseContext context) { T property = _parseJson(value, dataType, parameters, context); property.setParameters(parameters); return property; }
[ "public", "final", "T", "parseJson", "(", "JCalValue", "value", ",", "ICalDataType", "dataType", ",", "ICalParameters", "parameters", ",", "ParseContext", "context", ")", "{", "T", "property", "=", "_parseJson", "(", "value", ",", "dataType", ",", "parameters", ",", "context", ")", ";", "property", ".", "setParameters", "(", "parameters", ")", ";", "return", "property", ";", "}" ]
Unmarshals a property's value from a JSON data stream (jCal). @param value the property's JSON value @param dataType the data type @param parameters the parsed parameters @param context the context @return the unmarshalled property @throws CannotParseException if the scribe could not parse the property's value @throws SkipMeException if the property should not be added to the final {@link ICalendar} object
[ "Unmarshals", "a", "property", "s", "value", "from", "a", "JSON", "data", "stream", "(", "jCal", ")", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/io/scribe/property/ICalPropertyScribe.java#L279-L283
apache/incubator-druid
core/src/main/java/org/apache/druid/java/util/common/io/NativeIO.java
NativeIO.trySkipCache
public static void trySkipCache(int fd, long offset, long len) { """ Remove pages from the file system page cache when they wont be accessed again @param fd The file descriptor of the source file. @param offset The offset within the file. @param len The length to be flushed. """ if (!initialized || !fadvisePossible || fd < 0) { return; } try { // we ignore the return value as this is just best effort to avoid the cache posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); } catch (UnsupportedOperationException uoe) { log.warn(uoe, "posix_fadvise is not supported"); fadvisePossible = false; } catch (UnsatisfiedLinkError ule) { // if JNA is unavailable just skipping Direct I/O // instance of this class will act like normal RandomAccessFile log.warn(ule, "Unsatisfied Link error: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); fadvisePossible = false; } catch (Exception e) { // This is best effort anyway so lets just log that there was an // exception and forget log.warn(e, "Unknown exception: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); } }
java
public static void trySkipCache(int fd, long offset, long len) { if (!initialized || !fadvisePossible || fd < 0) { return; } try { // we ignore the return value as this is just best effort to avoid the cache posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); } catch (UnsupportedOperationException uoe) { log.warn(uoe, "posix_fadvise is not supported"); fadvisePossible = false; } catch (UnsatisfiedLinkError ule) { // if JNA is unavailable just skipping Direct I/O // instance of this class will act like normal RandomAccessFile log.warn(ule, "Unsatisfied Link error: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); fadvisePossible = false; } catch (Exception e) { // This is best effort anyway so lets just log that there was an // exception and forget log.warn(e, "Unknown exception: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); } }
[ "public", "static", "void", "trySkipCache", "(", "int", "fd", ",", "long", "offset", ",", "long", "len", ")", "{", "if", "(", "!", "initialized", "||", "!", "fadvisePossible", "||", "fd", "<", "0", ")", "{", "return", ";", "}", "try", "{", "// we ignore the return value as this is just best effort to avoid the cache", "posix_fadvise", "(", "fd", ",", "offset", ",", "len", ",", "POSIX_FADV_DONTNEED", ")", ";", "}", "catch", "(", "UnsupportedOperationException", "uoe", ")", "{", "log", ".", "warn", "(", "uoe", ",", "\"posix_fadvise is not supported\"", ")", ";", "fadvisePossible", "=", "false", ";", "}", "catch", "(", "UnsatisfiedLinkError", "ule", ")", "{", "// if JNA is unavailable just skipping Direct I/O", "// instance of this class will act like normal RandomAccessFile", "log", ".", "warn", "(", "ule", ",", "\"Unsatisfied Link error: posix_fadvise failed on file descriptor [%d], offset [%d]\"", ",", "fd", ",", "offset", ")", ";", "fadvisePossible", "=", "false", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// This is best effort anyway so lets just log that there was an", "// exception and forget", "log", ".", "warn", "(", "e", ",", "\"Unknown exception: posix_fadvise failed on file descriptor [%d], offset [%d]\"", ",", "fd", ",", "offset", ")", ";", "}", "}" ]
Remove pages from the file system page cache when they wont be accessed again @param fd The file descriptor of the source file. @param offset The offset within the file. @param len The length to be flushed.
[ "Remove", "pages", "from", "the", "file", "system", "page", "cache", "when", "they", "wont", "be", "accessed", "again" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/io/NativeIO.java#L131-L157
lessthanoptimal/ejml
main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java
ReadMatrixCsv.readCDRM
public CMatrixRMaj readCDRM(int numRows, int numCols) throws IOException { """ Reads in a {@link CMatrixRMaj} from the IO stream where the user specifies the matrix dimensions. @param numRows Number of rows in the matrix @param numCols Number of columns in the matrix @return CMatrixRMaj @throws IOException """ CMatrixRMaj A = new CMatrixRMaj(numRows,numCols); int wordsCol = numCols*2; for( int i = 0; i < numRows; i++ ) { List<String> words = extractWords(); if( words == null ) throw new IOException("Too few rows found. expected "+numRows+" actual "+i); if( words.size() != wordsCol ) throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol); for( int j = 0; j < wordsCol; j += 2 ) { float real = Float.parseFloat(words.get(j)); float imaginary = Float.parseFloat(words.get(j+1)); A.set(i, j, real, imaginary); } } return A; }
java
public CMatrixRMaj readCDRM(int numRows, int numCols) throws IOException { CMatrixRMaj A = new CMatrixRMaj(numRows,numCols); int wordsCol = numCols*2; for( int i = 0; i < numRows; i++ ) { List<String> words = extractWords(); if( words == null ) throw new IOException("Too few rows found. expected "+numRows+" actual "+i); if( words.size() != wordsCol ) throw new IOException("Unexpected number of words in column. Found "+words.size()+" expected "+wordsCol); for( int j = 0; j < wordsCol; j += 2 ) { float real = Float.parseFloat(words.get(j)); float imaginary = Float.parseFloat(words.get(j+1)); A.set(i, j, real, imaginary); } } return A; }
[ "public", "CMatrixRMaj", "readCDRM", "(", "int", "numRows", ",", "int", "numCols", ")", "throws", "IOException", "{", "CMatrixRMaj", "A", "=", "new", "CMatrixRMaj", "(", "numRows", ",", "numCols", ")", ";", "int", "wordsCol", "=", "numCols", "*", "2", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numRows", ";", "i", "++", ")", "{", "List", "<", "String", ">", "words", "=", "extractWords", "(", ")", ";", "if", "(", "words", "==", "null", ")", "throw", "new", "IOException", "(", "\"Too few rows found. expected \"", "+", "numRows", "+", "\" actual \"", "+", "i", ")", ";", "if", "(", "words", ".", "size", "(", ")", "!=", "wordsCol", ")", "throw", "new", "IOException", "(", "\"Unexpected number of words in column. Found \"", "+", "words", ".", "size", "(", ")", "+", "\" expected \"", "+", "wordsCol", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "wordsCol", ";", "j", "+=", "2", ")", "{", "float", "real", "=", "Float", ".", "parseFloat", "(", "words", ".", "get", "(", "j", ")", ")", ";", "float", "imaginary", "=", "Float", ".", "parseFloat", "(", "words", ".", "get", "(", "j", "+", "1", ")", ")", ";", "A", ".", "set", "(", "i", ",", "j", ",", "real", ",", "imaginary", ")", ";", "}", "}", "return", "A", ";", "}" ]
Reads in a {@link CMatrixRMaj} from the IO stream where the user specifies the matrix dimensions. @param numRows Number of rows in the matrix @param numCols Number of columns in the matrix @return CMatrixRMaj @throws IOException
[ "Reads", "in", "a", "{", "@link", "CMatrixRMaj", "}", "from", "the", "IO", "stream", "where", "the", "user", "specifies", "the", "matrix", "dimensions", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ReadMatrixCsv.java#L216-L239
UrielCh/ovh-java-sdk
ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java
ApiOvhEmailpro.service_account_email_fullAccess_allowedAccountId_DELETE
public OvhTask service_account_email_fullAccess_allowedAccountId_DELETE(String service, String email, Long allowedAccountId) throws IOException { """ Revoke full access REST: DELETE /email/pro/{service}/account/{email}/fullAccess/{allowedAccountId} @param service [required] The internal name of your pro organization @param email [required] Default email for this mailbox @param allowedAccountId [required] Account id to give full access API beta """ String qPath = "/email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}"; StringBuilder sb = path(qPath, service, email, allowedAccountId); String resp = exec(qPath, "DELETE", sb.toString(), null); return convertTo(resp, OvhTask.class); }
java
public OvhTask service_account_email_fullAccess_allowedAccountId_DELETE(String service, String email, Long allowedAccountId) throws IOException { String qPath = "/email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}"; StringBuilder sb = path(qPath, service, email, allowedAccountId); String resp = exec(qPath, "DELETE", sb.toString(), null); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "service_account_email_fullAccess_allowedAccountId_DELETE", "(", "String", "service", ",", "String", "email", ",", "Long", "allowedAccountId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/pro/{service}/account/{email}/fullAccess/{allowedAccountId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "service", ",", "email", ",", "allowedAccountId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"DELETE\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Revoke full access REST: DELETE /email/pro/{service}/account/{email}/fullAccess/{allowedAccountId} @param service [required] The internal name of your pro organization @param email [required] Default email for this mailbox @param allowedAccountId [required] Account id to give full access API beta
[ "Revoke", "full", "access" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L354-L359
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/base/base_resource.java
base_resource.update_resource
protected base_resource[] update_resource(nitro_service service, options option) throws Exception { """ Use this method to perform a modify operation on MPS resource. @param service nitro_service object. @param option options class object. @return status of the operation performed. @throws Exception """ if (!service.isLogin() && !get_object_type().equals("login")) service.login(); String request = resource_to_string(service, option); return put_data(service,request); }
java
protected base_resource[] update_resource(nitro_service service, options option) throws Exception { if (!service.isLogin() && !get_object_type().equals("login")) service.login(); String request = resource_to_string(service, option); return put_data(service,request); }
[ "protected", "base_resource", "[", "]", "update_resource", "(", "nitro_service", "service", ",", "options", "option", ")", "throws", "Exception", "{", "if", "(", "!", "service", ".", "isLogin", "(", ")", "&&", "!", "get_object_type", "(", ")", ".", "equals", "(", "\"login\"", ")", ")", "service", ".", "login", "(", ")", ";", "String", "request", "=", "resource_to_string", "(", "service", ",", "option", ")", ";", "return", "put_data", "(", "service", ",", "request", ")", ";", "}" ]
Use this method to perform a modify operation on MPS resource. @param service nitro_service object. @param option options class object. @return status of the operation performed. @throws Exception
[ "Use", "this", "method", "to", "perform", "a", "modify", "operation", "on", "MPS", "resource", "." ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/base/base_resource.java#L249-L255
sagiegurari/fax4j
src/main/java/org/fax4j/spi/interfax/InterfaxMailFaxClientSpi.java
InterfaxMailFaxClientSpi.createSubmitFaxJobMessage
@Override protected Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder) { """ This function will create the message used to invoke the fax job action.<br> If this method returns null, the SPI will throw an UnsupportedOperationException. @param faxJob The fax job object containing the needed information @param mailResourcesHolder The mail resources holder @return The message to send (if null, the SPI will throw an UnsupportedOperationException) """ //set from String from=faxJob.getSenderEmail(); if((from==null)||(from.length()==0)) { throw new FaxException("From address not provided."); } //create message Message message=super.createSubmitFaxJobMessage(faxJob,mailResourcesHolder); return message; }
java
@Override protected Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder) { //set from String from=faxJob.getSenderEmail(); if((from==null)||(from.length()==0)) { throw new FaxException("From address not provided."); } //create message Message message=super.createSubmitFaxJobMessage(faxJob,mailResourcesHolder); return message; }
[ "@", "Override", "protected", "Message", "createSubmitFaxJobMessage", "(", "FaxJob", "faxJob", ",", "MailResourcesHolder", "mailResourcesHolder", ")", "{", "//set from", "String", "from", "=", "faxJob", ".", "getSenderEmail", "(", ")", ";", "if", "(", "(", "from", "==", "null", ")", "||", "(", "from", ".", "length", "(", ")", "==", "0", ")", ")", "{", "throw", "new", "FaxException", "(", "\"From address not provided.\"", ")", ";", "}", "//create message", "Message", "message", "=", "super", ".", "createSubmitFaxJobMessage", "(", "faxJob", ",", "mailResourcesHolder", ")", ";", "return", "message", ";", "}" ]
This function will create the message used to invoke the fax job action.<br> If this method returns null, the SPI will throw an UnsupportedOperationException. @param faxJob The fax job object containing the needed information @param mailResourcesHolder The mail resources holder @return The message to send (if null, the SPI will throw an UnsupportedOperationException)
[ "This", "function", "will", "create", "the", "message", "used", "to", "invoke", "the", "fax", "job", "action", ".", "<br", ">", "If", "this", "method", "returns", "null", "the", "SPI", "will", "throw", "an", "UnsupportedOperationException", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/interfax/InterfaxMailFaxClientSpi.java#L175-L189
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/PrefHelper.java
PrefHelper.setInteger
public void setInteger(String key, int value) { """ <p>Sets the value of the {@link String} key value supplied in preferences.</p> @param key A {@link String} value containing the key to reference. @param value An {@link Integer} value to set the preference record to. """ prefHelper_.prefsEditor_.putInt(key, value); prefHelper_.prefsEditor_.apply(); }
java
public void setInteger(String key, int value) { prefHelper_.prefsEditor_.putInt(key, value); prefHelper_.prefsEditor_.apply(); }
[ "public", "void", "setInteger", "(", "String", "key", ",", "int", "value", ")", "{", "prefHelper_", ".", "prefsEditor_", ".", "putInt", "(", "key", ",", "value", ")", ";", "prefHelper_", ".", "prefsEditor_", ".", "apply", "(", ")", ";", "}" ]
<p>Sets the value of the {@link String} key value supplied in preferences.</p> @param key A {@link String} value containing the key to reference. @param value An {@link Integer} value to set the preference record to.
[ "<p", ">", "Sets", "the", "value", "of", "the", "{", "@link", "String", "}", "key", "value", "supplied", "in", "preferences", ".", "<", "/", "p", ">" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/PrefHelper.java#L970-L973
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/JobsInner.java
JobsInner.cancelJobAsync
public Observable<Void> cancelJobAsync(String resourceGroupName, String accountName, String transformName, String jobName) { """ Cancel Job. Cancel a Job. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param transformName The Transform name. @param jobName The Job name. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return cancelJobWithServiceResponseAsync(resourceGroupName, accountName, transformName, jobName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> cancelJobAsync(String resourceGroupName, String accountName, String transformName, String jobName) { return cancelJobWithServiceResponseAsync(resourceGroupName, accountName, transformName, jobName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "cancelJobAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "transformName", ",", "String", "jobName", ")", "{", "return", "cancelJobWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ",", "transformName", ",", "jobName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Cancel Job. Cancel a Job. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param transformName The Transform name. @param jobName The Job name. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Cancel", "Job", ".", "Cancel", "a", "Job", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_03_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_03_30_preview/implementation/JobsInner.java#L738-L745
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/BaseTangramEngine.java
BaseTangramEngine.insertData
@Deprecated public void insertData(int position, @Nullable List<Card> data) { """ Insert parsed data to Tangram at target position. It cause full screen item's rebinding, be careful. @param position Target insert position. @param data Parsed data list. """ Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.insertGroup(position, data); }
java
@Deprecated public void insertData(int position, @Nullable List<Card> data) { Preconditions.checkState(mGroupBasicAdapter != null, "Must call bindView() first"); this.mGroupBasicAdapter.insertGroup(position, data); }
[ "@", "Deprecated", "public", "void", "insertData", "(", "int", "position", ",", "@", "Nullable", "List", "<", "Card", ">", "data", ")", "{", "Preconditions", ".", "checkState", "(", "mGroupBasicAdapter", "!=", "null", ",", "\"Must call bindView() first\"", ")", ";", "this", ".", "mGroupBasicAdapter", ".", "insertGroup", "(", "position", ",", "data", ")", ";", "}" ]
Insert parsed data to Tangram at target position. It cause full screen item's rebinding, be careful. @param position Target insert position. @param data Parsed data list.
[ "Insert", "parsed", "data", "to", "Tangram", "at", "target", "position", ".", "It", "cause", "full", "screen", "item", "s", "rebinding", "be", "careful", "." ]
train
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/BaseTangramEngine.java#L337-L341
geomajas/geomajas-project-client-gwt2
impl/src/main/java/org/geomajas/gwt2/client/service/DomService.java
DomService.setLeft
public static void setLeft(Element element, int left) { """ Apply the "left" style attribute on the given element. @param element The DOM element. @param left The left value. """ if (Dom.isIE()) { // Limitation in IE8... while (left > 1000000) { left -= 1000000; } while (left < -1000000) { left += 1000000; } } Dom.setStyleAttribute(element, "left", left + "px"); }
java
public static void setLeft(Element element, int left) { if (Dom.isIE()) { // Limitation in IE8... while (left > 1000000) { left -= 1000000; } while (left < -1000000) { left += 1000000; } } Dom.setStyleAttribute(element, "left", left + "px"); }
[ "public", "static", "void", "setLeft", "(", "Element", "element", ",", "int", "left", ")", "{", "if", "(", "Dom", ".", "isIE", "(", ")", ")", "{", "// Limitation in IE8...", "while", "(", "left", ">", "1000000", ")", "{", "left", "-=", "1000000", ";", "}", "while", "(", "left", "<", "-", "1000000", ")", "{", "left", "+=", "1000000", ";", "}", "}", "Dom", ".", "setStyleAttribute", "(", "element", ",", "\"left\"", ",", "left", "+", "\"px\"", ")", ";", "}" ]
Apply the "left" style attribute on the given element. @param element The DOM element. @param left The left value.
[ "Apply", "the", "left", "style", "attribute", "on", "the", "given", "element", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/impl/src/main/java/org/geomajas/gwt2/client/service/DomService.java#L80-L90
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/TransitiveGroup.java
TransitiveGroup.checkTransitive
private boolean checkTransitive(String groupStart, String groupIn, String groupEnd, Collection<GroupTransition> localChecked, Deque<GroupTransition> found, boolean first) { """ Check transitive groups. @param groupStart The first group. @param groupIn The local group in. @param groupEnd The last group. @param localChecked Current checked transitions. @param found Transitions found. @param first <code>true</code> if first pass, <code>false</code> else. @return <code>true</code> if transitive valid, <code>false</code> else. """ boolean ok = false; for (final String groupOut : mapGroup.getGroups()) { final GroupTransition transitive = new GroupTransition(groupIn, groupOut); final boolean firstOrNext = first && groupIn.equals(groupStart) || !first && !groupIn.equals(groupOut); if (firstOrNext && !localChecked.contains(transitive)) { localChecked.add(transitive); final boolean nextFirst = countTransitions(groupStart, transitive, groupEnd, found, first); if (groupOut.equals(groupEnd)) { ok = true; } else { checkTransitive(groupStart, groupOut, groupEnd, localChecked, found, nextFirst); } } } return ok; }
java
private boolean checkTransitive(String groupStart, String groupIn, String groupEnd, Collection<GroupTransition> localChecked, Deque<GroupTransition> found, boolean first) { boolean ok = false; for (final String groupOut : mapGroup.getGroups()) { final GroupTransition transitive = new GroupTransition(groupIn, groupOut); final boolean firstOrNext = first && groupIn.equals(groupStart) || !first && !groupIn.equals(groupOut); if (firstOrNext && !localChecked.contains(transitive)) { localChecked.add(transitive); final boolean nextFirst = countTransitions(groupStart, transitive, groupEnd, found, first); if (groupOut.equals(groupEnd)) { ok = true; } else { checkTransitive(groupStart, groupOut, groupEnd, localChecked, found, nextFirst); } } } return ok; }
[ "private", "boolean", "checkTransitive", "(", "String", "groupStart", ",", "String", "groupIn", ",", "String", "groupEnd", ",", "Collection", "<", "GroupTransition", ">", "localChecked", ",", "Deque", "<", "GroupTransition", ">", "found", ",", "boolean", "first", ")", "{", "boolean", "ok", "=", "false", ";", "for", "(", "final", "String", "groupOut", ":", "mapGroup", ".", "getGroups", "(", ")", ")", "{", "final", "GroupTransition", "transitive", "=", "new", "GroupTransition", "(", "groupIn", ",", "groupOut", ")", ";", "final", "boolean", "firstOrNext", "=", "first", "&&", "groupIn", ".", "equals", "(", "groupStart", ")", "||", "!", "first", "&&", "!", "groupIn", ".", "equals", "(", "groupOut", ")", ";", "if", "(", "firstOrNext", "&&", "!", "localChecked", ".", "contains", "(", "transitive", ")", ")", "{", "localChecked", ".", "add", "(", "transitive", ")", ";", "final", "boolean", "nextFirst", "=", "countTransitions", "(", "groupStart", ",", "transitive", ",", "groupEnd", ",", "found", ",", "first", ")", ";", "if", "(", "groupOut", ".", "equals", "(", "groupEnd", ")", ")", "{", "ok", "=", "true", ";", "}", "else", "{", "checkTransitive", "(", "groupStart", ",", "groupOut", ",", "groupEnd", ",", "localChecked", ",", "found", ",", "nextFirst", ")", ";", "}", "}", "}", "return", "ok", ";", "}" ]
Check transitive groups. @param groupStart The first group. @param groupIn The local group in. @param groupEnd The last group. @param localChecked Current checked transitions. @param found Transitions found. @param first <code>true</code> if first pass, <code>false</code> else. @return <code>true</code> if transitive valid, <code>false</code> else.
[ "Check", "transitive", "groups", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/TransitiveGroup.java#L222-L250
grails/grails-core
grails-web-common/src/main/groovy/org/grails/web/util/WebUtils.java
WebUtils.resolveView
public static View resolveView(HttpServletRequest request, String viewName, String controllerName, ViewResolver viewResolver) throws Exception { """ Resolves a view for the given view name and controller name @param request The request @param viewName The view name @param controllerName The controller name @param viewResolver The resolver @return A View or null @throws Exception Thrown if an error occurs """ GrailsWebRequest webRequest = GrailsWebRequest.lookup(request); Locale locale = webRequest != null ? webRequest.getLocale() : Locale.getDefault() ; return viewResolver.resolveViewName(addViewPrefix(viewName, controllerName), locale); }
java
public static View resolveView(HttpServletRequest request, String viewName, String controllerName, ViewResolver viewResolver) throws Exception { GrailsWebRequest webRequest = GrailsWebRequest.lookup(request); Locale locale = webRequest != null ? webRequest.getLocale() : Locale.getDefault() ; return viewResolver.resolveViewName(addViewPrefix(viewName, controllerName), locale); }
[ "public", "static", "View", "resolveView", "(", "HttpServletRequest", "request", ",", "String", "viewName", ",", "String", "controllerName", ",", "ViewResolver", "viewResolver", ")", "throws", "Exception", "{", "GrailsWebRequest", "webRequest", "=", "GrailsWebRequest", ".", "lookup", "(", "request", ")", ";", "Locale", "locale", "=", "webRequest", "!=", "null", "?", "webRequest", ".", "getLocale", "(", ")", ":", "Locale", ".", "getDefault", "(", ")", ";", "return", "viewResolver", ".", "resolveViewName", "(", "addViewPrefix", "(", "viewName", ",", "controllerName", ")", ",", "locale", ")", ";", "}" ]
Resolves a view for the given view name and controller name @param request The request @param viewName The view name @param controllerName The controller name @param viewResolver The resolver @return A View or null @throws Exception Thrown if an error occurs
[ "Resolves", "a", "view", "for", "the", "given", "view", "name", "and", "controller", "name" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/util/WebUtils.java#L191-L195
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java
GISCoordinates.L93_EL2
@Pure public static Point2d L93_EL2(double x, double y) { """ This function convert France Lambert 93 coordinate to extended France Lambert II coordinate. @param x is the coordinate in France Lambert 93 @param y is the coordinate in France Lambert 93 @return the extended France Lambert II coordinate. """ final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_93_N, LAMBERT_93_C, LAMBERT_93_XS, LAMBERT_93_YS); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_2E_N, LAMBERT_2E_C, LAMBERT_2E_XS, LAMBERT_2E_YS); }
java
@Pure public static Point2d L93_EL2(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_93_N, LAMBERT_93_C, LAMBERT_93_XS, LAMBERT_93_YS); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_2E_N, LAMBERT_2E_C, LAMBERT_2E_XS, LAMBERT_2E_YS); }
[ "@", "Pure", "public", "static", "Point2d", "L93_EL2", "(", "double", "x", ",", "double", "y", ")", "{", "final", "Point2d", "ntfLambdaPhi", "=", "NTFLambert_NTFLambdaPhi", "(", "x", ",", "y", ",", "LAMBERT_93_N", ",", "LAMBERT_93_C", ",", "LAMBERT_93_XS", ",", "LAMBERT_93_YS", ")", ";", "return", "NTFLambdaPhi_NTFLambert", "(", "ntfLambdaPhi", ".", "getX", "(", ")", ",", "ntfLambdaPhi", ".", "getY", "(", ")", ",", "LAMBERT_2E_N", ",", "LAMBERT_2E_C", ",", "LAMBERT_2E_XS", ",", "LAMBERT_2E_YS", ")", ";", "}" ]
This function convert France Lambert 93 coordinate to extended France Lambert II coordinate. @param x is the coordinate in France Lambert 93 @param y is the coordinate in France Lambert 93 @return the extended France Lambert II coordinate.
[ "This", "function", "convert", "France", "Lambert", "93", "coordinate", "to", "extended", "France", "Lambert", "II", "coordinate", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java#L823-L836
ThreeTen/threetenbp
src/main/java/org/threeten/bp/LocalDate.java
LocalDate.resolvePreviousValid
private static LocalDate resolvePreviousValid(int year, int month, int day) { """ Resolves the date, resolving days past the end of month. @param year the year to represent, validated from MIN_YEAR to MAX_YEAR @param month the month-of-year to represent, validated from 1 to 12 @param day the day-of-month to represent, validated from 1 to 31 @return the resolved date, not null """ switch (month) { case 2: day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); break; case 4: case 6: case 9: case 11: day = Math.min(day, 30); break; } return LocalDate.of(year, month, day); }
java
private static LocalDate resolvePreviousValid(int year, int month, int day) { switch (month) { case 2: day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28); break; case 4: case 6: case 9: case 11: day = Math.min(day, 30); break; } return LocalDate.of(year, month, day); }
[ "private", "static", "LocalDate", "resolvePreviousValid", "(", "int", "year", ",", "int", "month", ",", "int", "day", ")", "{", "switch", "(", "month", ")", "{", "case", "2", ":", "day", "=", "Math", ".", "min", "(", "day", ",", "IsoChronology", ".", "INSTANCE", ".", "isLeapYear", "(", "year", ")", "?", "29", ":", "28", ")", ";", "break", ";", "case", "4", ":", "case", "6", ":", "case", "9", ":", "case", "11", ":", "day", "=", "Math", ".", "min", "(", "day", ",", "30", ")", ";", "break", ";", "}", "return", "LocalDate", ".", "of", "(", "year", ",", "month", ",", "day", ")", ";", "}" ]
Resolves the date, resolving days past the end of month. @param year the year to represent, validated from MIN_YEAR to MAX_YEAR @param month the month-of-year to represent, validated from 1 to 12 @param day the day-of-month to represent, validated from 1 to 31 @return the resolved date, not null
[ "Resolves", "the", "date", "resolving", "days", "past", "the", "end", "of", "month", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/LocalDate.java#L399-L412
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsSession.java
PresentsSession.resumeSession
protected void resumeSession (AuthRequest req, PresentsConnection conn) { """ Called by the client manager when a new connection arrives that authenticates as this already established client. This must only be called from the congmr thread. """ // check to see if we've already got a connection object, in which case it's probably stale Connection oldconn = getConnection(); if (oldconn != null && !oldconn.isClosed()) { log.info("Closing stale connection", "old", oldconn, "new", conn); // close the old connection (which results in everything being properly unregistered) oldconn.close(); } // note our new auth request (so that we can deliver the proper bootstrap services) _areq = req; // start using the new connection setConnection(conn); // if a client connects, drops the connection and reconnects within the span of a very // short period of time, we'll find ourselves in resumeSession() before their client object // was resolved from the initial connection; in such a case, we can simply bail out here // and let the original session establishment code take care of initializing this resumed // session if (_clobj == null) { log.info("Rapid-fire reconnect caused us to arrive in resumeSession() before the " + "original session resolved its client object " + this + "."); return; } // we need to get onto the dobj thread so that we can finalize resumption of the session _omgr.postRunnable(new Runnable() { public void run () { // now that we're on the dobjmgr thread we can resume our session resumption finishResumeSession(); } }); }
java
protected void resumeSession (AuthRequest req, PresentsConnection conn) { // check to see if we've already got a connection object, in which case it's probably stale Connection oldconn = getConnection(); if (oldconn != null && !oldconn.isClosed()) { log.info("Closing stale connection", "old", oldconn, "new", conn); // close the old connection (which results in everything being properly unregistered) oldconn.close(); } // note our new auth request (so that we can deliver the proper bootstrap services) _areq = req; // start using the new connection setConnection(conn); // if a client connects, drops the connection and reconnects within the span of a very // short period of time, we'll find ourselves in resumeSession() before their client object // was resolved from the initial connection; in such a case, we can simply bail out here // and let the original session establishment code take care of initializing this resumed // session if (_clobj == null) { log.info("Rapid-fire reconnect caused us to arrive in resumeSession() before the " + "original session resolved its client object " + this + "."); return; } // we need to get onto the dobj thread so that we can finalize resumption of the session _omgr.postRunnable(new Runnable() { public void run () { // now that we're on the dobjmgr thread we can resume our session resumption finishResumeSession(); } }); }
[ "protected", "void", "resumeSession", "(", "AuthRequest", "req", ",", "PresentsConnection", "conn", ")", "{", "// check to see if we've already got a connection object, in which case it's probably stale", "Connection", "oldconn", "=", "getConnection", "(", ")", ";", "if", "(", "oldconn", "!=", "null", "&&", "!", "oldconn", ".", "isClosed", "(", ")", ")", "{", "log", ".", "info", "(", "\"Closing stale connection\"", ",", "\"old\"", ",", "oldconn", ",", "\"new\"", ",", "conn", ")", ";", "// close the old connection (which results in everything being properly unregistered)", "oldconn", ".", "close", "(", ")", ";", "}", "// note our new auth request (so that we can deliver the proper bootstrap services)", "_areq", "=", "req", ";", "// start using the new connection", "setConnection", "(", "conn", ")", ";", "// if a client connects, drops the connection and reconnects within the span of a very", "// short period of time, we'll find ourselves in resumeSession() before their client object", "// was resolved from the initial connection; in such a case, we can simply bail out here", "// and let the original session establishment code take care of initializing this resumed", "// session", "if", "(", "_clobj", "==", "null", ")", "{", "log", ".", "info", "(", "\"Rapid-fire reconnect caused us to arrive in resumeSession() before the \"", "+", "\"original session resolved its client object \"", "+", "this", "+", "\".\"", ")", ";", "return", ";", "}", "// we need to get onto the dobj thread so that we can finalize resumption of the session", "_omgr", ".", "postRunnable", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "// now that we're on the dobjmgr thread we can resume our session resumption", "finishResumeSession", "(", ")", ";", "}", "}", ")", ";", "}" ]
Called by the client manager when a new connection arrives that authenticates as this already established client. This must only be called from the congmr thread.
[ "Called", "by", "the", "client", "manager", "when", "a", "new", "connection", "arrives", "that", "authenticates", "as", "this", "already", "established", "client", ".", "This", "must", "only", "be", "called", "from", "the", "congmr", "thread", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsSession.java#L513-L547
threerings/nenya
core/src/main/java/com/threerings/miso/data/SimpleMisoSceneModel.java
SimpleMisoSceneModel.getIndex
protected int getIndex (int x, int y) { """ Get the index into the baseTileIds[] for the specified x and y coordinates, or return -1 if the specified coordinates are outside of the viewable area. Assumption: The viewable area is centered and aligned as far to the top of the isometric scene as possible, such that the upper-left corner is at the point where the tiles (0, vwid) and (0, vwid-1) touch. The upper-right corner is at the point where the tiles (vwid-1, 0) and (vwid, 0) touch. The viewable area is made up of "fat" rows and "thin" rows. The fat rows display one more tile than the thin rows because their first and last tiles are halfway off the viewable area. The thin rows are fully contained within the viewable area except for the first and last thin rows, which display only their bottom and top halves, respectively. Note that #fatrows == #thinrows - 1; """ // check to see if the index lies in one of the "fat" rows if (((x + y) & 1) == (vwidth & 1)) { int col = (vwidth + x - y) >> 1; int row = x - col; if ((col < 0) || (col > vwidth) || (row < 0) || (row >= vheight)) { return -1; // out of view } return (vwidth + 1) * row + col; } else { // the index must be in a "thin" row int col = (vwidth + x - y - 1) >> 1; int row = x - col; if ((col < 0) || (col >= vwidth) || (row < 0) || (row > vheight)) { return -1; // out of view } // we store the all the fat rows first, then all the thin // rows, the '(vwidth + 1) * vheight' is the size of all // the fat rows. return row * vwidth + col + (vwidth + 1) * vheight; } }
java
protected int getIndex (int x, int y) { // check to see if the index lies in one of the "fat" rows if (((x + y) & 1) == (vwidth & 1)) { int col = (vwidth + x - y) >> 1; int row = x - col; if ((col < 0) || (col > vwidth) || (row < 0) || (row >= vheight)) { return -1; // out of view } return (vwidth + 1) * row + col; } else { // the index must be in a "thin" row int col = (vwidth + x - y - 1) >> 1; int row = x - col; if ((col < 0) || (col >= vwidth) || (row < 0) || (row > vheight)) { return -1; // out of view } // we store the all the fat rows first, then all the thin // rows, the '(vwidth + 1) * vheight' is the size of all // the fat rows. return row * vwidth + col + (vwidth + 1) * vheight; } }
[ "protected", "int", "getIndex", "(", "int", "x", ",", "int", "y", ")", "{", "// check to see if the index lies in one of the \"fat\" rows", "if", "(", "(", "(", "x", "+", "y", ")", "&", "1", ")", "==", "(", "vwidth", "&", "1", ")", ")", "{", "int", "col", "=", "(", "vwidth", "+", "x", "-", "y", ")", ">>", "1", ";", "int", "row", "=", "x", "-", "col", ";", "if", "(", "(", "col", "<", "0", ")", "||", "(", "col", ">", "vwidth", ")", "||", "(", "row", "<", "0", ")", "||", "(", "row", ">=", "vheight", ")", ")", "{", "return", "-", "1", ";", "// out of view", "}", "return", "(", "vwidth", "+", "1", ")", "*", "row", "+", "col", ";", "}", "else", "{", "// the index must be in a \"thin\" row", "int", "col", "=", "(", "vwidth", "+", "x", "-", "y", "-", "1", ")", ">>", "1", ";", "int", "row", "=", "x", "-", "col", ";", "if", "(", "(", "col", "<", "0", ")", "||", "(", "col", ">=", "vwidth", ")", "||", "(", "row", "<", "0", ")", "||", "(", "row", ">", "vheight", ")", ")", "{", "return", "-", "1", ";", "// out of view", "}", "// we store the all the fat rows first, then all the thin", "// rows, the '(vwidth + 1) * vheight' is the size of all", "// the fat rows.", "return", "row", "*", "vwidth", "+", "col", "+", "(", "vwidth", "+", "1", ")", "*", "vheight", ";", "}", "}" ]
Get the index into the baseTileIds[] for the specified x and y coordinates, or return -1 if the specified coordinates are outside of the viewable area. Assumption: The viewable area is centered and aligned as far to the top of the isometric scene as possible, such that the upper-left corner is at the point where the tiles (0, vwid) and (0, vwid-1) touch. The upper-right corner is at the point where the tiles (vwid-1, 0) and (vwid, 0) touch. The viewable area is made up of "fat" rows and "thin" rows. The fat rows display one more tile than the thin rows because their first and last tiles are halfway off the viewable area. The thin rows are fully contained within the viewable area except for the first and last thin rows, which display only their bottom and top halves, respectively. Note that #fatrows == #thinrows - 1;
[ "Get", "the", "index", "into", "the", "baseTileIds", "[]", "for", "the", "specified", "x", "and", "y", "coordinates", "or", "return", "-", "1", "if", "the", "specified", "coordinates", "are", "outside", "of", "the", "viewable", "area", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/data/SimpleMisoSceneModel.java#L223-L251
azkaban/azkaban
az-hdfs-viewer/src/main/java/azkaban/viewer/hdfs/ORCFileViewer.java
ORCFileViewer.getSchema
@Override public String getSchema(FileSystem fs, Path path) { """ Get schema in same syntax as in hadoop --orcdump {@inheritDoc} @see HdfsFileViewer#getSchema(org.apache.hadoop.fs.FileSystem, org.apache.hadoop.fs.Path) """ String schema = null; try { Reader orcReader = OrcFile.createReader(fs, path); schema = orcReader.getObjectInspector().getTypeName(); } catch (IOException e) { logger .warn("Cannot get schema for file: " + path.toUri().getPath()); return null; } return schema; }
java
@Override public String getSchema(FileSystem fs, Path path) { String schema = null; try { Reader orcReader = OrcFile.createReader(fs, path); schema = orcReader.getObjectInspector().getTypeName(); } catch (IOException e) { logger .warn("Cannot get schema for file: " + path.toUri().getPath()); return null; } return schema; }
[ "@", "Override", "public", "String", "getSchema", "(", "FileSystem", "fs", ",", "Path", "path", ")", "{", "String", "schema", "=", "null", ";", "try", "{", "Reader", "orcReader", "=", "OrcFile", ".", "createReader", "(", "fs", ",", "path", ")", ";", "schema", "=", "orcReader", ".", "getObjectInspector", "(", ")", ".", "getTypeName", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "warn", "(", "\"Cannot get schema for file: \"", "+", "path", ".", "toUri", "(", ")", ".", "getPath", "(", ")", ")", ";", "return", "null", ";", "}", "return", "schema", ";", "}" ]
Get schema in same syntax as in hadoop --orcdump {@inheritDoc} @see HdfsFileViewer#getSchema(org.apache.hadoop.fs.FileSystem, org.apache.hadoop.fs.Path)
[ "Get", "schema", "in", "same", "syntax", "as", "in", "hadoop", "--", "orcdump", "{", "@inheritDoc", "}" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-hdfs-viewer/src/main/java/azkaban/viewer/hdfs/ORCFileViewer.java#L139-L152
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleUserSegmentRelPersistenceImpl.java
CPRuleUserSegmentRelPersistenceImpl.findAll
@Override public List<CPRuleUserSegmentRel> findAll() { """ Returns all the cp rule user segment rels. @return the cp rule user segment rels """ return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CPRuleUserSegmentRel> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CPRuleUserSegmentRel", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the cp rule user segment rels. @return the cp rule user segment rels
[ "Returns", "all", "the", "cp", "rule", "user", "segment", "rels", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleUserSegmentRelPersistenceImpl.java#L1665-L1668
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java
TopologyManager.updateGraph
public static String updateGraph(SqlgGraph sqlgGraph, String version) { """ Updates sqlg_schema.V_graph's version to the new version and returns the old version. @param sqlgGraph The graph. @param version The new version. @return The old version. """ Connection conn = sqlgGraph.tx().getConnection(); try { DatabaseMetaData metadata = conn.getMetaData(); GraphTraversalSource traversalSource = sqlgGraph.topology(); List<Vertex> graphVertices = traversalSource.V().hasLabel(SQLG_SCHEMA + "." + Topology.SQLG_SCHEMA_GRAPH).toList(); Preconditions.checkState(graphVertices.size() == 1, "BUG: There can only ever be one graph vertex, found %s", graphVertices.size()); Vertex graph = graphVertices.get(0); String oldVersion = graph.value(SQLG_SCHEMA_GRAPH_VERSION); if (!oldVersion.equals(version)) { graph.property(SQLG_SCHEMA_GRAPH_VERSION, version); graph.property(SQLG_SCHEMA_GRAPH_DB_VERSION, metadata.getDatabaseProductVersion()); graph.property(UPDATED_ON, LocalDateTime.now()); } return oldVersion; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static String updateGraph(SqlgGraph sqlgGraph, String version) { Connection conn = sqlgGraph.tx().getConnection(); try { DatabaseMetaData metadata = conn.getMetaData(); GraphTraversalSource traversalSource = sqlgGraph.topology(); List<Vertex> graphVertices = traversalSource.V().hasLabel(SQLG_SCHEMA + "." + Topology.SQLG_SCHEMA_GRAPH).toList(); Preconditions.checkState(graphVertices.size() == 1, "BUG: There can only ever be one graph vertex, found %s", graphVertices.size()); Vertex graph = graphVertices.get(0); String oldVersion = graph.value(SQLG_SCHEMA_GRAPH_VERSION); if (!oldVersion.equals(version)) { graph.property(SQLG_SCHEMA_GRAPH_VERSION, version); graph.property(SQLG_SCHEMA_GRAPH_DB_VERSION, metadata.getDatabaseProductVersion()); graph.property(UPDATED_ON, LocalDateTime.now()); } return oldVersion; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "String", "updateGraph", "(", "SqlgGraph", "sqlgGraph", ",", "String", "version", ")", "{", "Connection", "conn", "=", "sqlgGraph", ".", "tx", "(", ")", ".", "getConnection", "(", ")", ";", "try", "{", "DatabaseMetaData", "metadata", "=", "conn", ".", "getMetaData", "(", ")", ";", "GraphTraversalSource", "traversalSource", "=", "sqlgGraph", ".", "topology", "(", ")", ";", "List", "<", "Vertex", ">", "graphVertices", "=", "traversalSource", ".", "V", "(", ")", ".", "hasLabel", "(", "SQLG_SCHEMA", "+", "\".\"", "+", "Topology", ".", "SQLG_SCHEMA_GRAPH", ")", ".", "toList", "(", ")", ";", "Preconditions", ".", "checkState", "(", "graphVertices", ".", "size", "(", ")", "==", "1", ",", "\"BUG: There can only ever be one graph vertex, found %s\"", ",", "graphVertices", ".", "size", "(", ")", ")", ";", "Vertex", "graph", "=", "graphVertices", ".", "get", "(", "0", ")", ";", "String", "oldVersion", "=", "graph", ".", "value", "(", "SQLG_SCHEMA_GRAPH_VERSION", ")", ";", "if", "(", "!", "oldVersion", ".", "equals", "(", "version", ")", ")", "{", "graph", ".", "property", "(", "SQLG_SCHEMA_GRAPH_VERSION", ",", "version", ")", ";", "graph", ".", "property", "(", "SQLG_SCHEMA_GRAPH_DB_VERSION", ",", "metadata", ".", "getDatabaseProductVersion", "(", ")", ")", ";", "graph", ".", "property", "(", "UPDATED_ON", ",", "LocalDateTime", ".", "now", "(", ")", ")", ";", "}", "return", "oldVersion", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Updates sqlg_schema.V_graph's version to the new version and returns the old version. @param sqlgGraph The graph. @param version The new version. @return The old version.
[ "Updates", "sqlg_schema", ".", "V_graph", "s", "version", "to", "the", "new", "version", "and", "returns", "the", "old", "version", "." ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/TopologyManager.java#L58-L76
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/CropDimension.java
CropDimension.fromCropString
public static @NotNull CropDimension fromCropString(@NotNull String cropString) { """ Get crop dimension from crop string. Please note: Crop string contains not width/height as 3rd/4th parameter but right, bottom. @param cropString Cropping string from CQ5 smartimage widget @return Crop dimension instance @throws IllegalArgumentException if crop string syntax is invalid """ if (StringUtils.isEmpty(cropString)) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } // strip off optional size parameter after "/" String crop = cropString; if (StringUtils.contains(crop, "/")) { crop = StringUtils.substringBefore(crop, "/"); } String[] parts = StringUtils.split(crop, ","); if (parts.length != 4) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } long x1 = NumberUtils.toLong(parts[0]); long y1 = NumberUtils.toLong(parts[1]); long x2 = NumberUtils.toLong(parts[2]); long y2 = NumberUtils.toLong(parts[3]); long width = x2 - x1; long height = y2 - y1; if (x1 < 0 || y1 < 0 || width <= 0 || height <= 0) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } return new CropDimension(x1, y1, width, height); }
java
public static @NotNull CropDimension fromCropString(@NotNull String cropString) { if (StringUtils.isEmpty(cropString)) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } // strip off optional size parameter after "/" String crop = cropString; if (StringUtils.contains(crop, "/")) { crop = StringUtils.substringBefore(crop, "/"); } String[] parts = StringUtils.split(crop, ","); if (parts.length != 4) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } long x1 = NumberUtils.toLong(parts[0]); long y1 = NumberUtils.toLong(parts[1]); long x2 = NumberUtils.toLong(parts[2]); long y2 = NumberUtils.toLong(parts[3]); long width = x2 - x1; long height = y2 - y1; if (x1 < 0 || y1 < 0 || width <= 0 || height <= 0) { throw new IllegalArgumentException("Invalid crop string: '" + cropString + "'."); } return new CropDimension(x1, y1, width, height); }
[ "public", "static", "@", "NotNull", "CropDimension", "fromCropString", "(", "@", "NotNull", "String", "cropString", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "cropString", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid crop string: '\"", "+", "cropString", "+", "\"'.\"", ")", ";", "}", "// strip off optional size parameter after \"/\"", "String", "crop", "=", "cropString", ";", "if", "(", "StringUtils", ".", "contains", "(", "crop", ",", "\"/\"", ")", ")", "{", "crop", "=", "StringUtils", ".", "substringBefore", "(", "crop", ",", "\"/\"", ")", ";", "}", "String", "[", "]", "parts", "=", "StringUtils", ".", "split", "(", "crop", ",", "\",\"", ")", ";", "if", "(", "parts", ".", "length", "!=", "4", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid crop string: '\"", "+", "cropString", "+", "\"'.\"", ")", ";", "}", "long", "x1", "=", "NumberUtils", ".", "toLong", "(", "parts", "[", "0", "]", ")", ";", "long", "y1", "=", "NumberUtils", ".", "toLong", "(", "parts", "[", "1", "]", ")", ";", "long", "x2", "=", "NumberUtils", ".", "toLong", "(", "parts", "[", "2", "]", ")", ";", "long", "y2", "=", "NumberUtils", ".", "toLong", "(", "parts", "[", "3", "]", ")", ";", "long", "width", "=", "x2", "-", "x1", ";", "long", "height", "=", "y2", "-", "y1", ";", "if", "(", "x1", "<", "0", "||", "y1", "<", "0", "||", "width", "<=", "0", "||", "height", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid crop string: '\"", "+", "cropString", "+", "\"'.\"", ")", ";", "}", "return", "new", "CropDimension", "(", "x1", ",", "y1", ",", "width", ",", "height", ")", ";", "}" ]
Get crop dimension from crop string. Please note: Crop string contains not width/height as 3rd/4th parameter but right, bottom. @param cropString Cropping string from CQ5 smartimage widget @return Crop dimension instance @throws IllegalArgumentException if crop string syntax is invalid
[ "Get", "crop", "dimension", "from", "crop", "string", ".", "Please", "note", ":", "Crop", "string", "contains", "not", "width", "/", "height", "as", "3rd", "/", "4th", "parameter", "but", "right", "bottom", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/CropDimension.java#L121-L146
autonomousapps/Cappuccino
cappuccino-sample/src/main/java/com/example/cappuccino/MainActivity.java
MainActivity.onClickSecondActivity
public void onClickSecondActivity(View view) { """ For some reason, we expect navigating to a new {@code Activity} to take a while (perhaps a network request is involved). Really what this is demonstrating is that a {@code CappuccinoIdlingResource} can be declared and used across multiple Activities. """ // Declare a new CappuccinoIdlingResource Cappuccino.newIdlingResourceWatcher(RESOURCE_MULTIPLE_ACTIVITIES); // Tell Cappuccino that the new resource is busy Cappuccino.markAsBusy(RESOURCE_MULTIPLE_ACTIVITIES); startActivity(new Intent(this, SecondActivity.class)); }
java
public void onClickSecondActivity(View view) { // Declare a new CappuccinoIdlingResource Cappuccino.newIdlingResourceWatcher(RESOURCE_MULTIPLE_ACTIVITIES); // Tell Cappuccino that the new resource is busy Cappuccino.markAsBusy(RESOURCE_MULTIPLE_ACTIVITIES); startActivity(new Intent(this, SecondActivity.class)); }
[ "public", "void", "onClickSecondActivity", "(", "View", "view", ")", "{", "// Declare a new CappuccinoIdlingResource", "Cappuccino", ".", "newIdlingResourceWatcher", "(", "RESOURCE_MULTIPLE_ACTIVITIES", ")", ";", "// Tell Cappuccino that the new resource is busy", "Cappuccino", ".", "markAsBusy", "(", "RESOURCE_MULTIPLE_ACTIVITIES", ")", ";", "startActivity", "(", "new", "Intent", "(", "this", ",", "SecondActivity", ".", "class", ")", ")", ";", "}" ]
For some reason, we expect navigating to a new {@code Activity} to take a while (perhaps a network request is involved). Really what this is demonstrating is that a {@code CappuccinoIdlingResource} can be declared and used across multiple Activities.
[ "For", "some", "reason", "we", "expect", "navigating", "to", "a", "new", "{" ]
train
https://github.com/autonomousapps/Cappuccino/blob/9324d040b6e8cab4bf7dcf71dbd3c761ae043cd9/cappuccino-sample/src/main/java/com/example/cappuccino/MainActivity.java#L74-L82
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java
TimestampProcessor.updateTimestampWithCurrentTime
public static <M extends MessageOrBuilder> M updateTimestampWithCurrentTime(final M messageOrBuilder, final Logger logger) { """ Method updates the timestamp field of the given message with the current time. In case of an error the original message is returned. @param <M> the message type of the message to update. @param messageOrBuilder the message @param logger the logger which is used for printing the exception stack in case something went wrong. @return the updated message or the original one in case of errors. """ try { return updateTimestampWithCurrentTime(messageOrBuilder); } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory(ex, logger); return messageOrBuilder; } }
java
public static <M extends MessageOrBuilder> M updateTimestampWithCurrentTime(final M messageOrBuilder, final Logger logger) { try { return updateTimestampWithCurrentTime(messageOrBuilder); } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory(ex, logger); return messageOrBuilder; } }
[ "public", "static", "<", "M", "extends", "MessageOrBuilder", ">", "M", "updateTimestampWithCurrentTime", "(", "final", "M", "messageOrBuilder", ",", "final", "Logger", "logger", ")", "{", "try", "{", "return", "updateTimestampWithCurrentTime", "(", "messageOrBuilder", ")", ";", "}", "catch", "(", "CouldNotPerformException", "ex", ")", "{", "ExceptionPrinter", ".", "printHistory", "(", "ex", ",", "logger", ")", ";", "return", "messageOrBuilder", ";", "}", "}" ]
Method updates the timestamp field of the given message with the current time. In case of an error the original message is returned. @param <M> the message type of the message to update. @param messageOrBuilder the message @param logger the logger which is used for printing the exception stack in case something went wrong. @return the updated message or the original one in case of errors.
[ "Method", "updates", "the", "timestamp", "field", "of", "the", "given", "message", "with", "the", "current", "time", ".", "In", "case", "of", "an", "error", "the", "original", "message", "is", "returned", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java#L232-L239
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java
AbstractErrorMetric.considerEstimatedPreference
public static double considerEstimatedPreference(final ErrorStrategy errorStrategy, final double recValue) { """ Method that returns an estimated preference according to a given value and an error strategy. @param errorStrategy the error strategy @param recValue the predicted value by the recommender @return an estimated preference according to the provided strategy """ boolean consider = true; double v = recValue; switch (errorStrategy) { default: case CONSIDER_EVERYTHING: break; case NOT_CONSIDER_NAN: consider = !Double.isNaN(recValue); break; case CONSIDER_NAN_AS_0: if (Double.isNaN(recValue)) { v = 0.0; } break; case CONSIDER_NAN_AS_1: if (Double.isNaN(recValue)) { v = 1.0; } break; case CONSIDER_NAN_AS_3: if (Double.isNaN(recValue)) { v = 3.0; } break; } if (consider) { return v; } else { return Double.NaN; } }
java
public static double considerEstimatedPreference(final ErrorStrategy errorStrategy, final double recValue) { boolean consider = true; double v = recValue; switch (errorStrategy) { default: case CONSIDER_EVERYTHING: break; case NOT_CONSIDER_NAN: consider = !Double.isNaN(recValue); break; case CONSIDER_NAN_AS_0: if (Double.isNaN(recValue)) { v = 0.0; } break; case CONSIDER_NAN_AS_1: if (Double.isNaN(recValue)) { v = 1.0; } break; case CONSIDER_NAN_AS_3: if (Double.isNaN(recValue)) { v = 3.0; } break; } if (consider) { return v; } else { return Double.NaN; } }
[ "public", "static", "double", "considerEstimatedPreference", "(", "final", "ErrorStrategy", "errorStrategy", ",", "final", "double", "recValue", ")", "{", "boolean", "consider", "=", "true", ";", "double", "v", "=", "recValue", ";", "switch", "(", "errorStrategy", ")", "{", "default", ":", "case", "CONSIDER_EVERYTHING", ":", "break", ";", "case", "NOT_CONSIDER_NAN", ":", "consider", "=", "!", "Double", ".", "isNaN", "(", "recValue", ")", ";", "break", ";", "case", "CONSIDER_NAN_AS_0", ":", "if", "(", "Double", ".", "isNaN", "(", "recValue", ")", ")", "{", "v", "=", "0.0", ";", "}", "break", ";", "case", "CONSIDER_NAN_AS_1", ":", "if", "(", "Double", ".", "isNaN", "(", "recValue", ")", ")", "{", "v", "=", "1.0", ";", "}", "break", ";", "case", "CONSIDER_NAN_AS_3", ":", "if", "(", "Double", ".", "isNaN", "(", "recValue", ")", ")", "{", "v", "=", "3.0", ";", "}", "break", ";", "}", "if", "(", "consider", ")", "{", "return", "v", ";", "}", "else", "{", "return", "Double", ".", "NaN", ";", "}", "}" ]
Method that returns an estimated preference according to a given value and an error strategy. @param errorStrategy the error strategy @param recValue the predicted value by the recommender @return an estimated preference according to the provided strategy
[ "Method", "that", "returns", "an", "estimated", "preference", "according", "to", "a", "given", "value", "and", "an", "error", "strategy", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java#L159-L190
Viascom/groundwork
foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/authorization/DefaultAuthorizationStrategy.java
DefaultAuthorizationStrategy.removeAuthorization
@Override public void removeAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { """ Remove a defined FoxHttpAuthorization from the AuthorizationStrategy @param foxHttpAuthorizationScope scope in which the authorization is used @param foxHttpAuthorization object of the same authorization """ ArrayList<FoxHttpAuthorization> authorizations = foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()); ArrayList<FoxHttpAuthorization> cleandAuthorizations = new ArrayList<>(); for (FoxHttpAuthorization authorization : authorizations) { if (authorization.getClass() != foxHttpAuthorization.getClass()) { cleandAuthorizations.add(authorization); } } foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), cleandAuthorizations); }
java
@Override public void removeAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { ArrayList<FoxHttpAuthorization> authorizations = foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()); ArrayList<FoxHttpAuthorization> cleandAuthorizations = new ArrayList<>(); for (FoxHttpAuthorization authorization : authorizations) { if (authorization.getClass() != foxHttpAuthorization.getClass()) { cleandAuthorizations.add(authorization); } } foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), cleandAuthorizations); }
[ "@", "Override", "public", "void", "removeAuthorization", "(", "FoxHttpAuthorizationScope", "foxHttpAuthorizationScope", ",", "FoxHttpAuthorization", "foxHttpAuthorization", ")", "{", "ArrayList", "<", "FoxHttpAuthorization", ">", "authorizations", "=", "foxHttpAuthorizations", ".", "get", "(", "foxHttpAuthorizationScope", ".", "toString", "(", ")", ")", ";", "ArrayList", "<", "FoxHttpAuthorization", ">", "cleandAuthorizations", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "FoxHttpAuthorization", "authorization", ":", "authorizations", ")", "{", "if", "(", "authorization", ".", "getClass", "(", ")", "!=", "foxHttpAuthorization", ".", "getClass", "(", ")", ")", "{", "cleandAuthorizations", ".", "add", "(", "authorization", ")", ";", "}", "}", "foxHttpAuthorizations", ".", "put", "(", "foxHttpAuthorizationScope", ".", "toString", "(", ")", ",", "cleandAuthorizations", ")", ";", "}" ]
Remove a defined FoxHttpAuthorization from the AuthorizationStrategy @param foxHttpAuthorizationScope scope in which the authorization is used @param foxHttpAuthorization object of the same authorization
[ "Remove", "a", "defined", "FoxHttpAuthorization", "from", "the", "AuthorizationStrategy" ]
train
https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/authorization/DefaultAuthorizationStrategy.java#L75-L85
jMetal/jMetal
jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/MOEADD.java
MOEADD.setLocation
public void setLocation(S indiv, double[] z_, double[] nz_) { """ Set the location of a solution based on the orthogonal distance """ int minIdx; double distance, minDist; minIdx = 0; distance = calculateDistance2(indiv, lambda[0], z_, nz_); minDist = distance; for (int i = 1; i < populationSize; i++) { distance = calculateDistance2(indiv, lambda[i], z_, nz_); if (distance < minDist) { minIdx = i; minDist = distance; } } //indiv.setRegion(minIdx); indiv.setAttribute("region", minIdx); //indiv.Set_associateDist(minDist); // indiv.setAttribute(ATTRIBUTES.DIST, minDist); }
java
public void setLocation(S indiv, double[] z_, double[] nz_) { int minIdx; double distance, minDist; minIdx = 0; distance = calculateDistance2(indiv, lambda[0], z_, nz_); minDist = distance; for (int i = 1; i < populationSize; i++) { distance = calculateDistance2(indiv, lambda[i], z_, nz_); if (distance < minDist) { minIdx = i; minDist = distance; } } //indiv.setRegion(minIdx); indiv.setAttribute("region", minIdx); //indiv.Set_associateDist(minDist); // indiv.setAttribute(ATTRIBUTES.DIST, minDist); }
[ "public", "void", "setLocation", "(", "S", "indiv", ",", "double", "[", "]", "z_", ",", "double", "[", "]", "nz_", ")", "{", "int", "minIdx", ";", "double", "distance", ",", "minDist", ";", "minIdx", "=", "0", ";", "distance", "=", "calculateDistance2", "(", "indiv", ",", "lambda", "[", "0", "]", ",", "z_", ",", "nz_", ")", ";", "minDist", "=", "distance", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "populationSize", ";", "i", "++", ")", "{", "distance", "=", "calculateDistance2", "(", "indiv", ",", "lambda", "[", "i", "]", ",", "z_", ",", "nz_", ")", ";", "if", "(", "distance", "<", "minDist", ")", "{", "minIdx", "=", "i", ";", "minDist", "=", "distance", ";", "}", "}", "//indiv.setRegion(minIdx);", "indiv", ".", "setAttribute", "(", "\"region\"", ",", "minIdx", ")", ";", "//indiv.Set_associateDist(minDist);", "// indiv.setAttribute(ATTRIBUTES.DIST, minDist);", "}" ]
Set the location of a solution based on the orthogonal distance
[ "Set", "the", "location", "of", "a", "solution", "based", "on", "the", "orthogonal", "distance" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/MOEADD.java#L1247-L1267
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java
StructuredQueryBuilder.valueConstraint
public StructuredQueryDefinition valueConstraint(String constraintName, double weight, String... values) { """ Matches the container specified by the constraint when it has a value with the same string value as at least one of the criteria values. @param constraintName the constraint definition @param weight the multiplier for the match in the document ranking @param values the possible values to match @return the StructuredQueryDefinition for the value constraint query """ return new ValueConstraintQuery(constraintName, weight, values); }
java
public StructuredQueryDefinition valueConstraint(String constraintName, double weight, String... values) { return new ValueConstraintQuery(constraintName, weight, values); }
[ "public", "StructuredQueryDefinition", "valueConstraint", "(", "String", "constraintName", ",", "double", "weight", ",", "String", "...", "values", ")", "{", "return", "new", "ValueConstraintQuery", "(", "constraintName", ",", "weight", ",", "values", ")", ";", "}" ]
Matches the container specified by the constraint when it has a value with the same string value as at least one of the criteria values. @param constraintName the constraint definition @param weight the multiplier for the match in the document ranking @param values the possible values to match @return the StructuredQueryDefinition for the value constraint query
[ "Matches", "the", "container", "specified", "by", "the", "constraint", "when", "it", "has", "a", "value", "with", "the", "same", "string", "value", "as", "at", "least", "one", "of", "the", "criteria", "values", "." ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java#L1045-L1047
aspectran/aspectran
shell/src/main/java/com/aspectran/shell/command/option/HelpFormatter.java
HelpFormatter.appendOptionGroup
private void appendOptionGroup(StringBuilder sb, OptionGroup group) { """ Appends the usage clause for an OptionGroup to a StringBuilder. The clause is wrapped in square brackets if the group is required. The display of the options is handled by appendOption. @param sb the StringBuilder to append to @param group the group to append """ if (!group.isRequired()) { sb.append(OPTIONAL_BRACKET_OPEN); } List<Option> optList = new ArrayList<>(group.getOptions()); if (optList.size() > 1 && getOptionComparator() != null) { optList.sort(getOptionComparator()); } // for each option in the OptionGroup for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // whether the option is required or not is handled at group level appendOption(sb, it.next(), true); if (it.hasNext()) { sb.append(" | "); } } if (!group.isRequired()) { sb.append(OPTIONAL_BRACKET_CLOSE); } }
java
private void appendOptionGroup(StringBuilder sb, OptionGroup group) { if (!group.isRequired()) { sb.append(OPTIONAL_BRACKET_OPEN); } List<Option> optList = new ArrayList<>(group.getOptions()); if (optList.size() > 1 && getOptionComparator() != null) { optList.sort(getOptionComparator()); } // for each option in the OptionGroup for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // whether the option is required or not is handled at group level appendOption(sb, it.next(), true); if (it.hasNext()) { sb.append(" | "); } } if (!group.isRequired()) { sb.append(OPTIONAL_BRACKET_CLOSE); } }
[ "private", "void", "appendOptionGroup", "(", "StringBuilder", "sb", ",", "OptionGroup", "group", ")", "{", "if", "(", "!", "group", ".", "isRequired", "(", ")", ")", "{", "sb", ".", "append", "(", "OPTIONAL_BRACKET_OPEN", ")", ";", "}", "List", "<", "Option", ">", "optList", "=", "new", "ArrayList", "<>", "(", "group", ".", "getOptions", "(", ")", ")", ";", "if", "(", "optList", ".", "size", "(", ")", ">", "1", "&&", "getOptionComparator", "(", ")", "!=", "null", ")", "{", "optList", ".", "sort", "(", "getOptionComparator", "(", ")", ")", ";", "}", "// for each option in the OptionGroup", "for", "(", "Iterator", "<", "Option", ">", "it", "=", "optList", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "// whether the option is required or not is handled at group level", "appendOption", "(", "sb", ",", "it", ".", "next", "(", ")", ",", "true", ")", ";", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "sb", ".", "append", "(", "\" | \"", ")", ";", "}", "}", "if", "(", "!", "group", ".", "isRequired", "(", ")", ")", "{", "sb", ".", "append", "(", "OPTIONAL_BRACKET_CLOSE", ")", ";", "}", "}" ]
Appends the usage clause for an OptionGroup to a StringBuilder. The clause is wrapped in square brackets if the group is required. The display of the options is handled by appendOption. @param sb the StringBuilder to append to @param group the group to append
[ "Appends", "the", "usage", "clause", "for", "an", "OptionGroup", "to", "a", "StringBuilder", ".", "The", "clause", "is", "wrapped", "in", "square", "brackets", "if", "the", "group", "is", "required", ".", "The", "display", "of", "the", "options", "is", "handled", "by", "appendOption", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/shell/src/main/java/com/aspectran/shell/command/option/HelpFormatter.java#L261-L280
OpenLiberty/open-liberty
dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/ELHelper.java
ELHelper.removeBrackets
@Trivial static String removeBrackets(String expression, boolean mask) { """ Remove the brackets from an EL expression. @param expression The expression to remove the brackets from. @param mask Set whether to mask the expression and result. Useful for when passwords might be contained in either the expression or the result. @return The EL expression without the brackets. """ final String methodName = "removeBrackets"; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, methodName, new Object[] { (expression == null) ? null : mask ? OBFUSCATED_STRING : expression, mask }); } expression = expression.trim(); if ((expression.startsWith("${") || expression.startsWith("#{")) && expression.endsWith("}")) { expression = expression.substring(2, expression.length() - 1); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, methodName, (expression == null) ? null : mask ? OBFUSCATED_STRING : expression); } return expression; }
java
@Trivial static String removeBrackets(String expression, boolean mask) { final String methodName = "removeBrackets"; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, methodName, new Object[] { (expression == null) ? null : mask ? OBFUSCATED_STRING : expression, mask }); } expression = expression.trim(); if ((expression.startsWith("${") || expression.startsWith("#{")) && expression.endsWith("}")) { expression = expression.substring(2, expression.length() - 1); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, methodName, (expression == null) ? null : mask ? OBFUSCATED_STRING : expression); } return expression; }
[ "@", "Trivial", "static", "String", "removeBrackets", "(", "String", "expression", ",", "boolean", "mask", ")", "{", "final", "String", "methodName", "=", "\"removeBrackets\"", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "entry", "(", "tc", ",", "methodName", ",", "new", "Object", "[", "]", "{", "(", "expression", "==", "null", ")", "?", "null", ":", "mask", "?", "OBFUSCATED_STRING", ":", "expression", ",", "mask", "}", ")", ";", "}", "expression", "=", "expression", ".", "trim", "(", ")", ";", "if", "(", "(", "expression", ".", "startsWith", "(", "\"${\"", ")", "||", "expression", ".", "startsWith", "(", "\"#{\"", ")", ")", "&&", "expression", ".", "endsWith", "(", "\"}\"", ")", ")", "{", "expression", "=", "expression", ".", "substring", "(", "2", ",", "expression", ".", "length", "(", ")", "-", "1", ")", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "{", "Tr", ".", "exit", "(", "tc", ",", "methodName", ",", "(", "expression", "==", "null", ")", "?", "null", ":", "mask", "?", "OBFUSCATED_STRING", ":", "expression", ")", ";", "}", "return", "expression", ";", "}" ]
Remove the brackets from an EL expression. @param expression The expression to remove the brackets from. @param mask Set whether to mask the expression and result. Useful for when passwords might be contained in either the expression or the result. @return The EL expression without the brackets.
[ "Remove", "the", "brackets", "from", "an", "EL", "expression", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.javaeesec/src/com/ibm/ws/security/javaeesec/identitystore/ELHelper.java#L459-L475
gitblit/fathom
fathom-x509/src/main/java/fathom/x509/X509Utils.java
X509Utils.getCertificate
public static X509Certificate getCertificate(String alias, File storeFile, String storePassword) { """ Retrieves the X509 certificate with the specified alias from the certificate store. @param alias @param storeFile @param storePassword @return the certificate """ try { KeyStore store = openKeyStore(storeFile, storePassword); X509Certificate caCert = (X509Certificate) store.getCertificate(alias); return caCert; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static X509Certificate getCertificate(String alias, File storeFile, String storePassword) { try { KeyStore store = openKeyStore(storeFile, storePassword); X509Certificate caCert = (X509Certificate) store.getCertificate(alias); return caCert; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "X509Certificate", "getCertificate", "(", "String", "alias", ",", "File", "storeFile", ",", "String", "storePassword", ")", "{", "try", "{", "KeyStore", "store", "=", "openKeyStore", "(", "storeFile", ",", "storePassword", ")", ";", "X509Certificate", "caCert", "=", "(", "X509Certificate", ")", "store", ".", "getCertificate", "(", "alias", ")", ";", "return", "caCert", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Retrieves the X509 certificate with the specified alias from the certificate store. @param alias @param storeFile @param storePassword @return the certificate
[ "Retrieves", "the", "X509", "certificate", "with", "the", "specified", "alias", "from", "the", "certificate", "store", "." ]
train
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-x509/src/main/java/fathom/x509/X509Utils.java#L396-L404
f2prateek/dart
henson/src/main/java/dart/henson/Bundler.java
Bundler.putIntegerArrayList
public Bundler putIntegerArrayList(String key, ArrayList<Integer> value) { """ Inserts an ArrayList<Integer> value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList<Integer> object, or null @return this bundler instance to chain method calls """ delegate.putIntegerArrayList(key, value); return this; }
java
public Bundler putIntegerArrayList(String key, ArrayList<Integer> value) { delegate.putIntegerArrayList(key, value); return this; }
[ "public", "Bundler", "putIntegerArrayList", "(", "String", "key", ",", "ArrayList", "<", "Integer", ">", "value", ")", "{", "delegate", ".", "putIntegerArrayList", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts an ArrayList<Integer> value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList<Integer> object, or null @return this bundler instance to chain method calls
[ "Inserts", "an", "ArrayList<Integer", ">", "value", "into", "the", "mapping", "of", "the", "underlying", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/f2prateek/dart/blob/7163b1b148e5141817975ae7dad99d58a8589aeb/henson/src/main/java/dart/henson/Bundler.java#L114-L117
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Node.java
Node.mergeEntries
protected void mergeEntries(int pos1, int pos2) { """ Merge the two entries at the given position. The entries are reordered in the <code>entries</code> array so that the non-empty entries are still at the beginning. @param pos1 The position of the first entry to be merged. This position has to be smaller than the the second position. @param pos2 The position of the second entry to be merged. This position has to be greater than the the first position. """ assert (this.numFreeEntries() == 0); assert (pos1 < pos2); this.entries[pos1].mergeWith(this.entries[pos2]); for (int i = pos2; i < entries.length - 1; i++) { entries[i] = entries[i + 1]; } entries[entries.length - 1].clear(); }
java
protected void mergeEntries(int pos1, int pos2) { assert (this.numFreeEntries() == 0); assert (pos1 < pos2); this.entries[pos1].mergeWith(this.entries[pos2]); for (int i = pos2; i < entries.length - 1; i++) { entries[i] = entries[i + 1]; } entries[entries.length - 1].clear(); }
[ "protected", "void", "mergeEntries", "(", "int", "pos1", ",", "int", "pos2", ")", "{", "assert", "(", "this", ".", "numFreeEntries", "(", ")", "==", "0", ")", ";", "assert", "(", "pos1", "<", "pos2", ")", ";", "this", ".", "entries", "[", "pos1", "]", ".", "mergeWith", "(", "this", ".", "entries", "[", "pos2", "]", ")", ";", "for", "(", "int", "i", "=", "pos2", ";", "i", "<", "entries", ".", "length", "-", "1", ";", "i", "++", ")", "{", "entries", "[", "i", "]", "=", "entries", "[", "i", "+", "1", "]", ";", "}", "entries", "[", "entries", ".", "length", "-", "1", "]", ".", "clear", "(", ")", ";", "}" ]
Merge the two entries at the given position. The entries are reordered in the <code>entries</code> array so that the non-empty entries are still at the beginning. @param pos1 The position of the first entry to be merged. This position has to be smaller than the the second position. @param pos2 The position of the second entry to be merged. This position has to be greater than the the first position.
[ "Merge", "the", "two", "entries", "at", "the", "given", "position", ".", "The", "entries", "are", "reordered", "in", "the", "<code", ">", "entries<", "/", "code", ">", "array", "so", "that", "the", "non", "-", "empty", "entries", "are", "still", "at", "the", "beginning", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Node.java#L309-L319
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/lang/Assert.java
Assert.notEmpty
public static void notEmpty(Object[] array, String message) { """ Assert that an array has elements; that is, it must not be <code>null</code> and must have at least one element. <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre> @param array the array to check @param message the exception message to use if the assertion fails @throws IllegalArgumentException if the object array is <code>null</code> or has no elements """ if (Objects.isEmpty(array)) { throw new IllegalArgumentException(message); } }
java
public static void notEmpty(Object[] array, String message) { if (Objects.isEmpty(array)) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "notEmpty", "(", "Object", "[", "]", "array", ",", "String", "message", ")", "{", "if", "(", "Objects", ".", "isEmpty", "(", "array", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "}", "}" ]
Assert that an array has elements; that is, it must not be <code>null</code> and must have at least one element. <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre> @param array the array to check @param message the exception message to use if the assertion fails @throws IllegalArgumentException if the object array is <code>null</code> or has no elements
[ "Assert", "that", "an", "array", "has", "elements", ";", "that", "is", "it", "must", "not", "be", "<code", ">", "null<", "/", "code", ">", "and", "must", "have", "at", "least", "one", "element", ".", "<pre", "class", "=", "code", ">", "Assert", ".", "notEmpty", "(", "array", "The", "array", "must", "have", "elements", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/jwtk/jjwt/blob/86b6096946752cffcfbc9b0a5503f1ea195cc140/api/src/main/java/io/jsonwebtoken/lang/Assert.java#L182-L186
agapsys/embedded-servlet-container
src/main/java/com/agapsys/jee/ServletContainer.java
ServletContainer.registerFilter
public SC registerFilter(Class<? extends Filter> filterClass, String urlPattern) { """ Registers a filter. @param filterClass class to be registered. @param urlPattern url pattern to be associated with given class. @return this """ __throwIfInitialized(); List<Class<? extends Filter>> filterList = filterMap.get(urlPattern); if (filterList == null) { filterList = new LinkedList<>(); filterMap.put(urlPattern, filterList); } if (!filterList.contains(filterClass)) { filterList.add(filterClass); } return (SC) this; }
java
public SC registerFilter(Class<? extends Filter> filterClass, String urlPattern) { __throwIfInitialized(); List<Class<? extends Filter>> filterList = filterMap.get(urlPattern); if (filterList == null) { filterList = new LinkedList<>(); filterMap.put(urlPattern, filterList); } if (!filterList.contains(filterClass)) { filterList.add(filterClass); } return (SC) this; }
[ "public", "SC", "registerFilter", "(", "Class", "<", "?", "extends", "Filter", ">", "filterClass", ",", "String", "urlPattern", ")", "{", "__throwIfInitialized", "(", ")", ";", "List", "<", "Class", "<", "?", "extends", "Filter", ">", ">", "filterList", "=", "filterMap", ".", "get", "(", "urlPattern", ")", ";", "if", "(", "filterList", "==", "null", ")", "{", "filterList", "=", "new", "LinkedList", "<>", "(", ")", ";", "filterMap", ".", "put", "(", "urlPattern", ",", "filterList", ")", ";", "}", "if", "(", "!", "filterList", ".", "contains", "(", "filterClass", ")", ")", "{", "filterList", ".", "add", "(", "filterClass", ")", ";", "}", "return", "(", "SC", ")", "this", ";", "}" ]
Registers a filter. @param filterClass class to be registered. @param urlPattern url pattern to be associated with given class. @return this
[ "Registers", "a", "filter", "." ]
train
https://github.com/agapsys/embedded-servlet-container/blob/28314a2600ad8550ed2c901d8e35d86583c26bb0/src/main/java/com/agapsys/jee/ServletContainer.java#L293-L308
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imageformat/ImageFormatCheckerUtils.java
ImageFormatCheckerUtils.asciiBytes
public static byte[] asciiBytes(String value) { """ Helper method that transforms provided string into it's byte representation using ASCII encoding. @param value the string to use @return byte array representing ascii encoded value """ Preconditions.checkNotNull(value); try { return value.getBytes("ASCII"); } catch (UnsupportedEncodingException uee) { // won't happen throw new RuntimeException("ASCII not found!", uee); } }
java
public static byte[] asciiBytes(String value) { Preconditions.checkNotNull(value); try { return value.getBytes("ASCII"); } catch (UnsupportedEncodingException uee) { // won't happen throw new RuntimeException("ASCII not found!", uee); } }
[ "public", "static", "byte", "[", "]", "asciiBytes", "(", "String", "value", ")", "{", "Preconditions", ".", "checkNotNull", "(", "value", ")", ";", "try", "{", "return", "value", ".", "getBytes", "(", "\"ASCII\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "uee", ")", "{", "// won't happen", "throw", "new", "RuntimeException", "(", "\"ASCII not found!\"", ",", "uee", ")", ";", "}", "}" ]
Helper method that transforms provided string into it's byte representation using ASCII encoding. @param value the string to use @return byte array representing ascii encoded value
[ "Helper", "method", "that", "transforms", "provided", "string", "into", "it", "s", "byte", "representation", "using", "ASCII", "encoding", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/ImageFormatCheckerUtils.java#L24-L32
joniles/mpxj
src/main/java/net/sf/mpxj/utility/TimephasedUtility.java
TimephasedUtility.getRangeDurationSubDay
private Duration getRangeDurationSubDay(ProjectCalendar projectCalendar, TimescaleUnits rangeUnits, DateRange range, List<TimephasedWork> assignments, int startIndex) { """ For a given date range, determine the duration of work, based on the timephased resource assignment data. This method deals with timescale units of less than a day. @param projectCalendar calendar used for the resource assignment calendar @param rangeUnits timescale units @param range target date range @param assignments timephased resource assignments @param startIndex index at which to start searching through the timephased resource assignments @return work duration """ throw new UnsupportedOperationException("Please request this functionality from the MPXJ maintainer"); }
java
private Duration getRangeDurationSubDay(ProjectCalendar projectCalendar, TimescaleUnits rangeUnits, DateRange range, List<TimephasedWork> assignments, int startIndex) { throw new UnsupportedOperationException("Please request this functionality from the MPXJ maintainer"); }
[ "private", "Duration", "getRangeDurationSubDay", "(", "ProjectCalendar", "projectCalendar", ",", "TimescaleUnits", "rangeUnits", ",", "DateRange", "range", ",", "List", "<", "TimephasedWork", ">", "assignments", ",", "int", "startIndex", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Please request this functionality from the MPXJ maintainer\"", ")", ";", "}" ]
For a given date range, determine the duration of work, based on the timephased resource assignment data. This method deals with timescale units of less than a day. @param projectCalendar calendar used for the resource assignment calendar @param rangeUnits timescale units @param range target date range @param assignments timephased resource assignments @param startIndex index at which to start searching through the timephased resource assignments @return work duration
[ "For", "a", "given", "date", "range", "determine", "the", "duration", "of", "work", "based", "on", "the", "timephased", "resource", "assignment", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/utility/TimephasedUtility.java#L283-L286
hpsa/hpe-application-automation-tools-plugin
src/main/java/com/hp/application/automation/tools/model/RunFromFileSystemModel.java
RunFromFileSystemModel.getProperties
@Nullable public Properties getProperties(EnvVars envVars, VariableResolver<String> varResolver) { """ Gets properties. @param envVars the env vars @return the properties """ return createProperties(envVars, varResolver); }
java
@Nullable public Properties getProperties(EnvVars envVars, VariableResolver<String> varResolver) { return createProperties(envVars, varResolver); }
[ "@", "Nullable", "public", "Properties", "getProperties", "(", "EnvVars", "envVars", ",", "VariableResolver", "<", "String", ">", "varResolver", ")", "{", "return", "createProperties", "(", "envVars", ",", "varResolver", ")", ";", "}" ]
Gets properties. @param envVars the env vars @return the properties
[ "Gets", "properties", "." ]
train
https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/model/RunFromFileSystemModel.java#L525-L529
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/managers/AccountManager.java
AccountManager.setPassword
@CheckReturnValue public AccountManager setPassword(String newPassword, String currentPassword) { """ Sets the password for the currently logged in client account. <br>If the new password is equal to the current password this does nothing. @param newPassword The new password for the currently logged in account @param currentPassword The <b>valid</b> current password for the represented account @throws net.dv8tion.jda.core.exceptions.AccountTypeException If the currently logged in account is not from {@link net.dv8tion.jda.core.AccountType#CLIENT} @throws IllegalArgumentException If any of the provided passwords are {@code null} or empty @return AccountManager for chaining convenience """ Checks.notNull(newPassword, "password"); Checks.check(newPassword.length() >= 6 && newPassword.length() <= 128, "Password must be between 2-128 characters long"); this.currentPassword = currentPassword; this.password = newPassword; set |= PASSWORD; return this; }
java
@CheckReturnValue public AccountManager setPassword(String newPassword, String currentPassword) { Checks.notNull(newPassword, "password"); Checks.check(newPassword.length() >= 6 && newPassword.length() <= 128, "Password must be between 2-128 characters long"); this.currentPassword = currentPassword; this.password = newPassword; set |= PASSWORD; return this; }
[ "@", "CheckReturnValue", "public", "AccountManager", "setPassword", "(", "String", "newPassword", ",", "String", "currentPassword", ")", "{", "Checks", ".", "notNull", "(", "newPassword", ",", "\"password\"", ")", ";", "Checks", ".", "check", "(", "newPassword", ".", "length", "(", ")", ">=", "6", "&&", "newPassword", ".", "length", "(", ")", "<=", "128", ",", "\"Password must be between 2-128 characters long\"", ")", ";", "this", ".", "currentPassword", "=", "currentPassword", ";", "this", ".", "password", "=", "newPassword", ";", "set", "|=", "PASSWORD", ";", "return", "this", ";", "}" ]
Sets the password for the currently logged in client account. <br>If the new password is equal to the current password this does nothing. @param newPassword The new password for the currently logged in account @param currentPassword The <b>valid</b> current password for the represented account @throws net.dv8tion.jda.core.exceptions.AccountTypeException If the currently logged in account is not from {@link net.dv8tion.jda.core.AccountType#CLIENT} @throws IllegalArgumentException If any of the provided passwords are {@code null} or empty @return AccountManager for chaining convenience
[ "Sets", "the", "password", "for", "the", "currently", "logged", "in", "client", "account", ".", "<br", ">", "If", "the", "new", "password", "is", "equal", "to", "the", "current", "password", "this", "does", "nothing", "." ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/managers/AccountManager.java#L304-L313
actorapp/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java
ImageLoading.loadReuseExact
public static ReuseResult loadReuseExact(String fileName, Bitmap dest) throws ImageLoadException { """ Loading bitmap with using reuse bitmap with the same size of source image. If it is unable to load with reuse method tries to load without it. Reuse works only in 3.0+ @param fileName Image file name @param dest reuse bitmap @return result of loading @throws ImageLoadException if it is unable to load file """ return loadBitmapReuseExact(new FileSource(fileName), dest); }
java
public static ReuseResult loadReuseExact(String fileName, Bitmap dest) throws ImageLoadException { return loadBitmapReuseExact(new FileSource(fileName), dest); }
[ "public", "static", "ReuseResult", "loadReuseExact", "(", "String", "fileName", ",", "Bitmap", "dest", ")", "throws", "ImageLoadException", "{", "return", "loadBitmapReuseExact", "(", "new", "FileSource", "(", "fileName", ")", ",", "dest", ")", ";", "}" ]
Loading bitmap with using reuse bitmap with the same size of source image. If it is unable to load with reuse method tries to load without it. Reuse works only in 3.0+ @param fileName Image file name @param dest reuse bitmap @return result of loading @throws ImageLoadException if it is unable to load file
[ "Loading", "bitmap", "with", "using", "reuse", "bitmap", "with", "the", "same", "size", "of", "source", "image", ".", "If", "it", "is", "unable", "to", "load", "with", "reuse", "method", "tries", "to", "load", "without", "it", ".", "Reuse", "works", "only", "in", "3", ".", "0", "+" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageLoading.java#L159-L161
lessthanoptimal/BoofCV
main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/PairwiseImageMatching.java
PairwiseImageMatching.addImage
public void addImage(T image , String cameraName ) { """ Adds a new observation from a camera. Detects features inside the and saves those. @param image The image """ PairwiseImageGraph.View view = new PairwiseImageGraph.View(graph.nodes.size(), new FastQueue<TupleDesc>(TupleDesc.class,true) { @Override protected TupleDesc createInstance() { return detDesc.createDescription(); } }); view.camera = graph.cameras.get(cameraName); if( view.camera == null ) throw new IllegalArgumentException("Must have added the camera first"); view.index = graph.nodes.size(); graph.nodes.add(view); detDesc.detect(image); // Pre-declare memory view.descriptions.growArray(detDesc.getNumberOfFeatures()); view.observationPixels.growArray(detDesc.getNumberOfFeatures()); for (int i = 0; i < detDesc.getNumberOfFeatures(); i++) { Point2D_F64 p = detDesc.getLocation(i); // save copies since detDesc recycles memory view.descriptions.grow().setTo(detDesc.getDescription(i)); view.observationPixels.grow().set(p); } if( view.camera.pixelToNorm == null ){ return; } view.observationNorm.growArray(detDesc.getNumberOfFeatures()); for (int i = 0; i < view.observationPixels.size; i++) { Point2D_F64 p = view.observationPixels.get(i); view.camera.pixelToNorm.compute(p.x,p.y,view.observationNorm.grow()); } if( verbose != null ) { verbose.println("Detected Features: "+detDesc.getNumberOfFeatures()); } }
java
public void addImage(T image , String cameraName ) { PairwiseImageGraph.View view = new PairwiseImageGraph.View(graph.nodes.size(), new FastQueue<TupleDesc>(TupleDesc.class,true) { @Override protected TupleDesc createInstance() { return detDesc.createDescription(); } }); view.camera = graph.cameras.get(cameraName); if( view.camera == null ) throw new IllegalArgumentException("Must have added the camera first"); view.index = graph.nodes.size(); graph.nodes.add(view); detDesc.detect(image); // Pre-declare memory view.descriptions.growArray(detDesc.getNumberOfFeatures()); view.observationPixels.growArray(detDesc.getNumberOfFeatures()); for (int i = 0; i < detDesc.getNumberOfFeatures(); i++) { Point2D_F64 p = detDesc.getLocation(i); // save copies since detDesc recycles memory view.descriptions.grow().setTo(detDesc.getDescription(i)); view.observationPixels.grow().set(p); } if( view.camera.pixelToNorm == null ){ return; } view.observationNorm.growArray(detDesc.getNumberOfFeatures()); for (int i = 0; i < view.observationPixels.size; i++) { Point2D_F64 p = view.observationPixels.get(i); view.camera.pixelToNorm.compute(p.x,p.y,view.observationNorm.grow()); } if( verbose != null ) { verbose.println("Detected Features: "+detDesc.getNumberOfFeatures()); } }
[ "public", "void", "addImage", "(", "T", "image", ",", "String", "cameraName", ")", "{", "PairwiseImageGraph", ".", "View", "view", "=", "new", "PairwiseImageGraph", ".", "View", "(", "graph", ".", "nodes", ".", "size", "(", ")", ",", "new", "FastQueue", "<", "TupleDesc", ">", "(", "TupleDesc", ".", "class", ",", "true", ")", "{", "@", "Override", "protected", "TupleDesc", "createInstance", "(", ")", "{", "return", "detDesc", ".", "createDescription", "(", ")", ";", "}", "}", ")", ";", "view", ".", "camera", "=", "graph", ".", "cameras", ".", "get", "(", "cameraName", ")", ";", "if", "(", "view", ".", "camera", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Must have added the camera first\"", ")", ";", "view", ".", "index", "=", "graph", ".", "nodes", ".", "size", "(", ")", ";", "graph", ".", "nodes", ".", "add", "(", "view", ")", ";", "detDesc", ".", "detect", "(", "image", ")", ";", "// Pre-declare memory", "view", ".", "descriptions", ".", "growArray", "(", "detDesc", ".", "getNumberOfFeatures", "(", ")", ")", ";", "view", ".", "observationPixels", ".", "growArray", "(", "detDesc", ".", "getNumberOfFeatures", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "detDesc", ".", "getNumberOfFeatures", "(", ")", ";", "i", "++", ")", "{", "Point2D_F64", "p", "=", "detDesc", ".", "getLocation", "(", "i", ")", ";", "// save copies since detDesc recycles memory", "view", ".", "descriptions", ".", "grow", "(", ")", ".", "setTo", "(", "detDesc", ".", "getDescription", "(", "i", ")", ")", ";", "view", ".", "observationPixels", ".", "grow", "(", ")", ".", "set", "(", "p", ")", ";", "}", "if", "(", "view", ".", "camera", ".", "pixelToNorm", "==", "null", ")", "{", "return", ";", "}", "view", ".", "observationNorm", ".", "growArray", "(", "detDesc", ".", "getNumberOfFeatures", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "view", ".", "observationPixels", ".", "size", ";", "i", "++", ")", "{", "Point2D_F64", "p", "=", "view", ".", "observationPixels", ".", "get", "(", "i", ")", ";", "view", ".", "camera", ".", "pixelToNorm", ".", "compute", "(", "p", ".", "x", ",", "p", ".", "y", ",", "view", ".", "observationNorm", ".", "grow", "(", ")", ")", ";", "}", "if", "(", "verbose", "!=", "null", ")", "{", "verbose", ".", "println", "(", "\"Detected Features: \"", "+", "detDesc", ".", "getNumberOfFeatures", "(", ")", ")", ";", "}", "}" ]
Adds a new observation from a camera. Detects features inside the and saves those. @param image The image
[ "Adds", "a", "new", "observation", "from", "a", "camera", ".", "Detects", "features", "inside", "the", "and", "saves", "those", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/PairwiseImageMatching.java#L118-L162
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.tracev
public void tracev(Throwable t, String format, Object... params) { """ Issue a log message with a level of TRACE using {@link java.text.MessageFormat}-style formatting. @param t the throwable @param format the message format string @param params the parameters """ doLog(Level.TRACE, FQCN, format, params, t); }
java
public void tracev(Throwable t, String format, Object... params) { doLog(Level.TRACE, FQCN, format, params, t); }
[ "public", "void", "tracev", "(", "Throwable", "t", ",", "String", "format", ",", "Object", "...", "params", ")", "{", "doLog", "(", "Level", ".", "TRACE", ",", "FQCN", ",", "format", ",", "params", ",", "t", ")", ";", "}" ]
Issue a log message with a level of TRACE using {@link java.text.MessageFormat}-style formatting. @param t the throwable @param format the message format string @param params the parameters
[ "Issue", "a", "log", "message", "with", "a", "level", "of", "TRACE", "using", "{", "@link", "java", ".", "text", ".", "MessageFormat", "}", "-", "style", "formatting", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L224-L226
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/query/DefaultQueryAction.java
DefaultQueryAction.setLimit
private void setLimit(int from, int size) { """ Add from and size to the ES query based on the 'LIMIT' clause @param from starts from document at position from @param size number of documents to return. """ request.setFrom(from); if (size > -1) { request.setSize(size); } }
java
private void setLimit(int from, int size) { request.setFrom(from); if (size > -1) { request.setSize(size); } }
[ "private", "void", "setLimit", "(", "int", "from", ",", "int", "size", ")", "{", "request", ".", "setFrom", "(", "from", ")", ";", "if", "(", "size", ">", "-", "1", ")", "{", "request", ".", "setSize", "(", "size", ")", ";", "}", "}" ]
Add from and size to the ES query based on the 'LIMIT' clause @param from starts from document at position from @param size number of documents to return.
[ "Add", "from", "and", "size", "to", "the", "ES", "query", "based", "on", "the", "LIMIT", "clause" ]
train
https://github.com/NLPchina/elasticsearch-sql/blob/eaab70b4bf1729978911b83eb96e816ebcfe6e7f/src/main/java/org/nlpcn/es4sql/query/DefaultQueryAction.java#L236-L242
apache/reef
lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/examples/matmul/MatMulFunction.java
MatMulFunction.call
@Override public MatMulOutput call(final MatMulInput input) throws Exception { """ Computes multiplication of two matrices. @param input Input which contains two matrices to multiply, and index of the sub-matrix in the entire result. @return Output which contains the sub-matrix and index of it in the entire result. @throws Exception If the two matrices cannot be multiplied. """ final int index = input.getIndex(); final Matrix<Double> leftMatrix = input.getLeftMatrix(); final Matrix<Double> rightMatrix = input.getRightMatrix(); final Matrix<Double> result = leftMatrix.multiply(rightMatrix); return new MatMulOutput(index, result); }
java
@Override public MatMulOutput call(final MatMulInput input) throws Exception { final int index = input.getIndex(); final Matrix<Double> leftMatrix = input.getLeftMatrix(); final Matrix<Double> rightMatrix = input.getRightMatrix(); final Matrix<Double> result = leftMatrix.multiply(rightMatrix); return new MatMulOutput(index, result); }
[ "@", "Override", "public", "MatMulOutput", "call", "(", "final", "MatMulInput", "input", ")", "throws", "Exception", "{", "final", "int", "index", "=", "input", ".", "getIndex", "(", ")", ";", "final", "Matrix", "<", "Double", ">", "leftMatrix", "=", "input", ".", "getLeftMatrix", "(", ")", ";", "final", "Matrix", "<", "Double", ">", "rightMatrix", "=", "input", ".", "getRightMatrix", "(", ")", ";", "final", "Matrix", "<", "Double", ">", "result", "=", "leftMatrix", ".", "multiply", "(", "rightMatrix", ")", ";", "return", "new", "MatMulOutput", "(", "index", ",", "result", ")", ";", "}" ]
Computes multiplication of two matrices. @param input Input which contains two matrices to multiply, and index of the sub-matrix in the entire result. @return Output which contains the sub-matrix and index of it in the entire result. @throws Exception If the two matrices cannot be multiplied.
[ "Computes", "multiplication", "of", "two", "matrices", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/examples/matmul/MatMulFunction.java#L34-L41
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java
DenseFlowPyramidBase.interpolateFlowScale
protected void interpolateFlowScale(GrayF32 prev, GrayF32 curr) { """ Takes the flow from the previous lower resolution layer and uses it to initialize the flow in the current layer. Adjusts for change in image scale. """ interp.setImage(prev); float scaleX = (float)prev.width/(float)curr.width; float scaleY = (float)prev.height/(float)curr.height; float scale = (float)prev.width/(float)curr.width; int indexCurr = 0; for( int y = 0; y < curr.height; y++ ) { float yy = y*scaleY; for( int x = 0; x < curr.width; x++ ) { float xx = x*scaleX; if( interp.isInFastBounds(xx,yy)) { curr.data[indexCurr++] = interp.get_fast(x * scaleX, y * scaleY) / scale; } else { curr.data[indexCurr++] = interp.get(x * scaleX, y * scaleY) / scale; } } } }
java
protected void interpolateFlowScale(GrayF32 prev, GrayF32 curr) { interp.setImage(prev); float scaleX = (float)prev.width/(float)curr.width; float scaleY = (float)prev.height/(float)curr.height; float scale = (float)prev.width/(float)curr.width; int indexCurr = 0; for( int y = 0; y < curr.height; y++ ) { float yy = y*scaleY; for( int x = 0; x < curr.width; x++ ) { float xx = x*scaleX; if( interp.isInFastBounds(xx,yy)) { curr.data[indexCurr++] = interp.get_fast(x * scaleX, y * scaleY) / scale; } else { curr.data[indexCurr++] = interp.get(x * scaleX, y * scaleY) / scale; } } } }
[ "protected", "void", "interpolateFlowScale", "(", "GrayF32", "prev", ",", "GrayF32", "curr", ")", "{", "interp", ".", "setImage", "(", "prev", ")", ";", "float", "scaleX", "=", "(", "float", ")", "prev", ".", "width", "/", "(", "float", ")", "curr", ".", "width", ";", "float", "scaleY", "=", "(", "float", ")", "prev", ".", "height", "/", "(", "float", ")", "curr", ".", "height", ";", "float", "scale", "=", "(", "float", ")", "prev", ".", "width", "/", "(", "float", ")", "curr", ".", "width", ";", "int", "indexCurr", "=", "0", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "curr", ".", "height", ";", "y", "++", ")", "{", "float", "yy", "=", "y", "*", "scaleY", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "curr", ".", "width", ";", "x", "++", ")", "{", "float", "xx", "=", "x", "*", "scaleX", ";", "if", "(", "interp", ".", "isInFastBounds", "(", "xx", ",", "yy", ")", ")", "{", "curr", ".", "data", "[", "indexCurr", "++", "]", "=", "interp", ".", "get_fast", "(", "x", "*", "scaleX", ",", "y", "*", "scaleY", ")", "/", "scale", ";", "}", "else", "{", "curr", ".", "data", "[", "indexCurr", "++", "]", "=", "interp", ".", "get", "(", "x", "*", "scaleX", ",", "y", "*", "scaleY", ")", "/", "scale", ";", "}", "}", "}", "}" ]
Takes the flow from the previous lower resolution layer and uses it to initialize the flow in the current layer. Adjusts for change in image scale.
[ "Takes", "the", "flow", "from", "the", "previous", "lower", "resolution", "layer", "and", "uses", "it", "to", "initialize", "the", "flow", "in", "the", "current", "layer", ".", "Adjusts", "for", "change", "in", "image", "scale", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseFlowPyramidBase.java#L96-L116
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/randomprojection/RPUtils.java
RPUtils.computeDistanceMulti
public static INDArray computeDistanceMulti(String function,INDArray x,INDArray y,INDArray result) { """ Compute the distance between 2 vectors given a function name. Valid function names: euclidean: euclidean distance cosinedistance: cosine distance cosine similarity: cosine similarity manhattan: manhattan distance jaccard: jaccard distance hamming: hamming distance @param function the function to use (default euclidean distance) @param x the first vector @param y the second vector @return the distance between the 2 vectors given the inputs """ ReduceOp op = (ReduceOp) getOp(function, x, y, result); op.setDimensions(1); Nd4j.getExecutioner().exec(op); return op.z(); }
java
public static INDArray computeDistanceMulti(String function,INDArray x,INDArray y,INDArray result) { ReduceOp op = (ReduceOp) getOp(function, x, y, result); op.setDimensions(1); Nd4j.getExecutioner().exec(op); return op.z(); }
[ "public", "static", "INDArray", "computeDistanceMulti", "(", "String", "function", ",", "INDArray", "x", ",", "INDArray", "y", ",", "INDArray", "result", ")", "{", "ReduceOp", "op", "=", "(", "ReduceOp", ")", "getOp", "(", "function", ",", "x", ",", "y", ",", "result", ")", ";", "op", ".", "setDimensions", "(", "1", ")", ";", "Nd4j", ".", "getExecutioner", "(", ")", ".", "exec", "(", "op", ")", ";", "return", "op", ".", "z", "(", ")", ";", "}" ]
Compute the distance between 2 vectors given a function name. Valid function names: euclidean: euclidean distance cosinedistance: cosine distance cosine similarity: cosine similarity manhattan: manhattan distance jaccard: jaccard distance hamming: hamming distance @param function the function to use (default euclidean distance) @param x the first vector @param y the second vector @return the distance between the 2 vectors given the inputs
[ "Compute", "the", "distance", "between", "2", "vectors", "given", "a", "function", "name", ".", "Valid", "function", "names", ":", "euclidean", ":", "euclidean", "distance", "cosinedistance", ":", "cosine", "distance", "cosine", "similarity", ":", "cosine", "similarity", "manhattan", ":", "manhattan", "distance", "jaccard", ":", "jaccard", "distance", "hamming", ":", "hamming", "distance" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/randomprojection/RPUtils.java#L324-L329
atomix/atomix
utils/src/main/java/io/atomix/utils/config/ConfigMapper.java
ConfigMapper.loadResources
public <T> T loadResources(Class<T> type, String... resources) { """ Loads the given resources using the configuration mapper. @param type the type to load @param resources the resources to load @param <T> the resulting type @return the loaded configuration """ return loadResources(type, Arrays.asList(resources)); }
java
public <T> T loadResources(Class<T> type, String... resources) { return loadResources(type, Arrays.asList(resources)); }
[ "public", "<", "T", ">", "T", "loadResources", "(", "Class", "<", "T", ">", "type", ",", "String", "...", "resources", ")", "{", "return", "loadResources", "(", "type", ",", "Arrays", ".", "asList", "(", "resources", ")", ")", ";", "}" ]
Loads the given resources using the configuration mapper. @param type the type to load @param resources the resources to load @param <T> the resulting type @return the loaded configuration
[ "Loads", "the", "given", "resources", "using", "the", "configuration", "mapper", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/config/ConfigMapper.java#L100-L102
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuStreamWaitEvent
public static int cuStreamWaitEvent(CUstream hStream, CUevent hEvent, int Flags) { """ Make a compute stream wait on an event. <pre> CUresult cuStreamWaitEvent ( CUstream hStream, CUevent hEvent, unsigned int Flags ) </pre> <div> <p>Make a compute stream wait on an event. Makes all future work submitted to <tt>hStream</tt> wait until <tt>hEvent</tt> reports completion before beginning execution. This synchronization will be performed efficiently on the device. The event <tt>hEvent</tt> may be from a different context than <tt>hStream</tt>, in which case this function will perform cross-device synchronization. </p> <p>The stream <tt>hStream</tt> will wait only for the completion of the most recent host call to cuEventRecord() on <tt>hEvent</tt>. Once this call has returned, any functions (including cuEventRecord() and cuEventDestroy()) may be called on <tt>hEvent</tt> again, and subsequent calls will not have any effect on <tt>hStream</tt>. </p> <p>If <tt>hStream</tt> is 0 (the NULL stream) any future work submitted in any stream will wait for <tt>hEvent</tt> to complete before beginning execution. This effectively creates a barrier for all future work submitted to the context. </p> <p>If cuEventRecord() has not been called on <tt>hEvent</tt>, this call acts as if the record has already completed, and so is a functional no-op. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param hStream Stream to wait @param hEvent Event to wait on (may not be NULL) @param Flags Parameters for the operation (must be 0) @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, @see JCudaDriver#cuStreamCreate @see JCudaDriver#cuEventRecord @see JCudaDriver#cuStreamQuery @see JCudaDriver#cuStreamSynchronize @see JCudaDriver#cuStreamAddCallback @see JCudaDriver#cuStreamDestroy """ return checkResult(cuStreamWaitEventNative(hStream, hEvent, Flags)); }
java
public static int cuStreamWaitEvent(CUstream hStream, CUevent hEvent, int Flags) { return checkResult(cuStreamWaitEventNative(hStream, hEvent, Flags)); }
[ "public", "static", "int", "cuStreamWaitEvent", "(", "CUstream", "hStream", ",", "CUevent", "hEvent", ",", "int", "Flags", ")", "{", "return", "checkResult", "(", "cuStreamWaitEventNative", "(", "hStream", ",", "hEvent", ",", "Flags", ")", ")", ";", "}" ]
Make a compute stream wait on an event. <pre> CUresult cuStreamWaitEvent ( CUstream hStream, CUevent hEvent, unsigned int Flags ) </pre> <div> <p>Make a compute stream wait on an event. Makes all future work submitted to <tt>hStream</tt> wait until <tt>hEvent</tt> reports completion before beginning execution. This synchronization will be performed efficiently on the device. The event <tt>hEvent</tt> may be from a different context than <tt>hStream</tt>, in which case this function will perform cross-device synchronization. </p> <p>The stream <tt>hStream</tt> will wait only for the completion of the most recent host call to cuEventRecord() on <tt>hEvent</tt>. Once this call has returned, any functions (including cuEventRecord() and cuEventDestroy()) may be called on <tt>hEvent</tt> again, and subsequent calls will not have any effect on <tt>hStream</tt>. </p> <p>If <tt>hStream</tt> is 0 (the NULL stream) any future work submitted in any stream will wait for <tt>hEvent</tt> to complete before beginning execution. This effectively creates a barrier for all future work submitted to the context. </p> <p>If cuEventRecord() has not been called on <tt>hEvent</tt>, this call acts as if the record has already completed, and so is a functional no-op. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param hStream Stream to wait @param hEvent Event to wait on (may not be NULL) @param Flags Parameters for the operation (must be 0) @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_HANDLE, @see JCudaDriver#cuStreamCreate @see JCudaDriver#cuEventRecord @see JCudaDriver#cuStreamQuery @see JCudaDriver#cuStreamSynchronize @see JCudaDriver#cuStreamAddCallback @see JCudaDriver#cuStreamDestroy
[ "Make", "a", "compute", "stream", "wait", "on", "an", "event", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L14606-L14609
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/kerneldiscovery/StandardKernelDiscoveryService.java
StandardKernelDiscoveryService.postConstruction
@Inject void postConstruction(NetworkService networkService, ExecutorService executorService) { """ Do the post initialization. @param networkService network service to be linked to. @param executorService execution service to use. """ this.network = networkService; this.network.addListener(new NetworkStartListener(), executorService.getExecutorService()); }
java
@Inject void postConstruction(NetworkService networkService, ExecutorService executorService) { this.network = networkService; this.network.addListener(new NetworkStartListener(), executorService.getExecutorService()); }
[ "@", "Inject", "void", "postConstruction", "(", "NetworkService", "networkService", ",", "ExecutorService", "executorService", ")", "{", "this", ".", "network", "=", "networkService", ";", "this", ".", "network", ".", "addListener", "(", "new", "NetworkStartListener", "(", ")", ",", "executorService", ".", "getExecutorService", "(", ")", ")", ";", "}" ]
Do the post initialization. @param networkService network service to be linked to. @param executorService execution service to use.
[ "Do", "the", "post", "initialization", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/kerneldiscovery/StandardKernelDiscoveryService.java#L85-L89
gallandarakhneorg/afc
advanced/gis/gisroad/src/main/java/org/arakhne/afc/gis/road/path/ClusteredRoadPath.java
ClusteredRoadPath.removeRoadSegmentAt
public RoadSegment removeRoadSegmentAt(int index) { """ Remove the road segment at the given index. @param index an index. @return the removed road segment. """ if (index >= 0) { int b = 0; for (final RoadPath p : this.paths) { int end = b + p.size(); if (index < end) { end = index - b; return removeRoadSegmentAt(p, end, null); } b = end; } } throw new IndexOutOfBoundsException(); }
java
public RoadSegment removeRoadSegmentAt(int index) { if (index >= 0) { int b = 0; for (final RoadPath p : this.paths) { int end = b + p.size(); if (index < end) { end = index - b; return removeRoadSegmentAt(p, end, null); } b = end; } } throw new IndexOutOfBoundsException(); }
[ "public", "RoadSegment", "removeRoadSegmentAt", "(", "int", "index", ")", "{", "if", "(", "index", ">=", "0", ")", "{", "int", "b", "=", "0", ";", "for", "(", "final", "RoadPath", "p", ":", "this", ".", "paths", ")", "{", "int", "end", "=", "b", "+", "p", ".", "size", "(", ")", ";", "if", "(", "index", "<", "end", ")", "{", "end", "=", "index", "-", "b", ";", "return", "removeRoadSegmentAt", "(", "p", ",", "end", ",", "null", ")", ";", "}", "b", "=", "end", ";", "}", "}", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}" ]
Remove the road segment at the given index. @param index an index. @return the removed road segment.
[ "Remove", "the", "road", "segment", "at", "the", "given", "index", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisroad/src/main/java/org/arakhne/afc/gis/road/path/ClusteredRoadPath.java#L255-L268
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/builder/AbstractProcessorBuilder.java
AbstractProcessorBuilder.registerForConversion
public <A extends Annotation> void registerForConversion(final Class<A> anno, final ConversionProcessorFactory<A> factory) { """ 変換のCellProcessorを作成するクラスを登録する。読み込み時と書き込み時は共通です。 @param <A> アノテーションのクラス @param anno 関連づけるアノテーション @param factory アノテーションを処理する{@link ConversionProcessorFactory}の実装。 """ this.conversionHandler.register(anno, factory); }
java
public <A extends Annotation> void registerForConversion(final Class<A> anno, final ConversionProcessorFactory<A> factory) { this.conversionHandler.register(anno, factory); }
[ "public", "<", "A", "extends", "Annotation", ">", "void", "registerForConversion", "(", "final", "Class", "<", "A", ">", "anno", ",", "final", "ConversionProcessorFactory", "<", "A", ">", "factory", ")", "{", "this", ".", "conversionHandler", ".", "register", "(", "anno", ",", "factory", ")", ";", "}" ]
変換のCellProcessorを作成するクラスを登録する。読み込み時と書き込み時は共通です。 @param <A> アノテーションのクラス @param anno 関連づけるアノテーション @param factory アノテーションを処理する{@link ConversionProcessorFactory}の実装。
[ "変換のCellProcessorを作成するクラスを登録する。読み込み時と書き込み時は共通です。" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/AbstractProcessorBuilder.java#L204-L206
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/LogQueryTool.java
LogQueryTool.exceptionWithQuery
public SQLException exceptionWithQuery(SQLException sqlEx, PrepareResult prepareResult) { """ Return exception with query information's. @param sqlEx current exception @param prepareResult prepare results @return exception with query information """ if (options.dumpQueriesOnException || sqlEx.getErrorCode() == 1064) { String querySql = prepareResult.getSql(); String message = sqlEx.getMessage(); if (options.maxQuerySizeToLog != 0 && querySql.length() > options.maxQuerySizeToLog - 3) { message += "\nQuery is: " + querySql.substring(0, options.maxQuerySizeToLog - 3) + "..."; } else { message += "\nQuery is: " + querySql; } message += "\njava thread: " + Thread.currentThread().getName(); return new SQLException(message, sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getCause()); } return sqlEx; }
java
public SQLException exceptionWithQuery(SQLException sqlEx, PrepareResult prepareResult) { if (options.dumpQueriesOnException || sqlEx.getErrorCode() == 1064) { String querySql = prepareResult.getSql(); String message = sqlEx.getMessage(); if (options.maxQuerySizeToLog != 0 && querySql.length() > options.maxQuerySizeToLog - 3) { message += "\nQuery is: " + querySql.substring(0, options.maxQuerySizeToLog - 3) + "..."; } else { message += "\nQuery is: " + querySql; } message += "\njava thread: " + Thread.currentThread().getName(); return new SQLException(message, sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getCause()); } return sqlEx; }
[ "public", "SQLException", "exceptionWithQuery", "(", "SQLException", "sqlEx", ",", "PrepareResult", "prepareResult", ")", "{", "if", "(", "options", ".", "dumpQueriesOnException", "||", "sqlEx", ".", "getErrorCode", "(", ")", "==", "1064", ")", "{", "String", "querySql", "=", "prepareResult", ".", "getSql", "(", ")", ";", "String", "message", "=", "sqlEx", ".", "getMessage", "(", ")", ";", "if", "(", "options", ".", "maxQuerySizeToLog", "!=", "0", "&&", "querySql", ".", "length", "(", ")", ">", "options", ".", "maxQuerySizeToLog", "-", "3", ")", "{", "message", "+=", "\"\\nQuery is: \"", "+", "querySql", ".", "substring", "(", "0", ",", "options", ".", "maxQuerySizeToLog", "-", "3", ")", "+", "\"...\"", ";", "}", "else", "{", "message", "+=", "\"\\nQuery is: \"", "+", "querySql", ";", "}", "message", "+=", "\"\\njava thread: \"", "+", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ";", "return", "new", "SQLException", "(", "message", ",", "sqlEx", ".", "getSQLState", "(", ")", ",", "sqlEx", ".", "getErrorCode", "(", ")", ",", "sqlEx", ".", "getCause", "(", ")", ")", ";", "}", "return", "sqlEx", ";", "}" ]
Return exception with query information's. @param sqlEx current exception @param prepareResult prepare results @return exception with query information
[ "Return", "exception", "with", "query", "information", "s", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/LogQueryTool.java#L175-L188
brianwhu/xillium
base/src/main/java/org/xillium/base/text/Balanced.java
Balanced.indexOf
public static int indexOf(String text, int begin, int end, char target, Functor<Integer, Integer> extra) { """ Returns the index within a string of the first occurrence of the specified character, similar to String.indexOf(). However, any occurrence of the specified character enclosed between balanced parentheses/brackets/braces is ignored. @param text a String @param begin a begin offset @param end an end offset @param target the character to search for @param extra an optional functor to provide balancing symbols in addition to the standard ones @return the index of the character in the string, or -1 if the specified character is not found """ return indexOf(text, begin, end, target, extra); }
java
public static int indexOf(String text, int begin, int end, char target, Functor<Integer, Integer> extra) { return indexOf(text, begin, end, target, extra); }
[ "public", "static", "int", "indexOf", "(", "String", "text", ",", "int", "begin", ",", "int", "end", ",", "char", "target", ",", "Functor", "<", "Integer", ",", "Integer", ">", "extra", ")", "{", "return", "indexOf", "(", "text", ",", "begin", ",", "end", ",", "target", ",", "extra", ")", ";", "}" ]
Returns the index within a string of the first occurrence of the specified character, similar to String.indexOf(). However, any occurrence of the specified character enclosed between balanced parentheses/brackets/braces is ignored. @param text a String @param begin a begin offset @param end an end offset @param target the character to search for @param extra an optional functor to provide balancing symbols in addition to the standard ones @return the index of the character in the string, or -1 if the specified character is not found
[ "Returns", "the", "index", "within", "a", "string", "of", "the", "first", "occurrence", "of", "the", "specified", "character", "similar", "to", "String", ".", "indexOf", "()", ".", "However", "any", "occurrence", "of", "the", "specified", "character", "enclosed", "between", "balanced", "parentheses", "/", "brackets", "/", "braces", "is", "ignored", "." ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/text/Balanced.java#L68-L70
pravega/pravega
common/src/main/java/io/pravega/common/util/BitConverter.java
BitConverter.writeLong
public static int writeLong(ArrayView target, int offset, long value) { """ Writes the given 64-bit Long to the given ArrayView at the given offset. @param target The ArrayView to write to. @param offset The offset within the ArrayView to write at. @param value The value to write. @return The number of bytes written. """ return writeLong(target.array(), target.arrayOffset() + offset, value); }
java
public static int writeLong(ArrayView target, int offset, long value) { return writeLong(target.array(), target.arrayOffset() + offset, value); }
[ "public", "static", "int", "writeLong", "(", "ArrayView", "target", ",", "int", "offset", ",", "long", "value", ")", "{", "return", "writeLong", "(", "target", ".", "array", "(", ")", ",", "target", ".", "arrayOffset", "(", ")", "+", "offset", ",", "value", ")", ";", "}" ]
Writes the given 64-bit Long to the given ArrayView at the given offset. @param target The ArrayView to write to. @param offset The offset within the ArrayView to write at. @param value The value to write. @return The number of bytes written.
[ "Writes", "the", "given", "64", "-", "bit", "Long", "to", "the", "given", "ArrayView", "at", "the", "given", "offset", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/BitConverter.java#L171-L173
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java
ClassUtils.getWriteMethod
public static final Method getWriteMethod(Class<?> clazz, String propertyName, Class<?> propertyType) { """ Lookup the setter method for the given property. @param clazz type which contains the property. @param propertyName name of the property. @param propertyType type of the property. @return a Method with write-access for the property. """ String propertyNameCapitalized = capitalize(propertyName); try { return clazz.getMethod("set" + propertyNameCapitalized, new Class[]{propertyType}); } catch (Exception e) { return null; } }
java
public static final Method getWriteMethod(Class<?> clazz, String propertyName, Class<?> propertyType) { String propertyNameCapitalized = capitalize(propertyName); try { return clazz.getMethod("set" + propertyNameCapitalized, new Class[]{propertyType}); } catch (Exception e) { return null; } }
[ "public", "static", "final", "Method", "getWriteMethod", "(", "Class", "<", "?", ">", "clazz", ",", "String", "propertyName", ",", "Class", "<", "?", ">", "propertyType", ")", "{", "String", "propertyNameCapitalized", "=", "capitalize", "(", "propertyName", ")", ";", "try", "{", "return", "clazz", ".", "getMethod", "(", "\"set\"", "+", "propertyNameCapitalized", ",", "new", "Class", "[", "]", "{", "propertyType", "}", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "}" ]
Lookup the setter method for the given property. @param clazz type which contains the property. @param propertyName name of the property. @param propertyType type of the property. @return a Method with write-access for the property.
[ "Lookup", "the", "setter", "method", "for", "the", "given", "property", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/table/ClassUtils.java#L99-L110
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.pressSpinnerItem
public void pressSpinnerItem(int spinnerIndex, int itemIndex) { """ Presses a Spinner (drop-down menu) item. @param spinnerIndex the index of the {@link Spinner} menu to use @param itemIndex the index of the {@link Spinner} item to press relative to the currently selected item. A Negative number moves up on the {@link Spinner}, positive moves down """ if(config.commandLogging){ Log.d(config.commandLoggingTag, "pressSpinnerItem("+spinnerIndex+", "+itemIndex+")"); } presser.pressSpinnerItem(spinnerIndex, itemIndex); }
java
public void pressSpinnerItem(int spinnerIndex, int itemIndex) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "pressSpinnerItem("+spinnerIndex+", "+itemIndex+")"); } presser.pressSpinnerItem(spinnerIndex, itemIndex); }
[ "public", "void", "pressSpinnerItem", "(", "int", "spinnerIndex", ",", "int", "itemIndex", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"pressSpinnerItem(\"", "+", "spinnerIndex", "+", "\", \"", "+", "itemIndex", "+", "\")\"", ")", ";", "}", "presser", ".", "pressSpinnerItem", "(", "spinnerIndex", ",", "itemIndex", ")", ";", "}" ]
Presses a Spinner (drop-down menu) item. @param spinnerIndex the index of the {@link Spinner} menu to use @param itemIndex the index of the {@link Spinner} item to press relative to the currently selected item. A Negative number moves up on the {@link Spinner}, positive moves down
[ "Presses", "a", "Spinner", "(", "drop", "-", "down", "menu", ")", "item", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1424-L1431
alkacon/opencms-core
src/org/opencms/lock/CmsLockManager.java
CmsLockManager.moveResource
public void moveResource(String source, String destination) { """ Moves a lock during the move resource operation.<p> @param source the source root path @param destination the destination root path """ CmsLock lock = OpenCms.getMemoryMonitor().getCachedLock(source); if (lock != null) { OpenCms.getMemoryMonitor().uncacheLock(lock.getResourceName()); CmsLock newLock = new CmsLock(destination, lock.getUserId(), lock.getProject(), lock.getType()); lock = lock.getRelatedLock(); if ((lock != null) && !lock.isNullLock()) { CmsLock relatedLock = new CmsLock(destination, lock.getUserId(), lock.getProject(), lock.getType()); newLock.setRelatedLock(relatedLock); } OpenCms.getMemoryMonitor().cacheLock(newLock); } }
java
public void moveResource(String source, String destination) { CmsLock lock = OpenCms.getMemoryMonitor().getCachedLock(source); if (lock != null) { OpenCms.getMemoryMonitor().uncacheLock(lock.getResourceName()); CmsLock newLock = new CmsLock(destination, lock.getUserId(), lock.getProject(), lock.getType()); lock = lock.getRelatedLock(); if ((lock != null) && !lock.isNullLock()) { CmsLock relatedLock = new CmsLock(destination, lock.getUserId(), lock.getProject(), lock.getType()); newLock.setRelatedLock(relatedLock); } OpenCms.getMemoryMonitor().cacheLock(newLock); } }
[ "public", "void", "moveResource", "(", "String", "source", ",", "String", "destination", ")", "{", "CmsLock", "lock", "=", "OpenCms", ".", "getMemoryMonitor", "(", ")", ".", "getCachedLock", "(", "source", ")", ";", "if", "(", "lock", "!=", "null", ")", "{", "OpenCms", ".", "getMemoryMonitor", "(", ")", ".", "uncacheLock", "(", "lock", ".", "getResourceName", "(", ")", ")", ";", "CmsLock", "newLock", "=", "new", "CmsLock", "(", "destination", ",", "lock", ".", "getUserId", "(", ")", ",", "lock", ".", "getProject", "(", ")", ",", "lock", ".", "getType", "(", ")", ")", ";", "lock", "=", "lock", ".", "getRelatedLock", "(", ")", ";", "if", "(", "(", "lock", "!=", "null", ")", "&&", "!", "lock", ".", "isNullLock", "(", ")", ")", "{", "CmsLock", "relatedLock", "=", "new", "CmsLock", "(", "destination", ",", "lock", ".", "getUserId", "(", ")", ",", "lock", ".", "getProject", "(", ")", ",", "lock", ".", "getType", "(", ")", ")", ";", "newLock", ".", "setRelatedLock", "(", "relatedLock", ")", ";", "}", "OpenCms", ".", "getMemoryMonitor", "(", ")", ".", "cacheLock", "(", "newLock", ")", ";", "}", "}" ]
Moves a lock during the move resource operation.<p> @param source the source root path @param destination the destination root path
[ "Moves", "a", "lock", "during", "the", "move", "resource", "operation", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/lock/CmsLockManager.java#L452-L465
pwittchen/prefser
library/src/main/java/com/github/pwittchen/prefser/library/rx2/Prefser.java
Prefser.observe
public <T> Observable<T> observe(@NonNull final String key, @NonNull final TypeToken<T> typeTokenOfT, final T defaultValue) { """ Gets value from SharedPreferences with a given key and type token as a RxJava Observable, which can be subscribed. If value is not found, we can return defaultValue. @param key key of the preference @param typeTokenOfT type token of T (e.g. {@code new TypeToken<List<String>> {}) @param defaultValue default value of the preference (e.g. "" or "undefined") @param <T> return type of the preference (e.g. String) @return Observable value from SharedPreferences associated with given key or default value """ Preconditions.checkNotNull(key, KEY_IS_NULL); Preconditions.checkNotNull(typeTokenOfT, TYPE_TOKEN_OF_T_IS_NULL); return observePreferences().filter(new Predicate<String>() { @Override public boolean test(@io.reactivex.annotations.NonNull String filteredKey) throws Exception { return key.equals(filteredKey); } }).map(new Function<String, T>() { @Override public T apply(@io.reactivex.annotations.NonNull String s) throws Exception { return get(key, typeTokenOfT, defaultValue); } }); }
java
public <T> Observable<T> observe(@NonNull final String key, @NonNull final TypeToken<T> typeTokenOfT, final T defaultValue) { Preconditions.checkNotNull(key, KEY_IS_NULL); Preconditions.checkNotNull(typeTokenOfT, TYPE_TOKEN_OF_T_IS_NULL); return observePreferences().filter(new Predicate<String>() { @Override public boolean test(@io.reactivex.annotations.NonNull String filteredKey) throws Exception { return key.equals(filteredKey); } }).map(new Function<String, T>() { @Override public T apply(@io.reactivex.annotations.NonNull String s) throws Exception { return get(key, typeTokenOfT, defaultValue); } }); }
[ "public", "<", "T", ">", "Observable", "<", "T", ">", "observe", "(", "@", "NonNull", "final", "String", "key", ",", "@", "NonNull", "final", "TypeToken", "<", "T", ">", "typeTokenOfT", ",", "final", "T", "defaultValue", ")", "{", "Preconditions", ".", "checkNotNull", "(", "key", ",", "KEY_IS_NULL", ")", ";", "Preconditions", ".", "checkNotNull", "(", "typeTokenOfT", ",", "TYPE_TOKEN_OF_T_IS_NULL", ")", ";", "return", "observePreferences", "(", ")", ".", "filter", "(", "new", "Predicate", "<", "String", ">", "(", ")", "{", "@", "Override", "public", "boolean", "test", "(", "@", "io", ".", "reactivex", ".", "annotations", ".", "NonNull", "String", "filteredKey", ")", "throws", "Exception", "{", "return", "key", ".", "equals", "(", "filteredKey", ")", ";", "}", "}", ")", ".", "map", "(", "new", "Function", "<", "String", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "T", "apply", "(", "@", "io", ".", "reactivex", ".", "annotations", ".", "NonNull", "String", "s", ")", "throws", "Exception", "{", "return", "get", "(", "key", ",", "typeTokenOfT", ",", "defaultValue", ")", ";", "}", "}", ")", ";", "}" ]
Gets value from SharedPreferences with a given key and type token as a RxJava Observable, which can be subscribed. If value is not found, we can return defaultValue. @param key key of the preference @param typeTokenOfT type token of T (e.g. {@code new TypeToken<List<String>> {}) @param defaultValue default value of the preference (e.g. "" or "undefined") @param <T> return type of the preference (e.g. String) @return Observable value from SharedPreferences associated with given key or default value
[ "Gets", "value", "from", "SharedPreferences", "with", "a", "given", "key", "and", "type", "token", "as", "a", "RxJava", "Observable", "which", "can", "be", "subscribed", ".", "If", "value", "is", "not", "found", "we", "can", "return", "defaultValue", "." ]
train
https://github.com/pwittchen/prefser/blob/7dc7f980eeb71fd5617f8c749050c2400e4fbb2f/library/src/main/java/com/github/pwittchen/prefser/library/rx2/Prefser.java#L204-L219