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
palatable/lambda
src/main/java/com/jnape/palatable/lambda/adt/Maybe.java
Maybe.orElseThrow
public final <E extends Throwable> A orElseThrow(Supplier<E> throwableSupplier) throws E { """ If the value is present, return it; otherwise, throw the {@link Throwable} supplied by <code>throwableSupplier</code>. @param throwableSupplier the supplier of the potentially thrown {@link Throwable} @param <E> the Throwable type @return the value, if present @throws E the throwable, if the value is absent """ return orElseGet((CheckedSupplier<E, A>) () -> { throw throwableSupplier.get(); }); }
java
public final <E extends Throwable> A orElseThrow(Supplier<E> throwableSupplier) throws E { return orElseGet((CheckedSupplier<E, A>) () -> { throw throwableSupplier.get(); }); }
[ "public", "final", "<", "E", "extends", "Throwable", ">", "A", "orElseThrow", "(", "Supplier", "<", "E", ">", "throwableSupplier", ")", "throws", "E", "{", "return", "orElseGet", "(", "(", "CheckedSupplier", "<", "E", ",", "A", ">", ")", "(", ")", "->", "{", "throw", "throwableSupplier", ".", "get", "(", ")", ";", "}", ")", ";", "}" ]
If the value is present, return it; otherwise, throw the {@link Throwable} supplied by <code>throwableSupplier</code>. @param throwableSupplier the supplier of the potentially thrown {@link Throwable} @param <E> the Throwable type @return the value, if present @throws E the throwable, if the value is absent
[ "If", "the", "value", "is", "present", "return", "it", ";", "otherwise", "throw", "the", "{", "@link", "Throwable", "}", "supplied", "by", "<code", ">", "throwableSupplier<", "/", "code", ">", "." ]
train
https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/adt/Maybe.java#L72-L76
xcesco/kripton
kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/SQLiteUpdateTaskHelper.java
SQLiteUpdateTaskHelper.executeSQL
public static void executeSQL(final SQLiteDatabase database, Context context, int rawResourceId) { """ Execute SQL. @param database the database @param context the context @param rawResourceId the raw resource id """ String[] c = IOUtils.readTextFile(context, rawResourceId).split(";"); List<String> commands = Arrays.asList(c); executeSQL(database, commands); }
java
public static void executeSQL(final SQLiteDatabase database, Context context, int rawResourceId) { String[] c = IOUtils.readTextFile(context, rawResourceId).split(";"); List<String> commands = Arrays.asList(c); executeSQL(database, commands); }
[ "public", "static", "void", "executeSQL", "(", "final", "SQLiteDatabase", "database", ",", "Context", "context", ",", "int", "rawResourceId", ")", "{", "String", "[", "]", "c", "=", "IOUtils", ".", "readTextFile", "(", "context", ",", "rawResourceId", ")", ".", "split", "(", "\";\"", ")", ";", "List", "<", "String", ">", "commands", "=", "Arrays", ".", "asList", "(", "c", ")", ";", "executeSQL", "(", "database", ",", "commands", ")", ";", "}" ]
Execute SQL. @param database the database @param context the context @param rawResourceId the raw resource id
[ "Execute", "SQL", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/SQLiteUpdateTaskHelper.java#L232-L236
lightblue-platform/lightblue-migrator
migrator/src/main/java/com/redhat/lightblue/migrator/Controller.java
Controller.getMigrationConfiguration
public MigrationConfiguration getMigrationConfiguration(String configurationName) throws IOException, LightblueException { """ Read a configuration from the database whose name matches the the given configuration name """ DataFindRequest findRequest = new DataFindRequest("migrationConfiguration", null); findRequest.where(Query.and( Query.withValue("configurationName", Query.eq, configurationName), Query.withValue("consistencyCheckerName", Query.eq, cfg.getName())) ); findRequest.select(Projection.includeFieldRecursively("*")); LOGGER.debug("Loading configuration:{}", findRequest.getBody()); return lightblueClient.data(findRequest, MigrationConfiguration.class); }
java
public MigrationConfiguration getMigrationConfiguration(String configurationName) throws IOException, LightblueException { DataFindRequest findRequest = new DataFindRequest("migrationConfiguration", null); findRequest.where(Query.and( Query.withValue("configurationName", Query.eq, configurationName), Query.withValue("consistencyCheckerName", Query.eq, cfg.getName())) ); findRequest.select(Projection.includeFieldRecursively("*")); LOGGER.debug("Loading configuration:{}", findRequest.getBody()); return lightblueClient.data(findRequest, MigrationConfiguration.class); }
[ "public", "MigrationConfiguration", "getMigrationConfiguration", "(", "String", "configurationName", ")", "throws", "IOException", ",", "LightblueException", "{", "DataFindRequest", "findRequest", "=", "new", "DataFindRequest", "(", "\"migrationConfiguration\"", ",", "null", ")", ";", "findRequest", ".", "where", "(", "Query", ".", "and", "(", "Query", ".", "withValue", "(", "\"configurationName\"", ",", "Query", ".", "eq", ",", "configurationName", ")", ",", "Query", ".", "withValue", "(", "\"consistencyCheckerName\"", ",", "Query", ".", "eq", ",", "cfg", ".", "getName", "(", ")", ")", ")", ")", ";", "findRequest", ".", "select", "(", "Projection", ".", "includeFieldRecursively", "(", "\"*\"", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Loading configuration:{}\"", ",", "findRequest", ".", "getBody", "(", ")", ")", ";", "return", "lightblueClient", ".", "data", "(", "findRequest", ",", "MigrationConfiguration", ".", "class", ")", ";", "}" ]
Read a configuration from the database whose name matches the the given configuration name
[ "Read", "a", "configuration", "from", "the", "database", "whose", "name", "matches", "the", "the", "given", "configuration", "name" ]
train
https://github.com/lightblue-platform/lightblue-migrator/blob/ec20748557b40d1f7851e1816d1b76dae48d2027/migrator/src/main/java/com/redhat/lightblue/migrator/Controller.java#L92-L102
strator-dev/greenpepper
greenpepper/extensions/src/main/java/com/greenpepper/runner/repository/VFSRepository.java
VFSRepository.addProvider
public void addProvider(String urlScheme, FileProvider provider) throws FileSystemException { """ For testing purpose of new VFS providers (eg. Confluence, ...) @param urlScheme a {@link java.lang.String} object. @param provider a {@link org.apache.commons.vfs.provider.FileProvider} object. @throws org.apache.commons.vfs.FileSystemException if any. """ ((DefaultFileSystemManager)fileSystemManager).addProvider(urlScheme, provider); }
java
public void addProvider(String urlScheme, FileProvider provider) throws FileSystemException { ((DefaultFileSystemManager)fileSystemManager).addProvider(urlScheme, provider); }
[ "public", "void", "addProvider", "(", "String", "urlScheme", ",", "FileProvider", "provider", ")", "throws", "FileSystemException", "{", "(", "(", "DefaultFileSystemManager", ")", "fileSystemManager", ")", ".", "addProvider", "(", "urlScheme", ",", "provider", ")", ";", "}" ]
For testing purpose of new VFS providers (eg. Confluence, ...) @param urlScheme a {@link java.lang.String} object. @param provider a {@link org.apache.commons.vfs.provider.FileProvider} object. @throws org.apache.commons.vfs.FileSystemException if any.
[ "For", "testing", "purpose", "of", "new", "VFS", "providers", "(", "eg", ".", "Confluence", "...", ")" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/extensions/src/main/java/com/greenpepper/runner/repository/VFSRepository.java#L127-L130
tomgibara/streams
src/main/java/com/tomgibara/streams/StreamBytes.java
StreamBytes.writeStream
public WriteStream writeStream() { """ Attaches a writer to the object. If there is already an attached writer, the existing writer is returned. If a reader is attached to the object when this method is called, the reader is closed and immediately detached before a writer is created. @return the writer attached to this object """ detachReader(); if (writer == null) { writer = new BytesWriteStream(bytes, maxCapacity); } return writer; }
java
public WriteStream writeStream() { detachReader(); if (writer == null) { writer = new BytesWriteStream(bytes, maxCapacity); } return writer; }
[ "public", "WriteStream", "writeStream", "(", ")", "{", "detachReader", "(", ")", ";", "if", "(", "writer", "==", "null", ")", "{", "writer", "=", "new", "BytesWriteStream", "(", "bytes", ",", "maxCapacity", ")", ";", "}", "return", "writer", ";", "}" ]
Attaches a writer to the object. If there is already an attached writer, the existing writer is returned. If a reader is attached to the object when this method is called, the reader is closed and immediately detached before a writer is created. @return the writer attached to this object
[ "Attaches", "a", "writer", "to", "the", "object", ".", "If", "there", "is", "already", "an", "attached", "writer", "the", "existing", "writer", "is", "returned", ".", "If", "a", "reader", "is", "attached", "to", "the", "object", "when", "this", "method", "is", "called", "the", "reader", "is", "closed", "and", "immediately", "detached", "before", "a", "writer", "is", "created", "." ]
train
https://github.com/tomgibara/streams/blob/553dc97293a1f1fd2d88e08d26e19369e9ffa6d3/src/main/java/com/tomgibara/streams/StreamBytes.java#L108-L114
ecclesia/kipeto
kipeto-core/src/main/java/de/ecclesia/kipeto/repository/FileRepositoryStrategy.java
FileRepositoryStrategy.fileForItem
private File fileForItem(String id) { """ Gibt das mit der Id korrespondierende File-Objekt zurück. (Die Datei muss nicht existieren) @param id @return """ File subDir = subDirForId(id); String fileName = id.substring(SUBDIR_POLICY); return new File(subDir, fileName); }
java
private File fileForItem(String id) { File subDir = subDirForId(id); String fileName = id.substring(SUBDIR_POLICY); return new File(subDir, fileName); }
[ "private", "File", "fileForItem", "(", "String", "id", ")", "{", "File", "subDir", "=", "subDirForId", "(", "id", ")", ";", "String", "fileName", "=", "id", ".", "substring", "(", "SUBDIR_POLICY", ")", ";", "return", "new", "File", "(", "subDir", ",", "fileName", ")", ";", "}" ]
Gibt das mit der Id korrespondierende File-Objekt zurück. (Die Datei muss nicht existieren) @param id @return
[ "Gibt", "das", "mit", "der", "Id", "korrespondierende", "File", "-", "Objekt", "zurück", ".", "(", "Die", "Datei", "muss", "nicht", "existieren", ")" ]
train
https://github.com/ecclesia/kipeto/blob/ea39a10ae4eaa550f71a856ab2f2845270a64913/kipeto-core/src/main/java/de/ecclesia/kipeto/repository/FileRepositoryStrategy.java#L233-L237
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/parser/JavaParser.java
JavaParser.integerLiteral
public final void integerLiteral() throws RecognitionException { """ src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:595:1: integerLiteral : ( HexLiteral | OctalLiteral | DecimalLiteral ); """ int integerLiteral_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 62) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:596:5: ( HexLiteral | OctalLiteral | DecimalLiteral ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g: { if ( input.LA(1)==DecimalLiteral||input.LA(1)==HexLiteral||input.LA(1)==OctalLiteral ) { input.consume(); state.errorRecovery=false; state.failed=false; } else { if (state.backtracking>0) {state.failed=true; return;} MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 62, integerLiteral_StartIndex); } } }
java
public final void integerLiteral() throws RecognitionException { int integerLiteral_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 62) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:596:5: ( HexLiteral | OctalLiteral | DecimalLiteral ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g: { if ( input.LA(1)==DecimalLiteral||input.LA(1)==HexLiteral||input.LA(1)==OctalLiteral ) { input.consume(); state.errorRecovery=false; state.failed=false; } else { if (state.backtracking>0) {state.failed=true; return;} MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 62, integerLiteral_StartIndex); } } }
[ "public", "final", "void", "integerLiteral", "(", ")", "throws", "RecognitionException", "{", "int", "integerLiteral_StartIndex", "=", "input", ".", "index", "(", ")", ";", "try", "{", "if", "(", "state", ".", "backtracking", ">", "0", "&&", "alreadyParsedRule", "(", "input", ",", "62", ")", ")", "{", "return", ";", "}", "// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:596:5: ( HexLiteral | OctalLiteral | DecimalLiteral )", "// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:", "{", "if", "(", "input", ".", "LA", "(", "1", ")", "==", "DecimalLiteral", "||", "input", ".", "LA", "(", "1", ")", "==", "HexLiteral", "||", "input", ".", "LA", "(", "1", ")", "==", "OctalLiteral", ")", "{", "input", ".", "consume", "(", ")", ";", "state", ".", "errorRecovery", "=", "false", ";", "state", ".", "failed", "=", "false", ";", "}", "else", "{", "if", "(", "state", ".", "backtracking", ">", "0", ")", "{", "state", ".", "failed", "=", "true", ";", "return", ";", "}", "MismatchedSetException", "mse", "=", "new", "MismatchedSetException", "(", "null", ",", "input", ")", ";", "throw", "mse", ";", "}", "}", "}", "catch", "(", "RecognitionException", "re", ")", "{", "reportError", "(", "re", ")", ";", "recover", "(", "input", ",", "re", ")", ";", "}", "finally", "{", "// do for sure before leaving", "if", "(", "state", ".", "backtracking", ">", "0", ")", "{", "memoize", "(", "input", ",", "62", ",", "integerLiteral_StartIndex", ")", ";", "}", "}", "}" ]
src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:595:1: integerLiteral : ( HexLiteral | OctalLiteral | DecimalLiteral );
[ "src", "/", "main", "/", "resources", "/", "org", "/", "drools", "/", "compiler", "/", "semantics", "/", "java", "/", "parser", "/", "Java", ".", "g", ":", "595", ":", "1", ":", "integerLiteral", ":", "(", "HexLiteral", "|", "OctalLiteral", "|", "DecimalLiteral", ")", ";" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/parser/JavaParser.java#L5123-L5154
sarxos/webcam-capture
webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java
WebcamMotionDetector.notifyMotionListeners
private void notifyMotionListeners(BufferedImage currentOriginal) { """ Will notify all attached motion listeners. @param image with the motion detected """ WebcamMotionEvent wme = new WebcamMotionEvent(this, previousOriginal, currentOriginal, algorithm.getArea(), algorithm.getCog(), algorithm.getPoints()); for (WebcamMotionListener l : listeners) { try { l.motionDetected(wme); } catch (Exception e) { WebcamExceptionHandler.handle(e); } } }
java
private void notifyMotionListeners(BufferedImage currentOriginal) { WebcamMotionEvent wme = new WebcamMotionEvent(this, previousOriginal, currentOriginal, algorithm.getArea(), algorithm.getCog(), algorithm.getPoints()); for (WebcamMotionListener l : listeners) { try { l.motionDetected(wme); } catch (Exception e) { WebcamExceptionHandler.handle(e); } } }
[ "private", "void", "notifyMotionListeners", "(", "BufferedImage", "currentOriginal", ")", "{", "WebcamMotionEvent", "wme", "=", "new", "WebcamMotionEvent", "(", "this", ",", "previousOriginal", ",", "currentOriginal", ",", "algorithm", ".", "getArea", "(", ")", ",", "algorithm", ".", "getCog", "(", ")", ",", "algorithm", ".", "getPoints", "(", ")", ")", ";", "for", "(", "WebcamMotionListener", "l", ":", "listeners", ")", "{", "try", "{", "l", ".", "motionDetected", "(", "wme", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "WebcamExceptionHandler", ".", "handle", "(", "e", ")", ";", "}", "}", "}" ]
Will notify all attached motion listeners. @param image with the motion detected
[ "Will", "notify", "all", "attached", "motion", "listeners", "." ]
train
https://github.com/sarxos/webcam-capture/blob/efbdae04f9ba48db9ec621e94a9bcd6f031882c8/webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamMotionDetector.java#L276-L285
cdk/cdk
base/core/src/main/java/org/openscience/cdk/graph/GreedyBasis.java
GreedyBasis.addAll
final void addAll(final Iterable<Cycle> cycles) { """ Add all cycles to the basis. @param cycles new members of the basis """ for (final Cycle cycle : cycles) add(cycle); } /** * Check if all the edges of the <i>cycle</i> are present in the current * <i>basis</i>. * * @param cycle an initial cycle * @return any edges of the basis are present */ final boolean isSubsetOfBasis(final Cycle cycle) { final BitSet edgeVector = cycle.edgeVector(); final int intersect = and(edgesOfBasis, edgeVector).cardinality(); return intersect == cycle.length(); } /** * Determine whether the <i>candidate</i> cycle is linearly * <i>independent</i> from the current basis. * * @param candidate a cycle not in currently in the basis * @return the candidate is independent */ final boolean isIndependent(final Cycle candidate) { // simple checks for independence if (basis.isEmpty() || !isSubsetOfBasis(candidate)) return true; final BitMatrix matrix = BitMatrix.from(basis, candidate); // perform gaussian elimination matrix.eliminate(); // if the last row (candidate) was eliminated it is not independent return !matrix.eliminated(basis.size()); } /** and <i>s</i> and <i>t</i> without modifying <i>s</i> */ private static final BitSet and(final BitSet s, final BitSet t) { final BitSet u = (BitSet) s.clone(); u.and(t); return u; } }
java
final void addAll(final Iterable<Cycle> cycles) { for (final Cycle cycle : cycles) add(cycle); } /** * Check if all the edges of the <i>cycle</i> are present in the current * <i>basis</i>. * * @param cycle an initial cycle * @return any edges of the basis are present */ final boolean isSubsetOfBasis(final Cycle cycle) { final BitSet edgeVector = cycle.edgeVector(); final int intersect = and(edgesOfBasis, edgeVector).cardinality(); return intersect == cycle.length(); } /** * Determine whether the <i>candidate</i> cycle is linearly * <i>independent</i> from the current basis. * * @param candidate a cycle not in currently in the basis * @return the candidate is independent */ final boolean isIndependent(final Cycle candidate) { // simple checks for independence if (basis.isEmpty() || !isSubsetOfBasis(candidate)) return true; final BitMatrix matrix = BitMatrix.from(basis, candidate); // perform gaussian elimination matrix.eliminate(); // if the last row (candidate) was eliminated it is not independent return !matrix.eliminated(basis.size()); } /** and <i>s</i> and <i>t</i> without modifying <i>s</i> */ private static final BitSet and(final BitSet s, final BitSet t) { final BitSet u = (BitSet) s.clone(); u.and(t); return u; } }
[ "final", "void", "addAll", "(", "final", "Iterable", "<", "Cycle", ">", "cycles", ")", "{", "for", "(", "final", "Cycle", "cycle", ":", "cycles", ")", "add", "(", "cycle", ")", ";", "}", "/**\n * Check if all the edges of the <i>cycle</i> are present in the current\n * <i>basis</i>.\n *\n * @param cycle an initial cycle\n * @return any edges of the basis are present\n */", "final", "boolean", "isSubsetOfBasis", "(", "final", "Cycle", "cycle", ")", "{", "final", "BitSet", "edgeVector", "=", "cycle", ".", "edgeVector", "(", ")", ";", "final", "int", "intersect", "=", "and", "(", "edgesOfBasis", ",", "edgeVector", ")", ".", "cardinality", "(", ")", ";", "return", "intersect", "==", "cycle", ".", "length", "(", ")", ";", "}", "/**\n * Determine whether the <i>candidate</i> cycle is linearly\n * <i>independent</i> from the current basis.\n *\n * @param candidate a cycle not in currently in the basis\n * @return the candidate is independent\n */", "final", "boolean", "isIndependent", "", "(", "final", "Cycle", "candidate", ")", "{", "// simple checks for independence", "if", "(", "basis", ".", "isEmpty", "(", ")", "||", "!", "isSubsetOfBasis", "(", "candidate", ")", ")", "return", "true", ";", "final", "BitMatrix", "matrix", "=", "BitMatrix", ".", "from", "(", "basis", ",", "candidate", ")", ";", "// perform gaussian elimination", "matrix", ".", "eliminate", "(", ")", ";", "// if the last row (candidate) was eliminated it is not independent", "return", "!", "matrix", ".", "eliminated", "(", "basis", ".", "size", "(", ")", ")", ";", "}", "/** and <i>s</i> and <i>t</i> without modifying <i>s</i> */", "private", "static", "final", "BitSet", "and", "", "(", "final", "BitSet", "s", ",", "final", "BitSet", "t", ")", "{", "final", "BitSet", "u", "=", "(", "BitSet", ")", "s", ".", "clone", "(", ")", ";", "u", ".", "and", "(", "t", ")", ";", "return", "u", ";", "}", "}" ]
Add all cycles to the basis. @param cycles new members of the basis
[ "Add", "all", "cycles", "to", "the", "basis", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/GreedyBasis.java#L102-L147
dbracewell/mango
src/main/java/com/davidbracewell/io/JarUtils.java
JarUtils.getJarContents
public static List<Resource> getJarContents(@NonNull Resource resource) { """ <p> Traverse a jar file and get the package names in it </p> @param resource The jar file to traverse @return A Set of package names """ return getResourcesFromJar(resource, v -> true); }
java
public static List<Resource> getJarContents(@NonNull Resource resource) { return getResourcesFromJar(resource, v -> true); }
[ "public", "static", "List", "<", "Resource", ">", "getJarContents", "(", "@", "NonNull", "Resource", "resource", ")", "{", "return", "getResourcesFromJar", "(", "resource", ",", "v", "->", "true", ")", ";", "}" ]
<p> Traverse a jar file and get the package names in it </p> @param resource The jar file to traverse @return A Set of package names
[ "<p", ">", "Traverse", "a", "jar", "file", "and", "get", "the", "package", "names", "in", "it", "<", "/", "p", ">" ]
train
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/io/JarUtils.java#L69-L71
streamsets/datacollector-api
src/main/java/com/streamsets/pipeline/api/impl/Utils.java
Utils.checkArgument
public static void checkArgument(boolean expression, @Nullable Object msg) { """ Ensures the truth of an expression involving one or more parameters to the calling method. @param expression a boolean expression @param msg the exception message to use if the check fails; will be converted to a string using {@link String#valueOf(Object)} @throws IllegalArgumentException if {@code expression} is false """ if (!expression) { throw new IllegalArgumentException(String.valueOf(msg)); } }
java
public static void checkArgument(boolean expression, @Nullable Object msg) { if (!expression) { throw new IllegalArgumentException(String.valueOf(msg)); } }
[ "public", "static", "void", "checkArgument", "(", "boolean", "expression", ",", "@", "Nullable", "Object", "msg", ")", "{", "if", "(", "!", "expression", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "valueOf", "(", "msg", ")", ")", ";", "}", "}" ]
Ensures the truth of an expression involving one or more parameters to the calling method. @param expression a boolean expression @param msg the exception message to use if the check fails; will be converted to a string using {@link String#valueOf(Object)} @throws IllegalArgumentException if {@code expression} is false
[ "Ensures", "the", "truth", "of", "an", "expression", "involving", "one", "or", "more", "parameters", "to", "the", "calling", "method", "." ]
train
https://github.com/streamsets/datacollector-api/blob/ac832a97bea2fcef11f50fac6746e85019adad58/src/main/java/com/streamsets/pipeline/api/impl/Utils.java#L70-L74
vkostyukov/la4j
src/main/java/org/la4j/Vectors.java
Vectors.mkManhattanNormAccumulator
public static VectorAccumulator mkManhattanNormAccumulator() { """ Makes a Manhattan norm accumulator that allows to use {@link org.la4j.Vector#fold(org.la4j.vector.functor.VectorAccumulator)} method for norm calculation. @return a Manhattan norm accumulator """ return new VectorAccumulator() { private double result = 0.0; @Override public void update(int i, double value) { result += Math.abs(value); } @Override public double accumulate() { double value = result; result = 0.0; return value; } }; }
java
public static VectorAccumulator mkManhattanNormAccumulator() { return new VectorAccumulator() { private double result = 0.0; @Override public void update(int i, double value) { result += Math.abs(value); } @Override public double accumulate() { double value = result; result = 0.0; return value; } }; }
[ "public", "static", "VectorAccumulator", "mkManhattanNormAccumulator", "(", ")", "{", "return", "new", "VectorAccumulator", "(", ")", "{", "private", "double", "result", "=", "0.0", ";", "@", "Override", "public", "void", "update", "(", "int", "i", ",", "double", "value", ")", "{", "result", "+=", "Math", ".", "abs", "(", "value", ")", ";", "}", "@", "Override", "public", "double", "accumulate", "(", ")", "{", "double", "value", "=", "result", ";", "result", "=", "0.0", ";", "return", "value", ";", "}", "}", ";", "}" ]
Makes a Manhattan norm accumulator that allows to use {@link org.la4j.Vector#fold(org.la4j.vector.functor.VectorAccumulator)} method for norm calculation. @return a Manhattan norm accumulator
[ "Makes", "a", "Manhattan", "norm", "accumulator", "that", "allows", "to", "use", "{", "@link", "org", ".", "la4j", ".", "Vector#fold", "(", "org", ".", "la4j", ".", "vector", ".", "functor", ".", "VectorAccumulator", ")", "}", "method", "for", "norm", "calculation", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Vectors.java#L353-L369
grpc/grpc-java
okhttp/src/main/java/io/grpc/okhttp/AsyncSink.java
AsyncSink.becomeConnected
void becomeConnected(Sink sink, Socket socket) { """ Sets the actual sink. It is allowed to call write / flush operations on the sink iff calling this method is scheduled in the executor. The socket is needed for closing. <p>should only be called once by thread of executor. """ checkState(this.sink == null, "AsyncSink's becomeConnected should only be called once."); this.sink = checkNotNull(sink, "sink"); this.socket = checkNotNull(socket, "socket"); }
java
void becomeConnected(Sink sink, Socket socket) { checkState(this.sink == null, "AsyncSink's becomeConnected should only be called once."); this.sink = checkNotNull(sink, "sink"); this.socket = checkNotNull(socket, "socket"); }
[ "void", "becomeConnected", "(", "Sink", "sink", ",", "Socket", "socket", ")", "{", "checkState", "(", "this", ".", "sink", "==", "null", ",", "\"AsyncSink's becomeConnected should only be called once.\"", ")", ";", "this", ".", "sink", "=", "checkNotNull", "(", "sink", ",", "\"sink\"", ")", ";", "this", ".", "socket", "=", "checkNotNull", "(", "socket", ",", "\"socket\"", ")", ";", "}" ]
Sets the actual sink. It is allowed to call write / flush operations on the sink iff calling this method is scheduled in the executor. The socket is needed for closing. <p>should only be called once by thread of executor.
[ "Sets", "the", "actual", "sink", ".", "It", "is", "allowed", "to", "call", "write", "/", "flush", "operations", "on", "the", "sink", "iff", "calling", "this", "method", "is", "scheduled", "in", "the", "executor", ".", "The", "socket", "is", "needed", "for", "closing", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/okhttp/src/main/java/io/grpc/okhttp/AsyncSink.java#L69-L73
zaproxy/zaproxy
src/org/parosproxy/paros/view/AbstractParamContainerPanel.java
AbstractParamContainerPanel.getPanelHeadline
private JPanel getPanelHeadline() { """ Gets the headline panel, that shows the name of the (selected) panel and has the help button. @return the headline panel, never {@code null}. @see #getTxtHeadline() @see #getHelpButton() """ if (panelHeadline == null) { panelHeadline = new JPanel(); panelHeadline.setLayout(new BorderLayout(0, 0)); txtHeadline = getTxtHeadline(); panelHeadline.add(txtHeadline, BorderLayout.CENTER); JButton button = getHelpButton(); panelHeadline.add(button, BorderLayout.EAST); } return panelHeadline; }
java
private JPanel getPanelHeadline() { if (panelHeadline == null) { panelHeadline = new JPanel(); panelHeadline.setLayout(new BorderLayout(0, 0)); txtHeadline = getTxtHeadline(); panelHeadline.add(txtHeadline, BorderLayout.CENTER); JButton button = getHelpButton(); panelHeadline.add(button, BorderLayout.EAST); } return panelHeadline; }
[ "private", "JPanel", "getPanelHeadline", "(", ")", "{", "if", "(", "panelHeadline", "==", "null", ")", "{", "panelHeadline", "=", "new", "JPanel", "(", ")", ";", "panelHeadline", ".", "setLayout", "(", "new", "BorderLayout", "(", "0", ",", "0", ")", ")", ";", "txtHeadline", "=", "getTxtHeadline", "(", ")", ";", "panelHeadline", ".", "add", "(", "txtHeadline", ",", "BorderLayout", ".", "CENTER", ")", ";", "JButton", "button", "=", "getHelpButton", "(", ")", ";", "panelHeadline", ".", "add", "(", "button", ",", "BorderLayout", ".", "EAST", ")", ";", "}", "return", "panelHeadline", ";", "}" ]
Gets the headline panel, that shows the name of the (selected) panel and has the help button. @return the headline panel, never {@code null}. @see #getTxtHeadline() @see #getHelpButton()
[ "Gets", "the", "headline", "panel", "that", "shows", "the", "name", "of", "the", "(", "selected", ")", "panel", "and", "has", "the", "help", "button", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/AbstractParamContainerPanel.java#L268-L281
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/view/WeekView.java
WeekView.setWeekDayViewFactory
public final void setWeekDayViewFactory(Callback<WeekDayParameter, WeekDayView> factory) { """ Sets the value of {@link #weekDayViewFactoryProperty()}. @param factory the new factory """ requireNonNull(factory); weekDayViewFactoryProperty().set(factory); }
java
public final void setWeekDayViewFactory(Callback<WeekDayParameter, WeekDayView> factory) { requireNonNull(factory); weekDayViewFactoryProperty().set(factory); }
[ "public", "final", "void", "setWeekDayViewFactory", "(", "Callback", "<", "WeekDayParameter", ",", "WeekDayView", ">", "factory", ")", "{", "requireNonNull", "(", "factory", ")", ";", "weekDayViewFactoryProperty", "(", ")", ".", "set", "(", "factory", ")", ";", "}" ]
Sets the value of {@link #weekDayViewFactoryProperty()}. @param factory the new factory
[ "Sets", "the", "value", "of", "{", "@link", "#weekDayViewFactoryProperty", "()", "}", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/WeekView.java#L245-L248
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/context/PartialResponseWriter.java
PartialResponseWriter.startExtension
public void startExtension(Map<String, String> attributes) throws IOException { """ <p class="changed_added_2_0">Write the start of an extension operation.</p> @param attributes String name/value pairs for extension element attributes @throws IOException if an input/output error occurs @since 2.0 """ startChangesIfNecessary(); ResponseWriter writer = getWrapped(); writer.startElement("extension", null); if (attributes != null && !attributes.isEmpty()) { for (Map.Entry<String, String> entry : attributes.entrySet()) { writer.writeAttribute(entry.getKey(), entry.getValue(), null); } } }
java
public void startExtension(Map<String, String> attributes) throws IOException { startChangesIfNecessary(); ResponseWriter writer = getWrapped(); writer.startElement("extension", null); if (attributes != null && !attributes.isEmpty()) { for (Map.Entry<String, String> entry : attributes.entrySet()) { writer.writeAttribute(entry.getKey(), entry.getValue(), null); } } }
[ "public", "void", "startExtension", "(", "Map", "<", "String", ",", "String", ">", "attributes", ")", "throws", "IOException", "{", "startChangesIfNecessary", "(", ")", ";", "ResponseWriter", "writer", "=", "getWrapped", "(", ")", ";", "writer", ".", "startElement", "(", "\"extension\"", ",", "null", ")", ";", "if", "(", "attributes", "!=", "null", "&&", "!", "attributes", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "attributes", ".", "entrySet", "(", ")", ")", "{", "writer", ".", "writeAttribute", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ",", "null", ")", ";", "}", "}", "}" ]
<p class="changed_added_2_0">Write the start of an extension operation.</p> @param attributes String name/value pairs for extension element attributes @throws IOException if an input/output error occurs @since 2.0
[ "<p", "class", "=", "changed_added_2_0", ">", "Write", "the", "start", "of", "an", "extension", "operation", ".", "<", "/", "p", ">" ]
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/context/PartialResponseWriter.java#L326-L335
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/monitor/UicStatsAsHtml.java
UicStatsAsHtml.writeRow
private static void writeRow(final PrintWriter writer, final UicStats.Stat stat) { """ Writes a row containing a single stat. @param writer the writer to write the row to. @param stat the stat to write. """ writer.print("<tr>"); writer.print("<td>" + stat.getClassName() + "</td>"); writer.print("<td>" + stat.getModelStateAsString() + "</td>"); if (stat.getSerializedSize() > 0) { writer.print("<td>" + stat.getSerializedSize() + "</td>"); } else { writer.print("<td>&#160;</td>"); } writer.print("<td>" + stat.getRef() + "</td>"); writer.print("<td>" + stat.getName() + "</td>"); if (stat.getComment() == null) { writer.print("<td>&#160;</td>"); } else { writer.print("<td>" + stat.getComment() + "</td>"); } writer.println("</tr>"); }
java
private static void writeRow(final PrintWriter writer, final UicStats.Stat stat) { writer.print("<tr>"); writer.print("<td>" + stat.getClassName() + "</td>"); writer.print("<td>" + stat.getModelStateAsString() + "</td>"); if (stat.getSerializedSize() > 0) { writer.print("<td>" + stat.getSerializedSize() + "</td>"); } else { writer.print("<td>&#160;</td>"); } writer.print("<td>" + stat.getRef() + "</td>"); writer.print("<td>" + stat.getName() + "</td>"); if (stat.getComment() == null) { writer.print("<td>&#160;</td>"); } else { writer.print("<td>" + stat.getComment() + "</td>"); } writer.println("</tr>"); }
[ "private", "static", "void", "writeRow", "(", "final", "PrintWriter", "writer", ",", "final", "UicStats", ".", "Stat", "stat", ")", "{", "writer", ".", "print", "(", "\"<tr>\"", ")", ";", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getClassName", "(", ")", "+", "\"</td>\"", ")", ";", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getModelStateAsString", "(", ")", "+", "\"</td>\"", ")", ";", "if", "(", "stat", ".", "getSerializedSize", "(", ")", ">", "0", ")", "{", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getSerializedSize", "(", ")", "+", "\"</td>\"", ")", ";", "}", "else", "{", "writer", ".", "print", "(", "\"<td>&#160;</td>\"", ")", ";", "}", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getRef", "(", ")", "+", "\"</td>\"", ")", ";", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getName", "(", ")", "+", "\"</td>\"", ")", ";", "if", "(", "stat", ".", "getComment", "(", ")", "==", "null", ")", "{", "writer", ".", "print", "(", "\"<td>&#160;</td>\"", ")", ";", "}", "else", "{", "writer", ".", "print", "(", "\"<td>\"", "+", "stat", ".", "getComment", "(", ")", "+", "\"</td>\"", ")", ";", "}", "writer", ".", "println", "(", "\"</tr>\"", ")", ";", "}" ]
Writes a row containing a single stat. @param writer the writer to write the row to. @param stat the stat to write.
[ "Writes", "a", "row", "containing", "a", "single", "stat", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/monitor/UicStatsAsHtml.java#L131-L152
JetBrains/xodus
entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java
PersistentEntityStoreImpl.getPropertyId
public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) { """ Gets id of a property and creates the new one if necessary. @param txn transaction @param propertyName name of the property. @param allowCreate if set to true and if there is no property named as propertyName, create the new id for the propertyName. @return < 0 if there is no such property and create=false, else id of the property """ return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName); }
java
public int getPropertyId(@NotNull final PersistentStoreTransaction txn, @NotNull final String propertyName, final boolean allowCreate) { return allowCreate ? propertyIds.getOrAllocateId(txn, propertyName) : propertyIds.getId(txn, propertyName); }
[ "public", "int", "getPropertyId", "(", "@", "NotNull", "final", "PersistentStoreTransaction", "txn", ",", "@", "NotNull", "final", "String", "propertyName", ",", "final", "boolean", "allowCreate", ")", "{", "return", "allowCreate", "?", "propertyIds", ".", "getOrAllocateId", "(", "txn", ",", "propertyName", ")", ":", "propertyIds", ".", "getId", "(", "txn", ",", "propertyName", ")", ";", "}" ]
Gets id of a property and creates the new one if necessary. @param txn transaction @param propertyName name of the property. @param allowCreate if set to true and if there is no property named as propertyName, create the new id for the propertyName. @return < 0 if there is no such property and create=false, else id of the property
[ "Gets", "id", "of", "a", "property", "and", "creates", "the", "new", "one", "if", "necessary", "." ]
train
https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java#L1725-L1727
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.batchMmul
public SDVariable[] batchMmul(SDVariable[] matricesA, SDVariable[] matricesB, boolean transposeA, boolean transposeB) { """ Matrix multiply a batch of matrices. matricesA and matricesB have to be arrays of same length and each pair taken from these sets has to have dimensions (M, N) and (N, K), respectively. If transposeA is true, matrices from matricesA will have shape (N, M) instead. Likewise, if transposeB is true, matrices from matricesB will have shape (K, N). <p> <p> The result of this operation will be a batch of multiplied matrices. The result has the same length as both input batches and each output matrix is of shape (M, K). @param matricesA First array of input matrices, all of shape (M, N) or (N, M) @param matricesB Second array of input matrices, all of shape (N, K) or (K, N) @param transposeA whether first batch of matrices is transposed. @param transposeB whether second batch of matrices is transposed. @return Array of multiplied SDVariables of shape (M, K) """ return batchMmul(null, matricesA, matricesB, transposeA, transposeB); }
java
public SDVariable[] batchMmul(SDVariable[] matricesA, SDVariable[] matricesB, boolean transposeA, boolean transposeB) { return batchMmul(null, matricesA, matricesB, transposeA, transposeB); }
[ "public", "SDVariable", "[", "]", "batchMmul", "(", "SDVariable", "[", "]", "matricesA", ",", "SDVariable", "[", "]", "matricesB", ",", "boolean", "transposeA", ",", "boolean", "transposeB", ")", "{", "return", "batchMmul", "(", "null", ",", "matricesA", ",", "matricesB", ",", "transposeA", ",", "transposeB", ")", ";", "}" ]
Matrix multiply a batch of matrices. matricesA and matricesB have to be arrays of same length and each pair taken from these sets has to have dimensions (M, N) and (N, K), respectively. If transposeA is true, matrices from matricesA will have shape (N, M) instead. Likewise, if transposeB is true, matrices from matricesB will have shape (K, N). <p> <p> The result of this operation will be a batch of multiplied matrices. The result has the same length as both input batches and each output matrix is of shape (M, K). @param matricesA First array of input matrices, all of shape (M, N) or (N, M) @param matricesB Second array of input matrices, all of shape (N, K) or (K, N) @param transposeA whether first batch of matrices is transposed. @param transposeB whether second batch of matrices is transposed. @return Array of multiplied SDVariables of shape (M, K)
[ "Matrix", "multiply", "a", "batch", "of", "matrices", ".", "matricesA", "and", "matricesB", "have", "to", "be", "arrays", "of", "same", "length", "and", "each", "pair", "taken", "from", "these", "sets", "has", "to", "have", "dimensions", "(", "M", "N", ")", "and", "(", "N", "K", ")", "respectively", ".", "If", "transposeA", "is", "true", "matrices", "from", "matricesA", "will", "have", "shape", "(", "N", "M", ")", "instead", ".", "Likewise", "if", "transposeB", "is", "true", "matrices", "from", "matricesB", "will", "have", "shape", "(", "K", "N", ")", ".", "<p", ">", "<p", ">", "The", "result", "of", "this", "operation", "will", "be", "a", "batch", "of", "multiplied", "matrices", ".", "The", "result", "has", "the", "same", "length", "as", "both", "input", "batches", "and", "each", "output", "matrix", "is", "of", "shape", "(", "M", "K", ")", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L225-L228
sap-production/xcode-maven-plugin
modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/XCodePrepareBuildManager.java
XCodePrepareBuildManager.createDirectory
private static void createDirectory(final File directory) throws MojoExecutionException { """ Creates a directory. If the directory already exists the directory is deleted beforehand. @param directory @throws MojoExecutionException """ try { com.sap.prd.mobile.ios.mios.FileUtils.deleteDirectory(directory); } catch (IOException ex) { throw new MojoExecutionException("", ex); } if (!directory.mkdirs()) throw new MojoExecutionException("Cannot create directory (" + directory + ")"); }
java
private static void createDirectory(final File directory) throws MojoExecutionException { try { com.sap.prd.mobile.ios.mios.FileUtils.deleteDirectory(directory); } catch (IOException ex) { throw new MojoExecutionException("", ex); } if (!directory.mkdirs()) throw new MojoExecutionException("Cannot create directory (" + directory + ")"); }
[ "private", "static", "void", "createDirectory", "(", "final", "File", "directory", ")", "throws", "MojoExecutionException", "{", "try", "{", "com", ".", "sap", ".", "prd", ".", "mobile", ".", "ios", ".", "mios", ".", "FileUtils", ".", "deleteDirectory", "(", "directory", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"\"", ",", "ex", ")", ";", "}", "if", "(", "!", "directory", ".", "mkdirs", "(", ")", ")", "throw", "new", "MojoExecutionException", "(", "\"Cannot create directory (\"", "+", "directory", "+", "\")\"", ")", ";", "}" ]
Creates a directory. If the directory already exists the directory is deleted beforehand. @param directory @throws MojoExecutionException
[ "Creates", "a", "directory", ".", "If", "the", "directory", "already", "exists", "the", "directory", "is", "deleted", "beforehand", "." ]
train
https://github.com/sap-production/xcode-maven-plugin/blob/3f8aa380f501a1d7602f33fef2f6348354e7eb7c/modules/xcode-maven-plugin/src/main/java/com/sap/prd/mobile/ios/mios/XCodePrepareBuildManager.java#L446-L458
omadahealth/TypefaceView
lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceEditText.java
TypefaceEditText.setCustomTypeface
@BindingAdapter("bind:tv_typeface") public static void setCustomTypeface(TypefaceEditText editText, String type) { """ Data-binding method for custom attribute bind:tv_typeface to be set @param editText The instance of the object to set value on @param type The string name of the typeface, same as in xml """ editText.mCurrentTypeface = TypefaceType.getTypeface(type != null ? type : ""); Typeface typeface = getFont(editText.getContext(), editText.mCurrentTypeface.getAssetFileName()); editText.setTypeface(typeface); }
java
@BindingAdapter("bind:tv_typeface") public static void setCustomTypeface(TypefaceEditText editText, String type) { editText.mCurrentTypeface = TypefaceType.getTypeface(type != null ? type : ""); Typeface typeface = getFont(editText.getContext(), editText.mCurrentTypeface.getAssetFileName()); editText.setTypeface(typeface); }
[ "@", "BindingAdapter", "(", "\"bind:tv_typeface\"", ")", "public", "static", "void", "setCustomTypeface", "(", "TypefaceEditText", "editText", ",", "String", "type", ")", "{", "editText", ".", "mCurrentTypeface", "=", "TypefaceType", ".", "getTypeface", "(", "type", "!=", "null", "?", "type", ":", "\"\"", ")", ";", "Typeface", "typeface", "=", "getFont", "(", "editText", ".", "getContext", "(", ")", ",", "editText", ".", "mCurrentTypeface", ".", "getAssetFileName", "(", ")", ")", ";", "editText", ".", "setTypeface", "(", "typeface", ")", ";", "}" ]
Data-binding method for custom attribute bind:tv_typeface to be set @param editText The instance of the object to set value on @param type The string name of the typeface, same as in xml
[ "Data", "-", "binding", "method", "for", "custom", "attribute", "bind", ":", "tv_typeface", "to", "be", "set" ]
train
https://github.com/omadahealth/TypefaceView/blob/9a36a67b0fb26584c3e20a24f8f0bafad6a0badd/lib/src/main/java/com/github/omadahealth/typefaceview/TypefaceEditText.java#L120-L125
super-csv/super-csv
super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java
ForbidSubStr.execute
public Object execute(final Object value, final CsvContext context) { """ {@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value is in the forbidden list """ validateInputNotNull(value, context); final String stringValue = value.toString(); for( String forbidden : forbiddenSubStrings ) { if( stringValue.contains(forbidden) ) { throw new SuperCsvConstraintViolationException(String.format( "'%s' contains the forbidden substring '%s'", value, forbidden), context, this); } } return next.execute(value, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); final String stringValue = value.toString(); for( String forbidden : forbiddenSubStrings ) { if( stringValue.contains(forbidden) ) { throw new SuperCsvConstraintViolationException(String.format( "'%s' contains the forbidden substring '%s'", value, forbidden), context, this); } } return next.execute(value, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "final", "String", "stringValue", "=", "value", ".", "toString", "(", ")", ";", "for", "(", "String", "forbidden", ":", "forbiddenSubStrings", ")", "{", "if", "(", "stringValue", ".", "contains", "(", "forbidden", ")", ")", "{", "throw", "new", "SuperCsvConstraintViolationException", "(", "String", ".", "format", "(", "\"'%s' contains the forbidden substring '%s'\"", ",", "value", ",", "forbidden", ")", ",", "context", ",", "this", ")", ";", "}", "}", "return", "next", ".", "execute", "(", "value", ",", "context", ")", ";", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value is in the forbidden list
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/ForbidSubStr.java#L201-L214
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/FormatSet.java
FormatSet.customizeDateFormat
public static DateFormat customizeDateFormat(DateFormat formatter, boolean isoDateFormat) { """ Modifies an existing DateFormat object so that it can be used to format timestamps in the System.out, System.err and TraceOutput logs using either default date and time format or ISO-8601 date and time format @param formatter DateFormat object to be modified @param flag to use ISO-8601 date format for output. @return DateFormat object with adjusted pattern """ String pattern; int patternLength; int endOfSecsIndex; if (!!!isoDateFormat) { if (formatter instanceof SimpleDateFormat) { // Retrieve the pattern from the formatter, since we will need to modify it. SimpleDateFormat sdFormatter = (SimpleDateFormat) formatter; pattern = sdFormatter.toPattern(); // Append milliseconds and timezone after seconds patternLength = pattern.length(); endOfSecsIndex = pattern.lastIndexOf('s') + 1; String newPattern = pattern.substring(0, endOfSecsIndex) + ":SSS z"; if (endOfSecsIndex < patternLength) newPattern += pattern.substring(endOfSecsIndex, patternLength); // 0-23 hour clock (get rid of any other clock formats and am/pm) newPattern = newPattern.replace('h', 'H'); newPattern = newPattern.replace('K', 'H'); newPattern = newPattern.replace('k', 'H'); newPattern = newPattern.replace('a', ' '); newPattern = newPattern.trim(); sdFormatter.applyPattern(newPattern); formatter = sdFormatter; } else { formatter = new SimpleDateFormat("yy.MM.dd HH:mm:ss:SSS z"); } } else { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } // PK13288 Start - if (sysTimeZone != null) { formatter.setTimeZone(sysTimeZone); } // PK13288 End return formatter; }
java
public static DateFormat customizeDateFormat(DateFormat formatter, boolean isoDateFormat) { String pattern; int patternLength; int endOfSecsIndex; if (!!!isoDateFormat) { if (formatter instanceof SimpleDateFormat) { // Retrieve the pattern from the formatter, since we will need to modify it. SimpleDateFormat sdFormatter = (SimpleDateFormat) formatter; pattern = sdFormatter.toPattern(); // Append milliseconds and timezone after seconds patternLength = pattern.length(); endOfSecsIndex = pattern.lastIndexOf('s') + 1; String newPattern = pattern.substring(0, endOfSecsIndex) + ":SSS z"; if (endOfSecsIndex < patternLength) newPattern += pattern.substring(endOfSecsIndex, patternLength); // 0-23 hour clock (get rid of any other clock formats and am/pm) newPattern = newPattern.replace('h', 'H'); newPattern = newPattern.replace('K', 'H'); newPattern = newPattern.replace('k', 'H'); newPattern = newPattern.replace('a', ' '); newPattern = newPattern.trim(); sdFormatter.applyPattern(newPattern); formatter = sdFormatter; } else { formatter = new SimpleDateFormat("yy.MM.dd HH:mm:ss:SSS z"); } } else { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } // PK13288 Start - if (sysTimeZone != null) { formatter.setTimeZone(sysTimeZone); } // PK13288 End return formatter; }
[ "public", "static", "DateFormat", "customizeDateFormat", "(", "DateFormat", "formatter", ",", "boolean", "isoDateFormat", ")", "{", "String", "pattern", ";", "int", "patternLength", ";", "int", "endOfSecsIndex", ";", "if", "(", "!", "!", "!", "isoDateFormat", ")", "{", "if", "(", "formatter", "instanceof", "SimpleDateFormat", ")", "{", "// Retrieve the pattern from the formatter, since we will need to modify it.", "SimpleDateFormat", "sdFormatter", "=", "(", "SimpleDateFormat", ")", "formatter", ";", "pattern", "=", "sdFormatter", ".", "toPattern", "(", ")", ";", "// Append milliseconds and timezone after seconds", "patternLength", "=", "pattern", ".", "length", "(", ")", ";", "endOfSecsIndex", "=", "pattern", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ";", "String", "newPattern", "=", "pattern", ".", "substring", "(", "0", ",", "endOfSecsIndex", ")", "+", "\":SSS z\"", ";", "if", "(", "endOfSecsIndex", "<", "patternLength", ")", "newPattern", "+=", "pattern", ".", "substring", "(", "endOfSecsIndex", ",", "patternLength", ")", ";", "// 0-23 hour clock (get rid of any other clock formats and am/pm)", "newPattern", "=", "newPattern", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "newPattern", "=", "newPattern", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "newPattern", "=", "newPattern", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "newPattern", "=", "newPattern", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "newPattern", "=", "newPattern", ".", "trim", "(", ")", ";", "sdFormatter", ".", "applyPattern", "(", "newPattern", ")", ";", "formatter", "=", "sdFormatter", ";", "}", "else", "{", "formatter", "=", "new", "SimpleDateFormat", "(", "\"yy.MM.dd HH:mm:ss:SSS z\"", ")", ";", "}", "}", "else", "{", "formatter", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\"", ")", ";", "}", "// PK13288 Start -", "if", "(", "sysTimeZone", "!=", "null", ")", "{", "formatter", ".", "setTimeZone", "(", "sysTimeZone", ")", ";", "}", "// PK13288 End", "return", "formatter", ";", "}" ]
Modifies an existing DateFormat object so that it can be used to format timestamps in the System.out, System.err and TraceOutput logs using either default date and time format or ISO-8601 date and time format @param formatter DateFormat object to be modified @param flag to use ISO-8601 date format for output. @return DateFormat object with adjusted pattern
[ "Modifies", "an", "existing", "DateFormat", "object", "so", "that", "it", "can", "be", "used", "to", "format", "timestamps", "in", "the", "System", ".", "out", "System", ".", "err", "and", "TraceOutput", "logs", "using", "either", "default", "date", "and", "time", "format", "or", "ISO", "-", "8601", "date", "and", "time", "format" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/FormatSet.java#L127-L164
google/error-prone-javac
src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java
ElementScanner9.visitModule
@Override public R visitModule(ModuleElement e, P p) { """ Visits a {@code ModuleElement} by scanning the enclosed elements. @param e the element to visit @param p a visitor-specified parameter @return the result of the scan """ return scan(e.getEnclosedElements(), p); // TODO: Hmmm, this might not be right }
java
@Override public R visitModule(ModuleElement e, P p) { return scan(e.getEnclosedElements(), p); // TODO: Hmmm, this might not be right }
[ "@", "Override", "public", "R", "visitModule", "(", "ModuleElement", "e", ",", "P", "p", ")", "{", "return", "scan", "(", "e", ".", "getEnclosedElements", "(", ")", ",", "p", ")", ";", "// TODO: Hmmm, this might not be right", "}" ]
Visits a {@code ModuleElement} by scanning the enclosed elements. @param e the element to visit @param p a visitor-specified parameter @return the result of the scan
[ "Visits", "a", "{", "@code", "ModuleElement", "}", "by", "scanning", "the", "enclosed", "elements", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java#L121-L124
mikepenz/FastAdapter
library-extensions-expandable/src/main/java/com/mikepenz/fastadapter/expandable/ExpandableExtension.java
ExpandableExtension.getExpandedItemsCount
public int getExpandedItemsCount(int from, int position) { """ calculates the count of expandable items before a given position @param from the global start position you should pass here the count of items of the previous adapters (or 0 if you want to start from the beginning) @param position the global position @return the count of expandable items before a given position """ int totalAddedItems = 0; //first we find out how many items were added in total //also counting subItems Item tmp; for (int i = from; i < position; i++) { tmp = mFastAdapter.getItem(i); if (tmp instanceof IExpandable) { IExpandable tmpExpandable = ((IExpandable) tmp); if (tmpExpandable.getSubItems() != null && tmpExpandable.isExpanded()) { totalAddedItems = totalAddedItems + tmpExpandable.getSubItems().size(); } } } return totalAddedItems; }
java
public int getExpandedItemsCount(int from, int position) { int totalAddedItems = 0; //first we find out how many items were added in total //also counting subItems Item tmp; for (int i = from; i < position; i++) { tmp = mFastAdapter.getItem(i); if (tmp instanceof IExpandable) { IExpandable tmpExpandable = ((IExpandable) tmp); if (tmpExpandable.getSubItems() != null && tmpExpandable.isExpanded()) { totalAddedItems = totalAddedItems + tmpExpandable.getSubItems().size(); } } } return totalAddedItems; }
[ "public", "int", "getExpandedItemsCount", "(", "int", "from", ",", "int", "position", ")", "{", "int", "totalAddedItems", "=", "0", ";", "//first we find out how many items were added in total", "//also counting subItems", "Item", "tmp", ";", "for", "(", "int", "i", "=", "from", ";", "i", "<", "position", ";", "i", "++", ")", "{", "tmp", "=", "mFastAdapter", ".", "getItem", "(", "i", ")", ";", "if", "(", "tmp", "instanceof", "IExpandable", ")", "{", "IExpandable", "tmpExpandable", "=", "(", "(", "IExpandable", ")", "tmp", ")", ";", "if", "(", "tmpExpandable", ".", "getSubItems", "(", ")", "!=", "null", "&&", "tmpExpandable", ".", "isExpanded", "(", ")", ")", "{", "totalAddedItems", "=", "totalAddedItems", "+", "tmpExpandable", ".", "getSubItems", "(", ")", ".", "size", "(", ")", ";", "}", "}", "}", "return", "totalAddedItems", ";", "}" ]
calculates the count of expandable items before a given position @param from the global start position you should pass here the count of items of the previous adapters (or 0 if you want to start from the beginning) @param position the global position @return the count of expandable items before a given position
[ "calculates", "the", "count", "of", "expandable", "items", "before", "a", "given", "position" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions-expandable/src/main/java/com/mikepenz/fastadapter/expandable/ExpandableExtension.java#L465-L480
alkacon/opencms-core
src/org/opencms/util/CmsFileUtil.java
CmsFileUtil.readFile
public static String readFile(String filename, String encoding) throws IOException { """ Reads a file from the class loader and converts it to a String with the specified encoding.<p> @param filename the file to read @param encoding the encoding to use when converting the file content to a String @return the read file convered to a String @throws IOException in case of file access errors """ return new String(readFile(filename), encoding); }
java
public static String readFile(String filename, String encoding) throws IOException { return new String(readFile(filename), encoding); }
[ "public", "static", "String", "readFile", "(", "String", "filename", ",", "String", "encoding", ")", "throws", "IOException", "{", "return", "new", "String", "(", "readFile", "(", "filename", ")", ",", "encoding", ")", ";", "}" ]
Reads a file from the class loader and converts it to a String with the specified encoding.<p> @param filename the file to read @param encoding the encoding to use when converting the file content to a String @return the read file convered to a String @throws IOException in case of file access errors
[ "Reads", "a", "file", "from", "the", "class", "loader", "and", "converts", "it", "to", "a", "String", "with", "the", "specified", "encoding", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsFileUtil.java#L628-L631
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java
CmsSitemapController.ensureUniqueName
public void ensureUniqueName(CmsClientSitemapEntry parent, String newName, I_CmsSimpleCallback<String> callback) { """ Ensure the uniqueness of a given URL-name within the children of the given parent site-map entry.<p> @param parent the parent entry @param newName the proposed name @param callback the callback to execute """ ensureUniqueName(parent.getSitePath(), newName, callback); }
java
public void ensureUniqueName(CmsClientSitemapEntry parent, String newName, I_CmsSimpleCallback<String> callback) { ensureUniqueName(parent.getSitePath(), newName, callback); }
[ "public", "void", "ensureUniqueName", "(", "CmsClientSitemapEntry", "parent", ",", "String", "newName", ",", "I_CmsSimpleCallback", "<", "String", ">", "callback", ")", "{", "ensureUniqueName", "(", "parent", ".", "getSitePath", "(", ")", ",", "newName", ",", "callback", ")", ";", "}" ]
Ensure the uniqueness of a given URL-name within the children of the given parent site-map entry.<p> @param parent the parent entry @param newName the proposed name @param callback the callback to execute
[ "Ensure", "the", "uniqueness", "of", "a", "given", "URL", "-", "name", "within", "the", "children", "of", "the", "given", "parent", "site", "-", "map", "entry", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L882-L885
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.transformEntries
public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) { """ Copies an existing ZIP file and transforms the given entries in it. @param is a ZIP input stream. @param entries ZIP entry transformers. @param os a ZIP output stream. @return <code>true</code> if at least one entry was replaced. """ if (log.isDebugEnabled()) log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(os); TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(is, action); // Finishes writing the contents of the ZIP output stream without closing // the underlying stream. out.finish(); return action.found(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
java
public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) { if (log.isDebugEnabled()) log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(os); TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(is, action); // Finishes writing the contents of the ZIP output stream without closing // the underlying stream. out.finish(); return action.found(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
[ "public", "static", "boolean", "transformEntries", "(", "InputStream", "is", ",", "ZipEntryTransformerEntry", "[", "]", "entries", ",", "OutputStream", "os", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"Copying '\"", "+", "is", "+", "\"' to '\"", "+", "os", "+", "\"' and transforming entries \"", "+", "Arrays", ".", "asList", "(", "entries", ")", "+", "\".\"", ")", ";", "try", "{", "ZipOutputStream", "out", "=", "new", "ZipOutputStream", "(", "os", ")", ";", "TransformerZipEntryCallback", "action", "=", "new", "TransformerZipEntryCallback", "(", "Arrays", ".", "asList", "(", "entries", ")", ",", "out", ")", ";", "iterate", "(", "is", ",", "action", ")", ";", "// Finishes writing the contents of the ZIP output stream without closing", "// the underlying stream.", "out", ".", "finish", "(", ")", ";", "return", "action", ".", "found", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "ZipExceptionUtil", ".", "rethrow", "(", "e", ")", ";", "}", "}" ]
Copies an existing ZIP file and transforms the given entries in it. @param is a ZIP input stream. @param entries ZIP entry transformers. @param os a ZIP output stream. @return <code>true</code> if at least one entry was replaced.
[ "Copies", "an", "existing", "ZIP", "file", "and", "transforms", "the", "given", "entries", "in", "it", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2925-L2941
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.mockStatic
public static synchronized void mockStatic(Class<?> type, Method... methods) { """ Enable static mocking for a class. @param type the class to enable static mocking @param methods optionally what methods to mock """ doMock(type, true, new DefaultMockStrategy(), null, methods); }
java
public static synchronized void mockStatic(Class<?> type, Method... methods) { doMock(type, true, new DefaultMockStrategy(), null, methods); }
[ "public", "static", "synchronized", "void", "mockStatic", "(", "Class", "<", "?", ">", "type", ",", "Method", "...", "methods", ")", "{", "doMock", "(", "type", ",", "true", ",", "new", "DefaultMockStrategy", "(", ")", ",", "null", ",", "methods", ")", ";", "}" ]
Enable static mocking for a class. @param type the class to enable static mocking @param methods optionally what methods to mock
[ "Enable", "static", "mocking", "for", "a", "class", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L249-L251
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java
EntrySerializer.serializeUpdateWithExplicitVersion
void serializeUpdateWithExplicitVersion(@NonNull Collection<TableEntry> entries, byte[] target) { """ Serializes the given {@link TableEntry} collection into the given byte array, explicitly recording the versions for each entry ({@link TableKey#getVersion()}). This should be used for {@link TableEntry} instances that were previously read from the Table Segment as only in that case does the version accurately reflect the entry's version. @param entries A Collection of {@link TableEntry} to serialize. @param target The byte array to serialize into. """ int offset = 0; for (TableEntry e : entries) { offset = serializeUpdate(e, target, offset, e.getKey().getVersion()); } }
java
void serializeUpdateWithExplicitVersion(@NonNull Collection<TableEntry> entries, byte[] target) { int offset = 0; for (TableEntry e : entries) { offset = serializeUpdate(e, target, offset, e.getKey().getVersion()); } }
[ "void", "serializeUpdateWithExplicitVersion", "(", "@", "NonNull", "Collection", "<", "TableEntry", ">", "entries", ",", "byte", "[", "]", "target", ")", "{", "int", "offset", "=", "0", ";", "for", "(", "TableEntry", "e", ":", "entries", ")", "{", "offset", "=", "serializeUpdate", "(", "e", ",", "target", ",", "offset", ",", "e", ".", "getKey", "(", ")", ".", "getVersion", "(", ")", ")", ";", "}", "}" ]
Serializes the given {@link TableEntry} collection into the given byte array, explicitly recording the versions for each entry ({@link TableKey#getVersion()}). This should be used for {@link TableEntry} instances that were previously read from the Table Segment as only in that case does the version accurately reflect the entry's version. @param entries A Collection of {@link TableEntry} to serialize. @param target The byte array to serialize into.
[ "Serializes", "the", "given", "{", "@link", "TableEntry", "}", "collection", "into", "the", "given", "byte", "array", "explicitly", "recording", "the", "versions", "for", "each", "entry", "(", "{", "@link", "TableKey#getVersion", "()", "}", ")", ".", "This", "should", "be", "used", "for", "{", "@link", "TableEntry", "}", "instances", "that", "were", "previously", "read", "from", "the", "Table", "Segment", "as", "only", "in", "that", "case", "does", "the", "version", "accurately", "reflect", "the", "entry", "s", "version", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java#L114-L119
algolia/instantsearch-android
core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java
Searcher.updateFacetRefinement
@NonNull public Searcher updateFacetRefinement(@NonNull String attribute, @NonNull String value, boolean active) { """ Adds or removes this facet refinement for the next queries according to its enabled status. @param attribute the attribute to facet on. @param value the value for this attribute. @param active if {@code true}, this facet value is currently refined on. @return this {@link Searcher} for chaining. """ if (active) { addFacetRefinement(attribute, value); } else { removeFacetRefinement(attribute, value); } return this; }
java
@NonNull public Searcher updateFacetRefinement(@NonNull String attribute, @NonNull String value, boolean active) { if (active) { addFacetRefinement(attribute, value); } else { removeFacetRefinement(attribute, value); } return this; }
[ "@", "NonNull", "public", "Searcher", "updateFacetRefinement", "(", "@", "NonNull", "String", "attribute", ",", "@", "NonNull", "String", "value", ",", "boolean", "active", ")", "{", "if", "(", "active", ")", "{", "addFacetRefinement", "(", "attribute", ",", "value", ")", ";", "}", "else", "{", "removeFacetRefinement", "(", "attribute", ",", "value", ")", ";", "}", "return", "this", ";", "}" ]
Adds or removes this facet refinement for the next queries according to its enabled status. @param attribute the attribute to facet on. @param value the value for this attribute. @param active if {@code true}, this facet value is currently refined on. @return this {@link Searcher} for chaining.
[ "Adds", "or", "removes", "this", "facet", "refinement", "for", "the", "next", "queries", "according", "to", "its", "enabled", "status", "." ]
train
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java#L607-L615
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Triangle.java
Triangle.setPoints
public Triangle setPoints(final Point2D a, final Point2D b, final Point2D c) { """ Sets this triangles points. @param 3 points {@link Point2D} @return this Triangle """ return setPoint2DArray(new Point2DArray(a, b, c)); }
java
public Triangle setPoints(final Point2D a, final Point2D b, final Point2D c) { return setPoint2DArray(new Point2DArray(a, b, c)); }
[ "public", "Triangle", "setPoints", "(", "final", "Point2D", "a", ",", "final", "Point2D", "b", ",", "final", "Point2D", "c", ")", "{", "return", "setPoint2DArray", "(", "new", "Point2DArray", "(", "a", ",", "b", ",", "c", ")", ")", ";", "}" ]
Sets this triangles points. @param 3 points {@link Point2D} @return this Triangle
[ "Sets", "this", "triangles", "points", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Triangle.java#L150-L153
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java
OverviewDocument.apply
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, OverviewDocument.Parameters params) { """ Builds the overview MarkupDocument. @return the overview MarkupDocument """ Swagger swagger = params.swagger; Info info = swagger.getInfo(); buildDocumentTitle(markupDocBuilder, info.getTitle()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildOverviewTitle(markupDocBuilder, labels.getLabel(Labels.OVERVIEW)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDescriptionParagraph(markupDocBuilder, info.getDescription()); buildVersionInfoSection(markupDocBuilder, info); buildContactInfoSection(markupDocBuilder, info.getContact()); buildLicenseInfoSection(markupDocBuilder, info); buildUriSchemeSection(markupDocBuilder, swagger); buildTagsSection(markupDocBuilder, swagger.getTags()); buildConsumesSection(markupDocBuilder, swagger.getConsumes()); buildProducesSection(markupDocBuilder, swagger.getProduces()); buildExternalDocsSection(markupDocBuilder, swagger.getExternalDocs()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); return markupDocBuilder; }
java
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, OverviewDocument.Parameters params) { Swagger swagger = params.swagger; Info info = swagger.getInfo(); buildDocumentTitle(markupDocBuilder, info.getTitle()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildOverviewTitle(markupDocBuilder, labels.getLabel(Labels.OVERVIEW)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildDescriptionParagraph(markupDocBuilder, info.getDescription()); buildVersionInfoSection(markupDocBuilder, info); buildContactInfoSection(markupDocBuilder, info.getContact()); buildLicenseInfoSection(markupDocBuilder, info); buildUriSchemeSection(markupDocBuilder, swagger); buildTagsSection(markupDocBuilder, swagger.getTags()); buildConsumesSection(markupDocBuilder, swagger.getConsumes()); buildProducesSection(markupDocBuilder, swagger.getProduces()); buildExternalDocsSection(markupDocBuilder, swagger.getExternalDocs()); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyOverviewDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); return markupDocBuilder; }
[ "@", "Override", "public", "MarkupDocBuilder", "apply", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "OverviewDocument", ".", "Parameters", "params", ")", "{", "Swagger", "swagger", "=", "params", ".", "swagger", ";", "Info", "info", "=", "swagger", ".", "getInfo", "(", ")", ";", "buildDocumentTitle", "(", "markupDocBuilder", ",", "info", ".", "getTitle", "(", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEFORE", ",", "markupDocBuilder", ")", ")", ";", "buildOverviewTitle", "(", "markupDocBuilder", ",", "labels", ".", "getLabel", "(", "Labels", ".", "OVERVIEW", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEGIN", ",", "markupDocBuilder", ")", ")", ";", "buildDescriptionParagraph", "(", "markupDocBuilder", ",", "info", ".", "getDescription", "(", ")", ")", ";", "buildVersionInfoSection", "(", "markupDocBuilder", ",", "info", ")", ";", "buildContactInfoSection", "(", "markupDocBuilder", ",", "info", ".", "getContact", "(", ")", ")", ";", "buildLicenseInfoSection", "(", "markupDocBuilder", ",", "info", ")", ";", "buildUriSchemeSection", "(", "markupDocBuilder", ",", "swagger", ")", ";", "buildTagsSection", "(", "markupDocBuilder", ",", "swagger", ".", "getTags", "(", ")", ")", ";", "buildConsumesSection", "(", "markupDocBuilder", ",", "swagger", ".", "getConsumes", "(", ")", ")", ";", "buildProducesSection", "(", "markupDocBuilder", ",", "swagger", ".", "getProduces", "(", ")", ")", ";", "buildExternalDocsSection", "(", "markupDocBuilder", ",", "swagger", ".", "getExternalDocs", "(", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_END", ",", "markupDocBuilder", ")", ")", ";", "applyOverviewDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_AFTER", ",", "markupDocBuilder", ")", ")", ";", "return", "markupDocBuilder", ";", "}" ]
Builds the overview MarkupDocument. @return the overview MarkupDocument
[ "Builds", "the", "overview", "MarkupDocument", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/OverviewDocument.java#L68-L88
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/FlowGraphPath.java
FlowGraphPath.updateJobDependencies
private void updateJobDependencies(List<JobExecutionPlan> jobExecutionPlans, Map<String, String> templateToJobNameMap) { """ A method to modify the {@link ConfigurationKeys#JOB_DEPENDENCIES} specified in a {@link JobTemplate} to those which are usable in a {@link JobSpec}. The {@link ConfigurationKeys#JOB_DEPENDENCIES} specified in a JobTemplate use the JobTemplate names (i.e. the file names of the templates without the extension). However, the same {@link FlowTemplate} may be used across multiple {@link FlowEdge}s. To ensure that we capture dependencies between jobs correctly as Dags from successive hops are merged, we translate the {@link JobTemplate} name specified in the dependencies config to {@link ConfigurationKeys#JOB_NAME_KEY} from the corresponding {@link JobSpec}, which is guaranteed to be globally unique. For example, consider a {@link JobTemplate} with URI job1.job which has "job.dependencies=job2,job3" (where job2.job and job3.job are URIs of other {@link JobTemplate}s). Also, let the job.name config for the three jobs (after {@link JobSpec} is compiled) be as follows: "job.name=flowgrp1_flowName1_jobName1_1111", "job.name=flowgrp1_flowName1_jobName2_1121", and "job.name=flowgrp1_flowName1_jobName3_1131". Then, for job1, this method will set "job.dependencies=flowgrp1_flowName1_jobName2_1121, flowgrp1_flowName1_jobName3_1131". @param jobExecutionPlans a list of {@link JobExecutionPlan}s @param templateToJobNameMap a HashMap that has the mapping from the {@link JobTemplate} names to job.name in corresponding {@link JobSpec} """ for (JobExecutionPlan jobExecutionPlan: jobExecutionPlans) { JobSpec jobSpec = jobExecutionPlan.getJobSpec(); List<String> updatedDependenciesList = new ArrayList<>(); if (jobSpec.getConfig().hasPath(ConfigurationKeys.JOB_DEPENDENCIES)) { for (String dependency : ConfigUtils.getStringList(jobSpec.getConfig(), ConfigurationKeys.JOB_DEPENDENCIES)) { if (!templateToJobNameMap.containsKey(dependency)) { //We should never hit this condition. The logic here is a safety check. throw new RuntimeException("TemplateToJobNameMap does not contain dependency " + dependency); } updatedDependenciesList.add(templateToJobNameMap.get(dependency)); } String updatedDependencies = Joiner.on(",").join(updatedDependenciesList); jobSpec.setConfig(jobSpec.getConfig().withValue(ConfigurationKeys.JOB_DEPENDENCIES, ConfigValueFactory.fromAnyRef(updatedDependencies))); } } }
java
private void updateJobDependencies(List<JobExecutionPlan> jobExecutionPlans, Map<String, String> templateToJobNameMap) { for (JobExecutionPlan jobExecutionPlan: jobExecutionPlans) { JobSpec jobSpec = jobExecutionPlan.getJobSpec(); List<String> updatedDependenciesList = new ArrayList<>(); if (jobSpec.getConfig().hasPath(ConfigurationKeys.JOB_DEPENDENCIES)) { for (String dependency : ConfigUtils.getStringList(jobSpec.getConfig(), ConfigurationKeys.JOB_DEPENDENCIES)) { if (!templateToJobNameMap.containsKey(dependency)) { //We should never hit this condition. The logic here is a safety check. throw new RuntimeException("TemplateToJobNameMap does not contain dependency " + dependency); } updatedDependenciesList.add(templateToJobNameMap.get(dependency)); } String updatedDependencies = Joiner.on(",").join(updatedDependenciesList); jobSpec.setConfig(jobSpec.getConfig().withValue(ConfigurationKeys.JOB_DEPENDENCIES, ConfigValueFactory.fromAnyRef(updatedDependencies))); } } }
[ "private", "void", "updateJobDependencies", "(", "List", "<", "JobExecutionPlan", ">", "jobExecutionPlans", ",", "Map", "<", "String", ",", "String", ">", "templateToJobNameMap", ")", "{", "for", "(", "JobExecutionPlan", "jobExecutionPlan", ":", "jobExecutionPlans", ")", "{", "JobSpec", "jobSpec", "=", "jobExecutionPlan", ".", "getJobSpec", "(", ")", ";", "List", "<", "String", ">", "updatedDependenciesList", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "hasPath", "(", "ConfigurationKeys", ".", "JOB_DEPENDENCIES", ")", ")", "{", "for", "(", "String", "dependency", ":", "ConfigUtils", ".", "getStringList", "(", "jobSpec", ".", "getConfig", "(", ")", ",", "ConfigurationKeys", ".", "JOB_DEPENDENCIES", ")", ")", "{", "if", "(", "!", "templateToJobNameMap", ".", "containsKey", "(", "dependency", ")", ")", "{", "//We should never hit this condition. The logic here is a safety check.", "throw", "new", "RuntimeException", "(", "\"TemplateToJobNameMap does not contain dependency \"", "+", "dependency", ")", ";", "}", "updatedDependenciesList", ".", "add", "(", "templateToJobNameMap", ".", "get", "(", "dependency", ")", ")", ";", "}", "String", "updatedDependencies", "=", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "updatedDependenciesList", ")", ";", "jobSpec", ".", "setConfig", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "withValue", "(", "ConfigurationKeys", ".", "JOB_DEPENDENCIES", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "updatedDependencies", ")", ")", ")", ";", "}", "}", "}" ]
A method to modify the {@link ConfigurationKeys#JOB_DEPENDENCIES} specified in a {@link JobTemplate} to those which are usable in a {@link JobSpec}. The {@link ConfigurationKeys#JOB_DEPENDENCIES} specified in a JobTemplate use the JobTemplate names (i.e. the file names of the templates without the extension). However, the same {@link FlowTemplate} may be used across multiple {@link FlowEdge}s. To ensure that we capture dependencies between jobs correctly as Dags from successive hops are merged, we translate the {@link JobTemplate} name specified in the dependencies config to {@link ConfigurationKeys#JOB_NAME_KEY} from the corresponding {@link JobSpec}, which is guaranteed to be globally unique. For example, consider a {@link JobTemplate} with URI job1.job which has "job.dependencies=job2,job3" (where job2.job and job3.job are URIs of other {@link JobTemplate}s). Also, let the job.name config for the three jobs (after {@link JobSpec} is compiled) be as follows: "job.name=flowgrp1_flowName1_jobName1_1111", "job.name=flowgrp1_flowName1_jobName2_1121", and "job.name=flowgrp1_flowName1_jobName3_1131". Then, for job1, this method will set "job.dependencies=flowgrp1_flowName1_jobName2_1121, flowgrp1_flowName1_jobName3_1131". @param jobExecutionPlans a list of {@link JobExecutionPlan}s @param templateToJobNameMap a HashMap that has the mapping from the {@link JobTemplate} names to job.name in corresponding {@link JobSpec}
[ "A", "method", "to", "modify", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/FlowGraphPath.java#L198-L214
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isFalse
public static void isFalse (final boolean bValue, @Nonnull final Supplier <? extends String> aMsg) { """ Check that the passed value is <code>false</code>. @param bValue The value to check. @param aMsg The message to be emitted in case the value is <code>true</code> @throws IllegalArgumentException if the passed value is not <code>null</code>. """ if (isEnabled ()) if (bValue) throw new IllegalArgumentException ("The expression must be false but it is not: " + aMsg.get ()); }
java
public static void isFalse (final boolean bValue, @Nonnull final Supplier <? extends String> aMsg) { if (isEnabled ()) if (bValue) throw new IllegalArgumentException ("The expression must be false but it is not: " + aMsg.get ()); }
[ "public", "static", "void", "isFalse", "(", "final", "boolean", "bValue", ",", "@", "Nonnull", "final", "Supplier", "<", "?", "extends", "String", ">", "aMsg", ")", "{", "if", "(", "isEnabled", "(", ")", ")", "if", "(", "bValue", ")", "throw", "new", "IllegalArgumentException", "(", "\"The expression must be false but it is not: \"", "+", "aMsg", ".", "get", "(", ")", ")", ";", "}" ]
Check that the passed value is <code>false</code>. @param bValue The value to check. @param aMsg The message to be emitted in case the value is <code>true</code> @throws IllegalArgumentException if the passed value is not <code>null</code>.
[ "Check", "that", "the", "passed", "value", "is", "<code", ">", "false<", "/", "code", ">", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L168-L173
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java
Parameters.assertExactlyOneDefined
public void assertExactlyOneDefined(final String param1, final String param2) { """ Throws a ParameterException unless exactly one parameter is defined. """ // Asserting that exactly one is defined is the same as asserting that they do not have the same // value for definedness. if (isPresent(param1) == isPresent(param2)) { throw new ParameterException( String.format("Exactly one of %s and %s must be defined.", param1, param2)); } }
java
public void assertExactlyOneDefined(final String param1, final String param2) { // Asserting that exactly one is defined is the same as asserting that they do not have the same // value for definedness. if (isPresent(param1) == isPresent(param2)) { throw new ParameterException( String.format("Exactly one of %s and %s must be defined.", param1, param2)); } }
[ "public", "void", "assertExactlyOneDefined", "(", "final", "String", "param1", ",", "final", "String", "param2", ")", "{", "// Asserting that exactly one is defined is the same as asserting that they do not have the same", "// value for definedness.", "if", "(", "isPresent", "(", "param1", ")", "==", "isPresent", "(", "param2", ")", ")", "{", "throw", "new", "ParameterException", "(", "String", ".", "format", "(", "\"Exactly one of %s and %s must be defined.\"", ",", "param1", ",", "param2", ")", ")", ";", "}", "}" ]
Throws a ParameterException unless exactly one parameter is defined.
[ "Throws", "a", "ParameterException", "unless", "exactly", "one", "parameter", "is", "defined", "." ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L1117-L1124
sagiegurari/fax4j
src/main/java/org/fax4j/util/SpiUtil.java
SpiUtil.replaceTemplateParameter
public static String replaceTemplateParameter(String template,String parameter,String value,TemplateParameterEncoder encoder) { """ This function replaces the parameter with the provided value. @param template The template @param parameter The parameter @param value The value @param encoder The encoder that encodes the template values (may be null) @return The updated template """ String text=template; if((text!=null)&&(parameter!=null)) { String updatedValue=value; if(updatedValue==null) { updatedValue=SpiUtil.EMPTY_STRING; } else if(encoder!=null) { updatedValue=encoder.encodeTemplateParameter(updatedValue); } text=text.replace(parameter,updatedValue); } return text; }
java
public static String replaceTemplateParameter(String template,String parameter,String value,TemplateParameterEncoder encoder) { String text=template; if((text!=null)&&(parameter!=null)) { String updatedValue=value; if(updatedValue==null) { updatedValue=SpiUtil.EMPTY_STRING; } else if(encoder!=null) { updatedValue=encoder.encodeTemplateParameter(updatedValue); } text=text.replace(parameter,updatedValue); } return text; }
[ "public", "static", "String", "replaceTemplateParameter", "(", "String", "template", ",", "String", "parameter", ",", "String", "value", ",", "TemplateParameterEncoder", "encoder", ")", "{", "String", "text", "=", "template", ";", "if", "(", "(", "text", "!=", "null", ")", "&&", "(", "parameter", "!=", "null", ")", ")", "{", "String", "updatedValue", "=", "value", ";", "if", "(", "updatedValue", "==", "null", ")", "{", "updatedValue", "=", "SpiUtil", ".", "EMPTY_STRING", ";", "}", "else", "if", "(", "encoder", "!=", "null", ")", "{", "updatedValue", "=", "encoder", ".", "encodeTemplateParameter", "(", "updatedValue", ")", ";", "}", "text", "=", "text", ".", "replace", "(", "parameter", ",", "updatedValue", ")", ";", "}", "return", "text", ";", "}" ]
This function replaces the parameter with the provided value. @param template The template @param parameter The parameter @param value The value @param encoder The encoder that encodes the template values (may be null) @return The updated template
[ "This", "function", "replaces", "the", "parameter", "with", "the", "provided", "value", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/util/SpiUtil.java#L183-L201
jenkinsci/ssh-slaves-plugin
src/main/java/hudson/plugins/sshslaves/SSHLauncher.java
SSHLauncher.verifyNoHeaderJunk
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { """ Makes sure that SSH connection won't produce any unwanted text, which will interfere with sftp execution. """ ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("exit 0",baos); final String s; //TODO: Seems we need to retrieve the encoding from the connection destination try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { // Should not happen throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }
java
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("exit 0",baos); final String s; //TODO: Seems we need to retrieve the encoding from the connection destination try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { // Should not happen throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }
[ "private", "void", "verifyNoHeaderJunk", "(", "TaskListener", "listener", ")", "throws", "IOException", ",", "InterruptedException", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "connection", ".", "exec", "(", "\"exit 0\"", ",", "baos", ")", ";", "final", "String", "s", ";", "//TODO: Seems we need to retrieve the encoding from the connection destination", "try", "{", "s", "=", "baos", ".", "toString", "(", "Charset", ".", "defaultCharset", "(", ")", ".", "name", "(", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "ex", ")", "{", "// Should not happen", "throw", "new", "IOException", "(", "\"Default encoding is unsupported\"", ",", "ex", ")", ";", "}", "if", "(", "s", ".", "length", "(", ")", "!=", "0", ")", "{", "listener", ".", "getLogger", "(", ")", ".", "println", "(", "Messages", ".", "SSHLauncher_SSHHeaderJunkDetected", "(", ")", ")", ";", "listener", ".", "getLogger", "(", ")", ".", "println", "(", "s", ")", ";", "throw", "new", "AbortException", "(", ")", ";", "}", "}" ]
Makes sure that SSH connection won't produce any unwanted text, which will interfere with sftp execution.
[ "Makes", "sure", "that", "SSH", "connection", "won", "t", "produce", "any", "unwanted", "text", "which", "will", "interfere", "with", "sftp", "execution", "." ]
train
https://github.com/jenkinsci/ssh-slaves-plugin/blob/95f528730fc1e01b25983459927b7516ead3ee00/src/main/java/hudson/plugins/sshslaves/SSHLauncher.java#L562-L578
morimekta/utils
io-util/src/main/java/net/morimekta/util/io/IOUtils.java
IOUtils.readString
public static String readString(Reader is, char term) throws IOException { """ Read next string from input stream. @param is The reader to read characters from. @param term Terminator character. @return The string up until, but not including the terminator. @throws IOException when unable to read from stream. """ CharArrayWriter baos = new CharArrayWriter(); int ch_int; while ((ch_int = is.read()) >= 0) { final char ch = (char) ch_int; if (ch == term) { break; } baos.write(ch); } return baos.toString(); }
java
public static String readString(Reader is, char term) throws IOException { CharArrayWriter baos = new CharArrayWriter(); int ch_int; while ((ch_int = is.read()) >= 0) { final char ch = (char) ch_int; if (ch == term) { break; } baos.write(ch); } return baos.toString(); }
[ "public", "static", "String", "readString", "(", "Reader", "is", ",", "char", "term", ")", "throws", "IOException", "{", "CharArrayWriter", "baos", "=", "new", "CharArrayWriter", "(", ")", ";", "int", "ch_int", ";", "while", "(", "(", "ch_int", "=", "is", ".", "read", "(", ")", ")", ">=", "0", ")", "{", "final", "char", "ch", "=", "(", "char", ")", "ch_int", ";", "if", "(", "ch", "==", "term", ")", "{", "break", ";", "}", "baos", ".", "write", "(", "ch", ")", ";", "}", "return", "baos", ".", "toString", "(", ")", ";", "}" ]
Read next string from input stream. @param is The reader to read characters from. @param term Terminator character. @return The string up until, but not including the terminator. @throws IOException when unable to read from stream.
[ "Read", "next", "string", "from", "input", "stream", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/IOUtils.java#L195-L208
canhnt/sne-xacml
sne-xacml/src/main/java/nl/uva/sne/midd/util/GenericUtils.java
GenericUtils.newInstance
public static <T> T newInstance(final T value) throws MIDDException { """ Create a new object of type <code>T</code>, which is cloned from <code>value</code>. The equivalent class copy constructor is invoked. @param value @param <T> @return @throws MIDDException """ if (value == null) { return null; } else { return newInstance(value, value.getClass()); } }
java
public static <T> T newInstance(final T value) throws MIDDException { if (value == null) { return null; } else { return newInstance(value, value.getClass()); } }
[ "public", "static", "<", "T", ">", "T", "newInstance", "(", "final", "T", "value", ")", "throws", "MIDDException", "{", "if", "(", "value", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "newInstance", "(", "value", ",", "value", ".", "getClass", "(", ")", ")", ";", "}", "}" ]
Create a new object of type <code>T</code>, which is cloned from <code>value</code>. The equivalent class copy constructor is invoked. @param value @param <T> @return @throws MIDDException
[ "Create", "a", "new", "object", "of", "type", "<code", ">", "T<", "/", "code", ">", "which", "is", "cloned", "from", "<code", ">", "value<", "/", "code", ">", ".", "The", "equivalent", "class", "copy", "constructor", "is", "invoked", "." ]
train
https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/util/GenericUtils.java#L62-L69
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java
MetadataFinder.requestMetadataFrom
@SuppressWarnings("WeakerAccess") public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) { """ Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID, unless we have a metadata cache available for the specified media slot, in which case that will be used instead. @param track uniquely identifies the track whose metadata is desired @param trackType identifies the type of track being requested, which affects the type of metadata request message that must be used @return the metadata, if any """ return requestMetadataInternal(track, trackType, false); }
java
@SuppressWarnings("WeakerAccess") public TrackMetadata requestMetadataFrom(final DataReference track, final CdjStatus.TrackType trackType) { return requestMetadataInternal(track, trackType, false); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "TrackMetadata", "requestMetadataFrom", "(", "final", "DataReference", "track", ",", "final", "CdjStatus", ".", "TrackType", "trackType", ")", "{", "return", "requestMetadataInternal", "(", "track", ",", "trackType", ",", "false", ")", ";", "}" ]
Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID, unless we have a metadata cache available for the specified media slot, in which case that will be used instead. @param track uniquely identifies the track whose metadata is desired @param trackType identifies the type of track being requested, which affects the type of metadata request message that must be used @return the metadata, if any
[ "Ask", "the", "specified", "player", "for", "metadata", "about", "the", "track", "in", "the", "specified", "slot", "with", "the", "specified", "rekordbox", "ID", "unless", "we", "have", "a", "metadata", "cache", "available", "for", "the", "specified", "media", "slot", "in", "which", "case", "that", "will", "be", "used", "instead", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L73-L76
alkacon/opencms-core
src/org/opencms/notification/CmsPublishNotification.java
CmsPublishNotification.appendList
private void appendList(StringBuffer buffer, List<Object> list) { """ Appends the contents of a list to the buffer with every entry in a new line.<p> @param buffer The buffer were the entries of the list will be appended. @param list The list with the entries to append to the buffer. """ Iterator<Object> iter = list.iterator(); while (iter.hasNext()) { Object entry = iter.next(); buffer.append(entry).append("<br/>\n"); } }
java
private void appendList(StringBuffer buffer, List<Object> list) { Iterator<Object> iter = list.iterator(); while (iter.hasNext()) { Object entry = iter.next(); buffer.append(entry).append("<br/>\n"); } }
[ "private", "void", "appendList", "(", "StringBuffer", "buffer", ",", "List", "<", "Object", ">", "list", ")", "{", "Iterator", "<", "Object", ">", "iter", "=", "list", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Object", "entry", "=", "iter", ".", "next", "(", ")", ";", "buffer", ".", "append", "(", "entry", ")", ".", "append", "(", "\"<br/>\\n\"", ")", ";", "}", "}" ]
Appends the contents of a list to the buffer with every entry in a new line.<p> @param buffer The buffer were the entries of the list will be appended. @param list The list with the entries to append to the buffer.
[ "Appends", "the", "contents", "of", "a", "list", "to", "the", "buffer", "with", "every", "entry", "in", "a", "new", "line", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/notification/CmsPublishNotification.java#L112-L119
pravega/pravega
controller/src/main/java/io/pravega/controller/server/rpc/auth/PravegaAuthManager.java
PravegaAuthManager.authenticateAndAuthorize
public boolean authenticateAndAuthorize(String resource, String credentials, AuthHandler.Permissions level) throws AuthenticationException { """ API to authenticate and authorize access to a given resource. @param resource The resource identifier for which the access needs to be controlled. @param credentials Credentials used for authentication. @param level Expected level of access. @return Returns true if the entity represented by the custom auth headers had given level of access to the resource. Returns false if the entity does not have access. @throws AuthenticationException if an authentication failure occurred. """ Preconditions.checkNotNull(credentials, "credentials"); boolean retVal = false; try { String[] parts = extractMethodAndToken(credentials); String method = parts[0]; String token = parts[1]; AuthHandler handler = getHandler(method); Preconditions.checkNotNull( handler, "Can not find handler."); Principal principal; if ((principal = handler.authenticate(token)) == null) { throw new AuthenticationException("Authentication failure"); } retVal = handler.authorize(resource, principal).ordinal() >= level.ordinal(); } catch (AuthException e) { throw new AuthenticationException("Authentication failure"); } return retVal; }
java
public boolean authenticateAndAuthorize(String resource, String credentials, AuthHandler.Permissions level) throws AuthenticationException { Preconditions.checkNotNull(credentials, "credentials"); boolean retVal = false; try { String[] parts = extractMethodAndToken(credentials); String method = parts[0]; String token = parts[1]; AuthHandler handler = getHandler(method); Preconditions.checkNotNull( handler, "Can not find handler."); Principal principal; if ((principal = handler.authenticate(token)) == null) { throw new AuthenticationException("Authentication failure"); } retVal = handler.authorize(resource, principal).ordinal() >= level.ordinal(); } catch (AuthException e) { throw new AuthenticationException("Authentication failure"); } return retVal; }
[ "public", "boolean", "authenticateAndAuthorize", "(", "String", "resource", ",", "String", "credentials", ",", "AuthHandler", ".", "Permissions", "level", ")", "throws", "AuthenticationException", "{", "Preconditions", ".", "checkNotNull", "(", "credentials", ",", "\"credentials\"", ")", ";", "boolean", "retVal", "=", "false", ";", "try", "{", "String", "[", "]", "parts", "=", "extractMethodAndToken", "(", "credentials", ")", ";", "String", "method", "=", "parts", "[", "0", "]", ";", "String", "token", "=", "parts", "[", "1", "]", ";", "AuthHandler", "handler", "=", "getHandler", "(", "method", ")", ";", "Preconditions", ".", "checkNotNull", "(", "handler", ",", "\"Can not find handler.\"", ")", ";", "Principal", "principal", ";", "if", "(", "(", "principal", "=", "handler", ".", "authenticate", "(", "token", ")", ")", "==", "null", ")", "{", "throw", "new", "AuthenticationException", "(", "\"Authentication failure\"", ")", ";", "}", "retVal", "=", "handler", ".", "authorize", "(", "resource", ",", "principal", ")", ".", "ordinal", "(", ")", ">=", "level", ".", "ordinal", "(", ")", ";", "}", "catch", "(", "AuthException", "e", ")", "{", "throw", "new", "AuthenticationException", "(", "\"Authentication failure\"", ")", ";", "}", "return", "retVal", ";", "}" ]
API to authenticate and authorize access to a given resource. @param resource The resource identifier for which the access needs to be controlled. @param credentials Credentials used for authentication. @param level Expected level of access. @return Returns true if the entity represented by the custom auth headers had given level of access to the resource. Returns false if the entity does not have access. @throws AuthenticationException if an authentication failure occurred.
[ "API", "to", "authenticate", "and", "authorize", "access", "to", "a", "given", "resource", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/rpc/auth/PravegaAuthManager.java#L65-L83
aws/aws-sdk-java
aws-java-sdk-sts/src/main/java/com/amazonaws/auth/SessionCredentialsProviderFactory.java
SessionCredentialsProviderFactory.getSessionCredentialsProvider
public static synchronized STSSessionCredentialsProvider getSessionCredentialsProvider(AWSCredentials longTermCredentials, String serviceEndpoint, ClientConfiguration stsClientConfiguration) { """ Gets a session credentials provider for the long-term credentials and service endpoint given. These are shared globally to support reuse of session tokens. @param longTermCredentials The long-term AWS account credentials used to initiate a session. @param serviceEndpoint The service endpoint for the service the session credentials will be used to access. @param stsClientConfiguration Client configuration for the {@link AWSSecurityTokenService} used to fetch session credentials. """ Key key = new Key(longTermCredentials.getAWSAccessKeyId(), serviceEndpoint); if ( !cache.containsKey(key) ) { cache.put(key, new STSSessionCredentialsProvider(longTermCredentials, stsClientConfiguration)); } return cache.get(key); }
java
public static synchronized STSSessionCredentialsProvider getSessionCredentialsProvider(AWSCredentials longTermCredentials, String serviceEndpoint, ClientConfiguration stsClientConfiguration) { Key key = new Key(longTermCredentials.getAWSAccessKeyId(), serviceEndpoint); if ( !cache.containsKey(key) ) { cache.put(key, new STSSessionCredentialsProvider(longTermCredentials, stsClientConfiguration)); } return cache.get(key); }
[ "public", "static", "synchronized", "STSSessionCredentialsProvider", "getSessionCredentialsProvider", "(", "AWSCredentials", "longTermCredentials", ",", "String", "serviceEndpoint", ",", "ClientConfiguration", "stsClientConfiguration", ")", "{", "Key", "key", "=", "new", "Key", "(", "longTermCredentials", ".", "getAWSAccessKeyId", "(", ")", ",", "serviceEndpoint", ")", ";", "if", "(", "!", "cache", ".", "containsKey", "(", "key", ")", ")", "{", "cache", ".", "put", "(", "key", ",", "new", "STSSessionCredentialsProvider", "(", "longTermCredentials", ",", "stsClientConfiguration", ")", ")", ";", "}", "return", "cache", ".", "get", "(", "key", ")", ";", "}" ]
Gets a session credentials provider for the long-term credentials and service endpoint given. These are shared globally to support reuse of session tokens. @param longTermCredentials The long-term AWS account credentials used to initiate a session. @param serviceEndpoint The service endpoint for the service the session credentials will be used to access. @param stsClientConfiguration Client configuration for the {@link AWSSecurityTokenService} used to fetch session credentials.
[ "Gets", "a", "session", "credentials", "provider", "for", "the", "long", "-", "term", "credentials", "and", "service", "endpoint", "given", ".", "These", "are", "shared", "globally", "to", "support", "reuse", "of", "session", "tokens", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sts/src/main/java/com/amazonaws/auth/SessionCredentialsProviderFactory.java#L91-L99
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java
Indices.isContiguous
public static boolean isContiguous(int[] indices, int diff) { """ Returns whether indices are contiguous by a certain amount or not @param indices the indices to test @param diff the difference considered to be contiguous @return whether the given indices are contiguous or not """ if (indices.length < 1) return true; for (int i = 1; i < indices.length; i++) { if (Math.abs(indices[i] - indices[i - 1]) > diff) return false; } return true; }
java
public static boolean isContiguous(int[] indices, int diff) { if (indices.length < 1) return true; for (int i = 1; i < indices.length; i++) { if (Math.abs(indices[i] - indices[i - 1]) > diff) return false; } return true; }
[ "public", "static", "boolean", "isContiguous", "(", "int", "[", "]", "indices", ",", "int", "diff", ")", "{", "if", "(", "indices", ".", "length", "<", "1", ")", "return", "true", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "indices", ".", "length", ";", "i", "++", ")", "{", "if", "(", "Math", ".", "abs", "(", "indices", "[", "i", "]", "-", "indices", "[", "i", "-", "1", "]", ")", ">", "diff", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns whether indices are contiguous by a certain amount or not @param indices the indices to test @param diff the difference considered to be contiguous @return whether the given indices are contiguous or not
[ "Returns", "whether", "indices", "are", "contiguous", "by", "a", "certain", "amount", "or", "not" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java#L276-L285
r0adkll/PostOffice
library/src/main/java/com/r0adkll/postoffice/styles/EditTextStyle.java
EditTextStyle.applyDesign
@Override public void applyDesign(Design design, int themeColor) { """ Apply a design to the style @param design the design, i.e. Holo, Material, Light, Dark """ Context ctx = mInputField.getContext(); int smallPadId = design.isMaterial() ? R.dimen.default_margin : R.dimen.default_margin_small; int largePadId = design.isMaterial() ? R.dimen.material_edittext_spacing : R.dimen.default_margin_small; int padLR = ctx.getResources().getDimensionPixelSize(largePadId); int padTB = ctx.getResources().getDimensionPixelSize(smallPadId); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(padLR, padTB, padLR, padTB); mInputField.setLayoutParams(params); if(design.isLight()) mInputField.setTextColor(mInputField.getResources().getColor(R.color.background_material_dark)); else mInputField.setTextColor(mInputField.getResources().getColor(R.color.background_material_light)); Drawable drawable; if(design.isMaterial()) { drawable = mInputField.getResources().getDrawable(R.drawable.edittext_mtrl_alpha); }else{ drawable = mInputField.getBackground(); } drawable.setColorFilter(themeColor, PorterDuff.Mode.SRC_ATOP); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mInputField.setBackground(drawable); else mInputField.setBackgroundDrawable(drawable); }
java
@Override public void applyDesign(Design design, int themeColor) { Context ctx = mInputField.getContext(); int smallPadId = design.isMaterial() ? R.dimen.default_margin : R.dimen.default_margin_small; int largePadId = design.isMaterial() ? R.dimen.material_edittext_spacing : R.dimen.default_margin_small; int padLR = ctx.getResources().getDimensionPixelSize(largePadId); int padTB = ctx.getResources().getDimensionPixelSize(smallPadId); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(padLR, padTB, padLR, padTB); mInputField.setLayoutParams(params); if(design.isLight()) mInputField.setTextColor(mInputField.getResources().getColor(R.color.background_material_dark)); else mInputField.setTextColor(mInputField.getResources().getColor(R.color.background_material_light)); Drawable drawable; if(design.isMaterial()) { drawable = mInputField.getResources().getDrawable(R.drawable.edittext_mtrl_alpha); }else{ drawable = mInputField.getBackground(); } drawable.setColorFilter(themeColor, PorterDuff.Mode.SRC_ATOP); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mInputField.setBackground(drawable); else mInputField.setBackgroundDrawable(drawable); }
[ "@", "Override", "public", "void", "applyDesign", "(", "Design", "design", ",", "int", "themeColor", ")", "{", "Context", "ctx", "=", "mInputField", ".", "getContext", "(", ")", ";", "int", "smallPadId", "=", "design", ".", "isMaterial", "(", ")", "?", "R", ".", "dimen", ".", "default_margin", ":", "R", ".", "dimen", ".", "default_margin_small", ";", "int", "largePadId", "=", "design", ".", "isMaterial", "(", ")", "?", "R", ".", "dimen", ".", "material_edittext_spacing", ":", "R", ".", "dimen", ".", "default_margin_small", ";", "int", "padLR", "=", "ctx", ".", "getResources", "(", ")", ".", "getDimensionPixelSize", "(", "largePadId", ")", ";", "int", "padTB", "=", "ctx", ".", "getResources", "(", ")", ".", "getDimensionPixelSize", "(", "smallPadId", ")", ";", "FrameLayout", ".", "LayoutParams", "params", "=", "new", "FrameLayout", ".", "LayoutParams", "(", "ViewGroup", ".", "LayoutParams", ".", "MATCH_PARENT", ",", "ViewGroup", ".", "LayoutParams", ".", "WRAP_CONTENT", ")", ";", "params", ".", "setMargins", "(", "padLR", ",", "padTB", ",", "padLR", ",", "padTB", ")", ";", "mInputField", ".", "setLayoutParams", "(", "params", ")", ";", "if", "(", "design", ".", "isLight", "(", ")", ")", "mInputField", ".", "setTextColor", "(", "mInputField", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "background_material_dark", ")", ")", ";", "else", "mInputField", ".", "setTextColor", "(", "mInputField", ".", "getResources", "(", ")", ".", "getColor", "(", "R", ".", "color", ".", "background_material_light", ")", ")", ";", "Drawable", "drawable", ";", "if", "(", "design", ".", "isMaterial", "(", ")", ")", "{", "drawable", "=", "mInputField", ".", "getResources", "(", ")", ".", "getDrawable", "(", "R", ".", "drawable", ".", "edittext_mtrl_alpha", ")", ";", "}", "else", "{", "drawable", "=", "mInputField", ".", "getBackground", "(", ")", ";", "}", "drawable", ".", "setColorFilter", "(", "themeColor", ",", "PorterDuff", ".", "Mode", ".", "SRC_ATOP", ")", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN", ")", "mInputField", ".", "setBackground", "(", "drawable", ")", ";", "else", "mInputField", ".", "setBackgroundDrawable", "(", "drawable", ")", ";", "}" ]
Apply a design to the style @param design the design, i.e. Holo, Material, Light, Dark
[ "Apply", "a", "design", "to", "the", "style" ]
train
https://github.com/r0adkll/PostOffice/blob/f98e365fd66c004ccce64ee87d9f471b97e4e3c2/library/src/main/java/com/r0adkll/postoffice/styles/EditTextStyle.java#L50-L82
3redronin/mu-server
src/main/java/io/muserver/ContextHandlerBuilder.java
ContextHandlerBuilder.addHandler
public ContextHandlerBuilder addHandler(Method method, String uriTemplate, RouteHandler handler) { """ Registers a new handler that will only be called if it matches the given route info (relative to the current context). @param method The method to match, or <code>null</code> to accept any method. @param uriTemplate A URL template, relative to the context. Supports plain URLs like <code>/abc</code> or paths with named parameters such as <code>/abc/{id}</code> or named parameters with regexes such as <code>/abc/{id : [0-9]+}</code> where the named parameter values can be accessed with the <code>pathParams</code> parameter in the route handler. @param handler The handler to invoke if the method and URI matches. @return Returns the server builder """ if (handler == null) { return this; } return addHandler(Routes.route(method, uriTemplate, handler)); }
java
public ContextHandlerBuilder addHandler(Method method, String uriTemplate, RouteHandler handler) { if (handler == null) { return this; } return addHandler(Routes.route(method, uriTemplate, handler)); }
[ "public", "ContextHandlerBuilder", "addHandler", "(", "Method", "method", ",", "String", "uriTemplate", ",", "RouteHandler", "handler", ")", "{", "if", "(", "handler", "==", "null", ")", "{", "return", "this", ";", "}", "return", "addHandler", "(", "Routes", ".", "route", "(", "method", ",", "uriTemplate", ",", "handler", ")", ")", ";", "}" ]
Registers a new handler that will only be called if it matches the given route info (relative to the current context). @param method The method to match, or <code>null</code> to accept any method. @param uriTemplate A URL template, relative to the context. Supports plain URLs like <code>/abc</code> or paths with named parameters such as <code>/abc/{id}</code> or named parameters with regexes such as <code>/abc/{id : [0-9]+}</code> where the named parameter values can be accessed with the <code>pathParams</code> parameter in the route handler. @param handler The handler to invoke if the method and URI matches. @return Returns the server builder
[ "Registers", "a", "new", "handler", "that", "will", "only", "be", "called", "if", "it", "matches", "the", "given", "route", "info", "(", "relative", "to", "the", "current", "context", ")", "." ]
train
https://github.com/3redronin/mu-server/blob/51598606a3082a121fbd785348ee9770b40308e6/src/main/java/io/muserver/ContextHandlerBuilder.java#L132-L137
aws/aws-sdk-java
aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/DescribeConfigurationResult.java
DescribeConfigurationResult.withTags
public DescribeConfigurationResult withTags(java.util.Map<String, String> tags) { """ The list of all tags associated with this configuration. @param tags The list of all tags associated with this configuration. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public DescribeConfigurationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DescribeConfigurationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
The list of all tags associated with this configuration. @param tags The list of all tags associated with this configuration. @return Returns a reference to this object so that method calls can be chained together.
[ "The", "list", "of", "all", "tags", "associated", "with", "this", "configuration", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/DescribeConfigurationResult.java#L381-L384
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/style/stylers/Image.java
Image.createImage
protected com.itextpdf.text.Image createImage(PdfContentByte canvas, DATATYPE data, float opacity) throws VectorPrintException, BadElementException { """ This implementation downloads an image from the URL taken from {@link #getUrl() }, which may be initialized by {@link #initURL(java.lang.String)}. Override this method if you want to construct an image from the data argument in another way. @param canvas @param data @param opacity the value of opacity @throws VectorPrintException @throws BadElementException @return the com.itextpdf.text.Image """ initURL(String.valueOf((data != null) ? convert(data) : getData())); com.itextpdf.text.Image img = null; if (isPdf()) { imageLoader.loadPdf(getUrl(), getWriter(), getValue(DocumentSettings.PASSWORD, byte[].class), imp, 1); img = imp.getImage(); } else if (getValue(TIFF, Boolean.class)) { imageLoader.loadTiff(getUrl(), imp, 1); img = imp.getImage(); } else { img = imageLoader.loadImage(getUrl(), opacity); } return img; }
java
protected com.itextpdf.text.Image createImage(PdfContentByte canvas, DATATYPE data, float opacity) throws VectorPrintException, BadElementException { initURL(String.valueOf((data != null) ? convert(data) : getData())); com.itextpdf.text.Image img = null; if (isPdf()) { imageLoader.loadPdf(getUrl(), getWriter(), getValue(DocumentSettings.PASSWORD, byte[].class), imp, 1); img = imp.getImage(); } else if (getValue(TIFF, Boolean.class)) { imageLoader.loadTiff(getUrl(), imp, 1); img = imp.getImage(); } else { img = imageLoader.loadImage(getUrl(), opacity); } return img; }
[ "protected", "com", ".", "itextpdf", ".", "text", ".", "Image", "createImage", "(", "PdfContentByte", "canvas", ",", "DATATYPE", "data", ",", "float", "opacity", ")", "throws", "VectorPrintException", ",", "BadElementException", "{", "initURL", "(", "String", ".", "valueOf", "(", "(", "data", "!=", "null", ")", "?", "convert", "(", "data", ")", ":", "getData", "(", ")", ")", ")", ";", "com", ".", "itextpdf", ".", "text", ".", "Image", "img", "=", "null", ";", "if", "(", "isPdf", "(", ")", ")", "{", "imageLoader", ".", "loadPdf", "(", "getUrl", "(", ")", ",", "getWriter", "(", ")", ",", "getValue", "(", "DocumentSettings", ".", "PASSWORD", ",", "byte", "[", "]", ".", "class", ")", ",", "imp", ",", "1", ")", ";", "img", "=", "imp", ".", "getImage", "(", ")", ";", "}", "else", "if", "(", "getValue", "(", "TIFF", ",", "Boolean", ".", "class", ")", ")", "{", "imageLoader", ".", "loadTiff", "(", "getUrl", "(", ")", ",", "imp", ",", "1", ")", ";", "img", "=", "imp", ".", "getImage", "(", ")", ";", "}", "else", "{", "img", "=", "imageLoader", ".", "loadImage", "(", "getUrl", "(", ")", ",", "opacity", ")", ";", "}", "return", "img", ";", "}" ]
This implementation downloads an image from the URL taken from {@link #getUrl() }, which may be initialized by {@link #initURL(java.lang.String)}. Override this method if you want to construct an image from the data argument in another way. @param canvas @param data @param opacity the value of opacity @throws VectorPrintException @throws BadElementException @return the com.itextpdf.text.Image
[ "This", "implementation", "downloads", "an", "image", "from", "the", "URL", "taken", "from", "{", "@link", "#getUrl", "()", "}", "which", "may", "be", "initialized", "by", "{", "@link", "#initURL", "(", "java", ".", "lang", ".", "String", ")", "}", ".", "Override", "this", "method", "if", "you", "want", "to", "construct", "an", "image", "from", "the", "data", "argument", "in", "another", "way", "." ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/stylers/Image.java#L245-L258
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/N1qlQuery.java
N1qlQuery.simple
public static SimpleN1qlQuery simple(String statement, N1qlParams params) { """ Create a new {@link N1qlQuery} with a plain raw statement in {@link String} form and custom query parameters. @param statement the raw statement string to execute (eg. "SELECT * FROM default"). @param params the {@link N1qlParams query parameters}. """ return simple(new RawStatement(statement), params); }
java
public static SimpleN1qlQuery simple(String statement, N1qlParams params) { return simple(new RawStatement(statement), params); }
[ "public", "static", "SimpleN1qlQuery", "simple", "(", "String", "statement", ",", "N1qlParams", "params", ")", "{", "return", "simple", "(", "new", "RawStatement", "(", "statement", ")", ",", "params", ")", ";", "}" ]
Create a new {@link N1qlQuery} with a plain raw statement in {@link String} form and custom query parameters. @param statement the raw statement string to execute (eg. "SELECT * FROM default"). @param params the {@link N1qlParams query parameters}.
[ "Create", "a", "new", "{", "@link", "N1qlQuery", "}", "with", "a", "plain", "raw", "statement", "in", "{", "@link", "String", "}", "form", "and", "custom", "query", "parameters", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/N1qlQuery.java#L115-L117
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryFileApi.java
RepositoryFileApi.getRawFile
public InputStream getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath) throws GitLabApiException { """ Get the raw file contents for a file by commit sha and path. V3: <pre><code>GitLab Endpoint: GET /projects/:id/repository/blobs/:sha</code></pre> V4: <pre><code>GitLab Endpoint: GET /projects/:id/repository/files/:filepath</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param commitOrBranchName the commit or branch name to get the file contents for @param filepath the path of the file to get @return an InputStream to read the raw file from @throws GitLabApiException if any exception occurs """ if (isApiVersion(ApiVersion.V3)) { Form formData = new GitLabApiForm().withParam("file_path", filepath, true); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", commitOrBranchName); return (response.readEntity(InputStream.class)); } else { Form formData = new GitLabApiForm().withParam("ref", commitOrBranchName, true); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filepath), "raw"); return (response.readEntity(InputStream.class)); } }
java
public InputStream getRawFile(Object projectIdOrPath, String commitOrBranchName, String filepath) throws GitLabApiException { if (isApiVersion(ApiVersion.V3)) { Form formData = new GitLabApiForm().withParam("file_path", filepath, true); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "blobs", commitOrBranchName); return (response.readEntity(InputStream.class)); } else { Form formData = new GitLabApiForm().withParam("ref", commitOrBranchName, true); Response response = getWithAccepts(Response.Status.OK, formData.asMap(), MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "files", urlEncode(filepath), "raw"); return (response.readEntity(InputStream.class)); } }
[ "public", "InputStream", "getRawFile", "(", "Object", "projectIdOrPath", ",", "String", "commitOrBranchName", ",", "String", "filepath", ")", "throws", "GitLabApiException", "{", "if", "(", "isApiVersion", "(", "ApiVersion", ".", "V3", ")", ")", "{", "Form", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "\"file_path\"", ",", "filepath", ",", "true", ")", ";", "Response", "response", "=", "getWithAccepts", "(", "Response", ".", "Status", ".", "OK", ",", "formData", ".", "asMap", "(", ")", ",", "MediaType", ".", "MEDIA_TYPE_WILDCARD", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"repository\"", ",", "\"blobs\"", ",", "commitOrBranchName", ")", ";", "return", "(", "response", ".", "readEntity", "(", "InputStream", ".", "class", ")", ")", ";", "}", "else", "{", "Form", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "\"ref\"", ",", "commitOrBranchName", ",", "true", ")", ";", "Response", "response", "=", "getWithAccepts", "(", "Response", ".", "Status", ".", "OK", ",", "formData", ".", "asMap", "(", ")", ",", "MediaType", ".", "MEDIA_TYPE_WILDCARD", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"repository\"", ",", "\"files\"", ",", "urlEncode", "(", "filepath", ")", ",", "\"raw\"", ")", ";", "return", "(", "response", ".", "readEntity", "(", "InputStream", ".", "class", ")", ")", ";", "}", "}" ]
Get the raw file contents for a file by commit sha and path. V3: <pre><code>GitLab Endpoint: GET /projects/:id/repository/blobs/:sha</code></pre> V4: <pre><code>GitLab Endpoint: GET /projects/:id/repository/files/:filepath</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param commitOrBranchName the commit or branch name to get the file contents for @param filepath the path of the file to get @return an InputStream to read the raw file from @throws GitLabApiException if any exception occurs
[ "Get", "the", "raw", "file", "contents", "for", "a", "file", "by", "commit", "sha", "and", "path", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryFileApi.java#L415-L428
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java
DefaultImageDecoder.decodeGif
public CloseableImage decodeGif( final EncodedImage encodedImage, final int length, final QualityInfo qualityInfo, final ImageDecodeOptions options) { """ Decodes gif into CloseableImage. @param encodedImage input image (encoded bytes plus meta data) @return a CloseableImage """ if (!options.forceStaticImage && mAnimatedGifDecoder != null) { return mAnimatedGifDecoder.decode(encodedImage, length, qualityInfo, options); } return decodeStaticImage(encodedImage, options); }
java
public CloseableImage decodeGif( final EncodedImage encodedImage, final int length, final QualityInfo qualityInfo, final ImageDecodeOptions options) { if (!options.forceStaticImage && mAnimatedGifDecoder != null) { return mAnimatedGifDecoder.decode(encodedImage, length, qualityInfo, options); } return decodeStaticImage(encodedImage, options); }
[ "public", "CloseableImage", "decodeGif", "(", "final", "EncodedImage", "encodedImage", ",", "final", "int", "length", ",", "final", "QualityInfo", "qualityInfo", ",", "final", "ImageDecodeOptions", "options", ")", "{", "if", "(", "!", "options", ".", "forceStaticImage", "&&", "mAnimatedGifDecoder", "!=", "null", ")", "{", "return", "mAnimatedGifDecoder", ".", "decode", "(", "encodedImage", ",", "length", ",", "qualityInfo", ",", "options", ")", ";", "}", "return", "decodeStaticImage", "(", "encodedImage", ",", "options", ")", ";", "}" ]
Decodes gif into CloseableImage. @param encodedImage input image (encoded bytes plus meta data) @return a CloseableImage
[ "Decodes", "gif", "into", "CloseableImage", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/decoder/DefaultImageDecoder.java#L130-L139
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java
WorkflowTriggersInner.setState
public void setState(String resourceGroupName, String workflowName, String triggerName, WorkflowTriggerInner source) { """ Sets the state of a workflow trigger. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param triggerName The workflow trigger name. @param source the WorkflowTriggerInner value @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ setStateWithServiceResponseAsync(resourceGroupName, workflowName, triggerName, source).toBlocking().single().body(); }
java
public void setState(String resourceGroupName, String workflowName, String triggerName, WorkflowTriggerInner source) { setStateWithServiceResponseAsync(resourceGroupName, workflowName, triggerName, source).toBlocking().single().body(); }
[ "public", "void", "setState", "(", "String", "resourceGroupName", ",", "String", "workflowName", ",", "String", "triggerName", ",", "WorkflowTriggerInner", "source", ")", "{", "setStateWithServiceResponseAsync", "(", "resourceGroupName", ",", "workflowName", ",", "triggerName", ",", "source", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Sets the state of a workflow trigger. @param resourceGroupName The resource group name. @param workflowName The workflow name. @param triggerName The workflow trigger name. @param source the WorkflowTriggerInner value @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Sets", "the", "state", "of", "a", "workflow", "trigger", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/WorkflowTriggersInner.java#L731-L733
infinispan/infinispan
core/src/main/java/org/infinispan/jmx/ComponentsJmxRegistration.java
ComponentsJmxRegistration.unregisterMBeans
public void unregisterMBeans(Collection<ResourceDMBean> resourceDMBeans) throws CacheException { """ Unregisters all the MBeans registered through {@link #registerMBeans(Collection)}. @param resourceDMBeans """ log.trace("Unregistering jmx resources.."); try { for (ResourceDMBean resource : resourceDMBeans) { JmxUtil.unregisterMBean(getObjectName(resource), mBeanServer); } } catch (Exception e) { throw new CacheException("Failure while unregistering mbeans", e); } }
java
public void unregisterMBeans(Collection<ResourceDMBean> resourceDMBeans) throws CacheException { log.trace("Unregistering jmx resources.."); try { for (ResourceDMBean resource : resourceDMBeans) { JmxUtil.unregisterMBean(getObjectName(resource), mBeanServer); } } catch (Exception e) { throw new CacheException("Failure while unregistering mbeans", e); } }
[ "public", "void", "unregisterMBeans", "(", "Collection", "<", "ResourceDMBean", ">", "resourceDMBeans", ")", "throws", "CacheException", "{", "log", ".", "trace", "(", "\"Unregistering jmx resources..\"", ")", ";", "try", "{", "for", "(", "ResourceDMBean", "resource", ":", "resourceDMBeans", ")", "{", "JmxUtil", ".", "unregisterMBean", "(", "getObjectName", "(", "resource", ")", ",", "mBeanServer", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "CacheException", "(", "\"Failure while unregistering mbeans\"", ",", "e", ")", ";", "}", "}" ]
Unregisters all the MBeans registered through {@link #registerMBeans(Collection)}. @param resourceDMBeans
[ "Unregisters", "all", "the", "MBeans", "registered", "through", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/jmx/ComponentsJmxRegistration.java#L68-L78
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/HybridRunbookWorkerGroupsInner.java
HybridRunbookWorkerGroupsInner.get
public HybridRunbookWorkerGroupInner get(String resourceGroupName, String automationAccountName, String hybridRunbookWorkerGroupName) { """ Retrieve a hybrid runbook worker group. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param hybridRunbookWorkerGroupName The hybrid runbook worker group name @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the HybridRunbookWorkerGroupInner object if successful. """ return getWithServiceResponseAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName).toBlocking().single().body(); }
java
public HybridRunbookWorkerGroupInner get(String resourceGroupName, String automationAccountName, String hybridRunbookWorkerGroupName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, hybridRunbookWorkerGroupName).toBlocking().single().body(); }
[ "public", "HybridRunbookWorkerGroupInner", "get", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "hybridRunbookWorkerGroupName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "hybridRunbookWorkerGroupName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve a hybrid runbook worker group. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param hybridRunbookWorkerGroupName The hybrid runbook worker group name @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the HybridRunbookWorkerGroupInner object if successful.
[ "Retrieve", "a", "hybrid", "runbook", "worker", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/HybridRunbookWorkerGroupsInner.java#L189-L191
forge/core
facets/api/src/main/java/org/jboss/forge/addon/facets/constraints/FacetInspector.java
FacetInspector.getAllRequiredFacets
public static <FACETTYPE extends Facet<?>> Set<Class<FACETTYPE>> getAllRequiredFacets(final Class<?> inspectedType) { """ Inspect the given {@link Class} for all {@link FacetConstraintType#REQUIRED} dependency {@link Facet} types. This method inspects the entire constraint tree. """ Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType, FacetConstraintType.REQUIRED); }
java
public static <FACETTYPE extends Facet<?>> Set<Class<FACETTYPE>> getAllRequiredFacets(final Class<?> inspectedType) { Set<Class<FACETTYPE>> seen = new LinkedHashSet<Class<FACETTYPE>>(); return getAllRelatedFacets(seen, inspectedType, FacetConstraintType.REQUIRED); }
[ "public", "static", "<", "FACETTYPE", "extends", "Facet", "<", "?", ">", ">", "Set", "<", "Class", "<", "FACETTYPE", ">", ">", "getAllRequiredFacets", "(", "final", "Class", "<", "?", ">", "inspectedType", ")", "{", "Set", "<", "Class", "<", "FACETTYPE", ">>", "seen", "=", "new", "LinkedHashSet", "<", "Class", "<", "FACETTYPE", ">", ">", "(", ")", ";", "return", "getAllRelatedFacets", "(", "seen", ",", "inspectedType", ",", "FacetConstraintType", ".", "REQUIRED", ")", ";", "}" ]
Inspect the given {@link Class} for all {@link FacetConstraintType#REQUIRED} dependency {@link Facet} types. This method inspects the entire constraint tree.
[ "Inspect", "the", "given", "{" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/facets/api/src/main/java/org/jboss/forge/addon/facets/constraints/FacetInspector.java#L146-L150
sporniket/core
sporniket-core-ui/src/main/java/com/sporniket/libre/ui/swing/ComponentFactory.java
ComponentFactory.getImageIcon
public static Icon getImageIcon(ClassLoader objectLoader, String fileName) throws UrlProviderException { """ Create an Image icon from a String. @param objectLoader This method use <i>objectLoader.getResource() </i> to retrieve the icon. @param fileName the name of the file. @return an Icon. @throws UrlProviderException if there is a problem to deal with. """ return getImageIcon(new ClassLoaderUrlProvider(objectLoader), fileName); }
java
public static Icon getImageIcon(ClassLoader objectLoader, String fileName) throws UrlProviderException { return getImageIcon(new ClassLoaderUrlProvider(objectLoader), fileName); }
[ "public", "static", "Icon", "getImageIcon", "(", "ClassLoader", "objectLoader", ",", "String", "fileName", ")", "throws", "UrlProviderException", "{", "return", "getImageIcon", "(", "new", "ClassLoaderUrlProvider", "(", "objectLoader", ")", ",", "fileName", ")", ";", "}" ]
Create an Image icon from a String. @param objectLoader This method use <i>objectLoader.getResource() </i> to retrieve the icon. @param fileName the name of the file. @return an Icon. @throws UrlProviderException if there is a problem to deal with.
[ "Create", "an", "Image", "icon", "from", "a", "String", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ui/src/main/java/com/sporniket/libre/ui/swing/ComponentFactory.java#L104-L107
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.getModuleLink
public Content getModuleLink(ModuleElement mdle, Content label) { """ Get Module link. @param mdle the module being documented @param label tag for the link @return a content for the module link """ boolean included = utils.isIncluded(mdle); return (included) ? getHyperLink(pathToRoot.resolve(DocPaths.moduleSummary(mdle)), label, "", "") : label; }
java
public Content getModuleLink(ModuleElement mdle, Content label) { boolean included = utils.isIncluded(mdle); return (included) ? getHyperLink(pathToRoot.resolve(DocPaths.moduleSummary(mdle)), label, "", "") : label; }
[ "public", "Content", "getModuleLink", "(", "ModuleElement", "mdle", ",", "Content", "label", ")", "{", "boolean", "included", "=", "utils", ".", "isIncluded", "(", "mdle", ")", ";", "return", "(", "included", ")", "?", "getHyperLink", "(", "pathToRoot", ".", "resolve", "(", "DocPaths", ".", "moduleSummary", "(", "mdle", ")", ")", ",", "label", ",", "\"\"", ",", "\"\"", ")", ":", "label", ";", "}" ]
Get Module link. @param mdle the module being documented @param label tag for the link @return a content for the module link
[ "Get", "Module", "link", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java#L1144-L1149
intellimate/Izou
src/main/java/org/intellimate/izou/security/SecurityBreachHandler.java
SecurityBreachHandler.handleBreach
void handleBreach(Exception e, Class[] classesStack) { """ Handles the potential security breach (sends out an email and does whatever else is necessary) @param e The exception that will be thrown @param classesStack the current class stack """ String subject = "Izou Security Exception: " + e.getMessage(); sendErrorReport(subject, e, classesStack); }
java
void handleBreach(Exception e, Class[] classesStack) { String subject = "Izou Security Exception: " + e.getMessage(); sendErrorReport(subject, e, classesStack); }
[ "void", "handleBreach", "(", "Exception", "e", ",", "Class", "[", "]", "classesStack", ")", "{", "String", "subject", "=", "\"Izou Security Exception: \"", "+", "e", ".", "getMessage", "(", ")", ";", "sendErrorReport", "(", "subject", ",", "e", ",", "classesStack", ")", ";", "}" ]
Handles the potential security breach (sends out an email and does whatever else is necessary) @param e The exception that will be thrown @param classesStack the current class stack
[ "Handles", "the", "potential", "security", "breach", "(", "sends", "out", "an", "email", "and", "does", "whatever", "else", "is", "necessary", ")" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/security/SecurityBreachHandler.java#L65-L68
bwkimmel/jdcp
jdcp-server/src/main/java/ca/eandb/jdcp/server/JobServer.java
JobServer.removeScheduledJob
private void removeScheduledJob(UUID jobId, boolean complete) { """ Removes a job. @param jobId The <code>UUID</code> identifying the job to be removed. @param complete A value indicating whether the job has been completed. """ ScheduledJob sched = jobs.remove(jobId); if (sched != null) { if (complete) { sched.notifyComplete(); if (logger.isInfoEnabled()) { logger.info("Job complete (" + jobId.toString() + ")"); } } else { sched.notifyCancelled(); if (logger.isInfoEnabled()) { logger.info("Job cancelled (" + jobId.toString() + ")"); } } jobs.remove(jobId); scheduler.removeJob(jobId); sched.classManager.release(); } }
java
private void removeScheduledJob(UUID jobId, boolean complete) { ScheduledJob sched = jobs.remove(jobId); if (sched != null) { if (complete) { sched.notifyComplete(); if (logger.isInfoEnabled()) { logger.info("Job complete (" + jobId.toString() + ")"); } } else { sched.notifyCancelled(); if (logger.isInfoEnabled()) { logger.info("Job cancelled (" + jobId.toString() + ")"); } } jobs.remove(jobId); scheduler.removeJob(jobId); sched.classManager.release(); } }
[ "private", "void", "removeScheduledJob", "(", "UUID", "jobId", ",", "boolean", "complete", ")", "{", "ScheduledJob", "sched", "=", "jobs", ".", "remove", "(", "jobId", ")", ";", "if", "(", "sched", "!=", "null", ")", "{", "if", "(", "complete", ")", "{", "sched", ".", "notifyComplete", "(", ")", ";", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "logger", ".", "info", "(", "\"Job complete (\"", "+", "jobId", ".", "toString", "(", ")", "+", "\")\"", ")", ";", "}", "}", "else", "{", "sched", ".", "notifyCancelled", "(", ")", ";", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "logger", ".", "info", "(", "\"Job cancelled (\"", "+", "jobId", ".", "toString", "(", ")", "+", "\")\"", ")", ";", "}", "}", "jobs", ".", "remove", "(", "jobId", ")", ";", "scheduler", ".", "removeJob", "(", "jobId", ")", ";", "sched", ".", "classManager", ".", "release", "(", ")", ";", "}", "}" ]
Removes a job. @param jobId The <code>UUID</code> identifying the job to be removed. @param complete A value indicating whether the job has been completed.
[ "Removes", "a", "job", "." ]
train
https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-server/src/main/java/ca/eandb/jdcp/server/JobServer.java#L547-L565
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java
SpaceRepository.fireSpaceAdded
protected void fireSpaceAdded(Space space, boolean isLocalCreation) { """ Notifies the listeners on the space creation. @param space the created space. @param isLocalCreation indicates if the creation of the space was initiated on the current kernel. """ if (this.externalListener != null) { this.externalListener.spaceCreated(space, isLocalCreation); } }
java
protected void fireSpaceAdded(Space space, boolean isLocalCreation) { if (this.externalListener != null) { this.externalListener.spaceCreated(space, isLocalCreation); } }
[ "protected", "void", "fireSpaceAdded", "(", "Space", "space", ",", "boolean", "isLocalCreation", ")", "{", "if", "(", "this", ".", "externalListener", "!=", "null", ")", "{", "this", ".", "externalListener", ".", "spaceCreated", "(", "space", ",", "isLocalCreation", ")", ";", "}", "}" ]
Notifies the listeners on the space creation. @param space the created space. @param isLocalCreation indicates if the creation of the space was initiated on the current kernel.
[ "Notifies", "the", "listeners", "on", "the", "space", "creation", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/contextspace/SpaceRepository.java#L383-L387
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.domain_account_accountName_migrate_destinationServiceName_GET
public OvhMigrationService domain_account_accountName_migrate_destinationServiceName_GET(String domain, String accountName, String destinationServiceName) throws IOException { """ Get this object properties REST: GET /email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName} @param domain [required] Name of your domain name @param accountName [required] Name of account @param destinationServiceName [required] Service name allowed as migration destination API beta """ String qPath = "/email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}"; StringBuilder sb = path(qPath, domain, accountName, destinationServiceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhMigrationService.class); }
java
public OvhMigrationService domain_account_accountName_migrate_destinationServiceName_GET(String domain, String accountName, String destinationServiceName) throws IOException { String qPath = "/email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}"; StringBuilder sb = path(qPath, domain, accountName, destinationServiceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhMigrationService.class); }
[ "public", "OvhMigrationService", "domain_account_accountName_migrate_destinationServiceName_GET", "(", "String", "domain", ",", "String", "accountName", ",", "String", "destinationServiceName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "domain", ",", "accountName", ",", "destinationServiceName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhMigrationService", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /email/domain/{domain}/account/{accountName}/migrate/{destinationServiceName} @param domain [required] Name of your domain name @param accountName [required] Name of account @param destinationServiceName [required] Service name allowed as migration destination API beta
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L449-L454
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendTextBlocking
public static void sendTextBlocking(final String message, final WebSocketChannel wsChannel) throws IOException { """ Sends a complete text message, invoking the callback when complete @param message The text to send @param wsChannel The web socket channel """ final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)); sendBlockingInternal(data, WebSocketFrameType.TEXT, wsChannel); }
java
public static void sendTextBlocking(final String message, final WebSocketChannel wsChannel) throws IOException { final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)); sendBlockingInternal(data, WebSocketFrameType.TEXT, wsChannel); }
[ "public", "static", "void", "sendTextBlocking", "(", "final", "String", "message", ",", "final", "WebSocketChannel", "wsChannel", ")", "throws", "IOException", "{", "final", "ByteBuffer", "data", "=", "ByteBuffer", ".", "wrap", "(", "message", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "sendBlockingInternal", "(", "data", ",", "WebSocketFrameType", ".", "TEXT", ",", "wsChannel", ")", ";", "}" ]
Sends a complete text message, invoking the callback when complete @param message The text to send @param wsChannel The web socket channel
[ "Sends", "a", "complete", "text", "message", "invoking", "the", "callback", "when", "complete" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L198-L201
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java
GenJsCodeVisitor.addCodeToRequireCss
private static void addCodeToRequireCss(JsDoc.Builder header, SoyFileNode soyFile) { """ Appends requirecss jsdoc tags in the file header section. @param soyFile The file with the templates.. """ SortedSet<String> requiredCssNamespaces = new TreeSet<>(); requiredCssNamespaces.addAll(soyFile.getRequiredCssNamespaces()); for (TemplateNode template : soyFile.getChildren()) { requiredCssNamespaces.addAll(template.getRequiredCssNamespaces()); } // NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in // the future, this might be supported per function. for (String requiredCssNamespace : requiredCssNamespaces) { header.addParameterizedAnnotation("requirecss", requiredCssNamespace); } }
java
private static void addCodeToRequireCss(JsDoc.Builder header, SoyFileNode soyFile) { SortedSet<String> requiredCssNamespaces = new TreeSet<>(); requiredCssNamespaces.addAll(soyFile.getRequiredCssNamespaces()); for (TemplateNode template : soyFile.getChildren()) { requiredCssNamespaces.addAll(template.getRequiredCssNamespaces()); } // NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in // the future, this might be supported per function. for (String requiredCssNamespace : requiredCssNamespaces) { header.addParameterizedAnnotation("requirecss", requiredCssNamespace); } }
[ "private", "static", "void", "addCodeToRequireCss", "(", "JsDoc", ".", "Builder", "header", ",", "SoyFileNode", "soyFile", ")", "{", "SortedSet", "<", "String", ">", "requiredCssNamespaces", "=", "new", "TreeSet", "<>", "(", ")", ";", "requiredCssNamespaces", ".", "addAll", "(", "soyFile", ".", "getRequiredCssNamespaces", "(", ")", ")", ";", "for", "(", "TemplateNode", "template", ":", "soyFile", ".", "getChildren", "(", ")", ")", "{", "requiredCssNamespaces", ".", "addAll", "(", "template", ".", "getRequiredCssNamespaces", "(", ")", ")", ";", "}", "// NOTE: CSS requires in JS can only be done on a file by file basis at this time. Perhaps in", "// the future, this might be supported per function.", "for", "(", "String", "requiredCssNamespace", ":", "requiredCssNamespaces", ")", "{", "header", ".", "addParameterizedAnnotation", "(", "\"requirecss\"", ",", "requiredCssNamespace", ")", ";", "}", "}" ]
Appends requirecss jsdoc tags in the file header section. @param soyFile The file with the templates..
[ "Appends", "requirecss", "jsdoc", "tags", "in", "the", "file", "header", "section", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L487-L500
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java
RowReaderDefaultImpl.readPkValuesFrom
public void readPkValuesFrom(ResultSetAndStatement rs_stmt, Map row) { """ /* @see RowReader#readPkValuesFrom(ResultSet, ClassDescriptor, Map) @throws PersistenceBrokerException if there is an error accessing the access layer """ String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); ClassDescriptor cld; if (ojbClass != null) { cld = m_cld.getRepository().getDescriptorFor(ojbClass); } else { cld = m_cld; } FieldDescriptor[] pkFields = cld.getPkFields(); readValuesFrom(rs_stmt, row, pkFields); }
java
public void readPkValuesFrom(ResultSetAndStatement rs_stmt, Map row) { String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); ClassDescriptor cld; if (ojbClass != null) { cld = m_cld.getRepository().getDescriptorFor(ojbClass); } else { cld = m_cld; } FieldDescriptor[] pkFields = cld.getPkFields(); readValuesFrom(rs_stmt, row, pkFields); }
[ "public", "void", "readPkValuesFrom", "(", "ResultSetAndStatement", "rs_stmt", ",", "Map", "row", ")", "{", "String", "ojbClass", "=", "SqlHelper", ".", "getOjbClassName", "(", "rs_stmt", ".", "m_rs", ")", ";", "ClassDescriptor", "cld", ";", "if", "(", "ojbClass", "!=", "null", ")", "{", "cld", "=", "m_cld", ".", "getRepository", "(", ")", ".", "getDescriptorFor", "(", "ojbClass", ")", ";", "}", "else", "{", "cld", "=", "m_cld", ";", "}", "FieldDescriptor", "[", "]", "pkFields", "=", "cld", ".", "getPkFields", "(", ")", ";", "readValuesFrom", "(", "rs_stmt", ",", "row", ",", "pkFields", ")", ";", "}" ]
/* @see RowReader#readPkValuesFrom(ResultSet, ClassDescriptor, Map) @throws PersistenceBrokerException if there is an error accessing the access layer
[ "/", "*" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java#L215-L231
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/api/common/operators/SingleInputSemanticProperties.java
SingleInputSemanticProperties.addForwardedField
public void addForwardedField(int sourceField, int destinationField) { """ Adds, to the existing information, a field that is forwarded directly from the source record(s) to the destination record(s). @param sourceField the position in the source record(s) @param destinationField the position in the destination record(s) """ FieldSet fs; if((fs = this.forwardedFields.get(sourceField)) != null) { fs.add(destinationField); } else { fs = new FieldSet(destinationField); this.forwardedFields.put(sourceField, fs); } }
java
public void addForwardedField(int sourceField, int destinationField) { FieldSet fs; if((fs = this.forwardedFields.get(sourceField)) != null) { fs.add(destinationField); } else { fs = new FieldSet(destinationField); this.forwardedFields.put(sourceField, fs); } }
[ "public", "void", "addForwardedField", "(", "int", "sourceField", ",", "int", "destinationField", ")", "{", "FieldSet", "fs", ";", "if", "(", "(", "fs", "=", "this", ".", "forwardedFields", ".", "get", "(", "sourceField", ")", ")", "!=", "null", ")", "{", "fs", ".", "add", "(", "destinationField", ")", ";", "}", "else", "{", "fs", "=", "new", "FieldSet", "(", "destinationField", ")", ";", "this", ".", "forwardedFields", ".", "put", "(", "sourceField", ",", "fs", ")", ";", "}", "}" ]
Adds, to the existing information, a field that is forwarded directly from the source record(s) to the destination record(s). @param sourceField the position in the source record(s) @param destinationField the position in the destination record(s)
[ "Adds", "to", "the", "existing", "information", "a", "field", "that", "is", "forwarded", "directly", "from", "the", "source", "record", "(", "s", ")", "to", "the", "destination", "record", "(", "s", ")", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/api/common/operators/SingleInputSemanticProperties.java#L51-L59
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternManipulator.java
IsotopePatternManipulator.sortByMass
public static IsotopePattern sortByMass(IsotopePattern isotopeP) { """ Return the isotope pattern sorted by mass to the highest abundance. @param isotopeP The IsotopePattern object to sort @return The IsotopePattern sorted """ try { IsotopePattern isoSort = (IsotopePattern) isotopeP.clone(); // Do nothing for empty isotope pattern if (isoSort.getNumberOfIsotopes() == 0) return isoSort; // Sort the isotopes List<IsotopeContainer> listISO = isoSort.getIsotopes(); Collections.sort(listISO, new Comparator<IsotopeContainer>() { @Override public int compare(IsotopeContainer o1, IsotopeContainer o2) { return Double.compare(o1.getMass(),o2.getMass()); } }); // Set the monoisotopic peak to the one with lowest mass isoSort.setMonoIsotope(listISO.get(0)); return isoSort; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; }
java
public static IsotopePattern sortByMass(IsotopePattern isotopeP) { try { IsotopePattern isoSort = (IsotopePattern) isotopeP.clone(); // Do nothing for empty isotope pattern if (isoSort.getNumberOfIsotopes() == 0) return isoSort; // Sort the isotopes List<IsotopeContainer> listISO = isoSort.getIsotopes(); Collections.sort(listISO, new Comparator<IsotopeContainer>() { @Override public int compare(IsotopeContainer o1, IsotopeContainer o2) { return Double.compare(o1.getMass(),o2.getMass()); } }); // Set the monoisotopic peak to the one with lowest mass isoSort.setMonoIsotope(listISO.get(0)); return isoSort; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; }
[ "public", "static", "IsotopePattern", "sortByMass", "(", "IsotopePattern", "isotopeP", ")", "{", "try", "{", "IsotopePattern", "isoSort", "=", "(", "IsotopePattern", ")", "isotopeP", ".", "clone", "(", ")", ";", "// Do nothing for empty isotope pattern", "if", "(", "isoSort", ".", "getNumberOfIsotopes", "(", ")", "==", "0", ")", "return", "isoSort", ";", "// Sort the isotopes", "List", "<", "IsotopeContainer", ">", "listISO", "=", "isoSort", ".", "getIsotopes", "(", ")", ";", "Collections", ".", "sort", "(", "listISO", ",", "new", "Comparator", "<", "IsotopeContainer", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "IsotopeContainer", "o1", ",", "IsotopeContainer", "o2", ")", "{", "return", "Double", ".", "compare", "(", "o1", ".", "getMass", "(", ")", ",", "o2", ".", "getMass", "(", ")", ")", ";", "}", "}", ")", ";", "// Set the monoisotopic peak to the one with lowest mass", "isoSort", ".", "setMonoIsotope", "(", "listISO", ".", "get", "(", "0", ")", ")", ";", "return", "isoSort", ";", "}", "catch", "(", "CloneNotSupportedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}" ]
Return the isotope pattern sorted by mass to the highest abundance. @param isotopeP The IsotopePattern object to sort @return The IsotopePattern sorted
[ "Return", "the", "isotope", "pattern", "sorted", "by", "mass", "to", "the", "highest", "abundance", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternManipulator.java#L113-L140
OpenLiberty/open-liberty
dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/clients/common/HashUtils.java
HashUtils.digest
@Sensitive @Trivial protected static String digest(@Sensitive String input, @Sensitive String algorithm, String charset) { """ generate hash code by using specified algorithm and character set. If there is some error, log the error. """ MessageDigest md; String output = null; if (input != null && input.length() > 0) { try { md = MessageDigest.getInstance(algorithm); md.update(input.getBytes(charset)); output = Base64Coder.toString(Base64Coder.base64Encode(md.digest())); } catch (NoSuchAlgorithmException nsae) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Exception instanciating MessageDigest. The algorithm is " + algorithm + nsae); } throw new RuntimeException("Exception instanciating MessageDigest : " + nsae); } catch (UnsupportedEncodingException uee) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Exception converting String object : " + uee); } throw new RuntimeException("Exception converting String object : " + uee); } } return output; }
java
@Sensitive @Trivial protected static String digest(@Sensitive String input, @Sensitive String algorithm, String charset) { MessageDigest md; String output = null; if (input != null && input.length() > 0) { try { md = MessageDigest.getInstance(algorithm); md.update(input.getBytes(charset)); output = Base64Coder.toString(Base64Coder.base64Encode(md.digest())); } catch (NoSuchAlgorithmException nsae) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Exception instanciating MessageDigest. The algorithm is " + algorithm + nsae); } throw new RuntimeException("Exception instanciating MessageDigest : " + nsae); } catch (UnsupportedEncodingException uee) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Exception converting String object : " + uee); } throw new RuntimeException("Exception converting String object : " + uee); } } return output; }
[ "@", "Sensitive", "@", "Trivial", "protected", "static", "String", "digest", "(", "@", "Sensitive", "String", "input", ",", "@", "Sensitive", "String", "algorithm", ",", "String", "charset", ")", "{", "MessageDigest", "md", ";", "String", "output", "=", "null", ";", "if", "(", "input", "!=", "null", "&&", "input", ".", "length", "(", ")", ">", "0", ")", "{", "try", "{", "md", "=", "MessageDigest", ".", "getInstance", "(", "algorithm", ")", ";", "md", ".", "update", "(", "input", ".", "getBytes", "(", "charset", ")", ")", ";", "output", "=", "Base64Coder", ".", "toString", "(", "Base64Coder", ".", "base64Encode", "(", "md", ".", "digest", "(", ")", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "nsae", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Exception instanciating MessageDigest. The algorithm is \"", "+", "algorithm", "+", "nsae", ")", ";", "}", "throw", "new", "RuntimeException", "(", "\"Exception instanciating MessageDigest : \"", "+", "nsae", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "uee", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"Exception converting String object : \"", "+", "uee", ")", ";", "}", "throw", "new", "RuntimeException", "(", "\"Exception converting String object : \"", "+", "uee", ")", ";", "}", "}", "return", "output", ";", "}" ]
generate hash code by using specified algorithm and character set. If there is some error, log the error.
[ "generate", "hash", "code", "by", "using", "specified", "algorithm", "and", "character", "set", ".", "If", "there", "is", "some", "error", "log", "the", "error", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/clients/common/HashUtils.java#L48-L71
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ms/MergeSmallRegions.java
MergeSmallRegions.selectMerge
protected void selectMerge( int pruneId , FastQueue<float[]> regionColor ) { """ Examine edges for the specified node and select node which it is the best match for it to merge with @param pruneId The prune Id of the segment which is to be merged into another segment @param regionColor List of region colors """ // Grab information on the region which is being pruned Node n = pruneGraph.get(pruneId); float[] targetColor = regionColor.get(n.segment); // segment ID and distance away from the most similar neighbor int bestId = -1; float bestDistance = Float.MAX_VALUE; // Examine all the segments it is connected to to see which one it is most similar too for( int i = 0; i < n.edges.size; i++ ) { int segment = n.edges.get(i); float[] neighborColor = regionColor.get(segment); float d = SegmentMeanShiftSearch.distanceSq(targetColor, neighborColor); if( d < bestDistance ) { bestDistance = d; bestId = segment; } } if( bestId == -1 ) throw new RuntimeException("No neighbors? Something went really wrong."); markMerge(n.segment, bestId); }
java
protected void selectMerge( int pruneId , FastQueue<float[]> regionColor ) { // Grab information on the region which is being pruned Node n = pruneGraph.get(pruneId); float[] targetColor = regionColor.get(n.segment); // segment ID and distance away from the most similar neighbor int bestId = -1; float bestDistance = Float.MAX_VALUE; // Examine all the segments it is connected to to see which one it is most similar too for( int i = 0; i < n.edges.size; i++ ) { int segment = n.edges.get(i); float[] neighborColor = regionColor.get(segment); float d = SegmentMeanShiftSearch.distanceSq(targetColor, neighborColor); if( d < bestDistance ) { bestDistance = d; bestId = segment; } } if( bestId == -1 ) throw new RuntimeException("No neighbors? Something went really wrong."); markMerge(n.segment, bestId); }
[ "protected", "void", "selectMerge", "(", "int", "pruneId", ",", "FastQueue", "<", "float", "[", "]", ">", "regionColor", ")", "{", "// Grab information on the region which is being pruned", "Node", "n", "=", "pruneGraph", ".", "get", "(", "pruneId", ")", ";", "float", "[", "]", "targetColor", "=", "regionColor", ".", "get", "(", "n", ".", "segment", ")", ";", "// segment ID and distance away from the most similar neighbor", "int", "bestId", "=", "-", "1", ";", "float", "bestDistance", "=", "Float", ".", "MAX_VALUE", ";", "// Examine all the segments it is connected to to see which one it is most similar too", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ".", "edges", ".", "size", ";", "i", "++", ")", "{", "int", "segment", "=", "n", ".", "edges", ".", "get", "(", "i", ")", ";", "float", "[", "]", "neighborColor", "=", "regionColor", ".", "get", "(", "segment", ")", ";", "float", "d", "=", "SegmentMeanShiftSearch", ".", "distanceSq", "(", "targetColor", ",", "neighborColor", ")", ";", "if", "(", "d", "<", "bestDistance", ")", "{", "bestDistance", "=", "d", ";", "bestId", "=", "segment", ";", "}", "}", "if", "(", "bestId", "==", "-", "1", ")", "throw", "new", "RuntimeException", "(", "\"No neighbors? Something went really wrong.\"", ")", ";", "markMerge", "(", "n", ".", "segment", ",", "bestId", ")", ";", "}" ]
Examine edges for the specified node and select node which it is the best match for it to merge with @param pruneId The prune Id of the segment which is to be merged into another segment @param regionColor List of region colors
[ "Examine", "edges", "for", "the", "specified", "node", "and", "select", "node", "which", "it", "is", "the", "best", "match", "for", "it", "to", "merge", "with" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ms/MergeSmallRegions.java#L343-L368
thorntail/thorntail
core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java
MavenArtifactUtil.createMavenArtifactLoader
public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { """ A utility method to create a Maven artifact resource loader for the given artifact name. @param mavenResolver the Maven resolver to use (must not be {@code null}) @param name the artifact name @return the resource loader @throws IOException if the artifact could not be resolved """ return createMavenArtifactLoader(mavenResolver, ArtifactCoordinates.fromString(name), name); }
java
public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { return createMavenArtifactLoader(mavenResolver, ArtifactCoordinates.fromString(name), name); }
[ "public", "static", "ResourceLoader", "createMavenArtifactLoader", "(", "final", "MavenResolver", "mavenResolver", ",", "final", "String", "name", ")", "throws", "IOException", "{", "return", "createMavenArtifactLoader", "(", "mavenResolver", ",", "ArtifactCoordinates", ".", "fromString", "(", "name", ")", ",", "name", ")", ";", "}" ]
A utility method to create a Maven artifact resource loader for the given artifact name. @param mavenResolver the Maven resolver to use (must not be {@code null}) @param name the artifact name @return the resource loader @throws IOException if the artifact could not be resolved
[ "A", "utility", "method", "to", "create", "a", "Maven", "artifact", "resource", "loader", "for", "the", "given", "artifact", "name", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java#L266-L268
fnklabs/draenei
src/main/java/com/fnklabs/draenei/orm/EntityMetadata.java
EntityMetadata.buildEntityMetadata
static <V> EntityMetadata buildEntityMetadata(@NotNull Class<V> clazz, @NotNull CassandraClient cassandraClient) throws MetadataException { """ Build cassandra entity metadata @param clazz Entity class @param cassandraClient Cassandra Client from which will be retrieved table information @param <V> Entity class type @return Entity metadata @throws MetadataException """ Table tableAnnotation = clazz.getAnnotation(Table.class); if (tableAnnotation == null) { throw new MetadataException(String.format("Table annotation is missing for %s", clazz.getName())); } String tableKeyspace = StringUtils.isEmpty(tableAnnotation.keyspace()) ? cassandraClient.getDefaultKeyspace() : tableAnnotation.keyspace(); String tableName = tableAnnotation.name(); TableMetadata tableMetadata = cassandraClient.getTableMetadata(tableKeyspace, tableName); EntityMetadata entityMetadata = new EntityMetadata( tableName, tableKeyspace, tableAnnotation.compactStorage(), tableAnnotation.fetchSize(), tableAnnotation.readConsistencyLevel(), tableAnnotation.writeConsistencyLevel(), tableMetadata ); try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { ColumnMetadata columnMetadata = buildColumnMetadata(propertyDescriptor, clazz, cassandraClient, tableMetadata); if (columnMetadata != null) { entityMetadata.addColumnMetadata(columnMetadata); } LOGGER.debug("Property descriptor: {} {}", propertyDescriptor.getName(), propertyDescriptor.getDisplayName()); } } catch (IntrospectionException e) { LOGGER.warn("Can't build column metadata", e); } EntityMetadata.validate(entityMetadata); return entityMetadata; }
java
static <V> EntityMetadata buildEntityMetadata(@NotNull Class<V> clazz, @NotNull CassandraClient cassandraClient) throws MetadataException { Table tableAnnotation = clazz.getAnnotation(Table.class); if (tableAnnotation == null) { throw new MetadataException(String.format("Table annotation is missing for %s", clazz.getName())); } String tableKeyspace = StringUtils.isEmpty(tableAnnotation.keyspace()) ? cassandraClient.getDefaultKeyspace() : tableAnnotation.keyspace(); String tableName = tableAnnotation.name(); TableMetadata tableMetadata = cassandraClient.getTableMetadata(tableKeyspace, tableName); EntityMetadata entityMetadata = new EntityMetadata( tableName, tableKeyspace, tableAnnotation.compactStorage(), tableAnnotation.fetchSize(), tableAnnotation.readConsistencyLevel(), tableAnnotation.writeConsistencyLevel(), tableMetadata ); try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { ColumnMetadata columnMetadata = buildColumnMetadata(propertyDescriptor, clazz, cassandraClient, tableMetadata); if (columnMetadata != null) { entityMetadata.addColumnMetadata(columnMetadata); } LOGGER.debug("Property descriptor: {} {}", propertyDescriptor.getName(), propertyDescriptor.getDisplayName()); } } catch (IntrospectionException e) { LOGGER.warn("Can't build column metadata", e); } EntityMetadata.validate(entityMetadata); return entityMetadata; }
[ "static", "<", "V", ">", "EntityMetadata", "buildEntityMetadata", "(", "@", "NotNull", "Class", "<", "V", ">", "clazz", ",", "@", "NotNull", "CassandraClient", "cassandraClient", ")", "throws", "MetadataException", "{", "Table", "tableAnnotation", "=", "clazz", ".", "getAnnotation", "(", "Table", ".", "class", ")", ";", "if", "(", "tableAnnotation", "==", "null", ")", "{", "throw", "new", "MetadataException", "(", "String", ".", "format", "(", "\"Table annotation is missing for %s\"", ",", "clazz", ".", "getName", "(", ")", ")", ")", ";", "}", "String", "tableKeyspace", "=", "StringUtils", ".", "isEmpty", "(", "tableAnnotation", ".", "keyspace", "(", ")", ")", "?", "cassandraClient", ".", "getDefaultKeyspace", "(", ")", ":", "tableAnnotation", ".", "keyspace", "(", ")", ";", "String", "tableName", "=", "tableAnnotation", ".", "name", "(", ")", ";", "TableMetadata", "tableMetadata", "=", "cassandraClient", ".", "getTableMetadata", "(", "tableKeyspace", ",", "tableName", ")", ";", "EntityMetadata", "entityMetadata", "=", "new", "EntityMetadata", "(", "tableName", ",", "tableKeyspace", ",", "tableAnnotation", ".", "compactStorage", "(", ")", ",", "tableAnnotation", ".", "fetchSize", "(", ")", ",", "tableAnnotation", ".", "readConsistencyLevel", "(", ")", ",", "tableAnnotation", ".", "writeConsistencyLevel", "(", ")", ",", "tableMetadata", ")", ";", "try", "{", "BeanInfo", "beanInfo", "=", "Introspector", ".", "getBeanInfo", "(", "clazz", ")", ";", "for", "(", "PropertyDescriptor", "propertyDescriptor", ":", "beanInfo", ".", "getPropertyDescriptors", "(", ")", ")", "{", "ColumnMetadata", "columnMetadata", "=", "buildColumnMetadata", "(", "propertyDescriptor", ",", "clazz", ",", "cassandraClient", ",", "tableMetadata", ")", ";", "if", "(", "columnMetadata", "!=", "null", ")", "{", "entityMetadata", ".", "addColumnMetadata", "(", "columnMetadata", ")", ";", "}", "LOGGER", ".", "debug", "(", "\"Property descriptor: {} {}\"", ",", "propertyDescriptor", ".", "getName", "(", ")", ",", "propertyDescriptor", ".", "getDisplayName", "(", ")", ")", ";", "}", "}", "catch", "(", "IntrospectionException", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"Can't build column metadata\"", ",", "e", ")", ";", "}", "EntityMetadata", ".", "validate", "(", "entityMetadata", ")", ";", "return", "entityMetadata", ";", "}" ]
Build cassandra entity metadata @param clazz Entity class @param cassandraClient Cassandra Client from which will be retrieved table information @param <V> Entity class type @return Entity metadata @throws MetadataException
[ "Build", "cassandra", "entity", "metadata" ]
train
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/EntityMetadata.java#L189-L232
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArrayList.java
CopyOnWriteArrayList.removeOrRetain
private int removeOrRetain(Collection<?> collection, boolean retain, int from, int to) { """ Removes or retains the elements in {@code collection}. Returns the number of elements removed. """ for (int i = from; i < to; i++) { if (collection.contains(elements[i]) == retain) { continue; } /* * We've encountered an element that must be removed! Create a new * array and copy in the surviving elements one by one. */ Object[] newElements = new Object[elements.length - 1]; System.arraycopy(elements, 0, newElements, 0, i); int newSize = i; for (int j = i + 1; j < to; j++) { if (collection.contains(elements[j]) == retain) { newElements[newSize++] = elements[j]; } } /* * Copy the elements after 'to'. This is only useful for sub lists, * where 'to' will be less than elements.length. */ System.arraycopy(elements, to, newElements, newSize, elements.length - to); newSize += (elements.length - to); if (newSize < newElements.length) { newElements = Arrays.copyOfRange(newElements, 0, newSize); // trim to size } int removed = elements.length - newElements.length; elements = newElements; return removed; } // we made it all the way through the loop without making any changes return 0; }
java
private int removeOrRetain(Collection<?> collection, boolean retain, int from, int to) { for (int i = from; i < to; i++) { if (collection.contains(elements[i]) == retain) { continue; } /* * We've encountered an element that must be removed! Create a new * array and copy in the surviving elements one by one. */ Object[] newElements = new Object[elements.length - 1]; System.arraycopy(elements, 0, newElements, 0, i); int newSize = i; for (int j = i + 1; j < to; j++) { if (collection.contains(elements[j]) == retain) { newElements[newSize++] = elements[j]; } } /* * Copy the elements after 'to'. This is only useful for sub lists, * where 'to' will be less than elements.length. */ System.arraycopy(elements, to, newElements, newSize, elements.length - to); newSize += (elements.length - to); if (newSize < newElements.length) { newElements = Arrays.copyOfRange(newElements, 0, newSize); // trim to size } int removed = elements.length - newElements.length; elements = newElements; return removed; } // we made it all the way through the loop without making any changes return 0; }
[ "private", "int", "removeOrRetain", "(", "Collection", "<", "?", ">", "collection", ",", "boolean", "retain", ",", "int", "from", ",", "int", "to", ")", "{", "for", "(", "int", "i", "=", "from", ";", "i", "<", "to", ";", "i", "++", ")", "{", "if", "(", "collection", ".", "contains", "(", "elements", "[", "i", "]", ")", "==", "retain", ")", "{", "continue", ";", "}", "/*\n * We've encountered an element that must be removed! Create a new\n * array and copy in the surviving elements one by one.\n */", "Object", "[", "]", "newElements", "=", "new", "Object", "[", "elements", ".", "length", "-", "1", "]", ";", "System", ".", "arraycopy", "(", "elements", ",", "0", ",", "newElements", ",", "0", ",", "i", ")", ";", "int", "newSize", "=", "i", ";", "for", "(", "int", "j", "=", "i", "+", "1", ";", "j", "<", "to", ";", "j", "++", ")", "{", "if", "(", "collection", ".", "contains", "(", "elements", "[", "j", "]", ")", "==", "retain", ")", "{", "newElements", "[", "newSize", "++", "]", "=", "elements", "[", "j", "]", ";", "}", "}", "/*\n * Copy the elements after 'to'. This is only useful for sub lists,\n * where 'to' will be less than elements.length.\n */", "System", ".", "arraycopy", "(", "elements", ",", "to", ",", "newElements", ",", "newSize", ",", "elements", ".", "length", "-", "to", ")", ";", "newSize", "+=", "(", "elements", ".", "length", "-", "to", ")", ";", "if", "(", "newSize", "<", "newElements", ".", "length", ")", "{", "newElements", "=", "Arrays", ".", "copyOfRange", "(", "newElements", ",", "0", ",", "newSize", ")", ";", "// trim to size", "}", "int", "removed", "=", "elements", ".", "length", "-", "newElements", ".", "length", ";", "elements", "=", "newElements", ";", "return", "removed", ";", "}", "// we made it all the way through the loop without making any changes", "return", "0", ";", "}" ]
Removes or retains the elements in {@code collection}. Returns the number of elements removed.
[ "Removes", "or", "retains", "the", "elements", "in", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CopyOnWriteArrayList.java#L435-L471
belaban/JGroups
src/org/jgroups/blocks/MessageDispatcher.java
MessageDispatcher.castMessageWithFuture
public <T> CompletableFuture<RspList<T>> castMessageWithFuture(final Collection<Address> dests, Buffer data, RequestOptions opts) throws Exception { """ Sends a message to all members and expects responses from members in dests (if non-null). @param dests A list of group members from which to expect responses (if the call is blocking). @param data The message to be sent @param opts A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details @return CompletableFuture<T> A future from which the results (RspList) can be retrieved, or null if the request was sent asynchronously @throws Exception If the request cannot be sent """ return cast(dests,data,opts,false); }
java
public <T> CompletableFuture<RspList<T>> castMessageWithFuture(final Collection<Address> dests, Buffer data, RequestOptions opts) throws Exception { return cast(dests,data,opts,false); }
[ "public", "<", "T", ">", "CompletableFuture", "<", "RspList", "<", "T", ">", ">", "castMessageWithFuture", "(", "final", "Collection", "<", "Address", ">", "dests", ",", "Buffer", "data", ",", "RequestOptions", "opts", ")", "throws", "Exception", "{", "return", "cast", "(", "dests", ",", "data", ",", "opts", ",", "false", ")", ";", "}" ]
Sends a message to all members and expects responses from members in dests (if non-null). @param dests A list of group members from which to expect responses (if the call is blocking). @param data The message to be sent @param opts A set of options that govern the call. See {@link org.jgroups.blocks.RequestOptions} for details @return CompletableFuture<T> A future from which the results (RspList) can be retrieved, or null if the request was sent asynchronously @throws Exception If the request cannot be sent
[ "Sends", "a", "message", "to", "all", "members", "and", "expects", "responses", "from", "members", "in", "dests", "(", "if", "non", "-", "null", ")", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/blocks/MessageDispatcher.java#L265-L268
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java
PersistenceController.updateConversations
public Observable<Boolean> updateConversations(List<ChatConversation> conversationsToUpdate) { """ Update conversations. @param conversationsToUpdate List of conversations to apply an update. @return Observable emitting result. """ return asObservable(new Executor<Boolean>() { @Override void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccess = true; for (ChatConversationBase conversation : conversationsToUpdate) { ChatConversationBase.Builder toSave = ChatConversationBase.baseBuilder(); ChatConversationBase saved = store.getConversation(conversation.getConversationId()); if (saved != null) { toSave.setConversationId(saved.getConversationId()); toSave.setFirstLocalEventId(saved.getFirstLocalEventId()); toSave.setLastLocalEventId(saved.getLastLocalEventId()); if (conversation.getLastRemoteEventId() == null) { toSave.setLastRemoteEventId(saved.getLastRemoteEventId()); } else { toSave.setLastRemoteEventId(Math.max(saved.getLastRemoteEventId(), conversation.getLastRemoteEventId())); } if (conversation.getUpdatedOn() == null) { toSave.setUpdatedOn(System.currentTimeMillis()); } else { toSave.setUpdatedOn(conversation.getUpdatedOn()); } toSave.setETag(conversation.getETag()); } isSuccess = isSuccess && store.update(toSave.build()); } store.endTransaction(); emitter.onNext(isSuccess); emitter.onCompleted(); } }); }
java
public Observable<Boolean> updateConversations(List<ChatConversation> conversationsToUpdate) { return asObservable(new Executor<Boolean>() { @Override void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccess = true; for (ChatConversationBase conversation : conversationsToUpdate) { ChatConversationBase.Builder toSave = ChatConversationBase.baseBuilder(); ChatConversationBase saved = store.getConversation(conversation.getConversationId()); if (saved != null) { toSave.setConversationId(saved.getConversationId()); toSave.setFirstLocalEventId(saved.getFirstLocalEventId()); toSave.setLastLocalEventId(saved.getLastLocalEventId()); if (conversation.getLastRemoteEventId() == null) { toSave.setLastRemoteEventId(saved.getLastRemoteEventId()); } else { toSave.setLastRemoteEventId(Math.max(saved.getLastRemoteEventId(), conversation.getLastRemoteEventId())); } if (conversation.getUpdatedOn() == null) { toSave.setUpdatedOn(System.currentTimeMillis()); } else { toSave.setUpdatedOn(conversation.getUpdatedOn()); } toSave.setETag(conversation.getETag()); } isSuccess = isSuccess && store.update(toSave.build()); } store.endTransaction(); emitter.onNext(isSuccess); emitter.onCompleted(); } }); }
[ "public", "Observable", "<", "Boolean", ">", "updateConversations", "(", "List", "<", "ChatConversation", ">", "conversationsToUpdate", ")", "{", "return", "asObservable", "(", "new", "Executor", "<", "Boolean", ">", "(", ")", "{", "@", "Override", "void", "execute", "(", "ChatStore", "store", ",", "Emitter", "<", "Boolean", ">", "emitter", ")", "{", "store", ".", "beginTransaction", "(", ")", ";", "boolean", "isSuccess", "=", "true", ";", "for", "(", "ChatConversationBase", "conversation", ":", "conversationsToUpdate", ")", "{", "ChatConversationBase", ".", "Builder", "toSave", "=", "ChatConversationBase", ".", "baseBuilder", "(", ")", ";", "ChatConversationBase", "saved", "=", "store", ".", "getConversation", "(", "conversation", ".", "getConversationId", "(", ")", ")", ";", "if", "(", "saved", "!=", "null", ")", "{", "toSave", ".", "setConversationId", "(", "saved", ".", "getConversationId", "(", ")", ")", ";", "toSave", ".", "setFirstLocalEventId", "(", "saved", ".", "getFirstLocalEventId", "(", ")", ")", ";", "toSave", ".", "setLastLocalEventId", "(", "saved", ".", "getLastLocalEventId", "(", ")", ")", ";", "if", "(", "conversation", ".", "getLastRemoteEventId", "(", ")", "==", "null", ")", "{", "toSave", ".", "setLastRemoteEventId", "(", "saved", ".", "getLastRemoteEventId", "(", ")", ")", ";", "}", "else", "{", "toSave", ".", "setLastRemoteEventId", "(", "Math", ".", "max", "(", "saved", ".", "getLastRemoteEventId", "(", ")", ",", "conversation", ".", "getLastRemoteEventId", "(", ")", ")", ")", ";", "}", "if", "(", "conversation", ".", "getUpdatedOn", "(", ")", "==", "null", ")", "{", "toSave", ".", "setUpdatedOn", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}", "else", "{", "toSave", ".", "setUpdatedOn", "(", "conversation", ".", "getUpdatedOn", "(", ")", ")", ";", "}", "toSave", ".", "setETag", "(", "conversation", ".", "getETag", "(", ")", ")", ";", "}", "isSuccess", "=", "isSuccess", "&&", "store", ".", "update", "(", "toSave", ".", "build", "(", ")", ")", ";", "}", "store", ".", "endTransaction", "(", ")", ";", "emitter", ".", "onNext", "(", "isSuccess", ")", ";", "emitter", ".", "onCompleted", "(", ")", ";", "}", "}", ")", ";", "}" ]
Update conversations. @param conversationsToUpdate List of conversations to apply an update. @return Observable emitting result.
[ "Update", "conversations", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java#L497-L537
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/DefaultPageShell.java
DefaultPageShell.addCssHeadlines
private void addCssHeadlines(final PrintWriter writer, final List cssHeadlines) { """ Add a list of css headline entries intended to be added only once to the page. @param writer the writer to write to. @param cssHeadlines a list of css entries to be added to the page as a whole. """ if (cssHeadlines == null || cssHeadlines.isEmpty()) { return; } writer.write("<!-- Start css headlines -->" + "\n<style type=\"" + WebUtilities.CONTENT_TYPE_CSS + "\" media=\"screen\">"); for (Object line : cssHeadlines) { writer.write("\n" + line); } writer.write("\n</style>" + "<!-- End css headlines -->"); }
java
private void addCssHeadlines(final PrintWriter writer, final List cssHeadlines) { if (cssHeadlines == null || cssHeadlines.isEmpty()) { return; } writer.write("<!-- Start css headlines -->" + "\n<style type=\"" + WebUtilities.CONTENT_TYPE_CSS + "\" media=\"screen\">"); for (Object line : cssHeadlines) { writer.write("\n" + line); } writer.write("\n</style>" + "<!-- End css headlines -->"); }
[ "private", "void", "addCssHeadlines", "(", "final", "PrintWriter", "writer", ",", "final", "List", "cssHeadlines", ")", "{", "if", "(", "cssHeadlines", "==", "null", "||", "cssHeadlines", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "writer", ".", "write", "(", "\"<!-- Start css headlines -->\"", "+", "\"\\n<style type=\\\"\"", "+", "WebUtilities", ".", "CONTENT_TYPE_CSS", "+", "\"\\\" media=\\\"screen\\\">\"", ")", ";", "for", "(", "Object", "line", ":", "cssHeadlines", ")", "{", "writer", ".", "write", "(", "\"\\n\"", "+", "line", ")", ";", "}", "writer", ".", "write", "(", "\"\\n</style>\"", "+", "\"<!-- End css headlines -->\"", ")", ";", "}" ]
Add a list of css headline entries intended to be added only once to the page. @param writer the writer to write to. @param cssHeadlines a list of css entries to be added to the page as a whole.
[ "Add", "a", "list", "of", "css", "headline", "entries", "intended", "to", "be", "added", "only", "once", "to", "the", "page", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/DefaultPageShell.java#L185-L199
hankcs/HanLP
src/main/java/com/hankcs/hanlp/classification/statistics/ContinuousDistributions.java
ContinuousDistributions.Gcf
protected static double Gcf(double x, double A) { """ Internal function used by GammaCdf @param x @param A @return """ // Good for X>A+1 double A0 = 0; double B0 = 1; double A1 = 1; double B1 = x; double AOLD = 0; double N = 0; while (Math.abs((A1 - AOLD) / A1) > .00001) { AOLD = A1; N = N + 1; A0 = A1 + (N - A) * A0; B0 = B1 + (N - A) * B0; A1 = x * A0 + N * A1; B1 = x * B0 + N * B1; A0 = A0 / B1; B0 = B0 / B1; A1 = A1 / B1; B1 = 1; } double Prob = Math.exp(A * Math.log(x) - x - LogGamma(A)) * A1; return 1.0 - Prob; }
java
protected static double Gcf(double x, double A) { // Good for X>A+1 double A0 = 0; double B0 = 1; double A1 = 1; double B1 = x; double AOLD = 0; double N = 0; while (Math.abs((A1 - AOLD) / A1) > .00001) { AOLD = A1; N = N + 1; A0 = A1 + (N - A) * A0; B0 = B1 + (N - A) * B0; A1 = x * A0 + N * A1; B1 = x * B0 + N * B1; A0 = A0 / B1; B0 = B0 / B1; A1 = A1 / B1; B1 = 1; } double Prob = Math.exp(A * Math.log(x) - x - LogGamma(A)) * A1; return 1.0 - Prob; }
[ "protected", "static", "double", "Gcf", "(", "double", "x", ",", "double", "A", ")", "{", "// Good for X>A+1", "double", "A0", "=", "0", ";", "double", "B0", "=", "1", ";", "double", "A1", "=", "1", ";", "double", "B1", "=", "x", ";", "double", "AOLD", "=", "0", ";", "double", "N", "=", "0", ";", "while", "(", "Math", ".", "abs", "(", "(", "A1", "-", "AOLD", ")", "/", "A1", ")", ">", ".00001", ")", "{", "AOLD", "=", "A1", ";", "N", "=", "N", "+", "1", ";", "A0", "=", "A1", "+", "(", "N", "-", "A", ")", "*", "A0", ";", "B0", "=", "B1", "+", "(", "N", "-", "A", ")", "*", "B0", ";", "A1", "=", "x", "*", "A0", "+", "N", "*", "A1", ";", "B1", "=", "x", "*", "B0", "+", "N", "*", "B1", ";", "A0", "=", "A0", "/", "B1", ";", "B0", "=", "B0", "/", "B1", ";", "A1", "=", "A1", "/", "B1", ";", "B1", "=", "1", ";", "}", "double", "Prob", "=", "Math", ".", "exp", "(", "A", "*", "Math", ".", "log", "(", "x", ")", "-", "x", "-", "LogGamma", "(", "A", ")", ")", "*", "A1", ";", "return", "1.0", "-", "Prob", ";", "}" ]
Internal function used by GammaCdf @param x @param A @return
[ "Internal", "function", "used", "by", "GammaCdf" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/classification/statistics/ContinuousDistributions.java#L125-L150
apache/spark
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java
ThriftHttpServlet.getAuthHeader
private String getAuthHeader(HttpServletRequest request, String authType) throws HttpAuthenticationException { """ Returns the base64 encoded auth header payload @param request @param authType @return @throws HttpAuthenticationException """ String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION); // Each http request must have an Authorization header if (authHeader == null || authHeader.isEmpty()) { throw new HttpAuthenticationException("Authorization header received " + "from the client is empty."); } String authHeaderBase64String; int beginIndex; if (isKerberosAuthMode(authType)) { beginIndex = (HttpAuthUtils.NEGOTIATE + " ").length(); } else { beginIndex = (HttpAuthUtils.BASIC + " ").length(); } authHeaderBase64String = authHeader.substring(beginIndex); // Authorization header must have a payload if (authHeaderBase64String == null || authHeaderBase64String.isEmpty()) { throw new HttpAuthenticationException("Authorization header received " + "from the client does not contain any data."); } return authHeaderBase64String; }
java
private String getAuthHeader(HttpServletRequest request, String authType) throws HttpAuthenticationException { String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION); // Each http request must have an Authorization header if (authHeader == null || authHeader.isEmpty()) { throw new HttpAuthenticationException("Authorization header received " + "from the client is empty."); } String authHeaderBase64String; int beginIndex; if (isKerberosAuthMode(authType)) { beginIndex = (HttpAuthUtils.NEGOTIATE + " ").length(); } else { beginIndex = (HttpAuthUtils.BASIC + " ").length(); } authHeaderBase64String = authHeader.substring(beginIndex); // Authorization header must have a payload if (authHeaderBase64String == null || authHeaderBase64String.isEmpty()) { throw new HttpAuthenticationException("Authorization header received " + "from the client does not contain any data."); } return authHeaderBase64String; }
[ "private", "String", "getAuthHeader", "(", "HttpServletRequest", "request", ",", "String", "authType", ")", "throws", "HttpAuthenticationException", "{", "String", "authHeader", "=", "request", ".", "getHeader", "(", "HttpAuthUtils", ".", "AUTHORIZATION", ")", ";", "// Each http request must have an Authorization header", "if", "(", "authHeader", "==", "null", "||", "authHeader", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "HttpAuthenticationException", "(", "\"Authorization header received \"", "+", "\"from the client is empty.\"", ")", ";", "}", "String", "authHeaderBase64String", ";", "int", "beginIndex", ";", "if", "(", "isKerberosAuthMode", "(", "authType", ")", ")", "{", "beginIndex", "=", "(", "HttpAuthUtils", ".", "NEGOTIATE", "+", "\" \"", ")", ".", "length", "(", ")", ";", "}", "else", "{", "beginIndex", "=", "(", "HttpAuthUtils", ".", "BASIC", "+", "\" \"", ")", ".", "length", "(", ")", ";", "}", "authHeaderBase64String", "=", "authHeader", ".", "substring", "(", "beginIndex", ")", ";", "// Authorization header must have a payload", "if", "(", "authHeaderBase64String", "==", "null", "||", "authHeaderBase64String", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "HttpAuthenticationException", "(", "\"Authorization header received \"", "+", "\"from the client does not contain any data.\"", ")", ";", "}", "return", "authHeaderBase64String", ";", "}" ]
Returns the base64 encoded auth header payload @param request @param authType @return @throws HttpAuthenticationException
[ "Returns", "the", "base64", "encoded", "auth", "header", "payload" ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java#L496-L520
softindex/datakernel
core-codegen/src/main/java/io/datakernel/codegen/Expressions.java
Expressions.cmpEq
public static PredicateDef cmpEq(Expression left, Expression right) { """ Verifies that the arguments are equal @param left first argument which will be compared @param right second argument which will be compared @return new instance of the PredicateDefCmp """ return cmp(CompareOperation.EQ, left, right); }
java
public static PredicateDef cmpEq(Expression left, Expression right) { return cmp(CompareOperation.EQ, left, right); }
[ "public", "static", "PredicateDef", "cmpEq", "(", "Expression", "left", ",", "Expression", "right", ")", "{", "return", "cmp", "(", "CompareOperation", ".", "EQ", ",", "left", ",", "right", ")", ";", "}" ]
Verifies that the arguments are equal @param left first argument which will be compared @param right second argument which will be compared @return new instance of the PredicateDefCmp
[ "Verifies", "that", "the", "arguments", "are", "equal" ]
train
https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-codegen/src/main/java/io/datakernel/codegen/Expressions.java#L191-L193
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java
EnumConstantBuilder.buildSignature
public void buildSignature(XMLNode node, Content enumConstantsTree) { """ Build the signature. @param node the XML element that specifies which components to document @param enumConstantsTree the content tree to which the documentation will be added """ enumConstantsTree.addContent(writer.getSignature(currentElement)); }
java
public void buildSignature(XMLNode node, Content enumConstantsTree) { enumConstantsTree.addContent(writer.getSignature(currentElement)); }
[ "public", "void", "buildSignature", "(", "XMLNode", "node", ",", "Content", "enumConstantsTree", ")", "{", "enumConstantsTree", ".", "addContent", "(", "writer", ".", "getSignature", "(", "currentElement", ")", ")", ";", "}" ]
Build the signature. @param node the XML element that specifies which components to document @param enumConstantsTree the content tree to which the documentation will be added
[ "Build", "the", "signature", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java#L162-L164
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.updateSasDefinitionAsync
public Observable<SasDefinitionBundle> updateSasDefinitionAsync(String vaultBaseUrl, String storageAccountName, String sasDefinitionName) { """ Updates the specified attributes associated with the given SAS definition. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SasDefinitionBundle object """ return updateSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName).map(new Func1<ServiceResponse<SasDefinitionBundle>, SasDefinitionBundle>() { @Override public SasDefinitionBundle call(ServiceResponse<SasDefinitionBundle> response) { return response.body(); } }); }
java
public Observable<SasDefinitionBundle> updateSasDefinitionAsync(String vaultBaseUrl, String storageAccountName, String sasDefinitionName) { return updateSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName).map(new Func1<ServiceResponse<SasDefinitionBundle>, SasDefinitionBundle>() { @Override public SasDefinitionBundle call(ServiceResponse<SasDefinitionBundle> response) { return response.body(); } }); }
[ "public", "Observable", "<", "SasDefinitionBundle", ">", "updateSasDefinitionAsync", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "String", "sasDefinitionName", ")", "{", "return", "updateSasDefinitionWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "storageAccountName", ",", "sasDefinitionName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "SasDefinitionBundle", ">", ",", "SasDefinitionBundle", ">", "(", ")", "{", "@", "Override", "public", "SasDefinitionBundle", "call", "(", "ServiceResponse", "<", "SasDefinitionBundle", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates the specified attributes associated with the given SAS definition. This operation requires the storage/setsas permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param sasDefinitionName The name of the SAS definition. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the SasDefinitionBundle object
[ "Updates", "the", "specified", "attributes", "associated", "with", "the", "given", "SAS", "definition", ".", "This", "operation", "requires", "the", "storage", "/", "setsas", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L11519-L11526
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java
LazyTreeReader.loadIndeces
public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) { """ Read any indeces that will be needed and return a startIndex after the values that have been read. """ if (present != null) { return present.loadIndeces(rowIndexEntries, startIndex); } else { return startIndex; } }
java
public int loadIndeces(List<RowIndexEntry> rowIndexEntries, int startIndex) { if (present != null) { return present.loadIndeces(rowIndexEntries, startIndex); } else { return startIndex; } }
[ "public", "int", "loadIndeces", "(", "List", "<", "RowIndexEntry", ">", "rowIndexEntries", ",", "int", "startIndex", ")", "{", "if", "(", "present", "!=", "null", ")", "{", "return", "present", ".", "loadIndeces", "(", "rowIndexEntries", ",", "startIndex", ")", ";", "}", "else", "{", "return", "startIndex", ";", "}", "}" ]
Read any indeces that will be needed and return a startIndex after the values that have been read.
[ "Read", "any", "indeces", "that", "will", "be", "needed", "and", "return", "a", "startIndex", "after", "the", "values", "that", "have", "been", "read", "." ]
train
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/lazy/LazyTreeReader.java#L371-L377
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCConnection.java
JDBCConnection.onStartEscapeSequence
private int onStartEscapeSequence(String sql, StringBuffer sb, int i) throws SQLException { """ is called from within nativeSQL when the start of an JDBC escape sequence is encountered """ sb.setCharAt(i++, ' '); i = StringUtil.skipSpaces(sql, i); if (sql.regionMatches(true, i, "fn ", 0, 3) || sql.regionMatches(true, i, "oj ", 0, 3) || sql.regionMatches(true, i, "ts ", 0, 3)) { sb.setCharAt(i++, ' '); sb.setCharAt(i++, ' '); } else if (sql.regionMatches(true, i, "d ", 0, 2) || sql.regionMatches(true, i, "t ", 0, 2)) { sb.setCharAt(i++, ' '); } else if (sql.regionMatches(true, i, "call ", 0, 5)) { i += 4; } else if (sql.regionMatches(true, i, "?= call ", 0, 8)) { sb.setCharAt(i++, ' '); sb.setCharAt(i++, ' '); i += 5; } else if (sql.regionMatches(true, i, "escape ", 0, 7)) { i += 6; } else { i--; throw Util.sqlException( Error.error( ErrorCode.JDBC_CONNECTION_NATIVE_SQL, sql.substring(i))); } return i; }
java
private int onStartEscapeSequence(String sql, StringBuffer sb, int i) throws SQLException { sb.setCharAt(i++, ' '); i = StringUtil.skipSpaces(sql, i); if (sql.regionMatches(true, i, "fn ", 0, 3) || sql.regionMatches(true, i, "oj ", 0, 3) || sql.regionMatches(true, i, "ts ", 0, 3)) { sb.setCharAt(i++, ' '); sb.setCharAt(i++, ' '); } else if (sql.regionMatches(true, i, "d ", 0, 2) || sql.regionMatches(true, i, "t ", 0, 2)) { sb.setCharAt(i++, ' '); } else if (sql.regionMatches(true, i, "call ", 0, 5)) { i += 4; } else if (sql.regionMatches(true, i, "?= call ", 0, 8)) { sb.setCharAt(i++, ' '); sb.setCharAt(i++, ' '); i += 5; } else if (sql.regionMatches(true, i, "escape ", 0, 7)) { i += 6; } else { i--; throw Util.sqlException( Error.error( ErrorCode.JDBC_CONNECTION_NATIVE_SQL, sql.substring(i))); } return i; }
[ "private", "int", "onStartEscapeSequence", "(", "String", "sql", ",", "StringBuffer", "sb", ",", "int", "i", ")", "throws", "SQLException", "{", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "i", "=", "StringUtil", ".", "skipSpaces", "(", "sql", ",", "i", ")", ";", "if", "(", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"fn \"", ",", "0", ",", "3", ")", "||", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"oj \"", ",", "0", ",", "3", ")", "||", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"ts \"", ",", "0", ",", "3", ")", ")", "{", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "}", "else", "if", "(", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"d \"", ",", "0", ",", "2", ")", "||", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"t \"", ",", "0", ",", "2", ")", ")", "{", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "}", "else", "if", "(", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"call \"", ",", "0", ",", "5", ")", ")", "{", "i", "+=", "4", ";", "}", "else", "if", "(", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"?= call \"", ",", "0", ",", "8", ")", ")", "{", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "sb", ".", "setCharAt", "(", "i", "++", ",", "'", "'", ")", ";", "i", "+=", "5", ";", "}", "else", "if", "(", "sql", ".", "regionMatches", "(", "true", ",", "i", ",", "\"escape \"", ",", "0", ",", "7", ")", ")", "{", "i", "+=", "6", ";", "}", "else", "{", "i", "--", ";", "throw", "Util", ".", "sqlException", "(", "Error", ".", "error", "(", "ErrorCode", ".", "JDBC_CONNECTION_NATIVE_SQL", ",", "sql", ".", "substring", "(", "i", ")", ")", ")", ";", "}", "return", "i", ";", "}" ]
is called from within nativeSQL when the start of an JDBC escape sequence is encountered
[ "is", "called", "from", "within", "nativeSQL", "when", "the", "start", "of", "an", "JDBC", "escape", "sequence", "is", "encountered" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCConnection.java#L3470-L3503
hankcs/HanLP
src/main/java/com/hankcs/hanlp/summary/TextRankSentence.java
TextRankSentence.getSummary
public static String getSummary(String document, int max_length, String sentence_separator) { """ 一句话调用接口 @param document 目标文档 @param max_length 需要摘要的长度 @param sentence_separator 句子分隔符,正则格式, 如:[。??!!;;] @return 摘要文本 """ List<String> sentenceList = splitSentence(document, sentence_separator); int sentence_count = sentenceList.size(); int document_length = document.length(); int sentence_length_avg = document_length / sentence_count; int size = max_length / sentence_length_avg + 1; List<List<String>> docs = convertSentenceListToDocument(sentenceList); TextRankSentence textRank = new TextRankSentence(docs); int[] topSentence = textRank.getTopSentence(size); List<String> resultList = new LinkedList<String>(); for (int i : topSentence) { resultList.add(sentenceList.get(i)); } resultList = permutation(resultList, sentenceList); resultList = pick_sentences(resultList, max_length); return TextUtility.join("。", resultList); }
java
public static String getSummary(String document, int max_length, String sentence_separator) { List<String> sentenceList = splitSentence(document, sentence_separator); int sentence_count = sentenceList.size(); int document_length = document.length(); int sentence_length_avg = document_length / sentence_count; int size = max_length / sentence_length_avg + 1; List<List<String>> docs = convertSentenceListToDocument(sentenceList); TextRankSentence textRank = new TextRankSentence(docs); int[] topSentence = textRank.getTopSentence(size); List<String> resultList = new LinkedList<String>(); for (int i : topSentence) { resultList.add(sentenceList.get(i)); } resultList = permutation(resultList, sentenceList); resultList = pick_sentences(resultList, max_length); return TextUtility.join("。", resultList); }
[ "public", "static", "String", "getSummary", "(", "String", "document", ",", "int", "max_length", ",", "String", "sentence_separator", ")", "{", "List", "<", "String", ">", "sentenceList", "=", "splitSentence", "(", "document", ",", "sentence_separator", ")", ";", "int", "sentence_count", "=", "sentenceList", ".", "size", "(", ")", ";", "int", "document_length", "=", "document", ".", "length", "(", ")", ";", "int", "sentence_length_avg", "=", "document_length", "/", "sentence_count", ";", "int", "size", "=", "max_length", "/", "sentence_length_avg", "+", "1", ";", "List", "<", "List", "<", "String", ">", ">", "docs", "=", "convertSentenceListToDocument", "(", "sentenceList", ")", ";", "TextRankSentence", "textRank", "=", "new", "TextRankSentence", "(", "docs", ")", ";", "int", "[", "]", "topSentence", "=", "textRank", ".", "getTopSentence", "(", "size", ")", ";", "List", "<", "String", ">", "resultList", "=", "new", "LinkedList", "<", "String", ">", "(", ")", ";", "for", "(", "int", "i", ":", "topSentence", ")", "{", "resultList", ".", "add", "(", "sentenceList", ".", "get", "(", "i", ")", ")", ";", "}", "resultList", "=", "permutation", "(", "resultList", ",", "sentenceList", ")", ";", "resultList", "=", "pick_sentences", "(", "resultList", ",", "max_length", ")", ";", "return", "TextUtility", ".", "join", "(", "\"。\", ", "r", "sultList);", "", "", "}" ]
一句话调用接口 @param document 目标文档 @param max_length 需要摘要的长度 @param sentence_separator 句子分隔符,正则格式, 如:[。??!!;;] @return 摘要文本
[ "一句话调用接口" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/summary/TextRankSentence.java#L274-L294
google/closure-templates
java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java
TranslateToPyExprVisitor.genTernaryConditional
private PyExpr genTernaryConditional(PyExpr conditionalExpr, PyExpr trueExpr, PyExpr falseExpr) { """ Generates a ternary conditional Python expression given the conditional and true/false expressions. @param conditionalExpr the conditional expression @param trueExpr the expression to execute if the conditional executes to true @param falseExpr the expression to execute if the conditional executes to false @return a ternary conditional expression """ // Python's ternary operator switches the order from <conditional> ? <true> : <false> to // <true> if <conditional> else <false>. int conditionalPrecedence = PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL); StringBuilder exprSb = new StringBuilder() .append(PyExprUtils.maybeProtect(trueExpr, conditionalPrecedence).getText()) .append(" if ") .append(PyExprUtils.maybeProtect(conditionalExpr, conditionalPrecedence).getText()) .append(" else ") .append(PyExprUtils.maybeProtect(falseExpr, conditionalPrecedence).getText()); return new PyExpr(exprSb.toString(), conditionalPrecedence); }
java
private PyExpr genTernaryConditional(PyExpr conditionalExpr, PyExpr trueExpr, PyExpr falseExpr) { // Python's ternary operator switches the order from <conditional> ? <true> : <false> to // <true> if <conditional> else <false>. int conditionalPrecedence = PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL); StringBuilder exprSb = new StringBuilder() .append(PyExprUtils.maybeProtect(trueExpr, conditionalPrecedence).getText()) .append(" if ") .append(PyExprUtils.maybeProtect(conditionalExpr, conditionalPrecedence).getText()) .append(" else ") .append(PyExprUtils.maybeProtect(falseExpr, conditionalPrecedence).getText()); return new PyExpr(exprSb.toString(), conditionalPrecedence); }
[ "private", "PyExpr", "genTernaryConditional", "(", "PyExpr", "conditionalExpr", ",", "PyExpr", "trueExpr", ",", "PyExpr", "falseExpr", ")", "{", "// Python's ternary operator switches the order from <conditional> ? <true> : <false> to", "// <true> if <conditional> else <false>.", "int", "conditionalPrecedence", "=", "PyExprUtils", ".", "pyPrecedenceForOperator", "(", "Operator", ".", "CONDITIONAL", ")", ";", "StringBuilder", "exprSb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "PyExprUtils", ".", "maybeProtect", "(", "trueExpr", ",", "conditionalPrecedence", ")", ".", "getText", "(", ")", ")", ".", "append", "(", "\" if \"", ")", ".", "append", "(", "PyExprUtils", ".", "maybeProtect", "(", "conditionalExpr", ",", "conditionalPrecedence", ")", ".", "getText", "(", ")", ")", ".", "append", "(", "\" else \"", ")", ".", "append", "(", "PyExprUtils", ".", "maybeProtect", "(", "falseExpr", ",", "conditionalPrecedence", ")", ".", "getText", "(", ")", ")", ";", "return", "new", "PyExpr", "(", "exprSb", ".", "toString", "(", ")", ",", "conditionalPrecedence", ")", ";", "}" ]
Generates a ternary conditional Python expression given the conditional and true/false expressions. @param conditionalExpr the conditional expression @param trueExpr the expression to execute if the conditional executes to true @param falseExpr the expression to execute if the conditional executes to false @return a ternary conditional expression
[ "Generates", "a", "ternary", "conditional", "Python", "expression", "given", "the", "conditional", "and", "true", "/", "false", "expressions", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java#L657-L670
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/KunderaMetadataManager.java
KunderaMetadataManager.getEntityMetadata
public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, String persistenceUnit, Class entityClass) { """ Gets the entity metadata. @param persistenceUnit the persistence unit @param entityClass the entity class @return the entity metadata """ return getMetamodel(kunderaMetadata, persistenceUnit).getEntityMetadata(entityClass); }
java
public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, String persistenceUnit, Class entityClass) { return getMetamodel(kunderaMetadata, persistenceUnit).getEntityMetadata(entityClass); }
[ "public", "static", "EntityMetadata", "getEntityMetadata", "(", "final", "KunderaMetadata", "kunderaMetadata", ",", "String", "persistenceUnit", ",", "Class", "entityClass", ")", "{", "return", "getMetamodel", "(", "kunderaMetadata", ",", "persistenceUnit", ")", ".", "getEntityMetadata", "(", "entityClass", ")", ";", "}" ]
Gets the entity metadata. @param persistenceUnit the persistence unit @param entityClass the entity class @return the entity metadata
[ "Gets", "the", "entity", "metadata", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/KunderaMetadataManager.java#L111-L115
jpelzer/pelzer-util
src/main/java/com/pelzer/util/l10n/Localizable.java
Localizable.setDefault
public void setDefault(E value, Locale locale) { """ Overrides the default locale value. @param value can be null, and subsequent calls to getDefault will return null @throws NullPointerException if locale is null. """ set(value, locale); this.defaultLocale = locale; }
java
public void setDefault(E value, Locale locale) { set(value, locale); this.defaultLocale = locale; }
[ "public", "void", "setDefault", "(", "E", "value", ",", "Locale", "locale", ")", "{", "set", "(", "value", ",", "locale", ")", ";", "this", ".", "defaultLocale", "=", "locale", ";", "}" ]
Overrides the default locale value. @param value can be null, and subsequent calls to getDefault will return null @throws NullPointerException if locale is null.
[ "Overrides", "the", "default", "locale", "value", "." ]
train
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/l10n/Localizable.java#L93-L96
geomajas/geomajas-project-client-gwt2
common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImpl.java
DomImpl.setElementAttributeNS
public void setElementAttributeNS(String ns, Element element, String attr, String value) { """ <p> Adds a new attribute in the given name-space to an element. </p> <p> There is an exception when using Internet Explorer! For Internet Explorer the attribute of type "namespace:attr" will be set. </p> @param ns The name-space to be used in the element creation. @param element The element to which the attribute is to be set. @param attr The name of the attribute. @param value The new value for the attribute. """ setNameSpaceAttribute(ns, element, attr, value); }
java
public void setElementAttributeNS(String ns, Element element, String attr, String value) { setNameSpaceAttribute(ns, element, attr, value); }
[ "public", "void", "setElementAttributeNS", "(", "String", "ns", ",", "Element", "element", ",", "String", "attr", ",", "String", "value", ")", "{", "setNameSpaceAttribute", "(", "ns", ",", "element", ",", "attr", ",", "value", ")", ";", "}" ]
<p> Adds a new attribute in the given name-space to an element. </p> <p> There is an exception when using Internet Explorer! For Internet Explorer the attribute of type "namespace:attr" will be set. </p> @param ns The name-space to be used in the element creation. @param element The element to which the attribute is to be set. @param attr The name of the attribute. @param value The new value for the attribute.
[ "<p", ">", "Adds", "a", "new", "attribute", "in", "the", "given", "name", "-", "space", "to", "an", "element", ".", "<", "/", "p", ">", "<p", ">", "There", "is", "an", "exception", "when", "using", "Internet", "Explorer!", "For", "Internet", "Explorer", "the", "attribute", "of", "type", "namespace", ":", "attr", "will", "be", "set", ".", "<", "/", "p", ">" ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/common-gwt/src/main/java/org/geomajas/gwt/client/util/impl/DomImpl.java#L161-L163
networknt/light-4j
email-sender/src/main/java/com/networknt/email/EmailSender.java
EmailSender.sendMail
public void sendMail (String to, String subject, String content) throws MessagingException { """ Send email with a string content. @param to destination email address @param subject email subject @param content email content @throws MessagingException message exception """ Properties props = new Properties(); props.put("mail.smtp.user", emailConfg.getUser()); props.put("mail.smtp.host", emailConfg.getHost()); props.put("mail.smtp.port", emailConfg.getPort()); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.debug", emailConfg.getDebug()); props.put("mail.smtp.auth", emailConfg.getAuth()); props.put("mail.smtp.ssl.trust", emailConfg.host); SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), (String)secret.get(SecretConstants.EMAIL_PASSWORD)); Session session = Session.getInstance(props, auth); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailConfg.getUser())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setContent(content, "text/html"); // Send message Transport.send(message); if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject); }
java
public void sendMail (String to, String subject, String content) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.user", emailConfg.getUser()); props.put("mail.smtp.host", emailConfg.getHost()); props.put("mail.smtp.port", emailConfg.getPort()); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.debug", emailConfg.getDebug()); props.put("mail.smtp.auth", emailConfg.getAuth()); props.put("mail.smtp.ssl.trust", emailConfg.host); SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), (String)secret.get(SecretConstants.EMAIL_PASSWORD)); Session session = Session.getInstance(props, auth); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailConfg.getUser())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setContent(content, "text/html"); // Send message Transport.send(message); if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject); }
[ "public", "void", "sendMail", "(", "String", "to", ",", "String", "subject", ",", "String", "content", ")", "throws", "MessagingException", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "props", ".", "put", "(", "\"mail.smtp.user\"", ",", "emailConfg", ".", "getUser", "(", ")", ")", ";", "props", ".", "put", "(", "\"mail.smtp.host\"", ",", "emailConfg", ".", "getHost", "(", ")", ")", ";", "props", ".", "put", "(", "\"mail.smtp.port\"", ",", "emailConfg", ".", "getPort", "(", ")", ")", ";", "props", ".", "put", "(", "\"mail.smtp.starttls.enable\"", ",", "\"true\"", ")", ";", "props", ".", "put", "(", "\"mail.smtp.debug\"", ",", "emailConfg", ".", "getDebug", "(", ")", ")", ";", "props", ".", "put", "(", "\"mail.smtp.auth\"", ",", "emailConfg", ".", "getAuth", "(", ")", ")", ";", "props", ".", "put", "(", "\"mail.smtp.ssl.trust\"", ",", "emailConfg", ".", "host", ")", ";", "SMTPAuthenticator", "auth", "=", "new", "SMTPAuthenticator", "(", "emailConfg", ".", "getUser", "(", ")", ",", "(", "String", ")", "secret", ".", "get", "(", "SecretConstants", ".", "EMAIL_PASSWORD", ")", ")", ";", "Session", "session", "=", "Session", ".", "getInstance", "(", "props", ",", "auth", ")", ";", "MimeMessage", "message", "=", "new", "MimeMessage", "(", "session", ")", ";", "message", ".", "setFrom", "(", "new", "InternetAddress", "(", "emailConfg", ".", "getUser", "(", ")", ")", ")", ";", "message", ".", "addRecipient", "(", "Message", ".", "RecipientType", ".", "TO", ",", "new", "InternetAddress", "(", "to", ")", ")", ";", "message", ".", "setSubject", "(", "subject", ")", ";", "message", ".", "setContent", "(", "content", ",", "\"text/html\"", ")", ";", "// Send message", "Transport", ".", "send", "(", "message", ")", ";", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "logger", ".", "info", "(", "\"An email has been sent to \"", "+", "to", "+", "\" with subject \"", "+", "subject", ")", ";", "}" ]
Send email with a string content. @param to destination email address @param subject email subject @param content email content @throws MessagingException message exception
[ "Send", "email", "with", "a", "string", "content", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/email-sender/src/main/java/com/networknt/email/EmailSender.java#L61-L86
networknt/light-4j
metrics/src/main/java/io/dropwizard/metrics/MetricName.java
MetricName.resolve
public MetricName resolve(String p) { """ Build the MetricName that is this with another path appended to it. The new MetricName inherits the tags of this one. @param p The extra path element to add to the new metric. @return A new metric name relative to the original by the path specified in p. """ final String next; if (p != null && !p.isEmpty()) { if (key != null && !key.isEmpty()) { next = key + SEPARATOR + p; } else { next = p; } } else { next = this.key; } return new MetricName(next, tags); }
java
public MetricName resolve(String p) { final String next; if (p != null && !p.isEmpty()) { if (key != null && !key.isEmpty()) { next = key + SEPARATOR + p; } else { next = p; } } else { next = this.key; } return new MetricName(next, tags); }
[ "public", "MetricName", "resolve", "(", "String", "p", ")", "{", "final", "String", "next", ";", "if", "(", "p", "!=", "null", "&&", "!", "p", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "key", "!=", "null", "&&", "!", "key", ".", "isEmpty", "(", ")", ")", "{", "next", "=", "key", "+", "SEPARATOR", "+", "p", ";", "}", "else", "{", "next", "=", "p", ";", "}", "}", "else", "{", "next", "=", "this", ".", "key", ";", "}", "return", "new", "MetricName", "(", "next", ",", "tags", ")", ";", "}" ]
Build the MetricName that is this with another path appended to it. The new MetricName inherits the tags of this one. @param p The extra path element to add to the new metric. @return A new metric name relative to the original by the path specified in p.
[ "Build", "the", "MetricName", "that", "is", "this", "with", "another", "path", "appended", "to", "it", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/metrics/src/main/java/io/dropwizard/metrics/MetricName.java#L82-L96
geomajas/geomajas-project-server
plugin/layer-wms/wms/src/main/java/org/geomajas/layer/wms/mvc/WmsProxyController.java
WmsProxyController.createErrorImage
private byte[] createErrorImage(int width, int height, Exception e) throws IOException { """ Create an error image should an error occur while fetching a WMS map. @param width image width @param height image height @param e exception @return error image @throws java.io.IOException oops """ String error = e.getMessage(); if (null == error) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); error = result.toString(); } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(Color.RED); g.drawString(error, ERROR_MESSAGE_X, height / 2); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", out); out.flush(); byte[] result = out.toByteArray(); out.close(); return result; }
java
private byte[] createErrorImage(int width, int height, Exception e) throws IOException { String error = e.getMessage(); if (null == error) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); error = result.toString(); } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(Color.RED); g.drawString(error, ERROR_MESSAGE_X, height / 2); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", out); out.flush(); byte[] result = out.toByteArray(); out.close(); return result; }
[ "private", "byte", "[", "]", "createErrorImage", "(", "int", "width", ",", "int", "height", ",", "Exception", "e", ")", "throws", "IOException", "{", "String", "error", "=", "e", ".", "getMessage", "(", ")", ";", "if", "(", "null", "==", "error", ")", "{", "Writer", "result", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "printWriter", "=", "new", "PrintWriter", "(", "result", ")", ";", "e", ".", "printStackTrace", "(", "printWriter", ")", ";", "error", "=", "result", ".", "toString", "(", ")", ";", "}", "BufferedImage", "image", "=", "new", "BufferedImage", "(", "width", ",", "height", ",", "BufferedImage", ".", "TYPE_4BYTE_ABGR", ")", ";", "Graphics2D", "g", "=", "(", "Graphics2D", ")", "image", ".", "getGraphics", "(", ")", ";", "g", ".", "setColor", "(", "Color", ".", "RED", ")", ";", "g", ".", "drawString", "(", "error", ",", "ERROR_MESSAGE_X", ",", "height", "/", "2", ")", ";", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "ImageIO", ".", "write", "(", "image", ",", "\"PNG\"", ",", "out", ")", ";", "out", ".", "flush", "(", ")", ";", "byte", "[", "]", "result", "=", "out", ".", "toByteArray", "(", ")", ";", "out", ".", "close", "(", ")", ";", "return", "result", ";", "}" ]
Create an error image should an error occur while fetching a WMS map. @param width image width @param height image height @param e exception @return error image @throws java.io.IOException oops
[ "Create", "an", "error", "image", "should", "an", "error", "occur", "while", "fetching", "a", "WMS", "map", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/layer-wms/wms/src/main/java/org/geomajas/layer/wms/mvc/WmsProxyController.java#L161-L183
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.nestingKind
public static Matcher<ClassTree> nestingKind(final NestingKind kind) { """ Matches an class based on whether it is nested in another class or method. @param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL """ return new Matcher<ClassTree>() { @Override public boolean matches(ClassTree classTree, VisitorState state) { ClassSymbol sym = ASTHelpers.getSymbol(classTree); return sym.getNestingKind() == kind; } }; }
java
public static Matcher<ClassTree> nestingKind(final NestingKind kind) { return new Matcher<ClassTree>() { @Override public boolean matches(ClassTree classTree, VisitorState state) { ClassSymbol sym = ASTHelpers.getSymbol(classTree); return sym.getNestingKind() == kind; } }; }
[ "public", "static", "Matcher", "<", "ClassTree", ">", "nestingKind", "(", "final", "NestingKind", "kind", ")", "{", "return", "new", "Matcher", "<", "ClassTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "ClassTree", "classTree", ",", "VisitorState", "state", ")", "{", "ClassSymbol", "sym", "=", "ASTHelpers", ".", "getSymbol", "(", "classTree", ")", ";", "return", "sym", ".", "getNestingKind", "(", ")", "==", "kind", ";", "}", "}", ";", "}" ]
Matches an class based on whether it is nested in another class or method. @param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL
[ "Matches", "an", "class", "based", "on", "whether", "it", "is", "nested", "in", "another", "class", "or", "method", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L1114-L1122
beanshell/beanshell
src/main/java/bsh/Types.java
Types.isJavaAssignable
static boolean isJavaAssignable( Class lhsType, Class rhsType ) { """ Test if a conversion of the rhsType type to the lhsType type is legal via standard Java assignment conversion rules (i.e. without a cast). The rules include Java 5 autoboxing/unboxing. <p/> For Java primitive TYPE classes this method takes primitive promotion into account. The ordinary Class.isAssignableFrom() does not take primitive promotion conversions into account. Note that Java allows additional assignments without a cast in combination with variable declarations and array allocations. Those are handled elsewhere (maybe should be here with a flag?) <p/> This class accepts a null rhsType type indicating that the rhsType was the value Primitive.NULL and allows it to be assigned to any reference lhsType type (non primitive). <p/> Note that the getAssignableForm() method is the primary bsh method for checking assignability. It adds additional bsh conversions, etc. @see #isBshAssignable( Class, Class ) @param lhsType assigning from rhsType to lhsType @param rhsType assigning from rhsType to lhsType """ return isJavaBaseAssignable( lhsType, rhsType ) || isJavaBoxTypesAssignable( lhsType, rhsType ); }
java
static boolean isJavaAssignable( Class lhsType, Class rhsType ) { return isJavaBaseAssignable( lhsType, rhsType ) || isJavaBoxTypesAssignable( lhsType, rhsType ); }
[ "static", "boolean", "isJavaAssignable", "(", "Class", "lhsType", ",", "Class", "rhsType", ")", "{", "return", "isJavaBaseAssignable", "(", "lhsType", ",", "rhsType", ")", "||", "isJavaBoxTypesAssignable", "(", "lhsType", ",", "rhsType", ")", ";", "}" ]
Test if a conversion of the rhsType type to the lhsType type is legal via standard Java assignment conversion rules (i.e. without a cast). The rules include Java 5 autoboxing/unboxing. <p/> For Java primitive TYPE classes this method takes primitive promotion into account. The ordinary Class.isAssignableFrom() does not take primitive promotion conversions into account. Note that Java allows additional assignments without a cast in combination with variable declarations and array allocations. Those are handled elsewhere (maybe should be here with a flag?) <p/> This class accepts a null rhsType type indicating that the rhsType was the value Primitive.NULL and allows it to be assigned to any reference lhsType type (non primitive). <p/> Note that the getAssignableForm() method is the primary bsh method for checking assignability. It adds additional bsh conversions, etc. @see #isBshAssignable( Class, Class ) @param lhsType assigning from rhsType to lhsType @param rhsType assigning from rhsType to lhsType
[ "Test", "if", "a", "conversion", "of", "the", "rhsType", "type", "to", "the", "lhsType", "type", "is", "legal", "via", "standard", "Java", "assignment", "conversion", "rules", "(", "i", ".", "e", ".", "without", "a", "cast", ")", ".", "The", "rules", "include", "Java", "5", "autoboxing", "/", "unboxing", ".", "<p", "/", ">" ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Types.java#L288-L291
attribyte/wpdb
src/main/java/org/attribyte/wp/db/DB.java
DB.createTerm
public Term createTerm(final String name, final String slug) throws SQLException { """ Creates a term. @param name The term name. @param slug The term slug. @return The created term. @throws SQLException on database error. """ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Timer.Context ctx = metrics.createTermTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(insertTermSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, name); stmt.setString(2, slug); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { return new Term(rs.getLong(1), name, slug); } else { throw new SQLException("Problem creating term (no generated id)"); } } finally { ctx.stop(); closeQuietly(conn, stmt, rs); } }
java
public Term createTerm(final String name, final String slug) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; Timer.Context ctx = metrics.createTermTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(insertTermSQL, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, name); stmt.setString(2, slug); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if(rs.next()) { return new Term(rs.getLong(1), name, slug); } else { throw new SQLException("Problem creating term (no generated id)"); } } finally { ctx.stop(); closeQuietly(conn, stmt, rs); } }
[ "public", "Term", "createTerm", "(", "final", "String", "name", ",", "final", "String", "slug", ")", "throws", "SQLException", "{", "Connection", "conn", "=", "null", ";", "PreparedStatement", "stmt", "=", "null", ";", "ResultSet", "rs", "=", "null", ";", "Timer", ".", "Context", "ctx", "=", "metrics", ".", "createTermTimer", ".", "time", "(", ")", ";", "try", "{", "conn", "=", "connectionSupplier", ".", "getConnection", "(", ")", ";", "stmt", "=", "conn", ".", "prepareStatement", "(", "insertTermSQL", ",", "Statement", ".", "RETURN_GENERATED_KEYS", ")", ";", "stmt", ".", "setString", "(", "1", ",", "name", ")", ";", "stmt", ".", "setString", "(", "2", ",", "slug", ")", ";", "stmt", ".", "executeUpdate", "(", ")", ";", "rs", "=", "stmt", ".", "getGeneratedKeys", "(", ")", ";", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "return", "new", "Term", "(", "rs", ".", "getLong", "(", "1", ")", ",", "name", ",", "slug", ")", ";", "}", "else", "{", "throw", "new", "SQLException", "(", "\"Problem creating term (no generated id)\"", ")", ";", "}", "}", "finally", "{", "ctx", ".", "stop", "(", ")", ";", "closeQuietly", "(", "conn", ",", "stmt", ",", "rs", ")", ";", "}", "}" ]
Creates a term. @param name The term name. @param slug The term slug. @return The created term. @throws SQLException on database error.
[ "Creates", "a", "term", "." ]
train
https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L2147-L2169
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java
JsonRpcBasicServer.writeAndFlushValue
private void writeAndFlushValue(OutputStream output, ObjectNode value) throws IOException { """ Writes and flushes a value to the given {@link OutputStream} and prevents Jackson from closing it. Also writes newline. @param output the {@link OutputStream} @param value the value to write @throws IOException on error """ logger.debug("Response: {}", value); for (JsonRpcInterceptor interceptor : interceptorList) { interceptor.postHandleJson(value); } mapper.writeValue(new NoCloseOutputStream(output), value); output.write('\n'); }
java
private void writeAndFlushValue(OutputStream output, ObjectNode value) throws IOException { logger.debug("Response: {}", value); for (JsonRpcInterceptor interceptor : interceptorList) { interceptor.postHandleJson(value); } mapper.writeValue(new NoCloseOutputStream(output), value); output.write('\n'); }
[ "private", "void", "writeAndFlushValue", "(", "OutputStream", "output", ",", "ObjectNode", "value", ")", "throws", "IOException", "{", "logger", ".", "debug", "(", "\"Response: {}\"", ",", "value", ")", ";", "for", "(", "JsonRpcInterceptor", "interceptor", ":", "interceptorList", ")", "{", "interceptor", ".", "postHandleJson", "(", "value", ")", ";", "}", "mapper", ".", "writeValue", "(", "new", "NoCloseOutputStream", "(", "output", ")", ",", "value", ")", ";", "output", ".", "write", "(", "'", "'", ")", ";", "}" ]
Writes and flushes a value to the given {@link OutputStream} and prevents Jackson from closing it. Also writes newline. @param output the {@link OutputStream} @param value the value to write @throws IOException on error
[ "Writes", "and", "flushes", "a", "value", "to", "the", "given", "{", "@link", "OutputStream", "}", "and", "prevents", "Jackson", "from", "closing", "it", ".", "Also", "writes", "newline", "." ]
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L866-L874
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/MD5Digest.java
MD5Digest.fromString
public static MD5Digest fromString(String md5String) { """ Static method to get an MD5Digest from a human-readable string representation @param md5String @return a filled out MD5Digest """ byte[] bytes; try { bytes = Hex.decodeHex(md5String.toCharArray()); return new MD5Digest(md5String, bytes); } catch (DecoderException e) { throw new IllegalArgumentException("Unable to convert md5string", e); } }
java
public static MD5Digest fromString(String md5String) { byte[] bytes; try { bytes = Hex.decodeHex(md5String.toCharArray()); return new MD5Digest(md5String, bytes); } catch (DecoderException e) { throw new IllegalArgumentException("Unable to convert md5string", e); } }
[ "public", "static", "MD5Digest", "fromString", "(", "String", "md5String", ")", "{", "byte", "[", "]", "bytes", ";", "try", "{", "bytes", "=", "Hex", ".", "decodeHex", "(", "md5String", ".", "toCharArray", "(", ")", ")", ";", "return", "new", "MD5Digest", "(", "md5String", ",", "bytes", ")", ";", "}", "catch", "(", "DecoderException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unable to convert md5string\"", ",", "e", ")", ";", "}", "}" ]
Static method to get an MD5Digest from a human-readable string representation @param md5String @return a filled out MD5Digest
[ "Static", "method", "to", "get", "an", "MD5Digest", "from", "a", "human", "-", "readable", "string", "representation" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/MD5Digest.java#L57-L65
scaleset/scaleset-geo
src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java
GoogleMapsTileMath.metersToLngLat
public Coordinate metersToLngLat(double mx, double my) { """ Converts XY point from Spherical Mercator (EPSG:3785) to lat/lon (EPSG:4326) @param mx the X coordinate in meters @param my the Y coordinate in meters @return The coordinate transformed to EPSG:4326 """ double lon = (mx / originShift) * 180.0; double lat = (my / originShift) * 180.0; lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0); return new Coordinate(lon, lat); }
java
public Coordinate metersToLngLat(double mx, double my) { double lon = (mx / originShift) * 180.0; double lat = (my / originShift) * 180.0; lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2.0); return new Coordinate(lon, lat); }
[ "public", "Coordinate", "metersToLngLat", "(", "double", "mx", ",", "double", "my", ")", "{", "double", "lon", "=", "(", "mx", "/", "originShift", ")", "*", "180.0", ";", "double", "lat", "=", "(", "my", "/", "originShift", ")", "*", "180.0", ";", "lat", "=", "180", "/", "Math", ".", "PI", "*", "(", "2", "*", "Math", ".", "atan", "(", "Math", ".", "exp", "(", "lat", "*", "Math", ".", "PI", "/", "180.0", ")", ")", "-", "Math", ".", "PI", "/", "2.0", ")", ";", "return", "new", "Coordinate", "(", "lon", ",", "lat", ")", ";", "}" ]
Converts XY point from Spherical Mercator (EPSG:3785) to lat/lon (EPSG:4326) @param mx the X coordinate in meters @param my the Y coordinate in meters @return The coordinate transformed to EPSG:4326
[ "Converts", "XY", "point", "from", "Spherical", "Mercator", "(", "EPSG", ":", "3785", ")", "to", "lat", "/", "lon", "(", "EPSG", ":", "4326", ")" ]
train
https://github.com/scaleset/scaleset-geo/blob/5cff2349668037dc287928a6c1a1f67c76d96b02/src/main/java/com/scaleset/geo/math/GoogleMapsTileMath.java#L148-L155
UrielCh/ovh-java-sdk
ovh-java-sdk-partners/src/main/java/net/minidev/ovh/api/ApiOvhPartners.java
ApiOvhPartners.register_company_companyId_application_POST
public OvhApplication register_company_companyId_application_POST(String companyId, Boolean termsAndConditionsOfServiceAccepted) throws IOException { """ Submit application information for validation REST: POST /partners/register/company/{companyId}/application @param companyId [required] Company's id @param termsAndConditionsOfServiceAccepted [required] I have read the terms and conditions of the OVH partner program and accept them """ String qPath = "/partners/register/company/{companyId}/application"; StringBuilder sb = path(qPath, companyId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "termsAndConditionsOfServiceAccepted", termsAndConditionsOfServiceAccepted); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhApplication.class); }
java
public OvhApplication register_company_companyId_application_POST(String companyId, Boolean termsAndConditionsOfServiceAccepted) throws IOException { String qPath = "/partners/register/company/{companyId}/application"; StringBuilder sb = path(qPath, companyId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "termsAndConditionsOfServiceAccepted", termsAndConditionsOfServiceAccepted); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhApplication.class); }
[ "public", "OvhApplication", "register_company_companyId_application_POST", "(", "String", "companyId", ",", "Boolean", "termsAndConditionsOfServiceAccepted", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/partners/register/company/{companyId}/application\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "companyId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"termsAndConditionsOfServiceAccepted\"", ",", "termsAndConditionsOfServiceAccepted", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhApplication", ".", "class", ")", ";", "}" ]
Submit application information for validation REST: POST /partners/register/company/{companyId}/application @param companyId [required] Company's id @param termsAndConditionsOfServiceAccepted [required] I have read the terms and conditions of the OVH partner program and accept them
[ "Submit", "application", "information", "for", "validation" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-partners/src/main/java/net/minidev/ovh/api/ApiOvhPartners.java#L338-L345
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessControlList.java
AccessControlList.addPermissions
public void addPermissions(String rawData) throws RepositoryException { """ Adds permissions @param rawData A semicolon separated string representing the list of permission entries to add, knowing that the syntax of a permission entry is ${identity} [read|add_node|set_property|remove] """ StringTokenizer listTokenizer = new StringTokenizer(rawData, AccessControlList.DELIMITER); if (listTokenizer.countTokens() < 1) throw new RepositoryException("AccessControlList " + rawData + " is empty or have a bad format"); while (listTokenizer.hasMoreTokens()) { String entry = listTokenizer.nextToken(); try { accessList.add(AccessControlEntry.parse(entry)); } catch (IllegalArgumentException e) { throw new RepositoryException("AccessControlEntry " + entry + " is empty or have a bad format", e); } } }
java
public void addPermissions(String rawData) throws RepositoryException { StringTokenizer listTokenizer = new StringTokenizer(rawData, AccessControlList.DELIMITER); if (listTokenizer.countTokens() < 1) throw new RepositoryException("AccessControlList " + rawData + " is empty or have a bad format"); while (listTokenizer.hasMoreTokens()) { String entry = listTokenizer.nextToken(); try { accessList.add(AccessControlEntry.parse(entry)); } catch (IllegalArgumentException e) { throw new RepositoryException("AccessControlEntry " + entry + " is empty or have a bad format", e); } } }
[ "public", "void", "addPermissions", "(", "String", "rawData", ")", "throws", "RepositoryException", "{", "StringTokenizer", "listTokenizer", "=", "new", "StringTokenizer", "(", "rawData", ",", "AccessControlList", ".", "DELIMITER", ")", ";", "if", "(", "listTokenizer", ".", "countTokens", "(", ")", "<", "1", ")", "throw", "new", "RepositoryException", "(", "\"AccessControlList \"", "+", "rawData", "+", "\" is empty or have a bad format\"", ")", ";", "while", "(", "listTokenizer", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "entry", "=", "listTokenizer", ".", "nextToken", "(", ")", ";", "try", "{", "accessList", ".", "add", "(", "AccessControlEntry", ".", "parse", "(", "entry", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RepositoryException", "(", "\"AccessControlEntry \"", "+", "entry", "+", "\" is empty or have a bad format\"", ",", "e", ")", ";", "}", "}", "}" ]
Adds permissions @param rawData A semicolon separated string representing the list of permission entries to add, knowing that the syntax of a permission entry is ${identity} [read|add_node|set_property|remove]
[ "Adds", "permissions" ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/access/AccessControlList.java#L107-L125
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java
ServiceDiscoveryManager.findServicesDiscoverInfo
public List<DiscoverInfo> findServicesDiscoverInfo(String feature, boolean stopOnFirst, boolean useCache) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { """ Find all services under the users service that provide a given feature. @param feature the feature to search for @param stopOnFirst if true, stop searching after the first service was found @param useCache if true, query a cache first to avoid network I/O @return a possible empty list of services providing the given feature @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException """ return findServicesDiscoverInfo(feature, stopOnFirst, useCache, null); }
java
public List<DiscoverInfo> findServicesDiscoverInfo(String feature, boolean stopOnFirst, boolean useCache) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return findServicesDiscoverInfo(feature, stopOnFirst, useCache, null); }
[ "public", "List", "<", "DiscoverInfo", ">", "findServicesDiscoverInfo", "(", "String", "feature", ",", "boolean", "stopOnFirst", ",", "boolean", "useCache", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "findServicesDiscoverInfo", "(", "feature", ",", "stopOnFirst", ",", "useCache", ",", "null", ")", ";", "}" ]
Find all services under the users service that provide a given feature. @param feature the feature to search for @param stopOnFirst if true, stop searching after the first service was found @param useCache if true, query a cache first to avoid network I/O @return a possible empty list of services providing the given feature @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException
[ "Find", "all", "services", "under", "the", "users", "service", "that", "provide", "a", "given", "feature", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java#L684-L687
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/transform/fft/GDiscreteFourierTransformOps.java
GDiscreteFourierTransformOps.shiftZeroFrequency
public static void shiftZeroFrequency(ImageInterleaved transform, boolean forward ) { """ Moves the zero-frequency component into the image center (width/2,height/2). This function can be called to undo the transform. @param transform the DFT which is to be shifted. @param forward If true then it does the shift in the forward direction. If false then it undoes the transforms. """ if( transform instanceof InterleavedF32 ) { DiscreteFourierTransformOps.shiftZeroFrequency((InterleavedF32) transform, forward); } else if( transform instanceof InterleavedF64 ) { DiscreteFourierTransformOps.shiftZeroFrequency((InterleavedF64)transform,forward); } else { throw new IllegalArgumentException("Unknown image type"); } }
java
public static void shiftZeroFrequency(ImageInterleaved transform, boolean forward ) { if( transform instanceof InterleavedF32 ) { DiscreteFourierTransformOps.shiftZeroFrequency((InterleavedF32) transform, forward); } else if( transform instanceof InterleavedF64 ) { DiscreteFourierTransformOps.shiftZeroFrequency((InterleavedF64)transform,forward); } else { throw new IllegalArgumentException("Unknown image type"); } }
[ "public", "static", "void", "shiftZeroFrequency", "(", "ImageInterleaved", "transform", ",", "boolean", "forward", ")", "{", "if", "(", "transform", "instanceof", "InterleavedF32", ")", "{", "DiscreteFourierTransformOps", ".", "shiftZeroFrequency", "(", "(", "InterleavedF32", ")", "transform", ",", "forward", ")", ";", "}", "else", "if", "(", "transform", "instanceof", "InterleavedF64", ")", "{", "DiscreteFourierTransformOps", ".", "shiftZeroFrequency", "(", "(", "InterleavedF64", ")", "transform", ",", "forward", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unknown image type\"", ")", ";", "}", "}" ]
Moves the zero-frequency component into the image center (width/2,height/2). This function can be called to undo the transform. @param transform the DFT which is to be shifted. @param forward If true then it does the shift in the forward direction. If false then it undoes the transforms.
[ "Moves", "the", "zero", "-", "frequency", "component", "into", "the", "image", "center", "(", "width", "/", "2", "height", "/", "2", ")", ".", "This", "function", "can", "be", "called", "to", "undo", "the", "transform", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/fft/GDiscreteFourierTransformOps.java#L57-L65