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
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Cryption.java
Cryption.interpret
public static String interpret(String text) { """ If the text is encrypted the decrypted value is returned. If the text is not encrypted to original text is returned. @param text the string values (encrypt or decrypted). Encrypted are prefixed with {cryption} @return if the value starts with the {cryption} prefix the encrypted value is return, else the given value is returned """ if (text == null) return null; if (isEncrypted(text)) { try { text = text.substring(CRYPTION_PREFIX.length()); text = getCanonical().decryptText(text); } catch (Exception e) { throw new ConfigException("Cannot interpret:" + text, e); } } return text; }
java
public static String interpret(String text) { if (text == null) return null; if (isEncrypted(text)) { try { text = text.substring(CRYPTION_PREFIX.length()); text = getCanonical().decryptText(text); } catch (Exception e) { throw new ConfigException("Cannot interpret:" + text, e); } } return text; }
[ "public", "static", "String", "interpret", "(", "String", "text", ")", "{", "if", "(", "text", "==", "null", ")", "return", "null", ";", "if", "(", "isEncrypted", "(", "text", ")", ")", "{", "try", "{", "text", "=", "text", ".", "substring", "(", "CRYPTION_PREFIX", ".", "length", "(", ")", ")", ";", "text", "=", "getCanonical", "(", ")", ".", "decryptText", "(", "text", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ConfigException", "(", "\"Cannot interpret:\"", "+", "text", ",", "e", ")", ";", "}", "}", "return", "text", ";", "}" ]
If the text is encrypted the decrypted value is returned. If the text is not encrypted to original text is returned. @param text the string values (encrypt or decrypted). Encrypted are prefixed with {cryption} @return if the value starts with the {cryption} prefix the encrypted value is return, else the given value is returned
[ "If", "the", "text", "is", "encrypted", "the", "decrypted", "value", "is", "returned", ".", "If", "the", "text", "is", "not", "encrypted", "to", "original", "text", "is", "returned", "." ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Cryption.java#L286-L305
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java
AnnotationTypeRequiredMemberBuilder.buildMemberComments
public void buildMemberComments(XMLNode node, Content annotationDocTree) { """ Build the comments for the member. Do nothing if {@link Configuration#nocomment} is set to true. @param node the XML element that specifies which components to document @param annotationDocTree the content tree to which the documentation will be added """ if(! configuration.nocomment) { writer.addComments(currentMember, annotationDocTree); } }
java
public void buildMemberComments(XMLNode node, Content annotationDocTree) { if(! configuration.nocomment) { writer.addComments(currentMember, annotationDocTree); } }
[ "public", "void", "buildMemberComments", "(", "XMLNode", "node", ",", "Content", "annotationDocTree", ")", "{", "if", "(", "!", "configuration", ".", "nocomment", ")", "{", "writer", ".", "addComments", "(", "currentMember", ",", "annotationDocTree", ")", ";", "}", "}" ]
Build the comments for the member. Do nothing if {@link Configuration#nocomment} is set to true. @param node the XML element that specifies which components to document @param annotationDocTree the content tree to which the documentation will be added
[ "Build", "the", "comments", "for", "the", "member", ".", "Do", "nothing", "if", "{", "@link", "Configuration#nocomment", "}", "is", "set", "to", "true", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java#L200-L204
h2oai/h2o-3
h2o-core/src/main/java/water/fvec/NewChunk.java
NewChunk.set_impl
@Override boolean set_impl(int i, long l) { """ in-range and refer to the inflated values of the original Chunk. """ if( _ds != null ) return set_impl(i,(double)l); if(_sparseLen != _len){ // sparse? int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0)i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } _ms.set(i,l); _xs.set(i,0); if(_missing != null)_missing.clear(i); _naCnt = -1; return true; }
java
@Override boolean set_impl(int i, long l) { if( _ds != null ) return set_impl(i,(double)l); if(_sparseLen != _len){ // sparse? int idx = Arrays.binarySearch(_id,0, _sparseLen,i); if(idx >= 0)i = idx; else cancel_sparse(); // for now don't bother setting the sparse value } _ms.set(i,l); _xs.set(i,0); if(_missing != null)_missing.clear(i); _naCnt = -1; return true; }
[ "@", "Override", "boolean", "set_impl", "(", "int", "i", ",", "long", "l", ")", "{", "if", "(", "_ds", "!=", "null", ")", "return", "set_impl", "(", "i", ",", "(", "double", ")", "l", ")", ";", "if", "(", "_sparseLen", "!=", "_len", ")", "{", "// sparse?", "int", "idx", "=", "Arrays", ".", "binarySearch", "(", "_id", ",", "0", ",", "_sparseLen", ",", "i", ")", ";", "if", "(", "idx", ">=", "0", ")", "i", "=", "idx", ";", "else", "cancel_sparse", "(", ")", ";", "// for now don't bother setting the sparse value", "}", "_ms", ".", "set", "(", "i", ",", "l", ")", ";", "_xs", ".", "set", "(", "i", ",", "0", ")", ";", "if", "(", "_missing", "!=", "null", ")", "_missing", ".", "clear", "(", "i", ")", ";", "_naCnt", "=", "-", "1", ";", "return", "true", ";", "}" ]
in-range and refer to the inflated values of the original Chunk.
[ "in", "-", "range", "and", "refer", "to", "the", "inflated", "values", "of", "the", "original", "Chunk", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/fvec/NewChunk.java#L1529-L1541
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.setGradientForVariableName
public void setGradientForVariableName(String variableName, SDVariable variable) { """ Assign a SDVariable to represent the gradient of the SDVariable with the specified name @param variableName the variable name to assign the gradient variable for @param variable the gradient variable """ Preconditions.checkState(variables.containsKey(variableName), "No variable exists with name \"%s\"", variableName); if (variable == null) { throw new ND4JIllegalStateException("Unable to set null gradient for variable name " + variableName); } variables.get(variableName).setGradient(variable); }
java
public void setGradientForVariableName(String variableName, SDVariable variable) { Preconditions.checkState(variables.containsKey(variableName), "No variable exists with name \"%s\"", variableName); if (variable == null) { throw new ND4JIllegalStateException("Unable to set null gradient for variable name " + variableName); } variables.get(variableName).setGradient(variable); }
[ "public", "void", "setGradientForVariableName", "(", "String", "variableName", ",", "SDVariable", "variable", ")", "{", "Preconditions", ".", "checkState", "(", "variables", ".", "containsKey", "(", "variableName", ")", ",", "\"No variable exists with name \\\"%s\\\"\"", ",", "variableName", ")", ";", "if", "(", "variable", "==", "null", ")", "{", "throw", "new", "ND4JIllegalStateException", "(", "\"Unable to set null gradient for variable name \"", "+", "variableName", ")", ";", "}", "variables", ".", "get", "(", "variableName", ")", ".", "setGradient", "(", "variable", ")", ";", "}" ]
Assign a SDVariable to represent the gradient of the SDVariable with the specified name @param variableName the variable name to assign the gradient variable for @param variable the gradient variable
[ "Assign", "a", "SDVariable", "to", "represent", "the", "gradient", "of", "the", "SDVariable", "with", "the", "specified", "name" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L2640-L2646
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java
DateControl.setDefaultCalendarProvider
public final void setDefaultCalendarProvider(Callback<DateControl, Calendar> provider) { """ Sets the value of {@link #defaultCalendarProviderProperty()}. @param provider the default calendar provider """ requireNonNull(provider); defaultCalendarProviderProperty().set(provider); }
java
public final void setDefaultCalendarProvider(Callback<DateControl, Calendar> provider) { requireNonNull(provider); defaultCalendarProviderProperty().set(provider); }
[ "public", "final", "void", "setDefaultCalendarProvider", "(", "Callback", "<", "DateControl", ",", "Calendar", ">", "provider", ")", "{", "requireNonNull", "(", "provider", ")", ";", "defaultCalendarProviderProperty", "(", ")", ".", "set", "(", "provider", ")", ";", "}" ]
Sets the value of {@link #defaultCalendarProviderProperty()}. @param provider the default calendar provider
[ "Sets", "the", "value", "of", "{", "@link", "#defaultCalendarProviderProperty", "()", "}", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/DateControl.java#L1383-L1386
clanie/clanie-core
src/main/java/dk/clanie/collections/NumberMap.java
NumberMap.newIntegerMap
public static <K> NumberMap<K, Integer> newIntegerMap() { """ Creates a NumberMap for Integers. @param <K> @return NumberMap&lt;K, Integer&gt; """ return new NumberMap<K, Integer>() { @Override public void add(K key, Integer addend) { put(key, containsKey(key) ? (get(key) + addend) : addend); } @Override public void sub(K key, Integer subtrahend) { put(key, (containsKey(key) ? get(key) : 0) - subtrahend); } }; }
java
public static <K> NumberMap<K, Integer> newIntegerMap() { return new NumberMap<K, Integer>() { @Override public void add(K key, Integer addend) { put(key, containsKey(key) ? (get(key) + addend) : addend); } @Override public void sub(K key, Integer subtrahend) { put(key, (containsKey(key) ? get(key) : 0) - subtrahend); } }; }
[ "public", "static", "<", "K", ">", "NumberMap", "<", "K", ",", "Integer", ">", "newIntegerMap", "(", ")", "{", "return", "new", "NumberMap", "<", "K", ",", "Integer", ">", "(", ")", "{", "@", "Override", "public", "void", "add", "(", "K", "key", ",", "Integer", "addend", ")", "{", "put", "(", "key", ",", "containsKey", "(", "key", ")", "?", "(", "get", "(", "key", ")", "+", "addend", ")", ":", "addend", ")", ";", "}", "@", "Override", "public", "void", "sub", "(", "K", "key", ",", "Integer", "subtrahend", ")", "{", "put", "(", "key", ",", "(", "containsKey", "(", "key", ")", "?", "get", "(", "key", ")", ":", "0", ")", "-", "subtrahend", ")", ";", "}", "}", ";", "}" ]
Creates a NumberMap for Integers. @param <K> @return NumberMap&lt;K, Integer&gt;
[ "Creates", "a", "NumberMap", "for", "Integers", "." ]
train
https://github.com/clanie/clanie-core/blob/ac8a655b93127f0e281b741c4d53f429be2816ad/src/main/java/dk/clanie/collections/NumberMap.java#L172-L183
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/spatialite/GTSpatialiteThreadsafeDb.java
GTSpatialiteThreadsafeDb.executeSqlFile
public void executeSqlFile( File file, int chunks, boolean eachLineAnSql ) throws Exception { """ Execute a insert/update sql file. @param file the file to run on this db. @param chunks commit interval. @throws Exception """ execOnConnection(mConn -> { boolean autoCommit = mConn.getAutoCommit(); mConn.setAutoCommit(false); Predicate<String> validSqlLine = s -> s.length() != 0 // && !s.startsWith("BEGIN") // && !s.startsWith("COMMIT") // ; Predicate<String> commentPredicate = s -> !s.startsWith("--"); try (IHMStatement pStmt = mConn.createStatement()) { final int[] counter = {1}; Stream<String> linesStream = null; if (eachLineAnSql) { linesStream = Files.lines(Paths.get(file.getAbsolutePath())).map(s -> s.trim()).filter(commentPredicate) .filter(validSqlLine); } else { linesStream = Arrays.stream(Files.lines(Paths.get(file.getAbsolutePath())).filter(commentPredicate) .collect(Collectors.joining()).split(";")).filter(validSqlLine); } Consumer<String> executeAction = s -> { try { pStmt.executeUpdate(s); counter[0]++; if (counter[0] % chunks == 0) { mConn.commit(); } } catch (Exception e) { throw new RuntimeException(e); } }; linesStream.forEach(executeAction); mConn.commit(); } mConn.setAutoCommit(autoCommit); return null; }); }
java
public void executeSqlFile( File file, int chunks, boolean eachLineAnSql ) throws Exception { execOnConnection(mConn -> { boolean autoCommit = mConn.getAutoCommit(); mConn.setAutoCommit(false); Predicate<String> validSqlLine = s -> s.length() != 0 // && !s.startsWith("BEGIN") // && !s.startsWith("COMMIT") // ; Predicate<String> commentPredicate = s -> !s.startsWith("--"); try (IHMStatement pStmt = mConn.createStatement()) { final int[] counter = {1}; Stream<String> linesStream = null; if (eachLineAnSql) { linesStream = Files.lines(Paths.get(file.getAbsolutePath())).map(s -> s.trim()).filter(commentPredicate) .filter(validSqlLine); } else { linesStream = Arrays.stream(Files.lines(Paths.get(file.getAbsolutePath())).filter(commentPredicate) .collect(Collectors.joining()).split(";")).filter(validSqlLine); } Consumer<String> executeAction = s -> { try { pStmt.executeUpdate(s); counter[0]++; if (counter[0] % chunks == 0) { mConn.commit(); } } catch (Exception e) { throw new RuntimeException(e); } }; linesStream.forEach(executeAction); mConn.commit(); } mConn.setAutoCommit(autoCommit); return null; }); }
[ "public", "void", "executeSqlFile", "(", "File", "file", ",", "int", "chunks", ",", "boolean", "eachLineAnSql", ")", "throws", "Exception", "{", "execOnConnection", "(", "mConn", "->", "{", "boolean", "autoCommit", "=", "mConn", ".", "getAutoCommit", "(", ")", ";", "mConn", ".", "setAutoCommit", "(", "false", ")", ";", "Predicate", "<", "String", ">", "validSqlLine", "=", "s", "->", "s", ".", "length", "(", ")", "!=", "0", "//", "&&", "!", "s", ".", "startsWith", "(", "\"BEGIN\"", ")", "//", "&&", "!", "s", ".", "startsWith", "(", "\"COMMIT\"", ")", "//", ";", "Predicate", "<", "String", ">", "commentPredicate", "=", "s", "->", "!", "s", ".", "startsWith", "(", "\"--\"", ")", ";", "try", "(", "IHMStatement", "pStmt", "=", "mConn", ".", "createStatement", "(", ")", ")", "{", "final", "int", "[", "]", "counter", "=", "{", "1", "}", ";", "Stream", "<", "String", ">", "linesStream", "=", "null", ";", "if", "(", "eachLineAnSql", ")", "{", "linesStream", "=", "Files", ".", "lines", "(", "Paths", ".", "get", "(", "file", ".", "getAbsolutePath", "(", ")", ")", ")", ".", "map", "(", "s", "->", "s", ".", "trim", "(", ")", ")", ".", "filter", "(", "commentPredicate", ")", ".", "filter", "(", "validSqlLine", ")", ";", "}", "else", "{", "linesStream", "=", "Arrays", ".", "stream", "(", "Files", ".", "lines", "(", "Paths", ".", "get", "(", "file", ".", "getAbsolutePath", "(", ")", ")", ")", ".", "filter", "(", "commentPredicate", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", ")", ")", ".", "split", "(", "\";\"", ")", ")", ".", "filter", "(", "validSqlLine", ")", ";", "}", "Consumer", "<", "String", ">", "executeAction", "=", "s", "->", "{", "try", "{", "pStmt", ".", "executeUpdate", "(", "s", ")", ";", "counter", "[", "0", "]", "++", ";", "if", "(", "counter", "[", "0", "]", "%", "chunks", "==", "0", ")", "{", "mConn", ".", "commit", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", ";", "linesStream", ".", "forEach", "(", "executeAction", ")", ";", "mConn", ".", "commit", "(", ")", ";", "}", "mConn", ".", "setAutoCommit", "(", "autoCommit", ")", ";", "return", "null", ";", "}", ")", ";", "}" ]
Execute a insert/update sql file. @param file the file to run on this db. @param chunks commit interval. @throws Exception
[ "Execute", "a", "insert", "/", "update", "sql", "file", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/spatialite/GTSpatialiteThreadsafeDb.java#L106-L147
strator-dev/greenpepper
greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java
ConfluenceGreenPepper.getSpecification
public Specification getSpecification(String spaceKey, String pageTitle) throws GreenPepperServerException { """ Retrieves the specification <p/> @param spaceKey Space Key @param pageTitle String pageTitle @return the specification. @throws com.greenpepper.server.GreenPepperServerException if any. """ Specification specification = Specification.newInstance(pageTitle); specification.setRepository(getHomeRepository(spaceKey)); return getGPServerService().getSpecification(specification); }
java
public Specification getSpecification(String spaceKey, String pageTitle) throws GreenPepperServerException { Specification specification = Specification.newInstance(pageTitle); specification.setRepository(getHomeRepository(spaceKey)); return getGPServerService().getSpecification(specification); }
[ "public", "Specification", "getSpecification", "(", "String", "spaceKey", ",", "String", "pageTitle", ")", "throws", "GreenPepperServerException", "{", "Specification", "specification", "=", "Specification", ".", "newInstance", "(", "pageTitle", ")", ";", "specification", ".", "setRepository", "(", "getHomeRepository", "(", "spaceKey", ")", ")", ";", "return", "getGPServerService", "(", ")", ".", "getSpecification", "(", "specification", ")", ";", "}" ]
Retrieves the specification <p/> @param spaceKey Space Key @param pageTitle String pageTitle @return the specification. @throws com.greenpepper.server.GreenPepperServerException if any.
[ "Retrieves", "the", "specification", "<p", "/", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L341-L345
VoltDB/voltdb
src/frontend/org/voltdb/PostgreSQLBackend.java
PostgreSQLBackend.runDDL
protected void runDDL(String ddl, boolean transformDdl) { """ Optionally, modifies DDL statements in such a way that PostgreSQL results will match VoltDB results; and then passes the remaining work to the base class version. """ String modifiedDdl = (transformDdl ? transformDDL(ddl) : ddl); printTransformedSql(ddl, modifiedDdl); super.runDDL(modifiedDdl); }
java
protected void runDDL(String ddl, boolean transformDdl) { String modifiedDdl = (transformDdl ? transformDDL(ddl) : ddl); printTransformedSql(ddl, modifiedDdl); super.runDDL(modifiedDdl); }
[ "protected", "void", "runDDL", "(", "String", "ddl", ",", "boolean", "transformDdl", ")", "{", "String", "modifiedDdl", "=", "(", "transformDdl", "?", "transformDDL", "(", "ddl", ")", ":", "ddl", ")", ";", "printTransformedSql", "(", "ddl", ",", "modifiedDdl", ")", ";", "super", ".", "runDDL", "(", "modifiedDdl", ")", ";", "}" ]
Optionally, modifies DDL statements in such a way that PostgreSQL results will match VoltDB results; and then passes the remaining work to the base class version.
[ "Optionally", "modifies", "DDL", "statements", "in", "such", "a", "way", "that", "PostgreSQL", "results", "will", "match", "VoltDB", "results", ";", "and", "then", "passes", "the", "remaining", "work", "to", "the", "base", "class", "version", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/PostgreSQLBackend.java#L601-L605
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryConversionsSingletonSpi.java
BaseMonetaryConversionsSingletonSpi.getConversion
public CurrencyConversion getConversion(CurrencyUnit termCurrency, String... providers) { """ Access an instance of {@link javax.money.convert.CurrencyConversion}. @param termCurrency the terminating/target currency unit, not null. @param providers the {@link javax.money.convert.ConversionQuery} provider names defines a corresponding provider chain that must be encapsulated by the resulting {@link javax .money.convert.CurrencyConversion}. By default the default provider chain as defined by #getDefaultRoundingProviderChain will be used. @return the corresponding conversion, not null. @throws javax.money.MonetaryException if no matching conversion could be found. @see #isConversionAvailable(javax.money.convert.ConversionQuery) """ return getConversion(ConversionQueryBuilder.of().setTermCurrency(termCurrency).setProviderNames(providers).build()); }
java
public CurrencyConversion getConversion(CurrencyUnit termCurrency, String... providers) { return getConversion(ConversionQueryBuilder.of().setTermCurrency(termCurrency).setProviderNames(providers).build()); }
[ "public", "CurrencyConversion", "getConversion", "(", "CurrencyUnit", "termCurrency", ",", "String", "...", "providers", ")", "{", "return", "getConversion", "(", "ConversionQueryBuilder", ".", "of", "(", ")", ".", "setTermCurrency", "(", "termCurrency", ")", ".", "setProviderNames", "(", "providers", ")", ".", "build", "(", ")", ")", ";", "}" ]
Access an instance of {@link javax.money.convert.CurrencyConversion}. @param termCurrency the terminating/target currency unit, not null. @param providers the {@link javax.money.convert.ConversionQuery} provider names defines a corresponding provider chain that must be encapsulated by the resulting {@link javax .money.convert.CurrencyConversion}. By default the default provider chain as defined by #getDefaultRoundingProviderChain will be used. @return the corresponding conversion, not null. @throws javax.money.MonetaryException if no matching conversion could be found. @see #isConversionAvailable(javax.money.convert.ConversionQuery)
[ "Access", "an", "instance", "of", "{", "@link", "javax", ".", "money", ".", "convert", ".", "CurrencyConversion", "}", "." ]
train
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryConversionsSingletonSpi.java#L179-L181
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPPUtility.java
MPPUtility.dumpBlockData
public static void dumpBlockData(int headerSize, int blockSize, byte[] data) { """ Dumps the contents of a structured block made up from a header and fixed sized records. @param headerSize header zie @param blockSize block size @param data data block """ if (data != null) { System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false)); int index = headerSize; while (index < data.length) { System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false)); index += blockSize; } } }
java
public static void dumpBlockData(int headerSize, int blockSize, byte[] data) { if (data != null) { System.out.println(ByteArrayHelper.hexdump(data, 0, headerSize, false)); int index = headerSize; while (index < data.length) { System.out.println(ByteArrayHelper.hexdump(data, index, blockSize, false)); index += blockSize; } } }
[ "public", "static", "void", "dumpBlockData", "(", "int", "headerSize", ",", "int", "blockSize", ",", "byte", "[", "]", "data", ")", "{", "if", "(", "data", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "ByteArrayHelper", ".", "hexdump", "(", "data", ",", "0", ",", "headerSize", ",", "false", ")", ")", ";", "int", "index", "=", "headerSize", ";", "while", "(", "index", "<", "data", ".", "length", ")", "{", "System", ".", "out", ".", "println", "(", "ByteArrayHelper", ".", "hexdump", "(", "data", ",", "index", ",", "blockSize", ",", "false", ")", ")", ";", "index", "+=", "blockSize", ";", "}", "}", "}" ]
Dumps the contents of a structured block made up from a header and fixed sized records. @param headerSize header zie @param blockSize block size @param data data block
[ "Dumps", "the", "contents", "of", "a", "structured", "block", "made", "up", "from", "a", "header", "and", "fixed", "sized", "records", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L1256-L1268
infinispan/infinispan
client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/SyncModeTransactionTable.java
SyncModeTransactionTable.createSynchronizationAdapter
private SynchronizationAdapter createSynchronizationAdapter(Transaction transaction) { """ Creates and registers the {@link SynchronizationAdapter} in the {@link Transaction}. """ SynchronizationAdapter adapter = new SynchronizationAdapter(transaction, RemoteXid.create(uuid)); try { transaction.registerSynchronization(adapter); } catch (RollbackException | SystemException e) { throw new CacheException(e); } if (trace) { log.tracef("Registered synchronization for transaction %s. Sync=%s", transaction, adapter); } return adapter; }
java
private SynchronizationAdapter createSynchronizationAdapter(Transaction transaction) { SynchronizationAdapter adapter = new SynchronizationAdapter(transaction, RemoteXid.create(uuid)); try { transaction.registerSynchronization(adapter); } catch (RollbackException | SystemException e) { throw new CacheException(e); } if (trace) { log.tracef("Registered synchronization for transaction %s. Sync=%s", transaction, adapter); } return adapter; }
[ "private", "SynchronizationAdapter", "createSynchronizationAdapter", "(", "Transaction", "transaction", ")", "{", "SynchronizationAdapter", "adapter", "=", "new", "SynchronizationAdapter", "(", "transaction", ",", "RemoteXid", ".", "create", "(", "uuid", ")", ")", ";", "try", "{", "transaction", ".", "registerSynchronization", "(", "adapter", ")", ";", "}", "catch", "(", "RollbackException", "|", "SystemException", "e", ")", "{", "throw", "new", "CacheException", "(", "e", ")", ";", "}", "if", "(", "trace", ")", "{", "log", ".", "tracef", "(", "\"Registered synchronization for transaction %s. Sync=%s\"", ",", "transaction", ",", "adapter", ")", ";", "}", "return", "adapter", ";", "}" ]
Creates and registers the {@link SynchronizationAdapter} in the {@link Transaction}.
[ "Creates", "and", "registers", "the", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/impl/transaction/SyncModeTransactionTable.java#L78-L89
the-fascinator/plugin-indexer-solr
src/main/java/com/googlecode/fascinator/indexer/SolrWrapperQueueConsumer.java
SolrWrapperQueueConsumer.addToBuffer
private void addToBuffer(String index, String document) { """ Add a new document into the buffer, and check if submission is required @param document : The Solr document to add to the buffer. """ if (timerMDC == null) { timerMDC = MDC.get("name"); } // Remove old entries from the buffer int removedSize = 0; if (docBuffer.containsKey(index)) { log.debug("Removing buffer duplicate: '{}'", index); removedSize = docBuffer.get(index).length(); docBuffer.remove(index); } int length = document.length() - removedSize; // If this is the first document in the buffer, record its age bufferYoungest = new Date().getTime(); if (docBuffer.isEmpty()) { bufferOldest = new Date().getTime(); log.debug("=== New buffer starting: {}", bufferOldest); } // Add to the buffer docBuffer.put(index, document); bufferSize += length; // Check if submission is required checkBuffer(); }
java
private void addToBuffer(String index, String document) { if (timerMDC == null) { timerMDC = MDC.get("name"); } // Remove old entries from the buffer int removedSize = 0; if (docBuffer.containsKey(index)) { log.debug("Removing buffer duplicate: '{}'", index); removedSize = docBuffer.get(index).length(); docBuffer.remove(index); } int length = document.length() - removedSize; // If this is the first document in the buffer, record its age bufferYoungest = new Date().getTime(); if (docBuffer.isEmpty()) { bufferOldest = new Date().getTime(); log.debug("=== New buffer starting: {}", bufferOldest); } // Add to the buffer docBuffer.put(index, document); bufferSize += length; // Check if submission is required checkBuffer(); }
[ "private", "void", "addToBuffer", "(", "String", "index", ",", "String", "document", ")", "{", "if", "(", "timerMDC", "==", "null", ")", "{", "timerMDC", "=", "MDC", ".", "get", "(", "\"name\"", ")", ";", "}", "// Remove old entries from the buffer", "int", "removedSize", "=", "0", ";", "if", "(", "docBuffer", ".", "containsKey", "(", "index", ")", ")", "{", "log", ".", "debug", "(", "\"Removing buffer duplicate: '{}'\"", ",", "index", ")", ";", "removedSize", "=", "docBuffer", ".", "get", "(", "index", ")", ".", "length", "(", ")", ";", "docBuffer", ".", "remove", "(", "index", ")", ";", "}", "int", "length", "=", "document", ".", "length", "(", ")", "-", "removedSize", ";", "// If this is the first document in the buffer, record its age", "bufferYoungest", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "if", "(", "docBuffer", ".", "isEmpty", "(", ")", ")", "{", "bufferOldest", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "log", ".", "debug", "(", "\"=== New buffer starting: {}\"", ",", "bufferOldest", ")", ";", "}", "// Add to the buffer", "docBuffer", ".", "put", "(", "index", ",", "document", ")", ";", "bufferSize", "+=", "length", ";", "// Check if submission is required", "checkBuffer", "(", ")", ";", "}" ]
Add a new document into the buffer, and check if submission is required @param document : The Solr document to add to the buffer.
[ "Add", "a", "new", "document", "into", "the", "buffer", "and", "check", "if", "submission", "is", "required" ]
train
https://github.com/the-fascinator/plugin-indexer-solr/blob/001159b18b78a87daa5d8b2a17ced28694bae156/src/main/java/com/googlecode/fascinator/indexer/SolrWrapperQueueConsumer.java#L441-L465
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/core/Parser.java
Parser.parseWithKeyword
public static boolean parseWithKeyword(final char[] query, int offset) { """ Parse string to check presence of WITH keyword regardless of case. @param query char[] of the query statement @param offset position of query to start checking @return boolean indicates presence of word """ if (query.length < (offset + 4)) { return false; } return (query[offset] | 32) == 'w' && (query[offset + 1] | 32) == 'i' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'h'; }
java
public static boolean parseWithKeyword(final char[] query, int offset) { if (query.length < (offset + 4)) { return false; } return (query[offset] | 32) == 'w' && (query[offset + 1] | 32) == 'i' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'h'; }
[ "public", "static", "boolean", "parseWithKeyword", "(", "final", "char", "[", "]", "query", ",", "int", "offset", ")", "{", "if", "(", "query", ".", "length", "<", "(", "offset", "+", "4", ")", ")", "{", "return", "false", ";", "}", "return", "(", "query", "[", "offset", "]", "|", "32", ")", "==", "'", "'", "&&", "(", "query", "[", "offset", "+", "1", "]", "|", "32", ")", "==", "'", "'", "&&", "(", "query", "[", "offset", "+", "2", "]", "|", "32", ")", "==", "'", "'", "&&", "(", "query", "[", "offset", "+", "3", "]", "|", "32", ")", "==", "'", "'", ";", "}" ]
Parse string to check presence of WITH keyword regardless of case. @param query char[] of the query statement @param offset position of query to start checking @return boolean indicates presence of word
[ "Parse", "string", "to", "check", "presence", "of", "WITH", "keyword", "regardless", "of", "case", "." ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L723-L732
deephacks/confit
api-model/src/main/java/org/deephacks/confit/model/Bean.java
Bean.addProperty
public void addProperty(final String propertyName, final String value) { """ Add a value to a property on this bean. @param propertyName name of the property as defined by the bean's schema. @param value final String representations of the property that conforms to its type as defined by the bean's schema. """ Preconditions.checkNotNull(propertyName); Preconditions.checkNotNull(value); List<String> values = properties.get(propertyName); if (values == null) { values = new ArrayList<>(); values.add(value); properties.put(propertyName, values); } else { values.add(value); } }
java
public void addProperty(final String propertyName, final String value) { Preconditions.checkNotNull(propertyName); Preconditions.checkNotNull(value); List<String> values = properties.get(propertyName); if (values == null) { values = new ArrayList<>(); values.add(value); properties.put(propertyName, values); } else { values.add(value); } }
[ "public", "void", "addProperty", "(", "final", "String", "propertyName", ",", "final", "String", "value", ")", "{", "Preconditions", ".", "checkNotNull", "(", "propertyName", ")", ";", "Preconditions", ".", "checkNotNull", "(", "value", ")", ";", "List", "<", "String", ">", "values", "=", "properties", ".", "get", "(", "propertyName", ")", ";", "if", "(", "values", "==", "null", ")", "{", "values", "=", "new", "ArrayList", "<>", "(", ")", ";", "values", ".", "add", "(", "value", ")", ";", "properties", ".", "put", "(", "propertyName", ",", "values", ")", ";", "}", "else", "{", "values", ".", "add", "(", "value", ")", ";", "}", "}" ]
Add a value to a property on this bean. @param propertyName name of the property as defined by the bean's schema. @param value final String representations of the property that conforms to its type as defined by the bean's schema.
[ "Add", "a", "value", "to", "a", "property", "on", "this", "bean", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-model/src/main/java/org/deephacks/confit/model/Bean.java#L163-L174
shrinkwrap/resolver
api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystemFactory.java
ResolverSystemFactory.createFromUserView
static <RESOLVERSYSTEMTYPE extends ResolverSystem> RESOLVERSYSTEMTYPE createFromUserView( final Class<RESOLVERSYSTEMTYPE> userViewClass) throws IllegalArgumentException { """ Creates a new {@link ResolverSystem} instance of the specified user view type using the {@link Thread} Context {@link ClassLoader}. Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} named "META-INF/services/$fullyQualfiedClassName" which should contain a key=value format with the key {@link ResolverSystemFactory#KEY_IMPL_CLASS_NAME}. The implementation class name must have a no-arg constructor. @param userViewClass The user view type @return The new {@link ResolverSystem} instance of the specified user view type created by using the {@link Thread} Context {@link ClassLoader}. @throws IllegalArgumentException If the user view class was not specified """ return createFromUserView(userViewClass, SecurityActions.getThreadContextClassLoader()); }
java
static <RESOLVERSYSTEMTYPE extends ResolverSystem> RESOLVERSYSTEMTYPE createFromUserView( final Class<RESOLVERSYSTEMTYPE> userViewClass) throws IllegalArgumentException { return createFromUserView(userViewClass, SecurityActions.getThreadContextClassLoader()); }
[ "static", "<", "RESOLVERSYSTEMTYPE", "extends", "ResolverSystem", ">", "RESOLVERSYSTEMTYPE", "createFromUserView", "(", "final", "Class", "<", "RESOLVERSYSTEMTYPE", ">", "userViewClass", ")", "throws", "IllegalArgumentException", "{", "return", "createFromUserView", "(", "userViewClass", ",", "SecurityActions", ".", "getThreadContextClassLoader", "(", ")", ")", ";", "}" ]
Creates a new {@link ResolverSystem} instance of the specified user view type using the {@link Thread} Context {@link ClassLoader}. Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} named "META-INF/services/$fullyQualfiedClassName" which should contain a key=value format with the key {@link ResolverSystemFactory#KEY_IMPL_CLASS_NAME}. The implementation class name must have a no-arg constructor. @param userViewClass The user view type @return The new {@link ResolverSystem} instance of the specified user view type created by using the {@link Thread} Context {@link ClassLoader}. @throws IllegalArgumentException If the user view class was not specified
[ "Creates", "a", "new", "{", "@link", "ResolverSystem", "}", "instance", "of", "the", "specified", "user", "view", "type", "using", "the", "{", "@link", "Thread", "}", "Context", "{", "@link", "ClassLoader", "}", ".", "Will", "consult", "a", "configuration", "file", "visible", "to", "the", "{", "@link", "Thread", "}", "Context", "{", "@link", "ClassLoader", "}", "named", "META", "-", "INF", "/", "services", "/", "$fullyQualfiedClassName", "which", "should", "contain", "a", "key", "=", "value", "format", "with", "the", "key", "{", "@link", "ResolverSystemFactory#KEY_IMPL_CLASS_NAME", "}", ".", "The", "implementation", "class", "name", "must", "have", "a", "no", "-", "arg", "constructor", "." ]
train
https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystemFactory.java#L52-L55
googleapis/google-cloud-java
google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/UpdateBuilder.java
UpdateBuilder.set
@Nonnull public T set(@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) { """ Overwrites the document referred to by this DocumentReference. If the document doesn't exist yet, it will be created. If a document already exists, it will be overwritten. @param documentReference The DocumentReference to overwrite. @param fields A map of the field paths and values for the document. @return The instance for chaining. """ return set(documentReference, fields, SetOptions.OVERWRITE); }
java
@Nonnull public T set(@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) { return set(documentReference, fields, SetOptions.OVERWRITE); }
[ "@", "Nonnull", "public", "T", "set", "(", "@", "Nonnull", "DocumentReference", "documentReference", ",", "@", "Nonnull", "Map", "<", "String", ",", "Object", ">", "fields", ")", "{", "return", "set", "(", "documentReference", ",", "fields", ",", "SetOptions", ".", "OVERWRITE", ")", ";", "}" ]
Overwrites the document referred to by this DocumentReference. If the document doesn't exist yet, it will be created. If a document already exists, it will be overwritten. @param documentReference The DocumentReference to overwrite. @param fields A map of the field paths and values for the document. @return The instance for chaining.
[ "Overwrites", "the", "document", "referred", "to", "by", "this", "DocumentReference", ".", "If", "the", "document", "doesn", "t", "exist", "yet", "it", "will", "be", "created", ".", "If", "a", "document", "already", "exists", "it", "will", "be", "overwritten", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/UpdateBuilder.java#L173-L176
lazy-koala/java-toolkit
fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java
TimeUtil.offsetDate
public static Date offsetDate(Date date, int calendarUnit, int dateOffset) { """ 将时间按照指定偏移单位和偏移量生成新的时间 <p>Function: offsetDate</p> <p>Description: </p> @param date @param calendarUnit @param dateOffset @return @author [email protected] @date 2015年6月18日 上午10:01:26 @version 1.0 """ if (date == null) { return null; } Calendar ca = Calendar.getInstance(); ca.setTime(date); ca.add(calendarUnit, dateOffset); return ca.getTime(); }
java
public static Date offsetDate(Date date, int calendarUnit, int dateOffset) { if (date == null) { return null; } Calendar ca = Calendar.getInstance(); ca.setTime(date); ca.add(calendarUnit, dateOffset); return ca.getTime(); }
[ "public", "static", "Date", "offsetDate", "(", "Date", "date", ",", "int", "calendarUnit", ",", "int", "dateOffset", ")", "{", "if", "(", "date", "==", "null", ")", "{", "return", "null", ";", "}", "Calendar", "ca", "=", "Calendar", ".", "getInstance", "(", ")", ";", "ca", ".", "setTime", "(", "date", ")", ";", "ca", ".", "add", "(", "calendarUnit", ",", "dateOffset", ")", ";", "return", "ca", ".", "getTime", "(", ")", ";", "}" ]
将时间按照指定偏移单位和偏移量生成新的时间 <p>Function: offsetDate</p> <p>Description: </p> @param date @param calendarUnit @param dateOffset @return @author [email protected] @date 2015年6月18日 上午10:01:26 @version 1.0
[ "将时间按照指定偏移单位和偏移量生成新的时间", "<p", ">", "Function", ":", "offsetDate<", "/", "p", ">", "<p", ">", "Description", ":", "<", "/", "p", ">" ]
train
https://github.com/lazy-koala/java-toolkit/blob/f46055fae0cc73049597a3708e515f5c6582d27a/fast-toolkit/src/main/java/com/thankjava/toolkit/core/utils/TimeUtil.java#L103-L113
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/NonObservingFSJobCatalog.java
NonObservingFSJobCatalog.put
@Override public synchronized void put(JobSpec jobSpec) { """ Allow user to programmatically add a new JobSpec. The method will materialized the jobSpec into real file. @param jobSpec The target JobSpec Object to be materialized. Noted that the URI return by getUri is a relative path. """ Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); try { long startTime = System.currentTimeMillis(); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobSpec.getUri()); boolean isUpdate = fs.exists(jobSpecPath); materializedJobSpec(jobSpecPath, jobSpec, this.fs); this.mutableMetrics.updatePutJobTime(startTime); if (isUpdate) { this.listeners.onUpdateJob(jobSpec); } else { this.listeners.onAddJob(jobSpec); } } catch (IOException e) { throw new RuntimeException("When persisting a new JobSpec, unexpected issues happen:" + e.getMessage()); } catch (JobSpecNotFoundException e) { throw new RuntimeException("When replacing a existed JobSpec, unexpected issue happen:" + e.getMessage()); } }
java
@Override public synchronized void put(JobSpec jobSpec) { Preconditions.checkState(state() == State.RUNNING, String.format("%s is not running.", this.getClass().getName())); Preconditions.checkNotNull(jobSpec); try { long startTime = System.currentTimeMillis(); Path jobSpecPath = getPathForURI(this.jobConfDirPath, jobSpec.getUri()); boolean isUpdate = fs.exists(jobSpecPath); materializedJobSpec(jobSpecPath, jobSpec, this.fs); this.mutableMetrics.updatePutJobTime(startTime); if (isUpdate) { this.listeners.onUpdateJob(jobSpec); } else { this.listeners.onAddJob(jobSpec); } } catch (IOException e) { throw new RuntimeException("When persisting a new JobSpec, unexpected issues happen:" + e.getMessage()); } catch (JobSpecNotFoundException e) { throw new RuntimeException("When replacing a existed JobSpec, unexpected issue happen:" + e.getMessage()); } }
[ "@", "Override", "public", "synchronized", "void", "put", "(", "JobSpec", "jobSpec", ")", "{", "Preconditions", ".", "checkState", "(", "state", "(", ")", "==", "State", ".", "RUNNING", ",", "String", ".", "format", "(", "\"%s is not running.\"", ",", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ")", ";", "Preconditions", ".", "checkNotNull", "(", "jobSpec", ")", ";", "try", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Path", "jobSpecPath", "=", "getPathForURI", "(", "this", ".", "jobConfDirPath", ",", "jobSpec", ".", "getUri", "(", ")", ")", ";", "boolean", "isUpdate", "=", "fs", ".", "exists", "(", "jobSpecPath", ")", ";", "materializedJobSpec", "(", "jobSpecPath", ",", "jobSpec", ",", "this", ".", "fs", ")", ";", "this", ".", "mutableMetrics", ".", "updatePutJobTime", "(", "startTime", ")", ";", "if", "(", "isUpdate", ")", "{", "this", ".", "listeners", ".", "onUpdateJob", "(", "jobSpec", ")", ";", "}", "else", "{", "this", ".", "listeners", ".", "onAddJob", "(", "jobSpec", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"When persisting a new JobSpec, unexpected issues happen:\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "JobSpecNotFoundException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"When replacing a existed JobSpec, unexpected issue happen:\"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Allow user to programmatically add a new JobSpec. The method will materialized the jobSpec into real file. @param jobSpec The target JobSpec Object to be materialized. Noted that the URI return by getUri is a relative path.
[ "Allow", "user", "to", "programmatically", "add", "a", "new", "JobSpec", ".", "The", "method", "will", "materialized", "the", "jobSpec", "into", "real", "file", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/job_catalog/NonObservingFSJobCatalog.java#L75-L96
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/utils/ImageSizeUtils.java
ImageSizeUtils.defineTargetSizeForView
public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) { """ Defines target size for image aware view. Size is defined by target {@link com.nostra13.universalimageloader.core.imageaware.ImageAware view} parameters, configuration parameters or device display dimensions.<br /> """ int width = imageAware.getWidth(); if (width <= 0) width = maxImageSize.getWidth(); int height = imageAware.getHeight(); if (height <= 0) height = maxImageSize.getHeight(); return new ImageSize(width, height); }
java
public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) { int width = imageAware.getWidth(); if (width <= 0) width = maxImageSize.getWidth(); int height = imageAware.getHeight(); if (height <= 0) height = maxImageSize.getHeight(); return new ImageSize(width, height); }
[ "public", "static", "ImageSize", "defineTargetSizeForView", "(", "ImageAware", "imageAware", ",", "ImageSize", "maxImageSize", ")", "{", "int", "width", "=", "imageAware", ".", "getWidth", "(", ")", ";", "if", "(", "width", "<=", "0", ")", "width", "=", "maxImageSize", ".", "getWidth", "(", ")", ";", "int", "height", "=", "imageAware", ".", "getHeight", "(", ")", ";", "if", "(", "height", "<=", "0", ")", "height", "=", "maxImageSize", ".", "getHeight", "(", ")", ";", "return", "new", "ImageSize", "(", "width", ",", "height", ")", ";", "}" ]
Defines target size for image aware view. Size is defined by target {@link com.nostra13.universalimageloader.core.imageaware.ImageAware view} parameters, configuration parameters or device display dimensions.<br />
[ "Defines", "target", "size", "for", "image", "aware", "view", ".", "Size", "is", "defined", "by", "target", "{" ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/utils/ImageSizeUtils.java#L53-L61
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/types/StringValue.java
StringValue.setValue
public void setValue(StringValue value, int offset, int len) { """ Sets the value of the StringValue to a substring of the given string. @param value The new string value. @param offset The position to start the substring. @param len The length of the substring. """ Validate.notNull(value); setValue(value.value, offset, len); }
java
public void setValue(StringValue value, int offset, int len) { Validate.notNull(value); setValue(value.value, offset, len); }
[ "public", "void", "setValue", "(", "StringValue", "value", ",", "int", "offset", ",", "int", "len", ")", "{", "Validate", ".", "notNull", "(", "value", ")", ";", "setValue", "(", "value", ".", "value", ",", "offset", ",", "len", ")", ";", "}" ]
Sets the value of the StringValue to a substring of the given string. @param value The new string value. @param offset The position to start the substring. @param len The length of the substring.
[ "Sets", "the", "value", "of", "the", "StringValue", "to", "a", "substring", "of", "the", "given", "string", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/types/StringValue.java#L166-L169
landawn/AbacusUtil
src/com/landawn/abacus/util/HBaseExecutor.java
HBaseExecutor.get
<T> T get(final Class<T> targetClass, final String tableName, final Object rowKey) throws UncheckedIOException { """ And it may cause error because the "Object" is ambiguous to any type. """ return get(targetClass, tableName, AnyGet.of(rowKey)); }
java
<T> T get(final Class<T> targetClass, final String tableName, final Object rowKey) throws UncheckedIOException { return get(targetClass, tableName, AnyGet.of(rowKey)); }
[ "<", "T", ">", "T", "get", "(", "final", "Class", "<", "T", ">", "targetClass", ",", "final", "String", "tableName", ",", "final", "Object", "rowKey", ")", "throws", "UncheckedIOException", "{", "return", "get", "(", "targetClass", ",", "tableName", ",", "AnyGet", ".", "of", "(", "rowKey", ")", ")", ";", "}" ]
And it may cause error because the "Object" is ambiguous to any type.
[ "And", "it", "may", "cause", "error", "because", "the", "Object", "is", "ambiguous", "to", "any", "type", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/HBaseExecutor.java#L802-L804
samskivert/samskivert
src/main/java/com/samskivert/util/ConfigUtil.java
ConfigUtil.getSystemProperty
public static int getSystemProperty (String key, int defval) { """ Obtains the specified system property via {@link System#getProperty}, parses it into an integer and returns the value. If the property is not set, the default value will be returned. If the property is not a properly formatted integer, an error will be logged and the default value will be returned. """ String valstr = System.getProperty(key); int value = defval; if (valstr != null) { try { value = Integer.parseInt(valstr); } catch (NumberFormatException nfe) { log.warning("'" + key + "' must be a numeric value", "value", valstr, "error", nfe); } } return value; }
java
public static int getSystemProperty (String key, int defval) { String valstr = System.getProperty(key); int value = defval; if (valstr != null) { try { value = Integer.parseInt(valstr); } catch (NumberFormatException nfe) { log.warning("'" + key + "' must be a numeric value", "value", valstr, "error", nfe); } } return value; }
[ "public", "static", "int", "getSystemProperty", "(", "String", "key", ",", "int", "defval", ")", "{", "String", "valstr", "=", "System", ".", "getProperty", "(", "key", ")", ";", "int", "value", "=", "defval", ";", "if", "(", "valstr", "!=", "null", ")", "{", "try", "{", "value", "=", "Integer", ".", "parseInt", "(", "valstr", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "log", ".", "warning", "(", "\"'\"", "+", "key", "+", "\"' must be a numeric value\"", ",", "\"value\"", ",", "valstr", ",", "\"error\"", ",", "nfe", ")", ";", "}", "}", "return", "value", ";", "}" ]
Obtains the specified system property via {@link System#getProperty}, parses it into an integer and returns the value. If the property is not set, the default value will be returned. If the property is not a properly formatted integer, an error will be logged and the default value will be returned.
[ "Obtains", "the", "specified", "system", "property", "via", "{" ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ConfigUtil.java#L29-L41
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/Compiler.java
Compiler.locationPathPattern
public Expression locationPathPattern(int opPos) throws TransformerException { """ Compile a location match pattern unit expression. @param opPos The current position in the m_opMap array. @return reference to {@link org.apache.xpath.patterns.StepPattern} instance. @throws TransformerException if a error occurs creating the Expression. """ opPos = getFirstChildPos(opPos); return stepPattern(opPos, 0, null); }
java
public Expression locationPathPattern(int opPos) throws TransformerException { opPos = getFirstChildPos(opPos); return stepPattern(opPos, 0, null); }
[ "public", "Expression", "locationPathPattern", "(", "int", "opPos", ")", "throws", "TransformerException", "{", "opPos", "=", "getFirstChildPos", "(", "opPos", ")", ";", "return", "stepPattern", "(", "opPos", ",", "0", ",", "null", ")", ";", "}" ]
Compile a location match pattern unit expression. @param opPos The current position in the m_opMap array. @return reference to {@link org.apache.xpath.patterns.StepPattern} instance. @throws TransformerException if a error occurs creating the Expression.
[ "Compile", "a", "location", "match", "pattern", "unit", "expression", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/Compiler.java#L724-L731
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java
LoadedClassCache.getClass
public static Class getClass(final ClassLoader cl, final String className) throws ClassNotFoundException { """ Returns a class object. If the class is new, a new Class object is created, otherwise the cached object is returned. @param cl the classloader @param className the class name @return the class object associated to the given class name * @throws ClassNotFoundException if the class can't be loaded """ if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); Class clazz = cd.getClass(className); if (clazz == null) { clazz = cl.loadClass(className); saveClass(cl, clazz); } return clazz; }
java
public static Class getClass(final ClassLoader cl, final String className) throws ClassNotFoundException { if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); Class clazz = cd.getClass(className); if (clazz == null) { clazz = cl.loadClass(className); saveClass(cl, clazz); } return clazz; }
[ "public", "static", "Class", "getClass", "(", "final", "ClassLoader", "cl", ",", "final", "String", "className", ")", "throws", "ClassNotFoundException", "{", "if", "(", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", "==", "null", ")", "{", "LOADED_PLUGINS", ".", "put", "(", "cl", ",", "new", "ClassesData", "(", ")", ")", ";", "}", "ClassesData", "cd", "=", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", ";", "Class", "clazz", "=", "cd", ".", "getClass", "(", "className", ")", ";", "if", "(", "clazz", "==", "null", ")", "{", "clazz", "=", "cl", ".", "loadClass", "(", "className", ")", ";", "saveClass", "(", "cl", ",", "clazz", ")", ";", "}", "return", "clazz", ";", "}" ]
Returns a class object. If the class is new, a new Class object is created, otherwise the cached object is returned. @param cl the classloader @param className the class name @return the class object associated to the given class name * @throws ClassNotFoundException if the class can't be loaded
[ "Returns", "a", "class", "object", ".", "If", "the", "class", "is", "new", "a", "new", "Class", "object", "is", "created", "otherwise", "the", "cached", "object", "is", "returned", "." ]
train
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java#L139-L152
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java
FeatureInfoBuilder.buildTableDataAndClose
public FeatureTableData buildTableDataAndClose(FeatureIndexResults results, double tolerance, LatLng clickLocation) { """ Build a feature results information message @param results feature index results @param tolerance distance tolerance @param clickLocation map click location @return feature table data or null if not results """ return buildTableDataAndClose(results, tolerance, clickLocation, null); }
java
public FeatureTableData buildTableDataAndClose(FeatureIndexResults results, double tolerance, LatLng clickLocation) { return buildTableDataAndClose(results, tolerance, clickLocation, null); }
[ "public", "FeatureTableData", "buildTableDataAndClose", "(", "FeatureIndexResults", "results", ",", "double", "tolerance", ",", "LatLng", "clickLocation", ")", "{", "return", "buildTableDataAndClose", "(", "results", ",", "tolerance", ",", "clickLocation", ",", "null", ")", ";", "}" ]
Build a feature results information message @param results feature index results @param tolerance distance tolerance @param clickLocation map click location @return feature table data or null if not results
[ "Build", "a", "feature", "results", "information", "message" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/FeatureInfoBuilder.java#L444-L446
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java
VirtualNetworkGatewayConnectionsInner.updateTagsAsync
public Observable<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) { """ Updates a virtual network gateway connection tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() { @Override public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() { @Override public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkGatewayConnectionInner", ">", "updateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayConnectionName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "updateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayConnectionName", ",", "tags", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "VirtualNetworkGatewayConnectionInner", ">", ",", "VirtualNetworkGatewayConnectionInner", ">", "(", ")", "{", "@", "Override", "public", "VirtualNetworkGatewayConnectionInner", "call", "(", "ServiceResponse", "<", "VirtualNetworkGatewayConnectionInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates a virtual network gateway connection tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "a", "virtual", "network", "gateway", "connection", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkGatewayConnectionsInner.java#L638-L645
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/UpdatePatchBaselineRequest.java
UpdatePatchBaselineRequest.getRejectedPatches
public java.util.List<String> getRejectedPatches() { """ <p> A list of explicitly rejected patches for the baseline. </p> <p> For information about accepted formats for lists of approved patches and rejected patches, see <a href= "https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html" >Package Name Formats for Approved and Rejected Patch Lists</a> in the <i>AWS Systems Manager User Guide</i>. </p> @return A list of explicitly rejected patches for the baseline.</p> <p> For information about accepted formats for lists of approved patches and rejected patches, see <a href= "https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html" >Package Name Formats for Approved and Rejected Patch Lists</a> in the <i>AWS Systems Manager User Guide</i>. """ if (rejectedPatches == null) { rejectedPatches = new com.amazonaws.internal.SdkInternalList<String>(); } return rejectedPatches; }
java
public java.util.List<String> getRejectedPatches() { if (rejectedPatches == null) { rejectedPatches = new com.amazonaws.internal.SdkInternalList<String>(); } return rejectedPatches; }
[ "public", "java", ".", "util", ".", "List", "<", "String", ">", "getRejectedPatches", "(", ")", "{", "if", "(", "rejectedPatches", "==", "null", ")", "{", "rejectedPatches", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "String", ">", "(", ")", ";", "}", "return", "rejectedPatches", ";", "}" ]
<p> A list of explicitly rejected patches for the baseline. </p> <p> For information about accepted formats for lists of approved patches and rejected patches, see <a href= "https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html" >Package Name Formats for Approved and Rejected Patch Lists</a> in the <i>AWS Systems Manager User Guide</i>. </p> @return A list of explicitly rejected patches for the baseline.</p> <p> For information about accepted formats for lists of approved patches and rejected patches, see <a href= "https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html" >Package Name Formats for Approved and Rejected Patch Lists</a> in the <i>AWS Systems Manager User Guide</i>.
[ "<p", ">", "A", "list", "of", "explicitly", "rejected", "patches", "for", "the", "baseline", ".", "<", "/", "p", ">", "<p", ">", "For", "information", "about", "accepted", "formats", "for", "lists", "of", "approved", "patches", "and", "rejected", "patches", "see", "<a", "href", "=", "https", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "systems", "-", "manager", "/", "latest", "/", "userguide", "/", "patch", "-", "manager", "-", "approved", "-", "rejected", "-", "package", "-", "name", "-", "formats", ".", "html", ">", "Package", "Name", "Formats", "for", "Approved", "and", "Rejected", "Patch", "Lists<", "/", "a", ">", "in", "the", "<i", ">", "AWS", "Systems", "Manager", "User", "Guide<", "/", "i", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/UpdatePatchBaselineRequest.java#L554-L559
cdk/cdk
base/valencycheck/src/main/java/org/openscience/cdk/tools/SaturationChecker.java
SaturationChecker.getCurrentMaxBondOrder
public double getCurrentMaxBondOrder(IAtom atom, IAtomContainer ac) throws CDKException { """ Returns the currently maximum formable bond order for this atom. @param atom The atom to be checked @param ac The AtomContainer that provides the context @return the currently maximum formable bond order for this atom """ IAtomType[] atomTypes = getAtomTypeFactory(atom.getBuilder()).getAtomTypes(atom.getSymbol()); if (atomTypes.length == 0) return 0; double bondOrderSum = ac.getBondOrderSum(atom); Integer hcount = atom.getImplicitHydrogenCount() == CDKConstants.UNSET ? 0 : atom.getImplicitHydrogenCount(); double max = 0; double current = 0; for (int f = 0; f < atomTypes.length; f++) { current = hcount + bondOrderSum; if (atomTypes[f].getBondOrderSum() - current > max) { max = atomTypes[f].getBondOrderSum() - current; } } return max; }
java
public double getCurrentMaxBondOrder(IAtom atom, IAtomContainer ac) throws CDKException { IAtomType[] atomTypes = getAtomTypeFactory(atom.getBuilder()).getAtomTypes(atom.getSymbol()); if (atomTypes.length == 0) return 0; double bondOrderSum = ac.getBondOrderSum(atom); Integer hcount = atom.getImplicitHydrogenCount() == CDKConstants.UNSET ? 0 : atom.getImplicitHydrogenCount(); double max = 0; double current = 0; for (int f = 0; f < atomTypes.length; f++) { current = hcount + bondOrderSum; if (atomTypes[f].getBondOrderSum() - current > max) { max = atomTypes[f].getBondOrderSum() - current; } } return max; }
[ "public", "double", "getCurrentMaxBondOrder", "(", "IAtom", "atom", ",", "IAtomContainer", "ac", ")", "throws", "CDKException", "{", "IAtomType", "[", "]", "atomTypes", "=", "getAtomTypeFactory", "(", "atom", ".", "getBuilder", "(", ")", ")", ".", "getAtomTypes", "(", "atom", ".", "getSymbol", "(", ")", ")", ";", "if", "(", "atomTypes", ".", "length", "==", "0", ")", "return", "0", ";", "double", "bondOrderSum", "=", "ac", ".", "getBondOrderSum", "(", "atom", ")", ";", "Integer", "hcount", "=", "atom", ".", "getImplicitHydrogenCount", "(", ")", "==", "CDKConstants", ".", "UNSET", "?", "0", ":", "atom", ".", "getImplicitHydrogenCount", "(", ")", ";", "double", "max", "=", "0", ";", "double", "current", "=", "0", ";", "for", "(", "int", "f", "=", "0", ";", "f", "<", "atomTypes", ".", "length", ";", "f", "++", ")", "{", "current", "=", "hcount", "+", "bondOrderSum", ";", "if", "(", "atomTypes", "[", "f", "]", ".", "getBondOrderSum", "(", ")", "-", "current", ">", "max", ")", "{", "max", "=", "atomTypes", "[", "f", "]", ".", "getBondOrderSum", "(", ")", "-", "current", ";", "}", "}", "return", "max", ";", "}" ]
Returns the currently maximum formable bond order for this atom. @param atom The atom to be checked @param ac The AtomContainer that provides the context @return the currently maximum formable bond order for this atom
[ "Returns", "the", "currently", "maximum", "formable", "bond", "order", "for", "this", "atom", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/valencycheck/src/main/java/org/openscience/cdk/tools/SaturationChecker.java#L226-L240
graylog-labs/syslog4j-graylog2
src/main/java/org/graylog2/syslog4j/impl/message/processor/structured/StructuredSyslogMessageProcessor.java
StructuredSyslogMessageProcessor.createSyslogHeader
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName) { """ /* (non-Javadoc) @see org.graylog2.syslog4j.SyslogMessageProcessorIF#createSyslogHeader(int, int, java.lang.String, boolean, boolean) This is compatible with RFC5424 protocol. RFC5424 does not allow flags of sendLocalTimestamp and sendLocalName be off and therefore the incoming flags will not be used in this method. """ return createSyslogHeaderInner(facility, level, localName, new Date()); }
java
public String createSyslogHeader(int facility, int level, String localName, boolean sendLocalTimestamp, boolean sendLocalName) { return createSyslogHeaderInner(facility, level, localName, new Date()); }
[ "public", "String", "createSyslogHeader", "(", "int", "facility", ",", "int", "level", ",", "String", "localName", ",", "boolean", "sendLocalTimestamp", ",", "boolean", "sendLocalName", ")", "{", "return", "createSyslogHeaderInner", "(", "facility", ",", "level", ",", "localName", ",", "new", "Date", "(", ")", ")", ";", "}" ]
/* (non-Javadoc) @see org.graylog2.syslog4j.SyslogMessageProcessorIF#createSyslogHeader(int, int, java.lang.String, boolean, boolean) This is compatible with RFC5424 protocol. RFC5424 does not allow flags of sendLocalTimestamp and sendLocalName be off and therefore the incoming flags will not be used in this method.
[ "/", "*", "(", "non", "-", "Javadoc", ")", "@see", "org", ".", "graylog2", ".", "syslog4j", ".", "SyslogMessageProcessorIF#createSyslogHeader", "(", "int", "int", "java", ".", "lang", ".", "String", "boolean", "boolean", ")" ]
train
https://github.com/graylog-labs/syslog4j-graylog2/blob/374bc20d77c3aaa36a68bec5125dd82ce0a88aab/src/main/java/org/graylog2/syslog4j/impl/message/processor/structured/StructuredSyslogMessageProcessor.java#L115-L117
googleads/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/utils/BatchJobUploader.java
BatchJobUploader.initiateResumableUpload
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException { """ Initiates the resumable upload by sending a request to Google Cloud Storage. @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob} @return the URI for the initiated resumable upload """ // This follows the Google Cloud Storage guidelines for initiating resumable uploads: // https://cloud.google.com/storage/docs/resumable-uploads-xml HttpRequestFactory requestFactory = httpTransport.createRequestFactory( req -> { HttpHeaders headers = createHttpHeaders(); headers.setContentLength(0L); headers.set("x-goog-resumable", "start"); req.setHeaders(headers); req.setLoggingEnabled(true); }); try { HttpRequest httpRequest = requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent()); HttpResponse response = httpRequest.execute(); if (response.getHeaders() == null || response.getHeaders().getLocation() == null) { throw new BatchJobException( "Initiate upload failed. Resumable upload URI was not in the response."); } return URI.create(response.getHeaders().getLocation()); } catch (IOException e) { throw new BatchJobException("Failed to initiate upload", e); } }
java
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException { // This follows the Google Cloud Storage guidelines for initiating resumable uploads: // https://cloud.google.com/storage/docs/resumable-uploads-xml HttpRequestFactory requestFactory = httpTransport.createRequestFactory( req -> { HttpHeaders headers = createHttpHeaders(); headers.setContentLength(0L); headers.set("x-goog-resumable", "start"); req.setHeaders(headers); req.setLoggingEnabled(true); }); try { HttpRequest httpRequest = requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent()); HttpResponse response = httpRequest.execute(); if (response.getHeaders() == null || response.getHeaders().getLocation() == null) { throw new BatchJobException( "Initiate upload failed. Resumable upload URI was not in the response."); } return URI.create(response.getHeaders().getLocation()); } catch (IOException e) { throw new BatchJobException("Failed to initiate upload", e); } }
[ "private", "URI", "initiateResumableUpload", "(", "URI", "batchJobUploadUrl", ")", "throws", "BatchJobException", "{", "// This follows the Google Cloud Storage guidelines for initiating resumable uploads:", "// https://cloud.google.com/storage/docs/resumable-uploads-xml", "HttpRequestFactory", "requestFactory", "=", "httpTransport", ".", "createRequestFactory", "(", "req", "->", "{", "HttpHeaders", "headers", "=", "createHttpHeaders", "(", ")", ";", "headers", ".", "setContentLength", "(", "0L", ")", ";", "headers", ".", "set", "(", "\"x-goog-resumable\"", ",", "\"start\"", ")", ";", "req", ".", "setHeaders", "(", "headers", ")", ";", "req", ".", "setLoggingEnabled", "(", "true", ")", ";", "}", ")", ";", "try", "{", "HttpRequest", "httpRequest", "=", "requestFactory", ".", "buildPostRequest", "(", "new", "GenericUrl", "(", "batchJobUploadUrl", ")", ",", "new", "EmptyContent", "(", ")", ")", ";", "HttpResponse", "response", "=", "httpRequest", ".", "execute", "(", ")", ";", "if", "(", "response", ".", "getHeaders", "(", ")", "==", "null", "||", "response", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", "==", "null", ")", "{", "throw", "new", "BatchJobException", "(", "\"Initiate upload failed. Resumable upload URI was not in the response.\"", ")", ";", "}", "return", "URI", ".", "create", "(", "response", ".", "getHeaders", "(", ")", ".", "getLocation", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "BatchJobException", "(", "\"Failed to initiate upload\"", ",", "e", ")", ";", "}", "}" ]
Initiates the resumable upload by sending a request to Google Cloud Storage. @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob} @return the URI for the initiated resumable upload
[ "Initiates", "the", "resumable", "upload", "by", "sending", "a", "request", "to", "Google", "Cloud", "Storage", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/utils/BatchJobUploader.java#L165-L190
ltearno/hexa.tools
hexa.css-maven-plugin/src/main/java/fr/lteconsulting/hexacssmaven/CssMapper.java
CssMapper.processFile
public static void processFile( String input, String mappingPath, String outputFile, boolean doPrune, Log log ) throws IOException { """ Process an input file @throws IOException In case there is a problem @param input The input file content @param mappingPath The file containing mapping information (lines in the form of newName=oldName) @param outputFile Path to the output file @param doPrune <code>true</code> if pruning unused CSS rules is needed @param log Maven logger """ Set<String> usedClassNames = new HashSet<>(); input = replaceClassNames( input, mappingPath, usedClassNames, log ); log.debug( usedClassNames.size() + " used css classes in the mapping file" ); log.debug( "used css classes : " + usedClassNames ); CssRewriter cssRewriter = new CssRewriter( usedClassNames, doPrune, log ); input = cssRewriter.process( input ); input += "\r\n// generated by HexaCss maven plugin, see http://www.lteconsulting.fr/hexacss"; writeFile( outputFile, input, log ); }
java
public static void processFile( String input, String mappingPath, String outputFile, boolean doPrune, Log log ) throws IOException { Set<String> usedClassNames = new HashSet<>(); input = replaceClassNames( input, mappingPath, usedClassNames, log ); log.debug( usedClassNames.size() + " used css classes in the mapping file" ); log.debug( "used css classes : " + usedClassNames ); CssRewriter cssRewriter = new CssRewriter( usedClassNames, doPrune, log ); input = cssRewriter.process( input ); input += "\r\n// generated by HexaCss maven plugin, see http://www.lteconsulting.fr/hexacss"; writeFile( outputFile, input, log ); }
[ "public", "static", "void", "processFile", "(", "String", "input", ",", "String", "mappingPath", ",", "String", "outputFile", ",", "boolean", "doPrune", ",", "Log", "log", ")", "throws", "IOException", "{", "Set", "<", "String", ">", "usedClassNames", "=", "new", "HashSet", "<>", "(", ")", ";", "input", "=", "replaceClassNames", "(", "input", ",", "mappingPath", ",", "usedClassNames", ",", "log", ")", ";", "log", ".", "debug", "(", "usedClassNames", ".", "size", "(", ")", "+", "\" used css classes in the mapping file\"", ")", ";", "log", ".", "debug", "(", "\"used css classes : \"", "+", "usedClassNames", ")", ";", "CssRewriter", "cssRewriter", "=", "new", "CssRewriter", "(", "usedClassNames", ",", "doPrune", ",", "log", ")", ";", "input", "=", "cssRewriter", ".", "process", "(", "input", ")", ";", "input", "+=", "\"\\r\\n// generated by HexaCss maven plugin, see http://www.lteconsulting.fr/hexacss\"", ";", "writeFile", "(", "outputFile", ",", "input", ",", "log", ")", ";", "}" ]
Process an input file @throws IOException In case there is a problem @param input The input file content @param mappingPath The file containing mapping information (lines in the form of newName=oldName) @param outputFile Path to the output file @param doPrune <code>true</code> if pruning unused CSS rules is needed @param log Maven logger
[ "Process", "an", "input", "file" ]
train
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.css-maven-plugin/src/main/java/fr/lteconsulting/hexacssmaven/CssMapper.java#L43-L58
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/bucket/BucketFlusher.java
BucketFlusher.createMarkerDocuments
private static Observable<List<String>> createMarkerDocuments(final ClusterFacade core, final String bucket) { """ Helper method to create marker documents for each partition. @param core the core reference. @param bucket the name of the bucket. @return a list of created flush marker IDs once they are completely upserted. """ return Observable .from(FLUSH_MARKERS) .flatMap(new Func1<String, Observable<UpsertResponse>>() { @Override public Observable<UpsertResponse> call(final String id) { return deferAndWatch(new Func1<Subscriber, Observable<? extends UpsertResponse>>() { @Override public Observable<? extends UpsertResponse> call(final Subscriber subscriber) { UpsertRequest request = new UpsertRequest(id, Unpooled.copiedBuffer(id, CharsetUtil.UTF_8), bucket); request.subscriber(subscriber); return core.send(request); } }); } }) .doOnNext(new Action1<UpsertResponse>() { @Override public void call(UpsertResponse response) { if (response.content() != null && response.content().refCnt() > 0) { response.content().release(); } } }) .last() .map(new Func1<UpsertResponse, List<String>>() { @Override public List<String> call(UpsertResponse response) { return FLUSH_MARKERS; } }); }
java
private static Observable<List<String>> createMarkerDocuments(final ClusterFacade core, final String bucket) { return Observable .from(FLUSH_MARKERS) .flatMap(new Func1<String, Observable<UpsertResponse>>() { @Override public Observable<UpsertResponse> call(final String id) { return deferAndWatch(new Func1<Subscriber, Observable<? extends UpsertResponse>>() { @Override public Observable<? extends UpsertResponse> call(final Subscriber subscriber) { UpsertRequest request = new UpsertRequest(id, Unpooled.copiedBuffer(id, CharsetUtil.UTF_8), bucket); request.subscriber(subscriber); return core.send(request); } }); } }) .doOnNext(new Action1<UpsertResponse>() { @Override public void call(UpsertResponse response) { if (response.content() != null && response.content().refCnt() > 0) { response.content().release(); } } }) .last() .map(new Func1<UpsertResponse, List<String>>() { @Override public List<String> call(UpsertResponse response) { return FLUSH_MARKERS; } }); }
[ "private", "static", "Observable", "<", "List", "<", "String", ">", ">", "createMarkerDocuments", "(", "final", "ClusterFacade", "core", ",", "final", "String", "bucket", ")", "{", "return", "Observable", ".", "from", "(", "FLUSH_MARKERS", ")", ".", "flatMap", "(", "new", "Func1", "<", "String", ",", "Observable", "<", "UpsertResponse", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "UpsertResponse", ">", "call", "(", "final", "String", "id", ")", "{", "return", "deferAndWatch", "(", "new", "Func1", "<", "Subscriber", ",", "Observable", "<", "?", "extends", "UpsertResponse", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "?", "extends", "UpsertResponse", ">", "call", "(", "final", "Subscriber", "subscriber", ")", "{", "UpsertRequest", "request", "=", "new", "UpsertRequest", "(", "id", ",", "Unpooled", ".", "copiedBuffer", "(", "id", ",", "CharsetUtil", ".", "UTF_8", ")", ",", "bucket", ")", ";", "request", ".", "subscriber", "(", "subscriber", ")", ";", "return", "core", ".", "send", "(", "request", ")", ";", "}", "}", ")", ";", "}", "}", ")", ".", "doOnNext", "(", "new", "Action1", "<", "UpsertResponse", ">", "(", ")", "{", "@", "Override", "public", "void", "call", "(", "UpsertResponse", "response", ")", "{", "if", "(", "response", ".", "content", "(", ")", "!=", "null", "&&", "response", ".", "content", "(", ")", ".", "refCnt", "(", ")", ">", "0", ")", "{", "response", ".", "content", "(", ")", ".", "release", "(", ")", ";", "}", "}", "}", ")", ".", "last", "(", ")", ".", "map", "(", "new", "Func1", "<", "UpsertResponse", ",", "List", "<", "String", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "String", ">", "call", "(", "UpsertResponse", "response", ")", "{", "return", "FLUSH_MARKERS", ";", "}", "}", ")", ";", "}" ]
Helper method to create marker documents for each partition. @param core the core reference. @param bucket the name of the bucket. @return a list of created flush marker IDs once they are completely upserted.
[ "Helper", "method", "to", "create", "marker", "documents", "for", "each", "partition", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/bucket/BucketFlusher.java#L118-L149
lightblueseas/swing-components
src/main/java/de/alpharogroup/swing/renderer/TableCellButtonRendererFactory.java
TableCellButtonRendererFactory.newTableCellButtonRenderer
public static TableCellButtonRenderer newTableCellButtonRenderer(String text) { """ Factory method for creating the new {@link TableCellButtonRenderer} with the given string @param text the text @return the new {@link TableCellButtonRenderer} """ return new TableCellButtonRenderer(null, null) { private static final long serialVersionUID = 1L; @Override protected String onSetText(final Object value) { String currentText = text; return currentText; } }; }
java
public static TableCellButtonRenderer newTableCellButtonRenderer(String text) { return new TableCellButtonRenderer(null, null) { private static final long serialVersionUID = 1L; @Override protected String onSetText(final Object value) { String currentText = text; return currentText; } }; }
[ "public", "static", "TableCellButtonRenderer", "newTableCellButtonRenderer", "(", "String", "text", ")", "{", "return", "new", "TableCellButtonRenderer", "(", "null", ",", "null", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "Override", "protected", "String", "onSetText", "(", "final", "Object", "value", ")", "{", "String", "currentText", "=", "text", ";", "return", "currentText", ";", "}", "}", ";", "}" ]
Factory method for creating the new {@link TableCellButtonRenderer} with the given string @param text the text @return the new {@link TableCellButtonRenderer}
[ "Factory", "method", "for", "creating", "the", "new", "{", "@link", "TableCellButtonRenderer", "}", "with", "the", "given", "string" ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/renderer/TableCellButtonRendererFactory.java#L40-L53
algolia/instantsearch-android
core/src/main/java/com/algolia/instantsearch/core/utils/JSONUtils.java
JSONUtils.getMapFromJSONPath
public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) { """ Gets a Map of attributes from a json object given a path to traverse. @param record a JSONObject to traverse. @param path the json path to follow. @return the attributes as a {@link HashMap}, or null if it was not found. """ return getObjectFromJSONPath(record, path); }
java
public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) { return getObjectFromJSONPath(record, path); }
[ "public", "static", "HashMap", "<", "String", ",", "String", ">", "getMapFromJSONPath", "(", "JSONObject", "record", ",", "String", "path", ")", "{", "return", "getObjectFromJSONPath", "(", "record", ",", "path", ")", ";", "}" ]
Gets a Map of attributes from a json object given a path to traverse. @param record a JSONObject to traverse. @param path the json path to follow. @return the attributes as a {@link HashMap}, or null if it was not found.
[ "Gets", "a", "Map", "of", "attributes", "from", "a", "json", "object", "given", "a", "path", "to", "traverse", "." ]
train
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/utils/JSONUtils.java#L33-L35
SpartaTech/sparta-spring-web-utils
src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java
PropertiesLoaderBuilder.addProperty
public PropertiesLoaderBuilder addProperty(String name, String value) { """ Adds a new property. Giving both name and value. This methods does not lookup in the Spring Context, it only adds property and value as given. @param name to be added in the properties @param value to be added in the properties @return PropertyLoaderBuilder to continue the builder chain """ props.put(name, value); return this; }
java
public PropertiesLoaderBuilder addProperty(String name, String value) { props.put(name, value); return this; }
[ "public", "PropertiesLoaderBuilder", "addProperty", "(", "String", "name", ",", "String", "value", ")", "{", "props", ".", "put", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a new property. Giving both name and value. This methods does not lookup in the Spring Context, it only adds property and value as given. @param name to be added in the properties @param value to be added in the properties @return PropertyLoaderBuilder to continue the builder chain
[ "Adds", "a", "new", "property", ".", "Giving", "both", "name", "and", "value", ".", "This", "methods", "does", "not", "lookup", "in", "the", "Spring", "Context", "it", "only", "adds", "property", "and", "value", "as", "given", "." ]
train
https://github.com/SpartaTech/sparta-spring-web-utils/blob/f5382474d46a6048d58707fc64e7936277e8b2ce/src/main/java/org/sparta/springwebutils/property/PropertiesLoaderBuilder.java#L58-L61
optimatika/ojAlgo-finance
src/main/java/org/ojalgo/finance/FinanceUtils.java
FinanceUtils.toGrowthFactorFromAnnualReturn
public static double toGrowthFactorFromAnnualReturn(double annualReturn, CalendarDateUnit growthFactorUnit) { """ GrowthFactor = exp(GrowthRate) @param annualReturn Annualised return (percentage per year) @param growthFactorUnit A growth factor unit @return A growth factor per unit (day, week, month, year...) """ double tmpAnnualGrowthFactor = PrimitiveMath.ONE + annualReturn; double tmpYearsPerGrowthFactorUnit = CalendarDateUnit.YEAR.convert(growthFactorUnit); return PrimitiveMath.POW.invoke(tmpAnnualGrowthFactor, tmpYearsPerGrowthFactorUnit); }
java
public static double toGrowthFactorFromAnnualReturn(double annualReturn, CalendarDateUnit growthFactorUnit) { double tmpAnnualGrowthFactor = PrimitiveMath.ONE + annualReturn; double tmpYearsPerGrowthFactorUnit = CalendarDateUnit.YEAR.convert(growthFactorUnit); return PrimitiveMath.POW.invoke(tmpAnnualGrowthFactor, tmpYearsPerGrowthFactorUnit); }
[ "public", "static", "double", "toGrowthFactorFromAnnualReturn", "(", "double", "annualReturn", ",", "CalendarDateUnit", "growthFactorUnit", ")", "{", "double", "tmpAnnualGrowthFactor", "=", "PrimitiveMath", ".", "ONE", "+", "annualReturn", ";", "double", "tmpYearsPerGrowthFactorUnit", "=", "CalendarDateUnit", ".", "YEAR", ".", "convert", "(", "growthFactorUnit", ")", ";", "return", "PrimitiveMath", ".", "POW", ".", "invoke", "(", "tmpAnnualGrowthFactor", ",", "tmpYearsPerGrowthFactorUnit", ")", ";", "}" ]
GrowthFactor = exp(GrowthRate) @param annualReturn Annualised return (percentage per year) @param growthFactorUnit A growth factor unit @return A growth factor per unit (day, week, month, year...)
[ "GrowthFactor", "=", "exp", "(", "GrowthRate", ")" ]
train
https://github.com/optimatika/ojAlgo-finance/blob/c8d3f7e1894d4263b7334bca3f4c060e466f8b15/src/main/java/org/ojalgo/finance/FinanceUtils.java#L444-L448
gwtbootstrap3/gwtbootstrap3-extras
src/main/java/org/gwtbootstrap3/extras/bootbox/client/options/DialogOptions.java
DialogOptions.addButton
public final void addButton(String label, String className) { """ Adds a custom button with a class name. @param label @param className """ addButton(label, className, SimpleCallback.DEFAULT_SIMPLE_CALLBACK); }
java
public final void addButton(String label, String className) { addButton(label, className, SimpleCallback.DEFAULT_SIMPLE_CALLBACK); }
[ "public", "final", "void", "addButton", "(", "String", "label", ",", "String", "className", ")", "{", "addButton", "(", "label", ",", "className", ",", "SimpleCallback", ".", "DEFAULT_SIMPLE_CALLBACK", ")", ";", "}" ]
Adds a custom button with a class name. @param label @param className
[ "Adds", "a", "custom", "button", "with", "a", "class", "name", "." ]
train
https://github.com/gwtbootstrap3/gwtbootstrap3-extras/blob/8e42aaffd2a082e9cb23a14c37a3c87b7cbdfa94/src/main/java/org/gwtbootstrap3/extras/bootbox/client/options/DialogOptions.java#L190-L192
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.findMemberType
Symbol findMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { """ Find qualified member type. @param env The current environment. @param site The original type from where the selection takes place. @param name The type's name. @param c The class to search for the member type. This is always a superclass or implemented interface of site's class. """ Symbol sym = findImmediateMemberType(env, site, name, c); if (sym != typeNotFound) return sym; return findInheritedMemberType(env, site, name, c); }
java
Symbol findMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { Symbol sym = findImmediateMemberType(env, site, name, c); if (sym != typeNotFound) return sym; return findInheritedMemberType(env, site, name, c); }
[ "Symbol", "findMemberType", "(", "Env", "<", "AttrContext", ">", "env", ",", "Type", "site", ",", "Name", "name", ",", "TypeSymbol", "c", ")", "{", "Symbol", "sym", "=", "findImmediateMemberType", "(", "env", ",", "site", ",", "name", ",", "c", ")", ";", "if", "(", "sym", "!=", "typeNotFound", ")", "return", "sym", ";", "return", "findInheritedMemberType", "(", "env", ",", "site", ",", "name", ",", "c", ")", ";", "}" ]
Find qualified member type. @param env The current environment. @param site The original type from where the selection takes place. @param name The type's name. @param c The class to search for the member type. This is always a superclass or implemented interface of site's class.
[ "Find", "qualified", "member", "type", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2221-L2232
f2prateek/dart
dart/src/main/java/dart/Dart.java
Dart.bindNavigationModel
public static void bindNavigationModel(Object target, Bundle source) { """ Inject fields annotated with {@link BindExtra} in the specified {@code target} using the {@code source} {@link android.os.Bundle} as the source. @param target Target class for field binding. @param source Bundle source on which extras will be looked up. @throws Dart.UnableToInjectException if binding could not be performed. """ bindNavigationModel(target, source, Finder.BUNDLE); }
java
public static void bindNavigationModel(Object target, Bundle source) { bindNavigationModel(target, source, Finder.BUNDLE); }
[ "public", "static", "void", "bindNavigationModel", "(", "Object", "target", ",", "Bundle", "source", ")", "{", "bindNavigationModel", "(", "target", ",", "source", ",", "Finder", ".", "BUNDLE", ")", ";", "}" ]
Inject fields annotated with {@link BindExtra} in the specified {@code target} using the {@code source} {@link android.os.Bundle} as the source. @param target Target class for field binding. @param source Bundle source on which extras will be looked up. @throws Dart.UnableToInjectException if binding could not be performed.
[ "Inject", "fields", "annotated", "with", "{", "@link", "BindExtra", "}", "in", "the", "specified", "{", "@code", "target", "}", "using", "the", "{", "@code", "source", "}", "{", "@link", "android", ".", "os", ".", "Bundle", "}", "as", "the", "source", "." ]
train
https://github.com/f2prateek/dart/blob/7163b1b148e5141817975ae7dad99d58a8589aeb/dart/src/main/java/dart/Dart.java#L117-L119
craterdog/java-security-framework
java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java
RsaCertificateManager.encodeSigningRequest
public String encodeSigningRequest(PKCS10CertificationRequest csr) { """ This method encodes a certificate signing request (CSR) into a string for transport purposes. This is a convenience method that really should be part of the <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle class in the signature. The java security framework does not have a similar class so it has been left out of the interface. @param csr The certificate signing request. @return The encoded certificate signing request string. """ logger.entry(); try (StringWriter swriter = new StringWriter(); PemWriter pwriter = new PemWriter(swriter)) { pwriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded())); pwriter.flush(); String result = swriter.toString(); logger.exit(); return result; } catch (IOException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a certificate signing request.", e); logger.error(exception.toString()); throw exception; } }
java
public String encodeSigningRequest(PKCS10CertificationRequest csr) { logger.entry(); try (StringWriter swriter = new StringWriter(); PemWriter pwriter = new PemWriter(swriter)) { pwriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded())); pwriter.flush(); String result = swriter.toString(); logger.exit(); return result; } catch (IOException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to encode a certificate signing request.", e); logger.error(exception.toString()); throw exception; } }
[ "public", "String", "encodeSigningRequest", "(", "PKCS10CertificationRequest", "csr", ")", "{", "logger", ".", "entry", "(", ")", ";", "try", "(", "StringWriter", "swriter", "=", "new", "StringWriter", "(", ")", ";", "PemWriter", "pwriter", "=", "new", "PemWriter", "(", "swriter", ")", ")", "{", "pwriter", ".", "writeObject", "(", "new", "PemObject", "(", "\"CERTIFICATE REQUEST\"", ",", "csr", ".", "getEncoded", "(", ")", ")", ")", ";", "pwriter", ".", "flush", "(", ")", ";", "String", "result", "=", "swriter", ".", "toString", "(", ")", ";", "logger", ".", "exit", "(", ")", ";", "return", "result", ";", "}", "catch", "(", "IOException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to encode a certificate signing request.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "}" ]
This method encodes a certificate signing request (CSR) into a string for transport purposes. This is a convenience method that really should be part of the <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle class in the signature. The java security framework does not have a similar class so it has been left out of the interface. @param csr The certificate signing request. @return The encoded certificate signing request string.
[ "This", "method", "encodes", "a", "certificate", "signing", "request", "(", "CSR", ")", "into", "a", "string", "for", "transport", "purposes", ".", "This", "is", "a", "convenience", "method", "that", "really", "should", "be", "part", "of", "the", "<code", ">", "CertificateManagement<", "/", "code", ">", "interface", "except", "that", "it", "depends", "on", "a", "Bouncy", "Castle", "class", "in", "the", "signature", ".", "The", "java", "security", "framework", "does", "not", "have", "a", "similar", "class", "so", "it", "has", "been", "left", "out", "of", "the", "interface", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-providers/src/main/java/craterdog/security/RsaCertificateManager.java#L220-L233
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
HtmlTree.CAPTION
public static HtmlTree CAPTION(Content body) { """ Generates a CAPTION tag with some content. @param body content for the tag @return an HtmlTree object for the CAPTION tag """ HtmlTree htmltree = new HtmlTree(HtmlTag.CAPTION, nullCheck(body)); return htmltree; }
java
public static HtmlTree CAPTION(Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.CAPTION, nullCheck(body)); return htmltree; }
[ "public", "static", "HtmlTree", "CAPTION", "(", "Content", "body", ")", "{", "HtmlTree", "htmltree", "=", "new", "HtmlTree", "(", "HtmlTag", ".", "CAPTION", ",", "nullCheck", "(", "body", ")", ")", ";", "return", "htmltree", ";", "}" ]
Generates a CAPTION tag with some content. @param body content for the tag @return an HtmlTree object for the CAPTION tag
[ "Generates", "a", "CAPTION", "tag", "with", "some", "content", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L288-L291
fuinorg/units4j
src/main/java/org/fuin/units4j/Units4JUtils.java
Units4JUtils.indexAllClasses
public static final void indexAllClasses(final Indexer indexer, final List<File> classFiles) { """ Index all class files in the given list. @param indexer Indexer to use. @param classFiles List of ".class" files. """ classFiles.forEach(file -> { try { final InputStream in = new FileInputStream(file); try { indexer.index(in); } finally { in.close(); } } catch (final IOException ex) { throw new RuntimeException(ex); } }); }
java
public static final void indexAllClasses(final Indexer indexer, final List<File> classFiles) { classFiles.forEach(file -> { try { final InputStream in = new FileInputStream(file); try { indexer.index(in); } finally { in.close(); } } catch (final IOException ex) { throw new RuntimeException(ex); } }); }
[ "public", "static", "final", "void", "indexAllClasses", "(", "final", "Indexer", "indexer", ",", "final", "List", "<", "File", ">", "classFiles", ")", "{", "classFiles", ".", "forEach", "(", "file", "->", "{", "try", "{", "final", "InputStream", "in", "=", "new", "FileInputStream", "(", "file", ")", ";", "try", "{", "indexer", ".", "index", "(", "in", ")", ";", "}", "finally", "{", "in", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "}", ")", ";", "}" ]
Index all class files in the given list. @param indexer Indexer to use. @param classFiles List of ".class" files.
[ "Index", "all", "class", "files", "in", "the", "given", "list", "." ]
train
https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/Units4JUtils.java#L386-L399
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/NLPSeg.java
NLPSeg.getNumericUnitComposedWord
private IWord getNumericUnitComposedWord(String numeric, IWord unitWord) { """ internal method to define the composed entity for numeric and unit word composed word @param numeric @param unitWord @return IWord """ IStringBuffer sb = new IStringBuffer(); sb.clear().append(numeric).append(unitWord.getValue()); IWord wd = new Word(sb.toString(), IWord.T_CJK_WORD); String[] entity = unitWord.getEntity(); int eIdx = ArrayUtil.startsWith(Entity.E_TIME_P, entity); if ( eIdx > -1 ) { sb.clear().append(entity[eIdx].replace("time.", "datetime.")); } else { sb.clear().append(Entity.E_NUC_PREFIX ).append(unitWord.getEntity(0)); } wd.setEntity(new String[] {sb.toString()}); wd.setPartSpeech(IWord.QUANTIFIER); sb.clear();sb = null; return wd; }
java
private IWord getNumericUnitComposedWord(String numeric, IWord unitWord) { IStringBuffer sb = new IStringBuffer(); sb.clear().append(numeric).append(unitWord.getValue()); IWord wd = new Word(sb.toString(), IWord.T_CJK_WORD); String[] entity = unitWord.getEntity(); int eIdx = ArrayUtil.startsWith(Entity.E_TIME_P, entity); if ( eIdx > -1 ) { sb.clear().append(entity[eIdx].replace("time.", "datetime.")); } else { sb.clear().append(Entity.E_NUC_PREFIX ).append(unitWord.getEntity(0)); } wd.setEntity(new String[] {sb.toString()}); wd.setPartSpeech(IWord.QUANTIFIER); sb.clear();sb = null; return wd; }
[ "private", "IWord", "getNumericUnitComposedWord", "(", "String", "numeric", ",", "IWord", "unitWord", ")", "{", "IStringBuffer", "sb", "=", "new", "IStringBuffer", "(", ")", ";", "sb", ".", "clear", "(", ")", ".", "append", "(", "numeric", ")", ".", "append", "(", "unitWord", ".", "getValue", "(", ")", ")", ";", "IWord", "wd", "=", "new", "Word", "(", "sb", ".", "toString", "(", ")", ",", "IWord", ".", "T_CJK_WORD", ")", ";", "String", "[", "]", "entity", "=", "unitWord", ".", "getEntity", "(", ")", ";", "int", "eIdx", "=", "ArrayUtil", ".", "startsWith", "(", "Entity", ".", "E_TIME_P", ",", "entity", ")", ";", "if", "(", "eIdx", ">", "-", "1", ")", "{", "sb", ".", "clear", "(", ")", ".", "append", "(", "entity", "[", "eIdx", "]", ".", "replace", "(", "\"time.\"", ",", "\"datetime.\"", ")", ")", ";", "}", "else", "{", "sb", ".", "clear", "(", ")", ".", "append", "(", "Entity", ".", "E_NUC_PREFIX", ")", ".", "append", "(", "unitWord", ".", "getEntity", "(", "0", ")", ")", ";", "}", "wd", ".", "setEntity", "(", "new", "String", "[", "]", "{", "sb", ".", "toString", "(", ")", "}", ")", ";", "wd", ".", "setPartSpeech", "(", "IWord", ".", "QUANTIFIER", ")", ";", "sb", ".", "clear", "(", ")", ";", "sb", "=", "null", ";", "return", "wd", ";", "}" ]
internal method to define the composed entity for numeric and unit word composed word @param numeric @param unitWord @return IWord
[ "internal", "method", "to", "define", "the", "composed", "entity", "for", "numeric", "and", "unit", "word", "composed", "word" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/tokenizer/NLPSeg.java#L398-L417
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTOutputStream.java
SRTOutputStream.write
public void write(byte[] b, int off, int len) throws IOException { """ This method was created in VisualAge. @param b byte[] @param off int @param len int """ if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"write", "Writing"); } if (_observer != null) _observer.alertFirstWrite(); _conn.write(b, off, len); }
java
public void write(byte[] b, int off, int len) throws IOException { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"write", "Writing"); } if (_observer != null) _observer.alertFirstWrite(); _conn.write(b, off, len); }
[ "public", "void", "write", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "com", ".", "ibm", ".", "ejs", ".", "ras", ".", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "//306998.15", "logger", ".", "logp", "(", "Level", ".", "FINE", ",", "CLASS_NAME", ",", "\"write\"", ",", "\"Writing\"", ")", ";", "}", "if", "(", "_observer", "!=", "null", ")", "_observer", ".", "alertFirstWrite", "(", ")", ";", "_conn", ".", "write", "(", "b", ",", "off", ",", "len", ")", ";", "}" ]
This method was created in VisualAge. @param b byte[] @param off int @param len int
[ "This", "method", "was", "created", "in", "VisualAge", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/srt/SRTOutputStream.java#L120-L129
aol/micro-server
micro-s3/src/main/java/com/oath/micro/server/s3/data/S3Utils.java
S3Utils.getInputStream
@Deprecated public InputStream getInputStream(String bucketName, String key, Supplier<File> tempFileSupplier) throws AmazonServiceException, AmazonClientException, InterruptedException, IOException { """ Method returns InputStream from S3Object. Multi-part download is used to get file. s3.tmp.dir property used to store temporary files. You can specify temporary file name by using tempFileSupplier object. @param bucketName @param key - @param tempFileSupplier - Supplier providing temporary filenames @return InputStream of @throws AmazonServiceException @throws AmazonClientException @throws InterruptedException @throws IOException @deprecated see ReadUtils """ return readUtils.getInputStream(bucketName, key, tempFileSupplier); }
java
@Deprecated public InputStream getInputStream(String bucketName, String key, Supplier<File> tempFileSupplier) throws AmazonServiceException, AmazonClientException, InterruptedException, IOException{ return readUtils.getInputStream(bucketName, key, tempFileSupplier); }
[ "@", "Deprecated", "public", "InputStream", "getInputStream", "(", "String", "bucketName", ",", "String", "key", ",", "Supplier", "<", "File", ">", "tempFileSupplier", ")", "throws", "AmazonServiceException", ",", "AmazonClientException", ",", "InterruptedException", ",", "IOException", "{", "return", "readUtils", ".", "getInputStream", "(", "bucketName", ",", "key", ",", "tempFileSupplier", ")", ";", "}" ]
Method returns InputStream from S3Object. Multi-part download is used to get file. s3.tmp.dir property used to store temporary files. You can specify temporary file name by using tempFileSupplier object. @param bucketName @param key - @param tempFileSupplier - Supplier providing temporary filenames @return InputStream of @throws AmazonServiceException @throws AmazonClientException @throws InterruptedException @throws IOException @deprecated see ReadUtils
[ "Method", "returns", "InputStream", "from", "S3Object", ".", "Multi", "-", "part", "download", "is", "used", "to", "get", "file", ".", "s3", ".", "tmp", ".", "dir", "property", "used", "to", "store", "temporary", "files", ".", "You", "can", "specify", "temporary", "file", "name", "by", "using", "tempFileSupplier", "object", "." ]
train
https://github.com/aol/micro-server/blob/5c7103c5b43d2f4d16350dbd2f9802af307c63f7/micro-s3/src/main/java/com/oath/micro/server/s3/data/S3Utils.java#L193-L196
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureFromHomographies.java
ProjectiveStructureFromHomographies.proccess
public boolean proccess(List<DMatrixRMaj> homographies_view0_to_viewI, List<List<PointIndex2D_F64>> observations , int totalFeatures ) { """ <p>Solves for camera matrices and scene structure.</p> Homographies from view i to 0:<br> x[0] = H*x[i] @param homographies_view0_to_viewI (Input) Homographies matching pixels from view i to view 0. @param observations (Input) Observed features in each view, except view 0. Indexes of points must be from 0 to totalFeatures-1 @param totalFeatures (Input) total number of features being solved for. Uses to sanity check input @return true if successful or false if it failed """ if( homographies_view0_to_viewI.size() != observations.size() ) { throw new IllegalArgumentException("Number of homographies and observations do not match"); } LowLevelMultiViewOps.computeNormalizationLL((List)observations,N); // Apply normalization to homographies this.homographies = homographies_view0_to_viewI; filterPointsOnPlaneAtInfinity(homographies, observations,totalFeatures); // compute some internal working variables and determine if there are enough observations to compute a // solution computeConstants(homographies_view0_to_viewI, filtered, totalFeatures); // Solve the problem constructLinearSystem(homographies, filtered); if( !svd.decompose(A)) return false; // get null vector. camera matrices and scene structure are extracted from B as requested SingularOps_DDRM.nullVector(svd,true,B); return true; }
java
public boolean proccess(List<DMatrixRMaj> homographies_view0_to_viewI, List<List<PointIndex2D_F64>> observations , int totalFeatures ) { if( homographies_view0_to_viewI.size() != observations.size() ) { throw new IllegalArgumentException("Number of homographies and observations do not match"); } LowLevelMultiViewOps.computeNormalizationLL((List)observations,N); // Apply normalization to homographies this.homographies = homographies_view0_to_viewI; filterPointsOnPlaneAtInfinity(homographies, observations,totalFeatures); // compute some internal working variables and determine if there are enough observations to compute a // solution computeConstants(homographies_view0_to_viewI, filtered, totalFeatures); // Solve the problem constructLinearSystem(homographies, filtered); if( !svd.decompose(A)) return false; // get null vector. camera matrices and scene structure are extracted from B as requested SingularOps_DDRM.nullVector(svd,true,B); return true; }
[ "public", "boolean", "proccess", "(", "List", "<", "DMatrixRMaj", ">", "homographies_view0_to_viewI", ",", "List", "<", "List", "<", "PointIndex2D_F64", ">", ">", "observations", ",", "int", "totalFeatures", ")", "{", "if", "(", "homographies_view0_to_viewI", ".", "size", "(", ")", "!=", "observations", ".", "size", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Number of homographies and observations do not match\"", ")", ";", "}", "LowLevelMultiViewOps", ".", "computeNormalizationLL", "(", "(", "List", ")", "observations", ",", "N", ")", ";", "// Apply normalization to homographies", "this", ".", "homographies", "=", "homographies_view0_to_viewI", ";", "filterPointsOnPlaneAtInfinity", "(", "homographies", ",", "observations", ",", "totalFeatures", ")", ";", "// compute some internal working variables and determine if there are enough observations to compute a", "// solution", "computeConstants", "(", "homographies_view0_to_viewI", ",", "filtered", ",", "totalFeatures", ")", ";", "// Solve the problem", "constructLinearSystem", "(", "homographies", ",", "filtered", ")", ";", "if", "(", "!", "svd", ".", "decompose", "(", "A", ")", ")", "return", "false", ";", "// get null vector. camera matrices and scene structure are extracted from B as requested", "SingularOps_DDRM", ".", "nullVector", "(", "svd", ",", "true", ",", "B", ")", ";", "return", "true", ";", "}" ]
<p>Solves for camera matrices and scene structure.</p> Homographies from view i to 0:<br> x[0] = H*x[i] @param homographies_view0_to_viewI (Input) Homographies matching pixels from view i to view 0. @param observations (Input) Observed features in each view, except view 0. Indexes of points must be from 0 to totalFeatures-1 @param totalFeatures (Input) total number of features being solved for. Uses to sanity check input @return true if successful or false if it failed
[ "<p", ">", "Solves", "for", "camera", "matrices", "and", "scene", "structure", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureFromHomographies.java#L108-L136
OpenTSDB/opentsdb
src/tree/Tree.java
Tree.addNotMatched
public void addNotMatched(final String tsuid, final String message) { """ Adds a TSUID to the not-matched local list when strict_matching is enabled. Must be synced with storage. @param tsuid TSUID to add to the set @throws IllegalArgumentException if the tsuid was invalid """ if (tsuid == null || tsuid.isEmpty()) { throw new IllegalArgumentException("Empty or null non matches not allowed"); } if (not_matched == null) { not_matched = new HashMap<String, String>(); } if (!not_matched.containsKey(tsuid)) { not_matched.put(tsuid, message); changed.put("not_matched", true); } }
java
public void addNotMatched(final String tsuid, final String message) { if (tsuid == null || tsuid.isEmpty()) { throw new IllegalArgumentException("Empty or null non matches not allowed"); } if (not_matched == null) { not_matched = new HashMap<String, String>(); } if (!not_matched.containsKey(tsuid)) { not_matched.put(tsuid, message); changed.put("not_matched", true); } }
[ "public", "void", "addNotMatched", "(", "final", "String", "tsuid", ",", "final", "String", "message", ")", "{", "if", "(", "tsuid", "==", "null", "||", "tsuid", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Empty or null non matches not allowed\"", ")", ";", "}", "if", "(", "not_matched", "==", "null", ")", "{", "not_matched", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "}", "if", "(", "!", "not_matched", ".", "containsKey", "(", "tsuid", ")", ")", "{", "not_matched", ".", "put", "(", "tsuid", ",", "message", ")", ";", "changed", ".", "put", "(", "\"not_matched\"", ",", "true", ")", ";", "}", "}" ]
Adds a TSUID to the not-matched local list when strict_matching is enabled. Must be synced with storage. @param tsuid TSUID to add to the set @throws IllegalArgumentException if the tsuid was invalid
[ "Adds", "a", "TSUID", "to", "the", "not", "-", "matched", "local", "list", "when", "strict_matching", "is", "enabled", ".", "Must", "be", "synced", "with", "storage", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tree/Tree.java#L291-L302
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.core/src/com/ibm/ws/ffdc/DiagnosticModule.java
DiagnosticModule.getDataForDirectives
public final void getDataForDirectives(String[] directives, Throwable ex, IncidentStream ffdcis, Object callerThis, Object[] catcherObjects, String sourceId) { """ Invoke all the ffdcdump methods for a set of directives @param directives The list of directives to be invoked @param ex The exception causing the incident @param ffdcis The incident stream on which to report @param callerThis The object reporting the incident @param catcherObjects Any additional interesting objects @param sourceId The sourceid of the class reporting the problem """ if (directives == null || directives.length <= 0 || !continueProcessing()) return; for (String s : directives) { String sName = s.toLowerCase(); for (Method m : _dumpMethods) { String mName = m.getName().toLowerCase(); if (mName.equals(sName)) { invokeDiagnosticMethod(m, ex, ffdcis, callerThis, catcherObjects, sourceId); break; } } if (!continueProcessing()) break; } }
java
public final void getDataForDirectives(String[] directives, Throwable ex, IncidentStream ffdcis, Object callerThis, Object[] catcherObjects, String sourceId) { if (directives == null || directives.length <= 0 || !continueProcessing()) return; for (String s : directives) { String sName = s.toLowerCase(); for (Method m : _dumpMethods) { String mName = m.getName().toLowerCase(); if (mName.equals(sName)) { invokeDiagnosticMethod(m, ex, ffdcis, callerThis, catcherObjects, sourceId); break; } } if (!continueProcessing()) break; } }
[ "public", "final", "void", "getDataForDirectives", "(", "String", "[", "]", "directives", ",", "Throwable", "ex", ",", "IncidentStream", "ffdcis", ",", "Object", "callerThis", ",", "Object", "[", "]", "catcherObjects", ",", "String", "sourceId", ")", "{", "if", "(", "directives", "==", "null", "||", "directives", ".", "length", "<=", "0", "||", "!", "continueProcessing", "(", ")", ")", "return", ";", "for", "(", "String", "s", ":", "directives", ")", "{", "String", "sName", "=", "s", ".", "toLowerCase", "(", ")", ";", "for", "(", "Method", "m", ":", "_dumpMethods", ")", "{", "String", "mName", "=", "m", ".", "getName", "(", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "mName", ".", "equals", "(", "sName", ")", ")", "{", "invokeDiagnosticMethod", "(", "m", ",", "ex", ",", "ffdcis", ",", "callerThis", ",", "catcherObjects", ",", "sourceId", ")", ";", "break", ";", "}", "}", "if", "(", "!", "continueProcessing", "(", ")", ")", "break", ";", "}", "}" ]
Invoke all the ffdcdump methods for a set of directives @param directives The list of directives to be invoked @param ex The exception causing the incident @param ffdcis The incident stream on which to report @param callerThis The object reporting the incident @param catcherObjects Any additional interesting objects @param sourceId The sourceid of the class reporting the problem
[ "Invoke", "all", "the", "ffdcdump", "methods", "for", "a", "set", "of", "directives" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/ws/ffdc/DiagnosticModule.java#L232-L249
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java
ExpressRouteCircuitsInner.beginListRoutesTableAsync
public Observable<ExpressRouteCircuitsRoutesTableListResultInner> beginListRoutesTableAsync(String resourceGroupName, String circuitName, String peeringName, String devicePath) { """ Gets the currently advertised routes table associated with the express route circuit in a resource group. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteCircuitsRoutesTableListResultInner object """ return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner>, ExpressRouteCircuitsRoutesTableListResultInner>() { @Override public ExpressRouteCircuitsRoutesTableListResultInner call(ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner> response) { return response.body(); } }); }
java
public Observable<ExpressRouteCircuitsRoutesTableListResultInner> beginListRoutesTableAsync(String resourceGroupName, String circuitName, String peeringName, String devicePath) { return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner>, ExpressRouteCircuitsRoutesTableListResultInner>() { @Override public ExpressRouteCircuitsRoutesTableListResultInner call(ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExpressRouteCircuitsRoutesTableListResultInner", ">", "beginListRoutesTableAsync", "(", "String", "resourceGroupName", ",", "String", "circuitName", ",", "String", "peeringName", ",", "String", "devicePath", ")", "{", "return", "beginListRoutesTableWithServiceResponseAsync", "(", "resourceGroupName", ",", "circuitName", ",", "peeringName", ",", "devicePath", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ExpressRouteCircuitsRoutesTableListResultInner", ">", ",", "ExpressRouteCircuitsRoutesTableListResultInner", ">", "(", ")", "{", "@", "Override", "public", "ExpressRouteCircuitsRoutesTableListResultInner", "call", "(", "ServiceResponse", "<", "ExpressRouteCircuitsRoutesTableListResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the currently advertised routes table associated with the express route circuit in a resource group. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param peeringName The name of the peering. @param devicePath The path of the device. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExpressRouteCircuitsRoutesTableListResultInner object
[ "Gets", "the", "currently", "advertised", "routes", "table", "associated", "with", "the", "express", "route", "circuit", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java#L1168-L1175
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.warnMissingProperty
@SuppressWarnings("unused") @Internal protected final void warnMissingProperty(Class type, String method, String property) { """ Allows printing warning messages produced by the compiler. @param type The type @param method The method @param property The property """ if (LOG.isWarnEnabled()) { LOG.warn("Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).", property, method, type); } }
java
@SuppressWarnings("unused") @Internal protected final void warnMissingProperty(Class type, String method, String property) { if (LOG.isWarnEnabled()) { LOG.warn("Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).", property, method, type); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "@", "Internal", "protected", "final", "void", "warnMissingProperty", "(", "Class", "type", ",", "String", "method", ",", "String", "property", ")", "{", "if", "(", "LOG", ".", "isWarnEnabled", "(", ")", ")", "{", "LOG", ".", "warn", "(", "\"Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library).\"", ",", "property", ",", "method", ",", "type", ")", ";", "}", "}" ]
Allows printing warning messages produced by the compiler. @param type The type @param method The method @param property The property
[ "Allows", "printing", "warning", "messages", "produced", "by", "the", "compiler", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L417-L423
xebia/Xebium
src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java
SeleniumDriverFixture.startBrowserOnUrlUsingRemoteServerOnHost
public void startBrowserOnUrlUsingRemoteServerOnHost(final String browser, final String browserUrl, final String serverHost) { """ <p><code> | start browser | <i>firefox</i> | on url | <i>http://localhost</i> | using remote server on host | <i>localhost</i> | </code></p> @param browser @param browserUrl @param serverHost @deprecated This call requires a Selenium 1 server. It is advised to use WebDriver. """ startBrowserOnUrlUsingRemoteServerOnHostOnPort(browser, browserUrl, serverHost, 4444); }
java
public void startBrowserOnUrlUsingRemoteServerOnHost(final String browser, final String browserUrl, final String serverHost) { startBrowserOnUrlUsingRemoteServerOnHostOnPort(browser, browserUrl, serverHost, 4444); }
[ "public", "void", "startBrowserOnUrlUsingRemoteServerOnHost", "(", "final", "String", "browser", ",", "final", "String", "browserUrl", ",", "final", "String", "serverHost", ")", "{", "startBrowserOnUrlUsingRemoteServerOnHostOnPort", "(", "browser", ",", "browserUrl", ",", "serverHost", ",", "4444", ")", ";", "}" ]
<p><code> | start browser | <i>firefox</i> | on url | <i>http://localhost</i> | using remote server on host | <i>localhost</i> | </code></p> @param browser @param browserUrl @param serverHost @deprecated This call requires a Selenium 1 server. It is advised to use WebDriver.
[ "<p", ">", "<code", ">", "|", "start", "browser", "|", "<i", ">", "firefox<", "/", "i", ">", "|", "on", "url", "|", "<i", ">", "http", ":", "//", "localhost<", "/", "i", ">", "|", "using", "remote", "server", "on", "host", "|", "<i", ">", "localhost<", "/", "i", ">", "|", "<", "/", "code", ">", "<", "/", "p", ">" ]
train
https://github.com/xebia/Xebium/blob/594f6d9e65622acdbd03dba0700b17645981da1f/src/main/java/com/xebia/incubator/xebium/SeleniumDriverFixture.java#L210-L212
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java
ProbeManagerImpl.createProbe
public synchronized ProbeImpl createProbe(Class<?> probedClass, String key, Constructor<?> ctor, Method method) { """ Create a new {@link ProbeImpl} with the specified information. @param probedClass the probe source @param key the unique name of the probe within the source class @param ctor the probed constructor or null @param method the probed method or null @param probeKind the kind of probe @return the new probe implementation """ ProbeImpl probeImpl = getProbe(probedClass, key); if (probeImpl == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "createProbe: " + key); } probeImpl = new ProbeImpl(this, probedClass, key, ctor, method); activeProbesById.put(Long.valueOf(probeImpl.getIdentifier()), probeImpl); Map<String, ProbeImpl> classProbes = probesByKey.get(probedClass); if (classProbes == null) { classProbes = new HashMap<String, ProbeImpl>(); probesByKey.put(probedClass, classProbes); } classProbes.put(key, probeImpl); } return probeImpl; }
java
public synchronized ProbeImpl createProbe(Class<?> probedClass, String key, Constructor<?> ctor, Method method) { ProbeImpl probeImpl = getProbe(probedClass, key); if (probeImpl == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "createProbe: " + key); } probeImpl = new ProbeImpl(this, probedClass, key, ctor, method); activeProbesById.put(Long.valueOf(probeImpl.getIdentifier()), probeImpl); Map<String, ProbeImpl> classProbes = probesByKey.get(probedClass); if (classProbes == null) { classProbes = new HashMap<String, ProbeImpl>(); probesByKey.put(probedClass, classProbes); } classProbes.put(key, probeImpl); } return probeImpl; }
[ "public", "synchronized", "ProbeImpl", "createProbe", "(", "Class", "<", "?", ">", "probedClass", ",", "String", "key", ",", "Constructor", "<", "?", ">", "ctor", ",", "Method", "method", ")", "{", "ProbeImpl", "probeImpl", "=", "getProbe", "(", "probedClass", ",", "key", ")", ";", "if", "(", "probeImpl", "==", "null", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "this", ",", "tc", ",", "\"createProbe: \"", "+", "key", ")", ";", "}", "probeImpl", "=", "new", "ProbeImpl", "(", "this", ",", "probedClass", ",", "key", ",", "ctor", ",", "method", ")", ";", "activeProbesById", ".", "put", "(", "Long", ".", "valueOf", "(", "probeImpl", ".", "getIdentifier", "(", ")", ")", ",", "probeImpl", ")", ";", "Map", "<", "String", ",", "ProbeImpl", ">", "classProbes", "=", "probesByKey", ".", "get", "(", "probedClass", ")", ";", "if", "(", "classProbes", "==", "null", ")", "{", "classProbes", "=", "new", "HashMap", "<", "String", ",", "ProbeImpl", ">", "(", ")", ";", "probesByKey", ".", "put", "(", "probedClass", ",", "classProbes", ")", ";", "}", "classProbes", ".", "put", "(", "key", ",", "probeImpl", ")", ";", "}", "return", "probeImpl", ";", "}" ]
Create a new {@link ProbeImpl} with the specified information. @param probedClass the probe source @param key the unique name of the probe within the source class @param ctor the probed constructor or null @param method the probed method or null @param probeKind the kind of probe @return the new probe implementation
[ "Create", "a", "new", "{", "@link", "ProbeImpl", "}", "with", "the", "specified", "information", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java#L636-L652
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/database/DBAccessFactory.java
DBAccessFactory.createDBAccess
public static IDBAccess createDBAccess(DBType dbType, Properties properties, String userId, String password) { """ create an IDBAccess (an accessor) for a specific database, supports authentication. @param dbType the type of database to access. Can be <br/>DBType.REMOTE or DBType.EMBEDDED or DBType.IN_MEMORY @param properties to configure the database connection. <br/>The appropriate database access class will pick the properties it needs. <br/>See also: DBProperties interface for required and optional properties. @param userId @param password @return an instance of IDBAccess """ return createDBAccess(dbType, properties, userId, password, null); }
java
public static IDBAccess createDBAccess(DBType dbType, Properties properties, String userId, String password) { return createDBAccess(dbType, properties, userId, password, null); }
[ "public", "static", "IDBAccess", "createDBAccess", "(", "DBType", "dbType", ",", "Properties", "properties", ",", "String", "userId", ",", "String", "password", ")", "{", "return", "createDBAccess", "(", "dbType", ",", "properties", ",", "userId", ",", "password", ",", "null", ")", ";", "}" ]
create an IDBAccess (an accessor) for a specific database, supports authentication. @param dbType the type of database to access. Can be <br/>DBType.REMOTE or DBType.EMBEDDED or DBType.IN_MEMORY @param properties to configure the database connection. <br/>The appropriate database access class will pick the properties it needs. <br/>See also: DBProperties interface for required and optional properties. @param userId @param password @return an instance of IDBAccess
[ "create", "an", "IDBAccess", "(", "an", "accessor", ")", "for", "a", "specific", "database", "supports", "authentication", "." ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/database/DBAccessFactory.java#L77-L80
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.displayMessageAtTheBeginningOfMethod
protected void displayMessageAtTheBeginningOfMethod(String methodName, String act, String concernedActivity, List<String> concernedActivities) { """ Displays message (concerned activity and list of authorized activities) at the beginning of method in logs. @param methodName is name of java method @param act is name of activity @param concernedActivity is concerned activity @param concernedActivities is a list of authorized activities """ logger.debug("{} {}: {} with {} concernedActivity(ies)", act, methodName, concernedActivity, concernedActivities.size()); int i = 0; for (final String activity : concernedActivities) { i++; logger.debug(" activity N°{}={}", i, activity); } }
java
protected void displayMessageAtTheBeginningOfMethod(String methodName, String act, String concernedActivity, List<String> concernedActivities) { logger.debug("{} {}: {} with {} concernedActivity(ies)", act, methodName, concernedActivity, concernedActivities.size()); int i = 0; for (final String activity : concernedActivities) { i++; logger.debug(" activity N°{}={}", i, activity); } }
[ "protected", "void", "displayMessageAtTheBeginningOfMethod", "(", "String", "methodName", ",", "String", "act", ",", "String", "concernedActivity", ",", "List", "<", "String", ">", "concernedActivities", ")", "{", "logger", ".", "debug", "(", "\"{} {}: {} with {} concernedActivity(ies)\"", ",", "act", ",", "methodName", ",", "concernedActivity", ",", "concernedActivities", ".", "size", "(", ")", ")", ";", "int", "i", "=", "0", ";", "for", "(", "final", "String", "activity", ":", "concernedActivities", ")", "{", "i", "++", ";", "logger", ".", "debug", "(", "\" activity N°{}={}\",", " ", ",", " ", "ctivity)", ";", "\r", "}", "}" ]
Displays message (concerned activity and list of authorized activities) at the beginning of method in logs. @param methodName is name of java method @param act is name of activity @param concernedActivity is concerned activity @param concernedActivities is a list of authorized activities
[ "Displays", "message", "(", "concerned", "activity", "and", "list", "of", "authorized", "activities", ")", "at", "the", "beginning", "of", "method", "in", "logs", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L825-L832
operasoftware/operaprestodriver
src/com/opera/core/systems/internal/StackHashMap.java
StackHashMap.putIfAbsent
public V putIfAbsent(K k, V v) { """ Puts a key to top of the map if absent if the key is present in stack it is removed @return the value if it is not contained, null otherwise """ synchronized (map) { if (!containsKey(k)) { list.addFirst(k); return map.put(k, v); } else { list.remove(k); } list.addFirst(k); return null; } }
java
public V putIfAbsent(K k, V v) { synchronized (map) { if (!containsKey(k)) { list.addFirst(k); return map.put(k, v); } else { list.remove(k); } list.addFirst(k); return null; } }
[ "public", "V", "putIfAbsent", "(", "K", "k", ",", "V", "v", ")", "{", "synchronized", "(", "map", ")", "{", "if", "(", "!", "containsKey", "(", "k", ")", ")", "{", "list", ".", "addFirst", "(", "k", ")", ";", "return", "map", ".", "put", "(", "k", ",", "v", ")", ";", "}", "else", "{", "list", ".", "remove", "(", "k", ")", ";", "}", "list", ".", "addFirst", "(", "k", ")", ";", "return", "null", ";", "}", "}" ]
Puts a key to top of the map if absent if the key is present in stack it is removed @return the value if it is not contained, null otherwise
[ "Puts", "a", "key", "to", "top", "of", "the", "map", "if", "absent", "if", "the", "key", "is", "present", "in", "stack", "it", "is", "removed" ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/internal/StackHashMap.java#L168-L179
Harium/keel
src/main/java/com/harium/keel/catalano/math/function/PerlinNoise.java
PerlinNoise.Function2D
public double Function2D(double x, double y) { """ 2-D Perlin noise function. @param x X Value. @param y Y Value. @return Returns function's value at point xy. """ double frequency = initFrequency; double amplitude = initAmplitude; double sum = 0; // octaves for (int i = 0; i < octaves; i++) { sum += SmoothedNoise(x * frequency, y * frequency) * amplitude; frequency *= 2; amplitude *= persistence; } return sum; }
java
public double Function2D(double x, double y) { double frequency = initFrequency; double amplitude = initAmplitude; double sum = 0; // octaves for (int i = 0; i < octaves; i++) { sum += SmoothedNoise(x * frequency, y * frequency) * amplitude; frequency *= 2; amplitude *= persistence; } return sum; }
[ "public", "double", "Function2D", "(", "double", "x", ",", "double", "y", ")", "{", "double", "frequency", "=", "initFrequency", ";", "double", "amplitude", "=", "initAmplitude", ";", "double", "sum", "=", "0", ";", "// octaves", "for", "(", "int", "i", "=", "0", ";", "i", "<", "octaves", ";", "i", "++", ")", "{", "sum", "+=", "SmoothedNoise", "(", "x", "*", "frequency", ",", "y", "*", "frequency", ")", "*", "amplitude", ";", "frequency", "*=", "2", ";", "amplitude", "*=", "persistence", ";", "}", "return", "sum", ";", "}" ]
2-D Perlin noise function. @param x X Value. @param y Y Value. @return Returns function's value at point xy.
[ "2", "-", "D", "Perlin", "noise", "function", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/function/PerlinNoise.java#L170-L183
trellis-ldp/trellis
components/webdav/src/main/java/org/trellisldp/webdav/impl/WebDAVUtils.java
WebDAVUtils.recursiveDelete
public static void recursiveDelete(final ServiceBundler services, final Session session, final IRI identifier, final String baseUrl) { """ Recursively delete resources under the given identifier. @param services the trellis services @param session the session @param identifier the identifier @param baseUrl the baseURL """ final List<IRI> resources = services.getResourceService().get(identifier) .thenApply(res -> res.stream(LDP.PreferContainment).map(Quad::getObject).filter(IRI.class::isInstance) .map(IRI.class::cast).collect(toList())).toCompletableFuture().join(); resources.forEach(id -> recursiveDelete(services, session, id, baseUrl)); resources.stream().parallel().map(id -> { final TrellisDataset immutable = TrellisDataset.createDataset(); services.getAuditService().creation(id, session).stream() .map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add); return services.getResourceService().delete(Metadata.builder(id).interactionModel(LDP.Resource) .container(identifier).build()) .thenCompose(future -> services.getResourceService().add(id, immutable.asDataset())) .whenComplete((a, b) -> immutable.close()) .thenAccept(future -> services.getEventService().emit(new SimpleEvent(externalUrl(id, baseUrl), session.getAgent(), asList(PROV.Activity, AS.Delete), singletonList(LDP.Resource)))); }) .map(CompletionStage::toCompletableFuture).forEach(CompletableFuture::join); }
java
public static void recursiveDelete(final ServiceBundler services, final Session session, final IRI identifier, final String baseUrl) { final List<IRI> resources = services.getResourceService().get(identifier) .thenApply(res -> res.stream(LDP.PreferContainment).map(Quad::getObject).filter(IRI.class::isInstance) .map(IRI.class::cast).collect(toList())).toCompletableFuture().join(); resources.forEach(id -> recursiveDelete(services, session, id, baseUrl)); resources.stream().parallel().map(id -> { final TrellisDataset immutable = TrellisDataset.createDataset(); services.getAuditService().creation(id, session).stream() .map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add); return services.getResourceService().delete(Metadata.builder(id).interactionModel(LDP.Resource) .container(identifier).build()) .thenCompose(future -> services.getResourceService().add(id, immutable.asDataset())) .whenComplete((a, b) -> immutable.close()) .thenAccept(future -> services.getEventService().emit(new SimpleEvent(externalUrl(id, baseUrl), session.getAgent(), asList(PROV.Activity, AS.Delete), singletonList(LDP.Resource)))); }) .map(CompletionStage::toCompletableFuture).forEach(CompletableFuture::join); }
[ "public", "static", "void", "recursiveDelete", "(", "final", "ServiceBundler", "services", ",", "final", "Session", "session", ",", "final", "IRI", "identifier", ",", "final", "String", "baseUrl", ")", "{", "final", "List", "<", "IRI", ">", "resources", "=", "services", ".", "getResourceService", "(", ")", ".", "get", "(", "identifier", ")", ".", "thenApply", "(", "res", "->", "res", ".", "stream", "(", "LDP", ".", "PreferContainment", ")", ".", "map", "(", "Quad", "::", "getObject", ")", ".", "filter", "(", "IRI", ".", "class", "::", "isInstance", ")", ".", "map", "(", "IRI", ".", "class", "::", "cast", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ".", "toCompletableFuture", "(", ")", ".", "join", "(", ")", ";", "resources", ".", "forEach", "(", "id", "->", "recursiveDelete", "(", "services", ",", "session", ",", "id", ",", "baseUrl", ")", ")", ";", "resources", ".", "stream", "(", ")", ".", "parallel", "(", ")", ".", "map", "(", "id", "->", "{", "final", "TrellisDataset", "immutable", "=", "TrellisDataset", ".", "createDataset", "(", ")", ";", "services", ".", "getAuditService", "(", ")", ".", "creation", "(", "id", ",", "session", ")", ".", "stream", "(", ")", ".", "map", "(", "skolemizeQuads", "(", "services", ".", "getResourceService", "(", ")", ",", "baseUrl", ")", ")", ".", "forEachOrdered", "(", "immutable", "::", "add", ")", ";", "return", "services", ".", "getResourceService", "(", ")", ".", "delete", "(", "Metadata", ".", "builder", "(", "id", ")", ".", "interactionModel", "(", "LDP", ".", "Resource", ")", ".", "container", "(", "identifier", ")", ".", "build", "(", ")", ")", ".", "thenCompose", "(", "future", "->", "services", ".", "getResourceService", "(", ")", ".", "add", "(", "id", ",", "immutable", ".", "asDataset", "(", ")", ")", ")", ".", "whenComplete", "(", "(", "a", ",", "b", ")", "->", "immutable", ".", "close", "(", ")", ")", ".", "thenAccept", "(", "future", "->", "services", ".", "getEventService", "(", ")", ".", "emit", "(", "new", "SimpleEvent", "(", "externalUrl", "(", "id", ",", "baseUrl", ")", ",", "session", ".", "getAgent", "(", ")", ",", "asList", "(", "PROV", ".", "Activity", ",", "AS", ".", "Delete", ")", ",", "singletonList", "(", "LDP", ".", "Resource", ")", ")", ")", ")", ";", "}", ")", ".", "map", "(", "CompletionStage", "::", "toCompletableFuture", ")", ".", "forEach", "(", "CompletableFuture", "::", "join", ")", ";", "}" ]
Recursively delete resources under the given identifier. @param services the trellis services @param session the session @param identifier the identifier @param baseUrl the baseURL
[ "Recursively", "delete", "resources", "under", "the", "given", "identifier", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/webdav/src/main/java/org/trellisldp/webdav/impl/WebDAVUtils.java#L65-L84
landawn/AbacusUtil
src/com/landawn/abacus/util/DateUtil.java
DateUtil.addMinutes
public static <T extends Calendar> T addMinutes(final T calendar, final int amount) { """ Adds a number of minutes to a calendar returning a new object. The original {@code Date} is unchanged. @param calendar the calendar, not null @param amount the amount to add, may be negative @return the new {@code Date} with the amount added @throws IllegalArgumentException if the calendar is null """ return roll(calendar, amount, CalendarUnit.MINUTE); }
java
public static <T extends Calendar> T addMinutes(final T calendar, final int amount) { return roll(calendar, amount, CalendarUnit.MINUTE); }
[ "public", "static", "<", "T", "extends", "Calendar", ">", "T", "addMinutes", "(", "final", "T", "calendar", ",", "final", "int", "amount", ")", "{", "return", "roll", "(", "calendar", ",", "amount", ",", "CalendarUnit", ".", "MINUTE", ")", ";", "}" ]
Adds a number of minutes to a calendar returning a new object. The original {@code Date} is unchanged. @param calendar the calendar, not null @param amount the amount to add, may be negative @return the new {@code Date} with the amount added @throws IllegalArgumentException if the calendar is null
[ "Adds", "a", "number", "of", "minutes", "to", "a", "calendar", "returning", "a", "new", "object", ".", "The", "original", "{", "@code", "Date", "}", "is", "unchanged", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L1133-L1135
kiswanij/jk-util
src/main/java/com/jk/util/JKDateTimeUtil.java
JKDateTimeUtil.compareTwoDates
public static CompareDates compareTwoDates(Date date1, Date date2) { """ Compare two dates. @param date1 the date 1 @param date2 the date 2 @return the compare dates """ Date d1 = new Date(date1.getTime());// to unify the format of the dates // before the compare Date d2 = new Date(date2.getTime()); if (d1.compareTo(d2) < 0) return CompareDates.DATE1_LESS_THAN_DATE2; else if (d1.compareTo(d2) > 0) return CompareDates.DATE1_GREATER_THAN_DATE2; else return CompareDates.DATE1_EQUAL_DATE2; }
java
public static CompareDates compareTwoDates(Date date1, Date date2) { Date d1 = new Date(date1.getTime());// to unify the format of the dates // before the compare Date d2 = new Date(date2.getTime()); if (d1.compareTo(d2) < 0) return CompareDates.DATE1_LESS_THAN_DATE2; else if (d1.compareTo(d2) > 0) return CompareDates.DATE1_GREATER_THAN_DATE2; else return CompareDates.DATE1_EQUAL_DATE2; }
[ "public", "static", "CompareDates", "compareTwoDates", "(", "Date", "date1", ",", "Date", "date2", ")", "{", "Date", "d1", "=", "new", "Date", "(", "date1", ".", "getTime", "(", ")", ")", ";", "// to unify the format of the dates\r", "// before the compare\r", "Date", "d2", "=", "new", "Date", "(", "date2", ".", "getTime", "(", ")", ")", ";", "if", "(", "d1", ".", "compareTo", "(", "d2", ")", "<", "0", ")", "return", "CompareDates", ".", "DATE1_LESS_THAN_DATE2", ";", "else", "if", "(", "d1", ".", "compareTo", "(", "d2", ")", ">", "0", ")", "return", "CompareDates", ".", "DATE1_GREATER_THAN_DATE2", ";", "else", "return", "CompareDates", ".", "DATE1_EQUAL_DATE2", ";", "}" ]
Compare two dates. @param date1 the date 1 @param date2 the date 2 @return the compare dates
[ "Compare", "two", "dates", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKDateTimeUtil.java#L203-L213
leancloud/java-sdk-all
android-sdk/mixpush-android/src/main/java/cn/leancloud/AVMixPushManager.java
AVMixPushManager.registerHMSPush
public static void registerHMSPush(Application application, String profile) { """ 初始化方法,建议在 Application onCreate 里面调用 @param application @param profile 华为推送配置 """ if (null == application) { throw new IllegalArgumentException("[HMS] context cannot be null."); } if (!isHuaweiPhone()) { printErrorLog("[HMS] register error, is not huawei phone!"); return; } if (!checkHuaweiManifest(application)) { printErrorLog("[HMS] register error, mainifest is incomplete!"); return; } hwDeviceProfile = profile; boolean hmsInitResult = com.huawei.android.hms.agent.HMSAgent.init(application); if (!hmsInitResult) { LOGGER.e("failed to init HMSAgent."); } LOGGER.d("[HMS] start register HMS push"); }
java
public static void registerHMSPush(Application application, String profile) { if (null == application) { throw new IllegalArgumentException("[HMS] context cannot be null."); } if (!isHuaweiPhone()) { printErrorLog("[HMS] register error, is not huawei phone!"); return; } if (!checkHuaweiManifest(application)) { printErrorLog("[HMS] register error, mainifest is incomplete!"); return; } hwDeviceProfile = profile; boolean hmsInitResult = com.huawei.android.hms.agent.HMSAgent.init(application); if (!hmsInitResult) { LOGGER.e("failed to init HMSAgent."); } LOGGER.d("[HMS] start register HMS push"); }
[ "public", "static", "void", "registerHMSPush", "(", "Application", "application", ",", "String", "profile", ")", "{", "if", "(", "null", "==", "application", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"[HMS] context cannot be null.\"", ")", ";", "}", "if", "(", "!", "isHuaweiPhone", "(", ")", ")", "{", "printErrorLog", "(", "\"[HMS] register error, is not huawei phone!\"", ")", ";", "return", ";", "}", "if", "(", "!", "checkHuaweiManifest", "(", "application", ")", ")", "{", "printErrorLog", "(", "\"[HMS] register error, mainifest is incomplete!\"", ")", ";", "return", ";", "}", "hwDeviceProfile", "=", "profile", ";", "boolean", "hmsInitResult", "=", "com", ".", "huawei", ".", "android", ".", "hms", ".", "agent", ".", "HMSAgent", ".", "init", "(", "application", ")", ";", "if", "(", "!", "hmsInitResult", ")", "{", "LOGGER", ".", "e", "(", "\"failed to init HMSAgent.\"", ")", ";", "}", "LOGGER", ".", "d", "(", "\"[HMS] start register HMS push\"", ")", ";", "}" ]
初始化方法,建议在 Application onCreate 里面调用 @param application @param profile 华为推送配置
[ "初始化方法,建议在", "Application", "onCreate", "里面调用" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/mixpush-android/src/main/java/cn/leancloud/AVMixPushManager.java#L107-L129
grpc/grpc-java
core/src/main/java/io/grpc/internal/AutoConfiguredLoadBalancerFactory.java
AutoConfiguredLoadBalancerFactory.selectLoadBalancerPolicy
@Nullable ConfigOrError selectLoadBalancerPolicy(Map<String, ?> serviceConfig) { """ Unlike a normal {@link LoadBalancer.Factory}, this accepts a full service config rather than the LoadBalancingConfig. @return null if no selection could be made. """ try { List<LbConfig> loadBalancerConfigs = null; if (serviceConfig != null) { List<Map<String, ?>> rawLbConfigs = ServiceConfigUtil.getLoadBalancingConfigsFromServiceConfig(serviceConfig); loadBalancerConfigs = ServiceConfigUtil.unwrapLoadBalancingConfigList(rawLbConfigs); } if (loadBalancerConfigs != null && !loadBalancerConfigs.isEmpty()) { List<String> policiesTried = new ArrayList<>(); for (LbConfig lbConfig : loadBalancerConfigs) { String policy = lbConfig.getPolicyName(); LoadBalancerProvider provider = registry.getProvider(policy); if (provider == null) { policiesTried.add(policy); } else { return ConfigOrError.fromConfig(new PolicySelection( provider, /* serverList= */ null, lbConfig.getRawConfigValue())); } } return ConfigOrError.fromError( Status.UNKNOWN.withDescription( "None of " + policiesTried + " specified by Service Config are available.")); } return null; } catch (RuntimeException e) { return ConfigOrError.fromError( Status.UNKNOWN.withDescription("can't parse load balancer configuration").withCause(e)); } }
java
@Nullable ConfigOrError selectLoadBalancerPolicy(Map<String, ?> serviceConfig) { try { List<LbConfig> loadBalancerConfigs = null; if (serviceConfig != null) { List<Map<String, ?>> rawLbConfigs = ServiceConfigUtil.getLoadBalancingConfigsFromServiceConfig(serviceConfig); loadBalancerConfigs = ServiceConfigUtil.unwrapLoadBalancingConfigList(rawLbConfigs); } if (loadBalancerConfigs != null && !loadBalancerConfigs.isEmpty()) { List<String> policiesTried = new ArrayList<>(); for (LbConfig lbConfig : loadBalancerConfigs) { String policy = lbConfig.getPolicyName(); LoadBalancerProvider provider = registry.getProvider(policy); if (provider == null) { policiesTried.add(policy); } else { return ConfigOrError.fromConfig(new PolicySelection( provider, /* serverList= */ null, lbConfig.getRawConfigValue())); } } return ConfigOrError.fromError( Status.UNKNOWN.withDescription( "None of " + policiesTried + " specified by Service Config are available.")); } return null; } catch (RuntimeException e) { return ConfigOrError.fromError( Status.UNKNOWN.withDescription("can't parse load balancer configuration").withCause(e)); } }
[ "@", "Nullable", "ConfigOrError", "selectLoadBalancerPolicy", "(", "Map", "<", "String", ",", "?", ">", "serviceConfig", ")", "{", "try", "{", "List", "<", "LbConfig", ">", "loadBalancerConfigs", "=", "null", ";", "if", "(", "serviceConfig", "!=", "null", ")", "{", "List", "<", "Map", "<", "String", ",", "?", ">", ">", "rawLbConfigs", "=", "ServiceConfigUtil", ".", "getLoadBalancingConfigsFromServiceConfig", "(", "serviceConfig", ")", ";", "loadBalancerConfigs", "=", "ServiceConfigUtil", ".", "unwrapLoadBalancingConfigList", "(", "rawLbConfigs", ")", ";", "}", "if", "(", "loadBalancerConfigs", "!=", "null", "&&", "!", "loadBalancerConfigs", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "String", ">", "policiesTried", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "LbConfig", "lbConfig", ":", "loadBalancerConfigs", ")", "{", "String", "policy", "=", "lbConfig", ".", "getPolicyName", "(", ")", ";", "LoadBalancerProvider", "provider", "=", "registry", ".", "getProvider", "(", "policy", ")", ";", "if", "(", "provider", "==", "null", ")", "{", "policiesTried", ".", "add", "(", "policy", ")", ";", "}", "else", "{", "return", "ConfigOrError", ".", "fromConfig", "(", "new", "PolicySelection", "(", "provider", ",", "/* serverList= */", "null", ",", "lbConfig", ".", "getRawConfigValue", "(", ")", ")", ")", ";", "}", "}", "return", "ConfigOrError", ".", "fromError", "(", "Status", ".", "UNKNOWN", ".", "withDescription", "(", "\"None of \"", "+", "policiesTried", "+", "\" specified by Service Config are available.\"", ")", ")", ";", "}", "return", "null", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "return", "ConfigOrError", ".", "fromError", "(", "Status", ".", "UNKNOWN", ".", "withDescription", "(", "\"can't parse load balancer configuration\"", ")", ".", "withCause", "(", "e", ")", ")", ";", "}", "}" ]
Unlike a normal {@link LoadBalancer.Factory}, this accepts a full service config rather than the LoadBalancingConfig. @return null if no selection could be made.
[ "Unlike", "a", "normal", "{", "@link", "LoadBalancer", ".", "Factory", "}", "this", "accepts", "a", "full", "service", "config", "rather", "than", "the", "LoadBalancingConfig", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/AutoConfiguredLoadBalancerFactory.java#L310-L342
katjahahn/PortEx
src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java
Visualizer.drawPixel
private void drawPixel(Color color, long fileOffset) { """ Draws a square pixel at fileOffset with color. @param color of the square pixel @param fileOffset file location that the square pixel represents """ long size = withMinLength(0); drawPixels(color, fileOffset, size); }
java
private void drawPixel(Color color, long fileOffset) { long size = withMinLength(0); drawPixels(color, fileOffset, size); }
[ "private", "void", "drawPixel", "(", "Color", "color", ",", "long", "fileOffset", ")", "{", "long", "size", "=", "withMinLength", "(", "0", ")", ";", "drawPixels", "(", "color", ",", "fileOffset", ",", "size", ")", ";", "}" ]
Draws a square pixel at fileOffset with color. @param color of the square pixel @param fileOffset file location that the square pixel represents
[ "Draws", "a", "square", "pixel", "at", "fileOffset", "with", "color", "." ]
train
https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java#L916-L919
census-instrumentation/opencensus-java
contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java
DropWizardMetrics.collectCounter
private Metric collectCounter(MetricName dropwizardMetric, Counter counter) { """ Returns a {@code Metric} collected from {@link Counter}. @param dropwizardMetric the metric name. @param counter the counter object to collect. @return a {@code Metric}. """ String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter"); String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter); AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels = DropWizardUtils.generateLabels(dropwizardMetric); MetricDescriptor metricDescriptor = MetricDescriptor.create( metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey()); TimeSeries timeSeries = TimeSeries.createWithOnePoint( labels.getValue(), Point.create(Value.longValue(counter.getCount()), clock.now()), null); return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries); }
java
private Metric collectCounter(MetricName dropwizardMetric, Counter counter) { String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "counter"); String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), counter); AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels = DropWizardUtils.generateLabels(dropwizardMetric); MetricDescriptor metricDescriptor = MetricDescriptor.create( metricName, metricDescription, DEFAULT_UNIT, Type.GAUGE_INT64, labels.getKey()); TimeSeries timeSeries = TimeSeries.createWithOnePoint( labels.getValue(), Point.create(Value.longValue(counter.getCount()), clock.now()), null); return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries); }
[ "private", "Metric", "collectCounter", "(", "MetricName", "dropwizardMetric", ",", "Counter", "counter", ")", "{", "String", "metricName", "=", "DropWizardUtils", ".", "generateFullMetricName", "(", "dropwizardMetric", ".", "getKey", "(", ")", ",", "\"counter\"", ")", ";", "String", "metricDescription", "=", "DropWizardUtils", ".", "generateFullMetricDescription", "(", "dropwizardMetric", ".", "getKey", "(", ")", ",", "counter", ")", ";", "AbstractMap", ".", "SimpleImmutableEntry", "<", "List", "<", "LabelKey", ">", ",", "List", "<", "LabelValue", ">", ">", "labels", "=", "DropWizardUtils", ".", "generateLabels", "(", "dropwizardMetric", ")", ";", "MetricDescriptor", "metricDescriptor", "=", "MetricDescriptor", ".", "create", "(", "metricName", ",", "metricDescription", ",", "DEFAULT_UNIT", ",", "Type", ".", "GAUGE_INT64", ",", "labels", ".", "getKey", "(", ")", ")", ";", "TimeSeries", "timeSeries", "=", "TimeSeries", ".", "createWithOnePoint", "(", "labels", ".", "getValue", "(", ")", ",", "Point", ".", "create", "(", "Value", ".", "longValue", "(", "counter", ".", "getCount", "(", ")", ")", ",", "clock", ".", "now", "(", ")", ")", ",", "null", ")", ";", "return", "Metric", ".", "createWithOneTimeSeries", "(", "metricDescriptor", ",", "timeSeries", ")", ";", "}" ]
Returns a {@code Metric} collected from {@link Counter}. @param dropwizardMetric the metric name. @param counter the counter object to collect. @return a {@code Metric}.
[ "Returns", "a", "{", "@code", "Metric", "}", "collected", "from", "{", "@link", "Counter", "}", "." ]
train
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/dropwizard5/src/main/java/io/opencensus/contrib/dropwizard5/DropWizardMetrics.java#L143-L162
square/picasso
picasso/src/main/java/com/squareup/picasso3/Picasso.java
Picasso.cancelTag
public void cancelTag(@NonNull Object tag) { """ Cancel any existing requests with given tag. You can set a tag on new requests with {@link RequestCreator#tag(Object)}. @see RequestCreator#tag(Object) """ checkMain(); checkNotNull(tag, "tag == null"); List<Action> actions = new ArrayList<>(targetToAction.values()); //noinspection ForLoopReplaceableByForEach for (int i = 0, n = actions.size(); i < n; i++) { Action action = actions.get(i); if (tag.equals(action.getTag())) { cancelExistingRequest(action.getTarget()); } } List<DeferredRequestCreator> deferredRequestCreators = new ArrayList<>(targetToDeferredRequestCreator.values()); //noinspection ForLoopReplaceableByForEach for (int i = 0, n = deferredRequestCreators.size(); i < n; i++) { DeferredRequestCreator deferredRequestCreator = deferredRequestCreators.get(i); if (tag.equals(deferredRequestCreator.getTag())) { deferredRequestCreator.cancel(); } } }
java
public void cancelTag(@NonNull Object tag) { checkMain(); checkNotNull(tag, "tag == null"); List<Action> actions = new ArrayList<>(targetToAction.values()); //noinspection ForLoopReplaceableByForEach for (int i = 0, n = actions.size(); i < n; i++) { Action action = actions.get(i); if (tag.equals(action.getTag())) { cancelExistingRequest(action.getTarget()); } } List<DeferredRequestCreator> deferredRequestCreators = new ArrayList<>(targetToDeferredRequestCreator.values()); //noinspection ForLoopReplaceableByForEach for (int i = 0, n = deferredRequestCreators.size(); i < n; i++) { DeferredRequestCreator deferredRequestCreator = deferredRequestCreators.get(i); if (tag.equals(deferredRequestCreator.getTag())) { deferredRequestCreator.cancel(); } } }
[ "public", "void", "cancelTag", "(", "@", "NonNull", "Object", "tag", ")", "{", "checkMain", "(", ")", ";", "checkNotNull", "(", "tag", ",", "\"tag == null\"", ")", ";", "List", "<", "Action", ">", "actions", "=", "new", "ArrayList", "<>", "(", "targetToAction", ".", "values", "(", ")", ")", ";", "//noinspection ForLoopReplaceableByForEach", "for", "(", "int", "i", "=", "0", ",", "n", "=", "actions", ".", "size", "(", ")", ";", "i", "<", "n", ";", "i", "++", ")", "{", "Action", "action", "=", "actions", ".", "get", "(", "i", ")", ";", "if", "(", "tag", ".", "equals", "(", "action", ".", "getTag", "(", ")", ")", ")", "{", "cancelExistingRequest", "(", "action", ".", "getTarget", "(", ")", ")", ";", "}", "}", "List", "<", "DeferredRequestCreator", ">", "deferredRequestCreators", "=", "new", "ArrayList", "<>", "(", "targetToDeferredRequestCreator", ".", "values", "(", ")", ")", ";", "//noinspection ForLoopReplaceableByForEach", "for", "(", "int", "i", "=", "0", ",", "n", "=", "deferredRequestCreators", ".", "size", "(", ")", ";", "i", "<", "n", ";", "i", "++", ")", "{", "DeferredRequestCreator", "deferredRequestCreator", "=", "deferredRequestCreators", ".", "get", "(", "i", ")", ";", "if", "(", "tag", ".", "equals", "(", "deferredRequestCreator", ".", "getTag", "(", ")", ")", ")", "{", "deferredRequestCreator", ".", "cancel", "(", ")", ";", "}", "}", "}" ]
Cancel any existing requests with given tag. You can set a tag on new requests with {@link RequestCreator#tag(Object)}. @see RequestCreator#tag(Object)
[ "Cancel", "any", "existing", "requests", "with", "given", "tag", ".", "You", "can", "set", "a", "tag", "on", "new", "requests", "with", "{", "@link", "RequestCreator#tag", "(", "Object", ")", "}", "." ]
train
https://github.com/square/picasso/blob/89f55b76e3be2b65e5997b7698f782f16f8547e3/picasso/src/main/java/com/squareup/picasso3/Picasso.java#L242-L264
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java
GeoLocationUtil.epsilonCompareToDistance
@Pure public static int epsilonCompareToDistance(double distance1, double distance2) { """ Replies if the specified distances are approximatively equal, less or greater than. @param distance1 the first distance. @param distance2 the second distance. @return a negative value if the parameter <var>distance1</var> is lower than <var>distance2</var>, a positive if <var>distance1</var> is greater than <var>distance2</var>, zero if the two parameters are approximatively equal. """ final double min = distance2 - distancePrecision; final double max = distance2 + distancePrecision; if (distance1 >= min && distance1 <= max) { return 0; } if (distance1 < min) { return -1; } return 1; }
java
@Pure public static int epsilonCompareToDistance(double distance1, double distance2) { final double min = distance2 - distancePrecision; final double max = distance2 + distancePrecision; if (distance1 >= min && distance1 <= max) { return 0; } if (distance1 < min) { return -1; } return 1; }
[ "@", "Pure", "public", "static", "int", "epsilonCompareToDistance", "(", "double", "distance1", ",", "double", "distance2", ")", "{", "final", "double", "min", "=", "distance2", "-", "distancePrecision", ";", "final", "double", "max", "=", "distance2", "+", "distancePrecision", ";", "if", "(", "distance1", ">=", "min", "&&", "distance1", "<=", "max", ")", "{", "return", "0", ";", "}", "if", "(", "distance1", "<", "min", ")", "{", "return", "-", "1", ";", "}", "return", "1", ";", "}" ]
Replies if the specified distances are approximatively equal, less or greater than. @param distance1 the first distance. @param distance2 the second distance. @return a negative value if the parameter <var>distance1</var> is lower than <var>distance2</var>, a positive if <var>distance1</var> is greater than <var>distance2</var>, zero if the two parameters are approximatively equal.
[ "Replies", "if", "the", "specified", "distances", "are", "approximatively", "equal", "less", "or", "greater", "than", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/location/GeoLocationUtil.java#L177-L188
jenkinsci/jenkins
core/src/main/java/hudson/Util.java
Util.fixNull
@Nonnull public static <T> T fixNull(@CheckForNull T s, @Nonnull T defaultValue) { """ Convert {@code null} to a default value. @param defaultValue Default value. It may be immutable or not, depending on the implementation. @since 2.144 """ return s != null ? s : defaultValue; }
java
@Nonnull public static <T> T fixNull(@CheckForNull T s, @Nonnull T defaultValue) { return s != null ? s : defaultValue; }
[ "@", "Nonnull", "public", "static", "<", "T", ">", "T", "fixNull", "(", "@", "CheckForNull", "T", "s", ",", "@", "Nonnull", "T", "defaultValue", ")", "{", "return", "s", "!=", "null", "?", "s", ":", "defaultValue", ";", "}" ]
Convert {@code null} to a default value. @param defaultValue Default value. It may be immutable or not, depending on the implementation. @since 2.144
[ "Convert", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L1002-L1005
actorapp/actor-platform
actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java
MarkdownParser.findUrl
private BasicUrl findUrl(TextCursor cursor, int limit) { """ Finding non-formatted urls in texts @param cursor current text cursor @param limit end of cursor @return founded url """ for (int i = cursor.currentOffset; i < limit; i++) { if (!isGoodAnchor(cursor.text, i - 1)) { continue; } String currentText = cursor.text.substring(i, limit); MatcherCompat matcher = Patterns.WEB_URL_START.matcher(currentText); if (matcher.hasMatch()) { String url = matcher.group(); int start = i + matcher.start(); return new BasicUrl(start, start + url.length()); } } return null; }
java
private BasicUrl findUrl(TextCursor cursor, int limit) { for (int i = cursor.currentOffset; i < limit; i++) { if (!isGoodAnchor(cursor.text, i - 1)) { continue; } String currentText = cursor.text.substring(i, limit); MatcherCompat matcher = Patterns.WEB_URL_START.matcher(currentText); if (matcher.hasMatch()) { String url = matcher.group(); int start = i + matcher.start(); return new BasicUrl(start, start + url.length()); } } return null; }
[ "private", "BasicUrl", "findUrl", "(", "TextCursor", "cursor", ",", "int", "limit", ")", "{", "for", "(", "int", "i", "=", "cursor", ".", "currentOffset", ";", "i", "<", "limit", ";", "i", "++", ")", "{", "if", "(", "!", "isGoodAnchor", "(", "cursor", ".", "text", ",", "i", "-", "1", ")", ")", "{", "continue", ";", "}", "String", "currentText", "=", "cursor", ".", "text", ".", "substring", "(", "i", ",", "limit", ")", ";", "MatcherCompat", "matcher", "=", "Patterns", ".", "WEB_URL_START", ".", "matcher", "(", "currentText", ")", ";", "if", "(", "matcher", ".", "hasMatch", "(", ")", ")", "{", "String", "url", "=", "matcher", ".", "group", "(", ")", ";", "int", "start", "=", "i", "+", "matcher", ".", "start", "(", ")", ";", "return", "new", "BasicUrl", "(", "start", ",", "start", "+", "url", ".", "length", "(", ")", ")", ";", "}", "}", "return", "null", ";", "}" ]
Finding non-formatted urls in texts @param cursor current text cursor @param limit end of cursor @return founded url
[ "Finding", "non", "-", "formatted", "urls", "in", "texts" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java#L353-L367
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_GET
public OvhExchangeServiceActiveSyncNotification organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_GET(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException { """ Get this object properties REST: GET /email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId} @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param notifiedAccountId [required] Notified Account Id """ String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}"; StringBuilder sb = path(qPath, organizationName, exchangeService, notifiedAccountId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhExchangeServiceActiveSyncNotification.class); }
java
public OvhExchangeServiceActiveSyncNotification organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_GET(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}"; StringBuilder sb = path(qPath, organizationName, exchangeService, notifiedAccountId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhExchangeServiceActiveSyncNotification.class); }
[ "public", "OvhExchangeServiceActiveSyncNotification", "organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_GET", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "Long", "notifiedAccountId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "organizationName", ",", "exchangeService", ",", "notifiedAccountId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhExchangeServiceActiveSyncNotification", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId} @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param notifiedAccountId [required] Notified Account Id
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2311-L2316
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/libs/modules/multiprocessing/GridNodeMultiProcessing.java
GridNodeMultiProcessing.processGridNodes
protected void processGridNodes( GridCoverage2D inElev, Calculator<GridNode> calculator ) throws Exception { """ Loops through all rows and cols of the given grid and calls the given calculator for each {@link GridNode}. """ RegionMap regionMap = regionMap(inElev); int cols = regionMap.getCols(); int rows = regionMap.getRows(); double xRes = regionMap.getXres(); double yRes = regionMap.getYres(); RandomIter elevationIter = CoverageUtilities.getRandomIterator(inElev); ExecutionPlanner planner = createDefaultPlanner(); planner.setNumberOfTasks(rows * cols); // Cycling into the valid region. for( int r = 0; r < rows; r++ ) { for( int c = 0; c < cols; c++ ) { int _c = c, _r = r; planner.submit(() -> { if (!pm.isCanceled()) { GridNode node = new GridNode(elevationIter, cols, rows, xRes, yRes, _c, _r); calculator.calculate(node); } }); } } planner.join(); }
java
protected void processGridNodes( GridCoverage2D inElev, Calculator<GridNode> calculator ) throws Exception { RegionMap regionMap = regionMap(inElev); int cols = regionMap.getCols(); int rows = regionMap.getRows(); double xRes = regionMap.getXres(); double yRes = regionMap.getYres(); RandomIter elevationIter = CoverageUtilities.getRandomIterator(inElev); ExecutionPlanner planner = createDefaultPlanner(); planner.setNumberOfTasks(rows * cols); // Cycling into the valid region. for( int r = 0; r < rows; r++ ) { for( int c = 0; c < cols; c++ ) { int _c = c, _r = r; planner.submit(() -> { if (!pm.isCanceled()) { GridNode node = new GridNode(elevationIter, cols, rows, xRes, yRes, _c, _r); calculator.calculate(node); } }); } } planner.join(); }
[ "protected", "void", "processGridNodes", "(", "GridCoverage2D", "inElev", ",", "Calculator", "<", "GridNode", ">", "calculator", ")", "throws", "Exception", "{", "RegionMap", "regionMap", "=", "regionMap", "(", "inElev", ")", ";", "int", "cols", "=", "regionMap", ".", "getCols", "(", ")", ";", "int", "rows", "=", "regionMap", ".", "getRows", "(", ")", ";", "double", "xRes", "=", "regionMap", ".", "getXres", "(", ")", ";", "double", "yRes", "=", "regionMap", ".", "getYres", "(", ")", ";", "RandomIter", "elevationIter", "=", "CoverageUtilities", ".", "getRandomIterator", "(", "inElev", ")", ";", "ExecutionPlanner", "planner", "=", "createDefaultPlanner", "(", ")", ";", "planner", ".", "setNumberOfTasks", "(", "rows", "*", "cols", ")", ";", "// Cycling into the valid region.", "for", "(", "int", "r", "=", "0", ";", "r", "<", "rows", ";", "r", "++", ")", "{", "for", "(", "int", "c", "=", "0", ";", "c", "<", "cols", ";", "c", "++", ")", "{", "int", "_c", "=", "c", ",", "_r", "=", "r", ";", "planner", ".", "submit", "(", "(", ")", "->", "{", "if", "(", "!", "pm", ".", "isCanceled", "(", ")", ")", "{", "GridNode", "node", "=", "new", "GridNode", "(", "elevationIter", ",", "cols", ",", "rows", ",", "xRes", ",", "yRes", ",", "_c", ",", "_r", ")", ";", "calculator", ".", "calculate", "(", "node", ")", ";", "}", "}", ")", ";", "}", "}", "planner", ".", "join", "(", ")", ";", "}" ]
Loops through all rows and cols of the given grid and calls the given calculator for each {@link GridNode}.
[ "Loops", "through", "all", "rows", "and", "cols", "of", "the", "given", "grid", "and", "calls", "the", "given", "calculator", "for", "each", "{" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/libs/modules/multiprocessing/GridNodeMultiProcessing.java#L55-L80
intellimate/Izou
src/main/java/org/intellimate/izou/security/AudioPermissionModule.java
AudioPermissionModule.registerOrThrow
private void registerOrThrow(AddOnModel addOn, String permissionMessage) throws IzouSoundPermissionException { """ registers the AddOn or throws the Exception @param addOn the AddOn to register @param permissionMessage the message of the exception @throws IzouSoundPermissionException if not eligible for registering """ Function<PluginDescriptor, Boolean> checkPlayPermission = descriptor -> { if (descriptor.getAddOnProperties() == null) throw new IzouPermissionException("addon_config.properties not found for addon:" + addOn); try { return descriptor.getAddOnProperties().getProperty("audio_output") != null && descriptor.getAddOnProperties().getProperty("audio_output").trim().equals("true") && descriptor.getAddOnProperties().getProperty("audio_usage_descripton") != null && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().equals("null") && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().isEmpty(); } catch (NullPointerException e) { return false; } }; registerOrThrow(addOn, () -> new IzouSoundPermissionException(permissionMessage), checkPlayPermission); }
java
private void registerOrThrow(AddOnModel addOn, String permissionMessage) throws IzouSoundPermissionException{ Function<PluginDescriptor, Boolean> checkPlayPermission = descriptor -> { if (descriptor.getAddOnProperties() == null) throw new IzouPermissionException("addon_config.properties not found for addon:" + addOn); try { return descriptor.getAddOnProperties().getProperty("audio_output") != null && descriptor.getAddOnProperties().getProperty("audio_output").trim().equals("true") && descriptor.getAddOnProperties().getProperty("audio_usage_descripton") != null && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().equals("null") && !descriptor.getAddOnProperties().getProperty("audio_usage_descripton").trim().isEmpty(); } catch (NullPointerException e) { return false; } }; registerOrThrow(addOn, () -> new IzouSoundPermissionException(permissionMessage), checkPlayPermission); }
[ "private", "void", "registerOrThrow", "(", "AddOnModel", "addOn", ",", "String", "permissionMessage", ")", "throws", "IzouSoundPermissionException", "{", "Function", "<", "PluginDescriptor", ",", "Boolean", ">", "checkPlayPermission", "=", "descriptor", "->", "{", "if", "(", "descriptor", ".", "getAddOnProperties", "(", ")", "==", "null", ")", "throw", "new", "IzouPermissionException", "(", "\"addon_config.properties not found for addon:\"", "+", "addOn", ")", ";", "try", "{", "return", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_output\"", ")", "!=", "null", "&&", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_output\"", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"true\"", ")", "&&", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", "!=", "null", "&&", "!", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"null\"", ")", "&&", "!", "descriptor", ".", "getAddOnProperties", "(", ")", ".", "getProperty", "(", "\"audio_usage_descripton\"", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ";", "}", "catch", "(", "NullPointerException", "e", ")", "{", "return", "false", ";", "}", "}", ";", "registerOrThrow", "(", "addOn", ",", "(", ")", "->", "new", "IzouSoundPermissionException", "(", "permissionMessage", ")", ",", "checkPlayPermission", ")", ";", "}" ]
registers the AddOn or throws the Exception @param addOn the AddOn to register @param permissionMessage the message of the exception @throws IzouSoundPermissionException if not eligible for registering
[ "registers", "the", "AddOn", "or", "throws", "the", "Exception" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/AudioPermissionModule.java#L54-L70
lonnyj/liquibase-spatial
src/main/java/liquibase/ext/spatial/sqlgenerator/OracleSpatialUtils.java
OracleSpatialUtils.loadOracleSrid
public static String loadOracleSrid(final String srid, final Database database) { """ Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID. @param srid the EPSG SRID. @param database the database instance. @return the corresponding Oracle SRID. """ final String oracleSrid; final JdbcConnection jdbcConnection = (JdbcConnection) database.getConnection(); final Connection connection = jdbcConnection.getUnderlyingConnection(); Statement statement = null; try { statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT " + EPSG_TO_ORACLE_FUNCTION + "(" + srid + ") FROM dual"); resultSet.next(); oracleSrid = resultSet.getString(1); } catch (final SQLException e) { throw new UnexpectedLiquibaseException("Failed to find the Oracle SRID for EPSG:" + srid, e); } finally { try { statement.close(); } catch (final SQLException ignore) { } } return oracleSrid; }
java
public static String loadOracleSrid(final String srid, final Database database) { final String oracleSrid; final JdbcConnection jdbcConnection = (JdbcConnection) database.getConnection(); final Connection connection = jdbcConnection.getUnderlyingConnection(); Statement statement = null; try { statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT " + EPSG_TO_ORACLE_FUNCTION + "(" + srid + ") FROM dual"); resultSet.next(); oracleSrid = resultSet.getString(1); } catch (final SQLException e) { throw new UnexpectedLiquibaseException("Failed to find the Oracle SRID for EPSG:" + srid, e); } finally { try { statement.close(); } catch (final SQLException ignore) { } } return oracleSrid; }
[ "public", "static", "String", "loadOracleSrid", "(", "final", "String", "srid", ",", "final", "Database", "database", ")", "{", "final", "String", "oracleSrid", ";", "final", "JdbcConnection", "jdbcConnection", "=", "(", "JdbcConnection", ")", "database", ".", "getConnection", "(", ")", ";", "final", "Connection", "connection", "=", "jdbcConnection", ".", "getUnderlyingConnection", "(", ")", ";", "Statement", "statement", "=", "null", ";", "try", "{", "statement", "=", "connection", ".", "createStatement", "(", ")", ";", "final", "ResultSet", "resultSet", "=", "statement", ".", "executeQuery", "(", "\"SELECT \"", "+", "EPSG_TO_ORACLE_FUNCTION", "+", "\"(\"", "+", "srid", "+", "\") FROM dual\"", ")", ";", "resultSet", ".", "next", "(", ")", ";", "oracleSrid", "=", "resultSet", ".", "getString", "(", "1", ")", ";", "}", "catch", "(", "final", "SQLException", "e", ")", "{", "throw", "new", "UnexpectedLiquibaseException", "(", "\"Failed to find the Oracle SRID for EPSG:\"", "+", "srid", ",", "e", ")", ";", "}", "finally", "{", "try", "{", "statement", ".", "close", "(", ")", ";", "}", "catch", "(", "final", "SQLException", "ignore", ")", "{", "}", "}", "return", "oracleSrid", ";", "}" ]
Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID. @param srid the EPSG SRID. @param database the database instance. @return the corresponding Oracle SRID.
[ "Queries", "to", "the", "database", "to", "convert", "the", "given", "EPSG", "SRID", "to", "the", "corresponding", "Oracle", "SRID", "." ]
train
https://github.com/lonnyj/liquibase-spatial/blob/36ae41b0d3d08bb00a22c856e51ffeed08891c0e/src/main/java/liquibase/ext/spatial/sqlgenerator/OracleSpatialUtils.java#L104-L125
haifengl/smile
math/src/main/java/smile/math/matrix/SparseMatrix.java
SparseMatrix.scatter
private static int scatter(SparseMatrix A, int j, double beta, int[] w, double[] x, int mark, SparseMatrix C, int nz) { """ x = x + beta * A(:,j), where x is a dense vector and A(:,j) is sparse. """ int[] Ap = A.colIndex; int[] Ai = A.rowIndex; double[] Ax = A.x; int[] Ci = C.rowIndex; for (int p = Ap[j]; p < Ap[j + 1]; p++) { int i = Ai[p]; // A(i,j) is nonzero if (w[i] < mark) { w[i] = mark; // i is new entry in column j Ci[nz++] = i; // add i to pattern of C(:,j) x[i] = beta * Ax[p]; // x(i) = beta*A(i,j) } else { x[i] += beta * Ax[p]; // i exists in C(:,j) already } } return nz; }
java
private static int scatter(SparseMatrix A, int j, double beta, int[] w, double[] x, int mark, SparseMatrix C, int nz) { int[] Ap = A.colIndex; int[] Ai = A.rowIndex; double[] Ax = A.x; int[] Ci = C.rowIndex; for (int p = Ap[j]; p < Ap[j + 1]; p++) { int i = Ai[p]; // A(i,j) is nonzero if (w[i] < mark) { w[i] = mark; // i is new entry in column j Ci[nz++] = i; // add i to pattern of C(:,j) x[i] = beta * Ax[p]; // x(i) = beta*A(i,j) } else { x[i] += beta * Ax[p]; // i exists in C(:,j) already } } return nz; }
[ "private", "static", "int", "scatter", "(", "SparseMatrix", "A", ",", "int", "j", ",", "double", "beta", ",", "int", "[", "]", "w", ",", "double", "[", "]", "x", ",", "int", "mark", ",", "SparseMatrix", "C", ",", "int", "nz", ")", "{", "int", "[", "]", "Ap", "=", "A", ".", "colIndex", ";", "int", "[", "]", "Ai", "=", "A", ".", "rowIndex", ";", "double", "[", "]", "Ax", "=", "A", ".", "x", ";", "int", "[", "]", "Ci", "=", "C", ".", "rowIndex", ";", "for", "(", "int", "p", "=", "Ap", "[", "j", "]", ";", "p", "<", "Ap", "[", "j", "+", "1", "]", ";", "p", "++", ")", "{", "int", "i", "=", "Ai", "[", "p", "]", ";", "// A(i,j) is nonzero", "if", "(", "w", "[", "i", "]", "<", "mark", ")", "{", "w", "[", "i", "]", "=", "mark", ";", "// i is new entry in column j", "Ci", "[", "nz", "++", "]", "=", "i", ";", "// add i to pattern of C(:,j)", "x", "[", "i", "]", "=", "beta", "*", "Ax", "[", "p", "]", ";", "// x(i) = beta*A(i,j)", "}", "else", "{", "x", "[", "i", "]", "+=", "beta", "*", "Ax", "[", "p", "]", ";", "// i exists in C(:,j) already", "}", "}", "return", "nz", ";", "}" ]
x = x + beta * A(:,j), where x is a dense vector and A(:,j) is sparse.
[ "x", "=", "x", "+", "beta", "*", "A", "(", ":", "j", ")", "where", "x", "is", "a", "dense", "vector", "and", "A", "(", ":", "j", ")", "is", "sparse", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/math/src/main/java/smile/math/matrix/SparseMatrix.java#L362-L380
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java
ContinuousDistributions.dirichletPdf
public static double dirichletPdf(double[] pi, double[] ai) { """ Calculates probability pi, ai under dirichlet distribution @param pi The vector with probabilities. @param ai The vector with pseudocounts. @return The probability """ double probability=1.0; double sumAi=0.0; double productGammaAi=1.0; double tmp; int piLength=pi.length; for(int i=0;i<piLength;++i) { tmp=ai[i]; sumAi+= tmp; productGammaAi*=gamma(tmp); probability*=Math.pow(pi[i], tmp-1); } probability*=gamma(sumAi)/productGammaAi; return probability; }
java
public static double dirichletPdf(double[] pi, double[] ai) { double probability=1.0; double sumAi=0.0; double productGammaAi=1.0; double tmp; int piLength=pi.length; for(int i=0;i<piLength;++i) { tmp=ai[i]; sumAi+= tmp; productGammaAi*=gamma(tmp); probability*=Math.pow(pi[i], tmp-1); } probability*=gamma(sumAi)/productGammaAi; return probability; }
[ "public", "static", "double", "dirichletPdf", "(", "double", "[", "]", "pi", ",", "double", "[", "]", "ai", ")", "{", "double", "probability", "=", "1.0", ";", "double", "sumAi", "=", "0.0", ";", "double", "productGammaAi", "=", "1.0", ";", "double", "tmp", ";", "int", "piLength", "=", "pi", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "piLength", ";", "++", "i", ")", "{", "tmp", "=", "ai", "[", "i", "]", ";", "sumAi", "+=", "tmp", ";", "productGammaAi", "*=", "gamma", "(", "tmp", ")", ";", "probability", "*=", "Math", ".", "pow", "(", "pi", "[", "i", "]", ",", "tmp", "-", "1", ")", ";", "}", "probability", "*=", "gamma", "(", "sumAi", ")", "/", "productGammaAi", ";", "return", "probability", ";", "}" ]
Calculates probability pi, ai under dirichlet distribution @param pi The vector with probabilities. @param ai The vector with pseudocounts. @return The probability
[ "Calculates", "probability", "pi", "ai", "under", "dirichlet", "distribution" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java#L593-L610
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/runtime/SARLRuntime.java
SARLRuntime.setDefaultSREInstall
public static void setDefaultSREInstall(ISREInstall sre, IProgressMonitor monitor) throws CoreException { """ Sets a SRE as the system-wide default SRE, and notifies registered SRE install change listeners of the change. @param sre The SRE to make the default. May be <code>null</code> to clear the default. @param monitor progress monitor or <code>null</code> @throws CoreException if trying to set the default SRE install encounters problems """ setDefaultSREInstall(sre, monitor, true); }
java
public static void setDefaultSREInstall(ISREInstall sre, IProgressMonitor monitor) throws CoreException { setDefaultSREInstall(sre, monitor, true); }
[ "public", "static", "void", "setDefaultSREInstall", "(", "ISREInstall", "sre", ",", "IProgressMonitor", "monitor", ")", "throws", "CoreException", "{", "setDefaultSREInstall", "(", "sre", ",", "monitor", ",", "true", ")", ";", "}" ]
Sets a SRE as the system-wide default SRE, and notifies registered SRE install change listeners of the change. @param sre The SRE to make the default. May be <code>null</code> to clear the default. @param monitor progress monitor or <code>null</code> @throws CoreException if trying to set the default SRE install encounters problems
[ "Sets", "a", "SRE", "as", "the", "system", "-", "wide", "default", "SRE", "and", "notifies", "registered", "SRE", "install", "change", "listeners", "of", "the", "change", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/runtime/SARLRuntime.java#L345-L347
WhereIsMyTransport/TransportApiSdk.Java
transportapisdk/src/main/java/transportapisdk/TransportApiClient.java
TransportApiClient.getLinesNearby
public TransportApiResult<List<Line>> getLinesNearby(LineQueryOptions options, double latitude, double longitude, int radiusInMeters) { """ Gets a list of lines nearby ordered by distance from the point specified. @param options Options to limit the results by. Default: LineQueryOptions.defaultQueryOptions() @param latitude Latitude in decimal degrees. @param longitude Longitude in decimal degrees. @param radiusInMeters Radius in meters to filter results by. @return A list of lines nearby the specified point. """ if (options == null) { options = LineQueryOptions.defaultQueryOptions(); } if (radiusInMeters < 0) { throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only."); } return TransportApiClientCalls.getLines(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null); }
java
public TransportApiResult<List<Line>> getLinesNearby(LineQueryOptions options, double latitude, double longitude, int radiusInMeters) { if (options == null) { options = LineQueryOptions.defaultQueryOptions(); } if (radiusInMeters < 0) { throw new IllegalArgumentException("Invalid limit. Valid values are positive numbers only."); } return TransportApiClientCalls.getLines(tokenComponent, settings, options, new Point(longitude, latitude), radiusInMeters, null); }
[ "public", "TransportApiResult", "<", "List", "<", "Line", ">", ">", "getLinesNearby", "(", "LineQueryOptions", "options", ",", "double", "latitude", ",", "double", "longitude", ",", "int", "radiusInMeters", ")", "{", "if", "(", "options", "==", "null", ")", "{", "options", "=", "LineQueryOptions", ".", "defaultQueryOptions", "(", ")", ";", "}", "if", "(", "radiusInMeters", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid limit. Valid values are positive numbers only.\"", ")", ";", "}", "return", "TransportApiClientCalls", ".", "getLines", "(", "tokenComponent", ",", "settings", ",", "options", ",", "new", "Point", "(", "longitude", ",", "latitude", ")", ",", "radiusInMeters", ",", "null", ")", ";", "}" ]
Gets a list of lines nearby ordered by distance from the point specified. @param options Options to limit the results by. Default: LineQueryOptions.defaultQueryOptions() @param latitude Latitude in decimal degrees. @param longitude Longitude in decimal degrees. @param radiusInMeters Radius in meters to filter results by. @return A list of lines nearby the specified point.
[ "Gets", "a", "list", "of", "lines", "nearby", "ordered", "by", "distance", "from", "the", "point", "specified", "." ]
train
https://github.com/WhereIsMyTransport/TransportApiSdk.Java/blob/f4ade7046c8dadfcb2976ee354f85f67a6e930a2/transportapisdk/src/main/java/transportapisdk/TransportApiClient.java#L193-L206
canhnt/sne-xacml
sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java
MIDDCombiner.combineExternalNodes
private ExternalNode3 combineExternalNodes(ExternalNode3 n1, ExternalNode3 n2) { """ Combine two external nodes following the algorithm in this.algo @param n1 @param n2 @return """ if (n1 == null || n2 == null) { throw new IllegalArgumentException("Input nodes must not be null"); } DecisionType combinedDecision = algo.combine(n1.getDecision(), n2.getDecision()); ExternalNode3 n = new ExternalNode3(combinedDecision); // only accept OE that match with combined decision. List<ObligationExpression> oes1 = getFulfilledObligationExpressions(n1.getObligationExpressions(), combinedDecision); List<ObligationExpression> oes2 = getFulfilledObligationExpressions(n2.getObligationExpressions(), combinedDecision); n.getObligationExpressions().addAll(oes1); n.getObligationExpressions().addAll(oes2); return n; }
java
private ExternalNode3 combineExternalNodes(ExternalNode3 n1, ExternalNode3 n2) { if (n1 == null || n2 == null) { throw new IllegalArgumentException("Input nodes must not be null"); } DecisionType combinedDecision = algo.combine(n1.getDecision(), n2.getDecision()); ExternalNode3 n = new ExternalNode3(combinedDecision); // only accept OE that match with combined decision. List<ObligationExpression> oes1 = getFulfilledObligationExpressions(n1.getObligationExpressions(), combinedDecision); List<ObligationExpression> oes2 = getFulfilledObligationExpressions(n2.getObligationExpressions(), combinedDecision); n.getObligationExpressions().addAll(oes1); n.getObligationExpressions().addAll(oes2); return n; }
[ "private", "ExternalNode3", "combineExternalNodes", "(", "ExternalNode3", "n1", ",", "ExternalNode3", "n2", ")", "{", "if", "(", "n1", "==", "null", "||", "n2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Input nodes must not be null\"", ")", ";", "}", "DecisionType", "combinedDecision", "=", "algo", ".", "combine", "(", "n1", ".", "getDecision", "(", ")", ",", "n2", ".", "getDecision", "(", ")", ")", ";", "ExternalNode3", "n", "=", "new", "ExternalNode3", "(", "combinedDecision", ")", ";", "// only accept OE that match with combined decision.", "List", "<", "ObligationExpression", ">", "oes1", "=", "getFulfilledObligationExpressions", "(", "n1", ".", "getObligationExpressions", "(", ")", ",", "combinedDecision", ")", ";", "List", "<", "ObligationExpression", ">", "oes2", "=", "getFulfilledObligationExpressions", "(", "n2", ".", "getObligationExpressions", "(", ")", ",", "combinedDecision", ")", ";", "n", ".", "getObligationExpressions", "(", ")", ".", "addAll", "(", "oes1", ")", ";", "n", ".", "getObligationExpressions", "(", ")", ".", "addAll", "(", "oes2", ")", ";", "return", "n", ";", "}" ]
Combine two external nodes following the algorithm in this.algo @param n1 @param n2 @return
[ "Combine", "two", "external", "nodes", "following", "the", "algorithm", "in", "this", ".", "algo" ]
train
https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java#L200-L217
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java
JsonUtil.putKey
public static void putKey(Writer writer, String key) throws IOException { """ Writes the given key as a JSON hash key, sanitizing with {@link #sanitize(String)} as a valid JSON-formatted data. @param writer {@link Writer} to be used for writing value @param key Keyの文字列表現 @throws IOException @author vvakame """ writer.write("\""); writer.write(sanitize(key)); writer.write("\":"); }
java
public static void putKey(Writer writer, String key) throws IOException { writer.write("\""); writer.write(sanitize(key)); writer.write("\":"); }
[ "public", "static", "void", "putKey", "(", "Writer", "writer", ",", "String", "key", ")", "throws", "IOException", "{", "writer", ".", "write", "(", "\"\\\"\"", ")", ";", "writer", ".", "write", "(", "sanitize", "(", "key", ")", ")", ";", "writer", ".", "write", "(", "\"\\\":\"", ")", ";", "}" ]
Writes the given key as a JSON hash key, sanitizing with {@link #sanitize(String)} as a valid JSON-formatted data. @param writer {@link Writer} to be used for writing value @param key Keyの文字列表現 @throws IOException @author vvakame
[ "Writes", "the", "given", "key", "as", "a", "JSON", "hash", "key", "sanitizing", "with", "{" ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L88-L92
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java
FastaWriterHelper.writeGeneSequence
public static void writeGeneSequence(OutputStream outputStream, Collection<GeneSequence> geneSequences,boolean showExonUppercase) throws Exception { """ Write a collection of GeneSequences to a file where if the gene is negative strand it will flip and complement the sequence @param outputStream @param dnaSequences @throws Exception """ FastaGeneWriter fastaWriter = new FastaGeneWriter( outputStream, geneSequences, new GenericFastaHeaderFormat<GeneSequence, NucleotideCompound>(),showExonUppercase); fastaWriter.process(); }
java
public static void writeGeneSequence(OutputStream outputStream, Collection<GeneSequence> geneSequences,boolean showExonUppercase) throws Exception { FastaGeneWriter fastaWriter = new FastaGeneWriter( outputStream, geneSequences, new GenericFastaHeaderFormat<GeneSequence, NucleotideCompound>(),showExonUppercase); fastaWriter.process(); }
[ "public", "static", "void", "writeGeneSequence", "(", "OutputStream", "outputStream", ",", "Collection", "<", "GeneSequence", ">", "geneSequences", ",", "boolean", "showExonUppercase", ")", "throws", "Exception", "{", "FastaGeneWriter", "fastaWriter", "=", "new", "FastaGeneWriter", "(", "outputStream", ",", "geneSequences", ",", "new", "GenericFastaHeaderFormat", "<", "GeneSequence", ",", "NucleotideCompound", ">", "(", ")", ",", "showExonUppercase", ")", ";", "fastaWriter", ".", "process", "(", ")", ";", "}" ]
Write a collection of GeneSequences to a file where if the gene is negative strand it will flip and complement the sequence @param outputStream @param dnaSequences @throws Exception
[ "Write", "a", "collection", "of", "GeneSequences", "to", "a", "file", "where", "if", "the", "gene", "is", "negative", "strand", "it", "will", "flip", "and", "complement", "the", "sequence" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java#L103-L109
phax/ph-web
ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java
UnifiedResponseDefaultSettings.setAllowMimeSniffing
public static void setAllowMimeSniffing (final boolean bAllow) { """ When specifying <code>false</code>, this method uses a special response header to prevent certain browsers from MIME-sniffing a response away from the declared content-type. When passing <code>true</code>, that header is removed. @param bAllow Whether or not sniffing should be allowed (default is <code>true</code>). """ if (bAllow) removeResponseHeaders (CHttpHeader.X_CONTENT_TYPE_OPTIONS); else setResponseHeader (CHttpHeader.X_CONTENT_TYPE_OPTIONS, CHttpHeader.VALUE_NOSNIFF); }
java
public static void setAllowMimeSniffing (final boolean bAllow) { if (bAllow) removeResponseHeaders (CHttpHeader.X_CONTENT_TYPE_OPTIONS); else setResponseHeader (CHttpHeader.X_CONTENT_TYPE_OPTIONS, CHttpHeader.VALUE_NOSNIFF); }
[ "public", "static", "void", "setAllowMimeSniffing", "(", "final", "boolean", "bAllow", ")", "{", "if", "(", "bAllow", ")", "removeResponseHeaders", "(", "CHttpHeader", ".", "X_CONTENT_TYPE_OPTIONS", ")", ";", "else", "setResponseHeader", "(", "CHttpHeader", ".", "X_CONTENT_TYPE_OPTIONS", ",", "CHttpHeader", ".", "VALUE_NOSNIFF", ")", ";", "}" ]
When specifying <code>false</code>, this method uses a special response header to prevent certain browsers from MIME-sniffing a response away from the declared content-type. When passing <code>true</code>, that header is removed. @param bAllow Whether or not sniffing should be allowed (default is <code>true</code>).
[ "When", "specifying", "<code", ">", "false<", "/", "code", ">", "this", "method", "uses", "a", "special", "response", "header", "to", "prevent", "certain", "browsers", "from", "MIME", "-", "sniffing", "a", "response", "away", "from", "the", "declared", "content", "-", "type", ".", "When", "passing", "<code", ">", "true<", "/", "code", ">", "that", "header", "is", "removed", "." ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/response/UnifiedResponseDefaultSettings.java#L89-L95
heinrichreimer/material-drawer
library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerProfile.java
DrawerProfile.setBackground
public DrawerProfile setBackground(Context context, Bitmap background) { """ Sets a background to the drawer profile @param background Background to set """ mBackground = new BitmapDrawable(context.getResources(), background); notifyDataChanged(); return this; }
java
public DrawerProfile setBackground(Context context, Bitmap background) { mBackground = new BitmapDrawable(context.getResources(), background); notifyDataChanged(); return this; }
[ "public", "DrawerProfile", "setBackground", "(", "Context", "context", ",", "Bitmap", "background", ")", "{", "mBackground", "=", "new", "BitmapDrawable", "(", "context", ".", "getResources", "(", ")", ",", "background", ")", ";", "notifyDataChanged", "(", ")", ";", "return", "this", ";", "}" ]
Sets a background to the drawer profile @param background Background to set
[ "Sets", "a", "background", "to", "the", "drawer", "profile" ]
train
https://github.com/heinrichreimer/material-drawer/blob/7c2406812d73f710ef8bb73d4a0f4bbef3b275ce/library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerProfile.java#L194-L198
awslabs/amazon-sqs-java-messaging-lib
src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java
NegativeAcknowledger.bulkAction
public void bulkAction(ArrayDeque<MessageManager> messageQueue, String queueUrl) throws JMSException { """ Bulk action for negative acknowledge on the list of messages of a specific queue. @param messageQueue Container for the list of message managers. @param queueUrl The queueUrl of the messages, which they received from. @throws JMSException If <code>action</code> throws. """ List<String> receiptHandles = new ArrayList<String>(); while (!messageQueue.isEmpty()) { receiptHandles.add(((SQSMessage) (messageQueue.pollFirst().getMessage())).getReceiptHandle()); // If there is more than 10 stop can call action if (receiptHandles.size() == SQSMessagingClientConstants.MAX_BATCH) { action(queueUrl, receiptHandles); receiptHandles.clear(); } } action(queueUrl, receiptHandles); }
java
public void bulkAction(ArrayDeque<MessageManager> messageQueue, String queueUrl) throws JMSException { List<String> receiptHandles = new ArrayList<String>(); while (!messageQueue.isEmpty()) { receiptHandles.add(((SQSMessage) (messageQueue.pollFirst().getMessage())).getReceiptHandle()); // If there is more than 10 stop can call action if (receiptHandles.size() == SQSMessagingClientConstants.MAX_BATCH) { action(queueUrl, receiptHandles); receiptHandles.clear(); } } action(queueUrl, receiptHandles); }
[ "public", "void", "bulkAction", "(", "ArrayDeque", "<", "MessageManager", ">", "messageQueue", ",", "String", "queueUrl", ")", "throws", "JMSException", "{", "List", "<", "String", ">", "receiptHandles", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "while", "(", "!", "messageQueue", ".", "isEmpty", "(", ")", ")", "{", "receiptHandles", ".", "add", "(", "(", "(", "SQSMessage", ")", "(", "messageQueue", ".", "pollFirst", "(", ")", ".", "getMessage", "(", ")", ")", ")", ".", "getReceiptHandle", "(", ")", ")", ";", "// If there is more than 10 stop can call action", "if", "(", "receiptHandles", ".", "size", "(", ")", "==", "SQSMessagingClientConstants", ".", "MAX_BATCH", ")", "{", "action", "(", "queueUrl", ",", "receiptHandles", ")", ";", "receiptHandles", ".", "clear", "(", ")", ";", "}", "}", "action", "(", "queueUrl", ",", "receiptHandles", ")", ";", "}" ]
Bulk action for negative acknowledge on the list of messages of a specific queue. @param messageQueue Container for the list of message managers. @param queueUrl The queueUrl of the messages, which they received from. @throws JMSException If <code>action</code> throws.
[ "Bulk", "action", "for", "negative", "acknowledge", "on", "the", "list", "of", "messages", "of", "a", "specific", "queue", "." ]
train
https://github.com/awslabs/amazon-sqs-java-messaging-lib/blob/efa716d34d51ef1c5572790626cdb795419cb342/src/main/java/com/amazon/sqs/javamessaging/acknowledge/NegativeAcknowledger.java#L60-L72
NessComputing/components-ness-quartz
src/main/java/com/nesscomputing/quartz/QuartzJob.java
QuartzJob.startTime
@SuppressWarnings("unchecked") public final SelfType startTime(final DateTime when, final TimeSpan jitter) { """ Set the time-of-day when the first run of the job will take place. """ // Find the current week day in the same time zone as the "when" time passed in. final DateTime now = new DateTime().withZone(when.getZone()); final int startWeekDay = when.getDayOfWeek(); final int currentWeekDay = now.getDayOfWeek(); // ( x + n ) % n is x for x > 0 and n - x for x < 0. final int daysTilStart = (startWeekDay - currentWeekDay + DAYS_PER_WEEK) % DAYS_PER_WEEK; Preconditions.checkState(daysTilStart >= 0 && daysTilStart < DAYS_PER_WEEK, "daysTilStart must be 0..%s, but is %s", DAYS_PER_WEEK, daysTilStart); // same trick as above, add a full week in millis and do the modulo. final long millisecondsTilStart = (when.getMillisOfDay() - now.getMillisOfDay() + daysTilStart * MILLIS_PER_DAY + MILLIS_PER_WEEK) % MILLIS_PER_WEEK; Preconditions.checkState(millisecondsTilStart >= 0 && millisecondsTilStart < MILLIS_PER_WEEK, "millisecondsTilStart must be 0..%s, but is %s", MILLIS_PER_WEEK, millisecondsTilStart); this.delay = Duration.millis((long)(ThreadLocalRandom.current().nextDouble() * jitter.getMillis()) + millisecondsTilStart); return (SelfType) this; }
java
@SuppressWarnings("unchecked") public final SelfType startTime(final DateTime when, final TimeSpan jitter) { // Find the current week day in the same time zone as the "when" time passed in. final DateTime now = new DateTime().withZone(when.getZone()); final int startWeekDay = when.getDayOfWeek(); final int currentWeekDay = now.getDayOfWeek(); // ( x + n ) % n is x for x > 0 and n - x for x < 0. final int daysTilStart = (startWeekDay - currentWeekDay + DAYS_PER_WEEK) % DAYS_PER_WEEK; Preconditions.checkState(daysTilStart >= 0 && daysTilStart < DAYS_PER_WEEK, "daysTilStart must be 0..%s, but is %s", DAYS_PER_WEEK, daysTilStart); // same trick as above, add a full week in millis and do the modulo. final long millisecondsTilStart = (when.getMillisOfDay() - now.getMillisOfDay() + daysTilStart * MILLIS_PER_DAY + MILLIS_PER_WEEK) % MILLIS_PER_WEEK; Preconditions.checkState(millisecondsTilStart >= 0 && millisecondsTilStart < MILLIS_PER_WEEK, "millisecondsTilStart must be 0..%s, but is %s", MILLIS_PER_WEEK, millisecondsTilStart); this.delay = Duration.millis((long)(ThreadLocalRandom.current().nextDouble() * jitter.getMillis()) + millisecondsTilStart); return (SelfType) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "final", "SelfType", "startTime", "(", "final", "DateTime", "when", ",", "final", "TimeSpan", "jitter", ")", "{", "// Find the current week day in the same time zone as the \"when\" time passed in.", "final", "DateTime", "now", "=", "new", "DateTime", "(", ")", ".", "withZone", "(", "when", ".", "getZone", "(", ")", ")", ";", "final", "int", "startWeekDay", "=", "when", ".", "getDayOfWeek", "(", ")", ";", "final", "int", "currentWeekDay", "=", "now", ".", "getDayOfWeek", "(", ")", ";", "// ( x + n ) % n is x for x > 0 and n - x for x < 0.", "final", "int", "daysTilStart", "=", "(", "startWeekDay", "-", "currentWeekDay", "+", "DAYS_PER_WEEK", ")", "%", "DAYS_PER_WEEK", ";", "Preconditions", ".", "checkState", "(", "daysTilStart", ">=", "0", "&&", "daysTilStart", "<", "DAYS_PER_WEEK", ",", "\"daysTilStart must be 0..%s, but is %s\"", ",", "DAYS_PER_WEEK", ",", "daysTilStart", ")", ";", "// same trick as above, add a full week in millis and do the modulo.", "final", "long", "millisecondsTilStart", "=", "(", "when", ".", "getMillisOfDay", "(", ")", "-", "now", ".", "getMillisOfDay", "(", ")", "+", "daysTilStart", "*", "MILLIS_PER_DAY", "+", "MILLIS_PER_WEEK", ")", "%", "MILLIS_PER_WEEK", ";", "Preconditions", ".", "checkState", "(", "millisecondsTilStart", ">=", "0", "&&", "millisecondsTilStart", "<", "MILLIS_PER_WEEK", ",", "\"millisecondsTilStart must be 0..%s, but is %s\"", ",", "MILLIS_PER_WEEK", ",", "millisecondsTilStart", ")", ";", "this", ".", "delay", "=", "Duration", ".", "millis", "(", "(", "long", ")", "(", "ThreadLocalRandom", ".", "current", "(", ")", ".", "nextDouble", "(", ")", "*", "jitter", ".", "getMillis", "(", ")", ")", "+", "millisecondsTilStart", ")", ";", "return", "(", "SelfType", ")", "this", ";", "}" ]
Set the time-of-day when the first run of the job will take place.
[ "Set", "the", "time", "-", "of", "-", "day", "when", "the", "first", "run", "of", "the", "job", "will", "take", "place", "." ]
train
https://github.com/NessComputing/components-ness-quartz/blob/fd41c440e21b31a5292a0606c8687eacfc5120ae/src/main/java/com/nesscomputing/quartz/QuartzJob.java#L87-L106
Cornutum/tcases
tcases-openapi/src/main/java/org/cornutum/tcases/openapi/reader/OpenApiReaderException.java
OpenApiReaderException.errorReasonFor
private static String errorReasonFor( URL location, List<String> errors) { """ Returns a reason for the errors in the document at the given location. """ return Stream.concat( Stream.of( String.format( "%s conformance problem(s) found in Open API document%s", errors.size(), locationId( location))), IntStream.range( 0, errors.size()).mapToObj( i -> String.format( "[%s] %s", i, errors.get(i)))) .collect( joining( "\n")); }
java
private static String errorReasonFor( URL location, List<String> errors) { return Stream.concat( Stream.of( String.format( "%s conformance problem(s) found in Open API document%s", errors.size(), locationId( location))), IntStream.range( 0, errors.size()).mapToObj( i -> String.format( "[%s] %s", i, errors.get(i)))) .collect( joining( "\n")); }
[ "private", "static", "String", "errorReasonFor", "(", "URL", "location", ",", "List", "<", "String", ">", "errors", ")", "{", "return", "Stream", ".", "concat", "(", "Stream", ".", "of", "(", "String", ".", "format", "(", "\"%s conformance problem(s) found in Open API document%s\"", ",", "errors", ".", "size", "(", ")", ",", "locationId", "(", "location", ")", ")", ")", ",", "IntStream", ".", "range", "(", "0", ",", "errors", ".", "size", "(", ")", ")", ".", "mapToObj", "(", "i", "->", "String", ".", "format", "(", "\"[%s] %s\"", ",", "i", ",", "errors", ".", "get", "(", "i", ")", ")", ")", ")", ".", "collect", "(", "joining", "(", "\"\\n\"", ")", ")", ";", "}" ]
Returns a reason for the errors in the document at the given location.
[ "Returns", "a", "reason", "for", "the", "errors", "in", "the", "document", "at", "the", "given", "location", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-openapi/src/main/java/org/cornutum/tcases/openapi/reader/OpenApiReaderException.java#L62-L69
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/util/event/EventDispatcherBase.java
EventDispatcherBase.dispatchEvent
protected <T> void dispatchEvent(DispatchQueueSelector queueSelector, List<T> listeners, Consumer<T> consumer) { """ Dispatches an event to the given listeners using the provided consumer. Calling this method usually looks like this: {@code dispatchEvent(server, listeners, listener -> listener.onXyz(event));} @param queueSelector The object which is used to determine in which queue the event should be dispatched. Usually the object is a server object (for server-dependent events), a discord api instance (for server-independent events, like DMs or GMs) or {@code null} (for lifecycle events, like connection lost, resume or reconnect). Providing {@code null} means, that already started dispatchings are going to be finished, then all events with a {@code null} queue selector are dispatched and finally other events are dispatched like normal again. Events with the same queue selector are dispatched sequentially in the correct order of enqueueal, but on arbitrary threads from a thread pool. Events with different queue selectors are dispatched in parallel. @param listeners A list with listeners which get consumed by the given consumer. @param consumer A consumer which consumes all listeners from the given list and is meant to call their {@code onXyz(Event)} method. @param <T> The type of the listener. """ api.getThreadPool().getSingleThreadExecutorService("Event Dispatch Queues Manager").submit(() -> { if (queueSelector != null) { // Object dependent listeners // Don't allow adding of more events while there are unfinished object independent tasks Queue<Runnable> objectIndependentQueue = queuedListenerTasks.get(null); while (!objectIndependentQueue.isEmpty()) { try { synchronized (queuedListenerTasks) { // Just to be on the safe side, we use a timeout of 5 seconds queuedListenerTasks.wait(5000); } } catch (InterruptedException ignored) { } } } Queue<Runnable> queue = queuedListenerTasks.computeIfAbsent( queueSelector, o -> new ConcurrentLinkedQueue<>()); listeners.forEach(listener -> queue.add(() -> consumer.accept(listener))); checkRunningListenersAndStartIfPossible(queueSelector); }); }
java
protected <T> void dispatchEvent(DispatchQueueSelector queueSelector, List<T> listeners, Consumer<T> consumer) { api.getThreadPool().getSingleThreadExecutorService("Event Dispatch Queues Manager").submit(() -> { if (queueSelector != null) { // Object dependent listeners // Don't allow adding of more events while there are unfinished object independent tasks Queue<Runnable> objectIndependentQueue = queuedListenerTasks.get(null); while (!objectIndependentQueue.isEmpty()) { try { synchronized (queuedListenerTasks) { // Just to be on the safe side, we use a timeout of 5 seconds queuedListenerTasks.wait(5000); } } catch (InterruptedException ignored) { } } } Queue<Runnable> queue = queuedListenerTasks.computeIfAbsent( queueSelector, o -> new ConcurrentLinkedQueue<>()); listeners.forEach(listener -> queue.add(() -> consumer.accept(listener))); checkRunningListenersAndStartIfPossible(queueSelector); }); }
[ "protected", "<", "T", ">", "void", "dispatchEvent", "(", "DispatchQueueSelector", "queueSelector", ",", "List", "<", "T", ">", "listeners", ",", "Consumer", "<", "T", ">", "consumer", ")", "{", "api", ".", "getThreadPool", "(", ")", ".", "getSingleThreadExecutorService", "(", "\"Event Dispatch Queues Manager\"", ")", ".", "submit", "(", "(", ")", "->", "{", "if", "(", "queueSelector", "!=", "null", ")", "{", "// Object dependent listeners", "// Don't allow adding of more events while there are unfinished object independent tasks", "Queue", "<", "Runnable", ">", "objectIndependentQueue", "=", "queuedListenerTasks", ".", "get", "(", "null", ")", ";", "while", "(", "!", "objectIndependentQueue", ".", "isEmpty", "(", ")", ")", "{", "try", "{", "synchronized", "(", "queuedListenerTasks", ")", "{", "// Just to be on the safe side, we use a timeout of 5 seconds", "queuedListenerTasks", ".", "wait", "(", "5000", ")", ";", "}", "}", "catch", "(", "InterruptedException", "ignored", ")", "{", "}", "}", "}", "Queue", "<", "Runnable", ">", "queue", "=", "queuedListenerTasks", ".", "computeIfAbsent", "(", "queueSelector", ",", "o", "->", "new", "ConcurrentLinkedQueue", "<>", "(", ")", ")", ";", "listeners", ".", "forEach", "(", "listener", "->", "queue", ".", "add", "(", "(", ")", "->", "consumer", ".", "accept", "(", "listener", ")", ")", ")", ";", "checkRunningListenersAndStartIfPossible", "(", "queueSelector", ")", ";", "}", ")", ";", "}" ]
Dispatches an event to the given listeners using the provided consumer. Calling this method usually looks like this: {@code dispatchEvent(server, listeners, listener -> listener.onXyz(event));} @param queueSelector The object which is used to determine in which queue the event should be dispatched. Usually the object is a server object (for server-dependent events), a discord api instance (for server-independent events, like DMs or GMs) or {@code null} (for lifecycle events, like connection lost, resume or reconnect). Providing {@code null} means, that already started dispatchings are going to be finished, then all events with a {@code null} queue selector are dispatched and finally other events are dispatched like normal again. Events with the same queue selector are dispatched sequentially in the correct order of enqueueal, but on arbitrary threads from a thread pool. Events with different queue selectors are dispatched in parallel. @param listeners A list with listeners which get consumed by the given consumer. @param consumer A consumer which consumes all listeners from the given list and is meant to call their {@code onXyz(Event)} method. @param <T> The type of the listener.
[ "Dispatches", "an", "event", "to", "the", "given", "listeners", "using", "the", "provided", "consumer", ".", "Calling", "this", "method", "usually", "looks", "like", "this", ":", "{", "@code", "dispatchEvent", "(", "server", "listeners", "listener", "-", ">", "listener", ".", "onXyz", "(", "event", "))", ";", "}" ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/util/event/EventDispatcherBase.java#L181-L200
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.mergeBrackets
@Pure @Inline(value = "TextUtil.join(' { """ Merge the given strings with to brackets. The brackets are used to delimit the groups of characters. <p>Examples: <ul> <li><code>mergeBrackets("a","b","cd")</code> returns the string <code>"{a}{b}{cd}"</code></li> <li><code>mergeBrackets("a{bcd")</code> returns the string <code>"{a{bcd}"</code></li> </ul> @param strs is the array of strings. @return the string with bracketed strings. @see #join(char, char, Iterable) """', '}', $1)", imported = {TextUtil.class}) public static String mergeBrackets(Iterable<?> strs) { return join('{', '}', strs); }
java
@Pure @Inline(value = "TextUtil.join('{', '}', $1)", imported = {TextUtil.class}) public static String mergeBrackets(Iterable<?> strs) { return join('{', '}', strs); }
[ "@", "Pure", "@", "Inline", "(", "value", "=", "\"TextUtil.join('{', '}', $1)\"", ",", "imported", "=", "{", "TextUtil", ".", "class", "}", ")", "public", "static", "String", "mergeBrackets", "(", "Iterable", "<", "?", ">", "strs", ")", "{", "return", "join", "(", "'", "'", ",", "'", "'", ",", "strs", ")", ";", "}" ]
Merge the given strings with to brackets. The brackets are used to delimit the groups of characters. <p>Examples: <ul> <li><code>mergeBrackets("a","b","cd")</code> returns the string <code>"{a}{b}{cd}"</code></li> <li><code>mergeBrackets("a{bcd")</code> returns the string <code>"{a{bcd}"</code></li> </ul> @param strs is the array of strings. @return the string with bracketed strings. @see #join(char, char, Iterable)
[ "Merge", "the", "given", "strings", "with", "to", "brackets", ".", "The", "brackets", "are", "used", "to", "delimit", "the", "groups", "of", "characters", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L864-L868
geomajas/geomajas-project-geometry
core/src/main/java/org/geomajas/geometry/service/GeometryIndexService.java
GeometryIndexService.isChildOf
public boolean isChildOf(GeometryIndex parentIndex, GeometryIndex childIndex) { """ Checks to see if a given index is the child of another index. @param parentIndex The so-called parent index. @param childIndex The so-called child index. @return Is the second index really a child of the first index? """ if (parentIndex.getValue() != childIndex.getValue()) { return false; } if (parentIndex.hasChild() && childIndex.hasChild()) { return isChildOf(parentIndex.getChild(), childIndex.getChild()); } else if (!parentIndex.hasChild() && childIndex.hasChild()) { return true; } return false; }
java
public boolean isChildOf(GeometryIndex parentIndex, GeometryIndex childIndex) { if (parentIndex.getValue() != childIndex.getValue()) { return false; } if (parentIndex.hasChild() && childIndex.hasChild()) { return isChildOf(parentIndex.getChild(), childIndex.getChild()); } else if (!parentIndex.hasChild() && childIndex.hasChild()) { return true; } return false; }
[ "public", "boolean", "isChildOf", "(", "GeometryIndex", "parentIndex", ",", "GeometryIndex", "childIndex", ")", "{", "if", "(", "parentIndex", ".", "getValue", "(", ")", "!=", "childIndex", ".", "getValue", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "parentIndex", ".", "hasChild", "(", ")", "&&", "childIndex", ".", "hasChild", "(", ")", ")", "{", "return", "isChildOf", "(", "parentIndex", ".", "getChild", "(", ")", ",", "childIndex", ".", "getChild", "(", ")", ")", ";", "}", "else", "if", "(", "!", "parentIndex", ".", "hasChild", "(", ")", "&&", "childIndex", ".", "hasChild", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks to see if a given index is the child of another index. @param parentIndex The so-called parent index. @param childIndex The so-called child index. @return Is the second index really a child of the first index?
[ "Checks", "to", "see", "if", "a", "given", "index", "is", "the", "child", "of", "another", "index", "." ]
train
https://github.com/geomajas/geomajas-project-geometry/blob/09a214fede69c9c01e41630828c4abbb551a557d/core/src/main/java/org/geomajas/geometry/service/GeometryIndexService.java#L337-L347
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/model/JavacElements.java
JavacElements.matchAnnoToTree
private JCTree matchAnnoToTree(AnnotationMirror findme, Element e, JCTree tree) { """ Returns the tree for an annotation given the annotated element and the element's own tree. Returns null if the tree cannot be found. """ Symbol sym = cast(Symbol.class, e); class Vis extends JCTree.Visitor { List<JCAnnotation> result = null; public void visitTopLevel(JCCompilationUnit tree) { result = tree.packageAnnotations; } public void visitClassDef(JCClassDecl tree) { result = tree.mods.annotations; } public void visitMethodDef(JCMethodDecl tree) { result = tree.mods.annotations; } public void visitVarDef(JCVariableDecl tree) { result = tree.mods.annotations; } } Vis vis = new Vis(); tree.accept(vis); if (vis.result == null) return null; List<Attribute.Compound> annos = sym.getRawAttributes(); return matchAnnoToTree(cast(Attribute.Compound.class, findme), annos, vis.result); }
java
private JCTree matchAnnoToTree(AnnotationMirror findme, Element e, JCTree tree) { Symbol sym = cast(Symbol.class, e); class Vis extends JCTree.Visitor { List<JCAnnotation> result = null; public void visitTopLevel(JCCompilationUnit tree) { result = tree.packageAnnotations; } public void visitClassDef(JCClassDecl tree) { result = tree.mods.annotations; } public void visitMethodDef(JCMethodDecl tree) { result = tree.mods.annotations; } public void visitVarDef(JCVariableDecl tree) { result = tree.mods.annotations; } } Vis vis = new Vis(); tree.accept(vis); if (vis.result == null) return null; List<Attribute.Compound> annos = sym.getRawAttributes(); return matchAnnoToTree(cast(Attribute.Compound.class, findme), annos, vis.result); }
[ "private", "JCTree", "matchAnnoToTree", "(", "AnnotationMirror", "findme", ",", "Element", "e", ",", "JCTree", "tree", ")", "{", "Symbol", "sym", "=", "cast", "(", "Symbol", ".", "class", ",", "e", ")", ";", "class", "Vis", "extends", "JCTree", ".", "Visitor", "{", "List", "<", "JCAnnotation", ">", "result", "=", "null", ";", "public", "void", "visitTopLevel", "(", "JCCompilationUnit", "tree", ")", "{", "result", "=", "tree", ".", "packageAnnotations", ";", "}", "public", "void", "visitClassDef", "(", "JCClassDecl", "tree", ")", "{", "result", "=", "tree", ".", "mods", ".", "annotations", ";", "}", "public", "void", "visitMethodDef", "(", "JCMethodDecl", "tree", ")", "{", "result", "=", "tree", ".", "mods", ".", "annotations", ";", "}", "public", "void", "visitVarDef", "(", "JCVariableDecl", "tree", ")", "{", "result", "=", "tree", ".", "mods", ".", "annotations", ";", "}", "}", "Vis", "vis", "=", "new", "Vis", "(", ")", ";", "tree", ".", "accept", "(", "vis", ")", ";", "if", "(", "vis", ".", "result", "==", "null", ")", "return", "null", ";", "List", "<", "Attribute", ".", "Compound", ">", "annos", "=", "sym", ".", "getRawAttributes", "(", ")", ";", "return", "matchAnnoToTree", "(", "cast", "(", "Attribute", ".", "Compound", ".", "class", ",", "findme", ")", ",", "annos", ",", "vis", ".", "result", ")", ";", "}" ]
Returns the tree for an annotation given the annotated element and the element's own tree. Returns null if the tree cannot be found.
[ "Returns", "the", "tree", "for", "an", "annotation", "given", "the", "annotated", "element", "and", "the", "element", "s", "own", "tree", ".", "Returns", "null", "if", "the", "tree", "cannot", "be", "found", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/model/JavacElements.java#L179-L206
visallo/vertexium
security/src/main/java/org/vertexium/security/ByteSequence.java
ByteSequence.compareTo
public int compareTo(ByteSequence obs) { """ Compares this byte sequence to another. @param obs byte sequence to compare @return comparison result @see #compareBytes(ByteSequence, ByteSequence) """ if (isBackedByArray() && obs.isBackedByArray()) { return WritableComparator.compareBytes(getBackingArray(), offset(), length(), obs.getBackingArray(), obs.offset(), obs.length()); } return compareBytes(this, obs); }
java
public int compareTo(ByteSequence obs) { if (isBackedByArray() && obs.isBackedByArray()) { return WritableComparator.compareBytes(getBackingArray(), offset(), length(), obs.getBackingArray(), obs.offset(), obs.length()); } return compareBytes(this, obs); }
[ "public", "int", "compareTo", "(", "ByteSequence", "obs", ")", "{", "if", "(", "isBackedByArray", "(", ")", "&&", "obs", ".", "isBackedByArray", "(", ")", ")", "{", "return", "WritableComparator", ".", "compareBytes", "(", "getBackingArray", "(", ")", ",", "offset", "(", ")", ",", "length", "(", ")", ",", "obs", ".", "getBackingArray", "(", ")", ",", "obs", ".", "offset", "(", ")", ",", "obs", ".", "length", "(", ")", ")", ";", "}", "return", "compareBytes", "(", "this", ",", "obs", ")", ";", "}" ]
Compares this byte sequence to another. @param obs byte sequence to compare @return comparison result @see #compareBytes(ByteSequence, ByteSequence)
[ "Compares", "this", "byte", "sequence", "to", "another", "." ]
train
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/ByteSequence.java#L113-L119
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.validUnionTypeExpression
private boolean validUnionTypeExpression(Node expr) { """ A Union type expression must be a valid type variable or a union(TTLExp, TTLExp, ...) """ // The expression must have at least three children: The union keyword and // two type expressions if (!checkParameterCount(expr, Keywords.UNION)) { return false; } int paramCount = getCallParamCount(expr); // Check if each of the members of the union is a valid type expression for (int i = 0; i < paramCount; i++) { if (!validTypeTransformationExpression(getCallArgument(expr, i))) { warnInvalidInside("union type", expr); return false; } } return true; }
java
private boolean validUnionTypeExpression(Node expr) { // The expression must have at least three children: The union keyword and // two type expressions if (!checkParameterCount(expr, Keywords.UNION)) { return false; } int paramCount = getCallParamCount(expr); // Check if each of the members of the union is a valid type expression for (int i = 0; i < paramCount; i++) { if (!validTypeTransformationExpression(getCallArgument(expr, i))) { warnInvalidInside("union type", expr); return false; } } return true; }
[ "private", "boolean", "validUnionTypeExpression", "(", "Node", "expr", ")", "{", "// The expression must have at least three children: The union keyword and", "// two type expressions", "if", "(", "!", "checkParameterCount", "(", "expr", ",", "Keywords", ".", "UNION", ")", ")", "{", "return", "false", ";", "}", "int", "paramCount", "=", "getCallParamCount", "(", "expr", ")", ";", "// Check if each of the members of the union is a valid type expression", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paramCount", ";", "i", "++", ")", "{", "if", "(", "!", "validTypeTransformationExpression", "(", "getCallArgument", "(", "expr", ",", "i", ")", ")", ")", "{", "warnInvalidInside", "(", "\"union type\"", ",", "expr", ")", ";", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
A Union type expression must be a valid type variable or a union(TTLExp, TTLExp, ...)
[ "A", "Union", "type", "expression", "must", "be", "a", "valid", "type", "variable", "or", "a", "union", "(", "TTLExp", "TTLExp", "...", ")" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L320-L335
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/out/XMxmlSerializer.java
XMxmlSerializer.addAttributes
protected void addAttributes(SXTag node, Collection<XAttribute> attributes) throws IOException { """ Helper method, adds attributes to a tag. @param node The tag to add attributes to. @param attributes The attributes to add. """ SXTag data = node.addChildNode("Data"); addAttributes(data, "", attributes); }
java
protected void addAttributes(SXTag node, Collection<XAttribute> attributes) throws IOException { SXTag data = node.addChildNode("Data"); addAttributes(data, "", attributes); }
[ "protected", "void", "addAttributes", "(", "SXTag", "node", ",", "Collection", "<", "XAttribute", ">", "attributes", ")", "throws", "IOException", "{", "SXTag", "data", "=", "node", ".", "addChildNode", "(", "\"Data\"", ")", ";", "addAttributes", "(", "data", ",", "\"\"", ",", "attributes", ")", ";", "}" ]
Helper method, adds attributes to a tag. @param node The tag to add attributes to. @param attributes The attributes to add.
[ "Helper", "method", "adds", "attributes", "to", "a", "tag", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/out/XMxmlSerializer.java#L232-L236
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java
MapConfigurationPropertySource.put
public void put(Object name, Object value) { """ Add an individual entry. @param name the name @param value the value """ this.source.put((name != null) ? name.toString() : null, value); }
java
public void put(Object name, Object value) { this.source.put((name != null) ? name.toString() : null, value); }
[ "public", "void", "put", "(", "Object", "name", ",", "Object", "value", ")", "{", "this", ".", "source", ".", "put", "(", "(", "name", "!=", "null", ")", "?", "name", ".", "toString", "(", ")", ":", "null", ",", "value", ")", ";", "}" ]
Add an individual entry. @param name the name @param value the value
[ "Add", "an", "individual", "entry", "." ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySource.java#L77-L79
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java
EmbedBuilder.setImage
public EmbedBuilder setImage(InputStream image, String fileType) { """ Sets the image of the embed. @param image The image. @param fileType The type of the file, e.g. "png" or "gif". @return The current instance in order to chain call methods. """ delegate.setImage(image, fileType); return this; }
java
public EmbedBuilder setImage(InputStream image, String fileType) { delegate.setImage(image, fileType); return this; }
[ "public", "EmbedBuilder", "setImage", "(", "InputStream", "image", ",", "String", "fileType", ")", "{", "delegate", ".", "setImage", "(", "image", ",", "fileType", ")", ";", "return", "this", ";", "}" ]
Sets the image of the embed. @param image The image. @param fileType The type of the file, e.g. "png" or "gif". @return The current instance in order to chain call methods.
[ "Sets", "the", "image", "of", "the", "embed", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/embed/EmbedBuilder.java#L278-L281
ops4j/org.ops4j.base
ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java
NullArgumentException.validateNotEmpty
public static void validateNotEmpty( String stringToCheck, String argumentName ) throws NullArgumentException { """ Validates that the string is not null and not an empty string without trimming the string. @param stringToCheck The object to be tested. @param argumentName The name of the object, which is used to construct the exception message. @throws NullArgumentException if the stringToCheck is either null or zero characters long. """ validateNotEmpty( stringToCheck, false, argumentName ); }
java
public static void validateNotEmpty( String stringToCheck, String argumentName ) throws NullArgumentException { validateNotEmpty( stringToCheck, false, argumentName ); }
[ "public", "static", "void", "validateNotEmpty", "(", "String", "stringToCheck", ",", "String", "argumentName", ")", "throws", "NullArgumentException", "{", "validateNotEmpty", "(", "stringToCheck", ",", "false", ",", "argumentName", ")", ";", "}" ]
Validates that the string is not null and not an empty string without trimming the string. @param stringToCheck The object to be tested. @param argumentName The name of the object, which is used to construct the exception message. @throws NullArgumentException if the stringToCheck is either null or zero characters long.
[ "Validates", "that", "the", "string", "is", "not", "null", "and", "not", "an", "empty", "string", "without", "trimming", "the", "string", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/NullArgumentException.java#L87-L91
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/Configuration.java
Configuration.getEnum
@PublicEvolving public <T extends Enum<T>> T getEnum( final Class<T> enumClass, final ConfigOption<String> configOption) { """ Returns the value associated with the given config option as an enum. @param enumClass The return enum class @param configOption The configuration option @throws IllegalArgumentException If the string associated with the given config option cannot be parsed as a value of the provided enum class. """ checkNotNull(enumClass, "enumClass must not be null"); checkNotNull(configOption, "configOption must not be null"); final String configValue = getString(configOption); try { return Enum.valueOf(enumClass, configValue.toUpperCase(Locale.ROOT)); } catch (final IllegalArgumentException | NullPointerException e) { final String errorMessage = String.format("Value for config option %s must be one of %s (was %s)", configOption.key(), Arrays.toString(enumClass.getEnumConstants()), configValue); throw new IllegalArgumentException(errorMessage, e); } }
java
@PublicEvolving public <T extends Enum<T>> T getEnum( final Class<T> enumClass, final ConfigOption<String> configOption) { checkNotNull(enumClass, "enumClass must not be null"); checkNotNull(configOption, "configOption must not be null"); final String configValue = getString(configOption); try { return Enum.valueOf(enumClass, configValue.toUpperCase(Locale.ROOT)); } catch (final IllegalArgumentException | NullPointerException e) { final String errorMessage = String.format("Value for config option %s must be one of %s (was %s)", configOption.key(), Arrays.toString(enumClass.getEnumConstants()), configValue); throw new IllegalArgumentException(errorMessage, e); } }
[ "@", "PublicEvolving", "public", "<", "T", "extends", "Enum", "<", "T", ">", ">", "T", "getEnum", "(", "final", "Class", "<", "T", ">", "enumClass", ",", "final", "ConfigOption", "<", "String", ">", "configOption", ")", "{", "checkNotNull", "(", "enumClass", ",", "\"enumClass must not be null\"", ")", ";", "checkNotNull", "(", "configOption", ",", "\"configOption must not be null\"", ")", ";", "final", "String", "configValue", "=", "getString", "(", "configOption", ")", ";", "try", "{", "return", "Enum", ".", "valueOf", "(", "enumClass", ",", "configValue", ".", "toUpperCase", "(", "Locale", ".", "ROOT", ")", ")", ";", "}", "catch", "(", "final", "IllegalArgumentException", "|", "NullPointerException", "e", ")", "{", "final", "String", "errorMessage", "=", "String", ".", "format", "(", "\"Value for config option %s must be one of %s (was %s)\"", ",", "configOption", ".", "key", "(", ")", ",", "Arrays", ".", "toString", "(", "enumClass", ".", "getEnumConstants", "(", ")", ")", ",", "configValue", ")", ";", "throw", "new", "IllegalArgumentException", "(", "errorMessage", ",", "e", ")", ";", "}", "}" ]
Returns the value associated with the given config option as an enum. @param enumClass The return enum class @param configOption The configuration option @throws IllegalArgumentException If the string associated with the given config option cannot be parsed as a value of the provided enum class.
[ "Returns", "the", "value", "associated", "with", "the", "given", "config", "option", "as", "an", "enum", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L622-L639
facebookarchive/hadoop-20
src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderTransactional.java
ServerLogReaderTransactional.updateState
private void updateState(FSEditLogOp op, boolean checkTxnId) throws IOException { """ For each operation read from the stream, check if this is a closing transaction. If so, we are sure we need to move to the next segment. We also mark that this is the most recent time, we read something valid from the input. """ InjectionHandler.processEvent(InjectionEvent.SERVERLOGREADER_UPDATE, op); if (checkTxnId) { mostRecentlyReadTransactionTxId = ServerLogReaderUtil.checkTransactionId( mostRecentlyReadTransactionTxId, op); } updateStreamPosition(); // read a valid operation core.getMetrics().readOperations.inc(); mostRecentlyReadTransactionTime = now(); // current log segment ends normally if (op.opCode == FSEditLogOpCodes.OP_END_LOG_SEGMENT) { LOG.info("Segment - ending log segment start txid: " + currentSegmentTxId + ", end txid: " + op.getTransactionId()); // move forward with next segment currentSegmentTxId = op.getTransactionId() + 1; // set the stream to null so the next getNotification() // will recreate it currentEditLogInputStream = null; // indicate that a new stream will be opened currentEditLogInputStreamPosition = -1; } else if (op.opCode == FSEditLogOpCodes.OP_START_LOG_SEGMENT) { LOG.info("Segment - starting log segment start txid: " + currentSegmentTxId); } }
java
private void updateState(FSEditLogOp op, boolean checkTxnId) throws IOException { InjectionHandler.processEvent(InjectionEvent.SERVERLOGREADER_UPDATE, op); if (checkTxnId) { mostRecentlyReadTransactionTxId = ServerLogReaderUtil.checkTransactionId( mostRecentlyReadTransactionTxId, op); } updateStreamPosition(); // read a valid operation core.getMetrics().readOperations.inc(); mostRecentlyReadTransactionTime = now(); // current log segment ends normally if (op.opCode == FSEditLogOpCodes.OP_END_LOG_SEGMENT) { LOG.info("Segment - ending log segment start txid: " + currentSegmentTxId + ", end txid: " + op.getTransactionId()); // move forward with next segment currentSegmentTxId = op.getTransactionId() + 1; // set the stream to null so the next getNotification() // will recreate it currentEditLogInputStream = null; // indicate that a new stream will be opened currentEditLogInputStreamPosition = -1; } else if (op.opCode == FSEditLogOpCodes.OP_START_LOG_SEGMENT) { LOG.info("Segment - starting log segment start txid: " + currentSegmentTxId); } }
[ "private", "void", "updateState", "(", "FSEditLogOp", "op", ",", "boolean", "checkTxnId", ")", "throws", "IOException", "{", "InjectionHandler", ".", "processEvent", "(", "InjectionEvent", ".", "SERVERLOGREADER_UPDATE", ",", "op", ")", ";", "if", "(", "checkTxnId", ")", "{", "mostRecentlyReadTransactionTxId", "=", "ServerLogReaderUtil", ".", "checkTransactionId", "(", "mostRecentlyReadTransactionTxId", ",", "op", ")", ";", "}", "updateStreamPosition", "(", ")", ";", "// read a valid operation", "core", ".", "getMetrics", "(", ")", ".", "readOperations", ".", "inc", "(", ")", ";", "mostRecentlyReadTransactionTime", "=", "now", "(", ")", ";", "// current log segment ends normally", "if", "(", "op", ".", "opCode", "==", "FSEditLogOpCodes", ".", "OP_END_LOG_SEGMENT", ")", "{", "LOG", ".", "info", "(", "\"Segment - ending log segment start txid: \"", "+", "currentSegmentTxId", "+", "\", end txid: \"", "+", "op", ".", "getTransactionId", "(", ")", ")", ";", "// move forward with next segment", "currentSegmentTxId", "=", "op", ".", "getTransactionId", "(", ")", "+", "1", ";", "// set the stream to null so the next getNotification()", "// will recreate it", "currentEditLogInputStream", "=", "null", ";", "// indicate that a new stream will be opened", "currentEditLogInputStreamPosition", "=", "-", "1", ";", "}", "else", "if", "(", "op", ".", "opCode", "==", "FSEditLogOpCodes", ".", "OP_START_LOG_SEGMENT", ")", "{", "LOG", ".", "info", "(", "\"Segment - starting log segment start txid: \"", "+", "currentSegmentTxId", ")", ";", "}", "}" ]
For each operation read from the stream, check if this is a closing transaction. If so, we are sure we need to move to the next segment. We also mark that this is the most recent time, we read something valid from the input.
[ "For", "each", "operation", "read", "from", "the", "stream", "check", "if", "this", "is", "a", "closing", "transaction", ".", "If", "so", "we", "are", "sure", "we", "need", "to", "move", "to", "the", "next", "segment", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerLogReaderTransactional.java#L253-L282
osglworks/java-tool
src/main/java/org/osgl/util/KVStore.java
KVStore.putValue
@Override public KVStore putValue(String key, Object val) { """ Put a simple data into the store with a key. The type of simple data should be allowed by {@link ValueObject} @param key the key @param val the value @return this store instance after the put operation finished @see ValueObject """ put(key, ValueObject.of(val)); return this; }
java
@Override public KVStore putValue(String key, Object val) { put(key, ValueObject.of(val)); return this; }
[ "@", "Override", "public", "KVStore", "putValue", "(", "String", "key", ",", "Object", "val", ")", "{", "put", "(", "key", ",", "ValueObject", ".", "of", "(", "val", ")", ")", ";", "return", "this", ";", "}" ]
Put a simple data into the store with a key. The type of simple data should be allowed by {@link ValueObject} @param key the key @param val the value @return this store instance after the put operation finished @see ValueObject
[ "Put", "a", "simple", "data", "into", "the", "store", "with", "a", "key", ".", "The", "type", "of", "simple", "data", "should", "be", "allowed", "by", "{" ]
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/KVStore.java#L62-L66
threerings/nenya
core/src/main/java/com/threerings/resource/ResourceManager.java
ResourceManager.createResourceBundle
protected ResourceBundle createResourceBundle (String setType, String path, List<ResourceBundle> dlist) { """ Creates a ResourceBundle based on the supplied definition information. """ if (setType.equals(FILE_SET_TYPE)) { FileResourceBundle bundle = createFileResourceBundle(getResourceFile(path), true, _unpack); if (!bundle.isUnpacked() || !bundle.sourceIsReady()) { dlist.add(bundle); } return bundle; } else if (setType.equals(NETWORK_SET_TYPE)) { return createNetworkResourceBundle(_networkRootPath, path, getResourceList()); } else { throw new IllegalArgumentException("Unknown set type: " + setType); } }
java
protected ResourceBundle createResourceBundle (String setType, String path, List<ResourceBundle> dlist) { if (setType.equals(FILE_SET_TYPE)) { FileResourceBundle bundle = createFileResourceBundle(getResourceFile(path), true, _unpack); if (!bundle.isUnpacked() || !bundle.sourceIsReady()) { dlist.add(bundle); } return bundle; } else if (setType.equals(NETWORK_SET_TYPE)) { return createNetworkResourceBundle(_networkRootPath, path, getResourceList()); } else { throw new IllegalArgumentException("Unknown set type: " + setType); } }
[ "protected", "ResourceBundle", "createResourceBundle", "(", "String", "setType", ",", "String", "path", ",", "List", "<", "ResourceBundle", ">", "dlist", ")", "{", "if", "(", "setType", ".", "equals", "(", "FILE_SET_TYPE", ")", ")", "{", "FileResourceBundle", "bundle", "=", "createFileResourceBundle", "(", "getResourceFile", "(", "path", ")", ",", "true", ",", "_unpack", ")", ";", "if", "(", "!", "bundle", ".", "isUnpacked", "(", ")", "||", "!", "bundle", ".", "sourceIsReady", "(", ")", ")", "{", "dlist", ".", "add", "(", "bundle", ")", ";", "}", "return", "bundle", ";", "}", "else", "if", "(", "setType", ".", "equals", "(", "NETWORK_SET_TYPE", ")", ")", "{", "return", "createNetworkResourceBundle", "(", "_networkRootPath", ",", "path", ",", "getResourceList", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unknown set type: \"", "+", "setType", ")", ";", "}", "}" ]
Creates a ResourceBundle based on the supplied definition information.
[ "Creates", "a", "ResourceBundle", "based", "on", "the", "supplied", "definition", "information", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L821-L836
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java
JBBPDslBuilder.FloatArray
public JBBPDslBuilder FloatArray(final String name, final String sizeExpression) { """ Add named float array which size calculated through expression. @param name name of the field, can be null for anonymous @param sizeExpression expression to be used to calculate size, must not be null @return the builder instance, must not be null """ final Item item = new Item(BinType.FLOAT_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
java
public JBBPDslBuilder FloatArray(final String name, final String sizeExpression) { final Item item = new Item(BinType.FLOAT_ARRAY, name, this.byteOrder); item.sizeExpression = assertExpressionChars(sizeExpression); this.addItem(item); return this; }
[ "public", "JBBPDslBuilder", "FloatArray", "(", "final", "String", "name", ",", "final", "String", "sizeExpression", ")", "{", "final", "Item", "item", "=", "new", "Item", "(", "BinType", ".", "FLOAT_ARRAY", ",", "name", ",", "this", ".", "byteOrder", ")", ";", "item", ".", "sizeExpression", "=", "assertExpressionChars", "(", "sizeExpression", ")", ";", "this", ".", "addItem", "(", "item", ")", ";", "return", "this", ";", "}" ]
Add named float array which size calculated through expression. @param name name of the field, can be null for anonymous @param sizeExpression expression to be used to calculate size, must not be null @return the builder instance, must not be null
[ "Add", "named", "float", "array", "which", "size", "calculated", "through", "expression", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L1267-L1272
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDisplayLayoutPersistenceImpl.java
CPDisplayLayoutPersistenceImpl.findAll
@Override public List<CPDisplayLayout> findAll(int start, int end) { """ Returns a range of all the cp display layouts. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDisplayLayoutModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of cp display layouts @param end the upper bound of the range of cp display layouts (not inclusive) @return the range of cp display layouts """ return findAll(start, end, null); }
java
@Override public List<CPDisplayLayout> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CPDisplayLayout", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp display layouts. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDisplayLayoutModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of cp display layouts @param end the upper bound of the range of cp display layouts (not inclusive) @return the range of cp display layouts
[ "Returns", "a", "range", "of", "all", "the", "cp", "display", "layouts", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDisplayLayoutPersistenceImpl.java#L2348-L2351