repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
jenkinsci/jenkins
core/src/main/java/jenkins/util/SystemProperties.java
SystemProperties.getString
public static String getString(String key, @CheckForNull String def, Level logLevel) { String value = System.getProperty(key); // keep passing on any exceptions if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (system): {0} => {1}", new Object[] {key, value}); } return value; } value = handler.getString(key); if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (context): {0} => {1}", new Object[]{key, value}); } return value; } value = def; if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (default): {0} => {1}", new Object[] {key, value}); } return value; }
java
public static String getString(String key, @CheckForNull String def, Level logLevel) { String value = System.getProperty(key); // keep passing on any exceptions if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (system): {0} => {1}", new Object[] {key, value}); } return value; } value = handler.getString(key); if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (context): {0} => {1}", new Object[]{key, value}); } return value; } value = def; if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (default): {0} => {1}", new Object[] {key, value}); } return value; }
[ "public", "static", "String", "getString", "(", "String", "key", ",", "@", "CheckForNull", "String", "def", ",", "Level", "logLevel", ")", "{", "String", "value", "=", "System", ".", "getProperty", "(", "key", ")", ";", "// keep passing on any exceptions", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (system): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}", "value", "=", "handler", ".", "getString", "(", "key", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (context): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}", "value", "=", "def", ";", "if", "(", "LOGGER", ".", "isLoggable", "(", "logLevel", ")", ")", "{", "LOGGER", ".", "log", "(", "logLevel", ",", "\"Property (default): {0} => {1}\"", ",", "new", "Object", "[", "]", "{", "key", ",", "value", "}", ")", ";", "}", "return", "value", ";", "}" ]
Gets the system property indicated by the specified key, or a default value. This behaves just like {@link System#getProperty(java.lang.String, java.lang.String)}, except that it also consults the {@link ServletContext}'s "init" parameters. @param key the name of the system property. @param def a default value. @param logLevel the level of the log if the provided key is not found. @return the string value of the system property, or {@code null} if the property is missing and the default value is {@code null}. @exception NullPointerException if {@code key} is {@code null}. @exception IllegalArgumentException if {@code key} is empty.
[ "Gets", "the", "system", "property", "indicated", "by", "the", "specified", "key", "or", "a", "default", "value", ".", "This", "behaves", "just", "like", "{", "@link", "System#getProperty", "(", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", ")", "}", "except", "that", "it", "also", "consults", "the", "{", "@link", "ServletContext", "}", "s", "init", "parameters", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/SystemProperties.java#L238-L260
j256/ormlite-core
src/main/java/com/j256/ormlite/table/TableUtils.java
TableUtils.createTable
public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig); return doCreateTable(dao, false); }
java
public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig); return doCreateTable(dao, false); }
[ "public", "static", "<", "T", ">", "int", "createTable", "(", "ConnectionSource", "connectionSource", ",", "DatabaseTableConfig", "<", "T", ">", "tableConfig", ")", "throws", "SQLException", "{", "Dao", "<", "T", ",", "?", ">", "dao", "=", "DaoManager", ".", "createDao", "(", "connectionSource", ",", "tableConfig", ")", ";", "return", "doCreateTable", "(", "dao", ",", "false", ")", ";", "}" ]
Issue the database statements to create the table associated with a table configuration. @param connectionSource connectionSource Associated connection source. @param tableConfig Hand or spring wired table configuration. If null then the class must have {@link DatabaseField} annotations. @return The number of statements executed to do so.
[ "Issue", "the", "database", "statements", "to", "create", "the", "table", "associated", "with", "a", "table", "configuration", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/table/TableUtils.java#L88-L92
looly/hutool
hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
MapUtil.getFloat
public static Float getFloat(Map<?, ?> map, Object key) { return get(map, key, Float.class); }
java
public static Float getFloat(Map<?, ?> map, Object key) { return get(map, key, Float.class); }
[ "public", "static", "Float", "getFloat", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "Object", "key", ")", "{", "return", "get", "(", "map", ",", "key", ",", "Float", ".", "class", ")", ";", "}" ]
获取Map指定key的值,并转换为Float @param map Map @param key 键 @return 值 @since 4.0.6
[ "获取Map指定key的值,并转换为Float" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L792-L794
EdwardRaff/JSAT
JSAT/src/jsat/distributions/kernels/PukKernel.java
PukKernel.setOmega
public void setOmega(double omega) { if(omega <= 0 || Double.isNaN(omega) || Double.isInfinite(omega)) throw new ArithmeticException("omega must be positive, not " + omega); this.omega = omega; this.cnst = Math.sqrt(Math.pow(2, 1/omega)-1); }
java
public void setOmega(double omega) { if(omega <= 0 || Double.isNaN(omega) || Double.isInfinite(omega)) throw new ArithmeticException("omega must be positive, not " + omega); this.omega = omega; this.cnst = Math.sqrt(Math.pow(2, 1/omega)-1); }
[ "public", "void", "setOmega", "(", "double", "omega", ")", "{", "if", "(", "omega", "<=", "0", "||", "Double", ".", "isNaN", "(", "omega", ")", "||", "Double", ".", "isInfinite", "(", "omega", ")", ")", "throw", "new", "ArithmeticException", "(", "\"omega must be positive, not \"", "+", "omega", ")", ";", "this", ".", "omega", "=", "omega", ";", "this", ".", "cnst", "=", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "2", ",", "1", "/", "omega", ")", "-", "1", ")", ";", "}" ]
Sets the omega parameter value, which controls the shape of the kernel @param omega the positive parameter value
[ "Sets", "the", "omega", "parameter", "value", "which", "controls", "the", "shape", "of", "the", "kernel" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/PukKernel.java#L47-L53
ops4j/org.ops4j.base
ops4j-base-monitors/src/main/java/org/ops4j/monitors/stream/StreamMonitorRouter.java
StreamMonitorRouter.notifyError
public void notifyError( URL resource, String message ) { synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); } } }
java
public void notifyError( URL resource, String message ) { synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); } } }
[ "public", "void", "notifyError", "(", "URL", "resource", ",", "String", "message", ")", "{", "synchronized", "(", "m_Monitors", ")", "{", "for", "(", "StreamMonitor", "monitor", ":", "m_Monitors", ")", "{", "monitor", ".", "notifyError", "(", "resource", ",", "message", ")", ";", "}", "}", "}" ]
Notify the monitor of the an error during the download process. @param resource the name of the remote resource. @param message a non-localized message describing the problem in english.
[ "Notify", "the", "monitor", "of", "the", "an", "error", "during", "the", "download", "process", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-monitors/src/main/java/org/ops4j/monitors/stream/StreamMonitorRouter.java#L88-L97
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java
CharacterUtils.toChars
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
java
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
[ "public", "final", "int", "toChars", "(", "int", "[", "]", "src", ",", "int", "srcOff", ",", "int", "srcLen", ",", "char", "[", "]", "dest", ",", "int", "destOff", ")", "{", "if", "(", "srcLen", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"srcLen must be >= 0\"", ")", ";", "}", "int", "written", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "srcLen", ";", "++", "i", ")", "{", "written", "+=", "Character", ".", "toChars", "(", "src", "[", "srcOff", "+", "i", "]", ",", "dest", ",", "destOff", "+", "written", ")", ";", "}", "return", "written", ";", "}" ]
Converts a sequence of unicode code points to a sequence of Java characters. @return the number of chars written to the destination buffer
[ "Converts", "a", "sequence", "of", "unicode", "code", "points", "to", "a", "sequence", "of", "Java", "characters", "." ]
train
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java#L153-L162
Alluxio/alluxio
core/server/common/src/main/java/alluxio/util/TarUtils.java
TarUtils.readTarGz
public static void readTarGz(Path dirPath, InputStream input) throws IOException { InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
java
public static void readTarGz(Path dirPath, InputStream input) throws IOException { InputStream zipStream = new GzipCompressorInputStream(input); TarArchiveInputStream archiveStream = new TarArchiveInputStream(zipStream); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { File outputFile = new File(dirPath.toFile(), entry.getName()); if (entry.isDirectory()) { outputFile.mkdirs(); } else { outputFile.getParentFile().mkdirs(); try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { IOUtils.copy(archiveStream, fileOut); } } } }
[ "public", "static", "void", "readTarGz", "(", "Path", "dirPath", ",", "InputStream", "input", ")", "throws", "IOException", "{", "InputStream", "zipStream", "=", "new", "GzipCompressorInputStream", "(", "input", ")", ";", "TarArchiveInputStream", "archiveStream", "=", "new", "TarArchiveInputStream", "(", "zipStream", ")", ";", "TarArchiveEntry", "entry", ";", "while", "(", "(", "entry", "=", "(", "TarArchiveEntry", ")", "archiveStream", ".", "getNextEntry", "(", ")", ")", "!=", "null", ")", "{", "File", "outputFile", "=", "new", "File", "(", "dirPath", ".", "toFile", "(", ")", ",", "entry", ".", "getName", "(", ")", ")", ";", "if", "(", "entry", ".", "isDirectory", "(", ")", ")", "{", "outputFile", ".", "mkdirs", "(", ")", ";", "}", "else", "{", "outputFile", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "try", "(", "FileOutputStream", "fileOut", "=", "new", "FileOutputStream", "(", "outputFile", ")", ")", "{", "IOUtils", ".", "copy", "(", "archiveStream", ",", "fileOut", ")", ";", "}", "}", "}", "}" ]
Reads a gzipped tar archive from a stream and writes it to the given path. @param dirPath the path to write the archive to @param input the input stream
[ "Reads", "a", "gzipped", "tar", "archive", "from", "a", "stream", "and", "writes", "it", "to", "the", "given", "path", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/util/TarUtils.java#L70-L85
mockito/mockito
src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java
PluginInitializer.loadImpl
public <T> T loadImpl(Class<T> service) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Enumeration<URL> resources; try { resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new IllegalStateException("Failed to load " + service, e); } try { String classOrAlias = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources)); if (classOrAlias != null) { if (classOrAlias.equals(alias)) { classOrAlias = plugins.getDefaultPluginClass(alias); } Class<?> pluginClass = loader.loadClass(classOrAlias); Object plugin = pluginClass.newInstance(); return service.cast(plugin); } return null; } catch (Exception e) { throw new IllegalStateException( "Failed to load " + service + " implementation declared in " + resources, e); } }
java
public <T> T loadImpl(Class<T> service) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Enumeration<URL> resources; try { resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new IllegalStateException("Failed to load " + service, e); } try { String classOrAlias = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources)); if (classOrAlias != null) { if (classOrAlias.equals(alias)) { classOrAlias = plugins.getDefaultPluginClass(alias); } Class<?> pluginClass = loader.loadClass(classOrAlias); Object plugin = pluginClass.newInstance(); return service.cast(plugin); } return null; } catch (Exception e) { throw new IllegalStateException( "Failed to load " + service + " implementation declared in " + resources, e); } }
[ "public", "<", "T", ">", "T", "loadImpl", "(", "Class", "<", "T", ">", "service", ")", "{", "ClassLoader", "loader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "if", "(", "loader", "==", "null", ")", "{", "loader", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "}", "Enumeration", "<", "URL", ">", "resources", ";", "try", "{", "resources", "=", "loader", ".", "getResources", "(", "\"mockito-extensions/\"", "+", "service", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to load \"", "+", "service", ",", "e", ")", ";", "}", "try", "{", "String", "classOrAlias", "=", "new", "PluginFinder", "(", "pluginSwitch", ")", ".", "findPluginClass", "(", "Iterables", ".", "toIterable", "(", "resources", ")", ")", ";", "if", "(", "classOrAlias", "!=", "null", ")", "{", "if", "(", "classOrAlias", ".", "equals", "(", "alias", ")", ")", "{", "classOrAlias", "=", "plugins", ".", "getDefaultPluginClass", "(", "alias", ")", ";", "}", "Class", "<", "?", ">", "pluginClass", "=", "loader", ".", "loadClass", "(", "classOrAlias", ")", ";", "Object", "plugin", "=", "pluginClass", ".", "newInstance", "(", ")", ";", "return", "service", ".", "cast", "(", "plugin", ")", ";", "}", "return", "null", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to load \"", "+", "service", "+", "\" implementation declared in \"", "+", "resources", ",", "e", ")", ";", "}", "}" ]
Equivalent to {@link java.util.ServiceLoader#load} but without requiring Java 6 / Android 2.3 (Gingerbread).
[ "Equivalent", "to", "{" ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java#L30-L57
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java
FindByIndexOptions.useIndex
public FindByIndexOptions useIndex(String designDocument, String indexName) { assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
java
public FindByIndexOptions useIndex(String designDocument, String indexName) { assertNotNull(designDocument, "designDocument"); assertNotNull(indexName, "indexName"); JsonArray index = new JsonArray(); index.add(new JsonPrimitive(designDocument)); index.add(new JsonPrimitive(indexName)); this.useIndex = index; return this; }
[ "public", "FindByIndexOptions", "useIndex", "(", "String", "designDocument", ",", "String", "indexName", ")", "{", "assertNotNull", "(", "designDocument", ",", "\"designDocument\"", ")", ";", "assertNotNull", "(", "indexName", ",", "\"indexName\"", ")", ";", "JsonArray", "index", "=", "new", "JsonArray", "(", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "designDocument", ")", ")", ";", "index", ".", "add", "(", "new", "JsonPrimitive", "(", "indexName", ")", ")", ";", "this", ".", "useIndex", "=", "index", ";", "return", "this", ";", "}" ]
Specify a specific index to run the query against @param designDocument set the design document to use @param indexName set the index name to use @return this to set additional options
[ "Specify", "a", "specific", "index", "to", "run", "the", "query", "against" ]
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/model/FindByIndexOptions.java#L128-L136
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java
DeferredAttr.attribSpeculativeLambda
JCLambda attribSpeculativeLambda(JCLambda that, Env<AttrContext> env, ResultInfo resultInfo) { ListBuffer<JCStatement> stats = new ListBuffer<>(); stats.addAll(that.params); if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { stats.add(make.Return((JCExpression)that.body)); } else { stats.add((JCBlock)that.body); } JCBlock lambdaBlock = make.Block(0, stats.toList()); Env<AttrContext> localEnv = attr.lambdaEnv(that, env); try { localEnv.info.returnResult = resultInfo; JCBlock speculativeTree = (JCBlock)attribSpeculative(lambdaBlock, localEnv, resultInfo); List<JCVariableDecl> args = speculativeTree.getStatements().stream() .filter(s -> s.hasTag(Tag.VARDEF)) .map(t -> (JCVariableDecl)t) .collect(List.collector()); JCTree lambdaBody = speculativeTree.getStatements().last(); if (lambdaBody.hasTag(Tag.RETURN)) { lambdaBody = ((JCReturn)lambdaBody).expr; } JCLambda speculativeLambda = make.Lambda(args, lambdaBody); attr.preFlow(speculativeLambda); flow.analyzeLambda(env, speculativeLambda, make, false); return speculativeLambda; } finally { localEnv.info.scope.leave(); } }
java
JCLambda attribSpeculativeLambda(JCLambda that, Env<AttrContext> env, ResultInfo resultInfo) { ListBuffer<JCStatement> stats = new ListBuffer<>(); stats.addAll(that.params); if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { stats.add(make.Return((JCExpression)that.body)); } else { stats.add((JCBlock)that.body); } JCBlock lambdaBlock = make.Block(0, stats.toList()); Env<AttrContext> localEnv = attr.lambdaEnv(that, env); try { localEnv.info.returnResult = resultInfo; JCBlock speculativeTree = (JCBlock)attribSpeculative(lambdaBlock, localEnv, resultInfo); List<JCVariableDecl> args = speculativeTree.getStatements().stream() .filter(s -> s.hasTag(Tag.VARDEF)) .map(t -> (JCVariableDecl)t) .collect(List.collector()); JCTree lambdaBody = speculativeTree.getStatements().last(); if (lambdaBody.hasTag(Tag.RETURN)) { lambdaBody = ((JCReturn)lambdaBody).expr; } JCLambda speculativeLambda = make.Lambda(args, lambdaBody); attr.preFlow(speculativeLambda); flow.analyzeLambda(env, speculativeLambda, make, false); return speculativeLambda; } finally { localEnv.info.scope.leave(); } }
[ "JCLambda", "attribSpeculativeLambda", "(", "JCLambda", "that", ",", "Env", "<", "AttrContext", ">", "env", ",", "ResultInfo", "resultInfo", ")", "{", "ListBuffer", "<", "JCStatement", ">", "stats", "=", "new", "ListBuffer", "<>", "(", ")", ";", "stats", ".", "addAll", "(", "that", ".", "params", ")", ";", "if", "(", "that", ".", "getBodyKind", "(", ")", "==", "JCLambda", ".", "BodyKind", ".", "EXPRESSION", ")", "{", "stats", ".", "add", "(", "make", ".", "Return", "(", "(", "JCExpression", ")", "that", ".", "body", ")", ")", ";", "}", "else", "{", "stats", ".", "add", "(", "(", "JCBlock", ")", "that", ".", "body", ")", ";", "}", "JCBlock", "lambdaBlock", "=", "make", ".", "Block", "(", "0", ",", "stats", ".", "toList", "(", ")", ")", ";", "Env", "<", "AttrContext", ">", "localEnv", "=", "attr", ".", "lambdaEnv", "(", "that", ",", "env", ")", ";", "try", "{", "localEnv", ".", "info", ".", "returnResult", "=", "resultInfo", ";", "JCBlock", "speculativeTree", "=", "(", "JCBlock", ")", "attribSpeculative", "(", "lambdaBlock", ",", "localEnv", ",", "resultInfo", ")", ";", "List", "<", "JCVariableDecl", ">", "args", "=", "speculativeTree", ".", "getStatements", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "s", "->", "s", ".", "hasTag", "(", "Tag", ".", "VARDEF", ")", ")", ".", "map", "(", "t", "->", "(", "JCVariableDecl", ")", "t", ")", ".", "collect", "(", "List", ".", "collector", "(", ")", ")", ";", "JCTree", "lambdaBody", "=", "speculativeTree", ".", "getStatements", "(", ")", ".", "last", "(", ")", ";", "if", "(", "lambdaBody", ".", "hasTag", "(", "Tag", ".", "RETURN", ")", ")", "{", "lambdaBody", "=", "(", "(", "JCReturn", ")", "lambdaBody", ")", ".", "expr", ";", "}", "JCLambda", "speculativeLambda", "=", "make", ".", "Lambda", "(", "args", ",", "lambdaBody", ")", ";", "attr", ".", "preFlow", "(", "speculativeLambda", ")", ";", "flow", ".", "analyzeLambda", "(", "env", ",", "speculativeLambda", ",", "make", ",", "false", ")", ";", "return", "speculativeLambda", ";", "}", "finally", "{", "localEnv", ".", "info", ".", "scope", ".", "leave", "(", ")", ";", "}", "}" ]
Performs speculative attribution of a lambda body and returns the speculative lambda tree, in the absence of a target-type. Since {@link Attr#visitLambda(JCLambda)} cannot type-check lambda bodies w/o a suitable target-type, this routine 'unrolls' the lambda by turning it into a regular block, speculatively type-checks the block and then puts back the pieces.
[ "Performs", "speculative", "attribution", "of", "a", "lambda", "body", "and", "returns", "the", "speculative", "lambda", "tree", "in", "the", "absence", "of", "a", "target", "-", "type", ".", "Since", "{" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/DeferredAttr.java#L435-L463
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/source/HiveSource.java
HiveSource.shouldCreateWorkunit
protected boolean shouldCreateWorkunit(long createTime, long updateTime, LongWatermark lowWatermark) { if (new DateTime(updateTime).isBefore(this.maxLookBackTime)) { return false; } return new DateTime(updateTime).isAfter(lowWatermark.getValue()); }
java
protected boolean shouldCreateWorkunit(long createTime, long updateTime, LongWatermark lowWatermark) { if (new DateTime(updateTime).isBefore(this.maxLookBackTime)) { return false; } return new DateTime(updateTime).isAfter(lowWatermark.getValue()); }
[ "protected", "boolean", "shouldCreateWorkunit", "(", "long", "createTime", ",", "long", "updateTime", ",", "LongWatermark", "lowWatermark", ")", "{", "if", "(", "new", "DateTime", "(", "updateTime", ")", ".", "isBefore", "(", "this", ".", "maxLookBackTime", ")", ")", "{", "return", "false", ";", "}", "return", "new", "DateTime", "(", "updateTime", ")", ".", "isAfter", "(", "lowWatermark", ".", "getValue", "(", ")", ")", ";", "}" ]
Check if workunit needs to be created. Returns <code>true</code> If the <code>updateTime</code> is greater than the <code>lowWatermark</code> and <code>maxLookBackTime</code> <code>createTime</code> is not used. It exists for backward compatibility
[ "Check", "if", "workunit", "needs", "to", "be", "created", ".", "Returns", "<code", ">", "true<", "/", "code", ">", "If", "the", "<code", ">", "updateTime<", "/", "code", ">", "is", "greater", "than", "the", "<code", ">", "lowWatermark<", "/", "code", ">", "and", "<code", ">", "maxLookBackTime<", "/", "code", ">", "<code", ">", "createTime<", "/", "code", ">", "is", "not", "used", ".", "It", "exists", "for", "backward", "compatibility" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/source/HiveSource.java#L399-L404
diirt/util
src/main/java/org/epics/util/array/ListMath.java
ListMath.inverseRescale
public static ListDouble inverseRescale(final ListNumber data, final double numerator, final double offset) { return new ListDouble() { @Override public double getDouble(int index) { return numerator / data.getDouble(index) + offset; } @Override public int size() { return data.size(); } }; }
java
public static ListDouble inverseRescale(final ListNumber data, final double numerator, final double offset) { return new ListDouble() { @Override public double getDouble(int index) { return numerator / data.getDouble(index) + offset; } @Override public int size() { return data.size(); } }; }
[ "public", "static", "ListDouble", "inverseRescale", "(", "final", "ListNumber", "data", ",", "final", "double", "numerator", ",", "final", "double", "offset", ")", "{", "return", "new", "ListDouble", "(", ")", "{", "@", "Override", "public", "double", "getDouble", "(", "int", "index", ")", "{", "return", "numerator", "/", "data", ".", "getDouble", "(", "index", ")", "+", "offset", ";", "}", "@", "Override", "public", "int", "size", "(", ")", "{", "return", "data", ".", "size", "(", ")", ";", "}", "}", ";", "}" ]
Performs a linear transformation on inverse value of each number in a list. @param data The list of numbers to divide the numerator by @param numerator The numerator for each division @param offset The additive constant @return result[x] = numerator / data[x] + offset
[ "Performs", "a", "linear", "transformation", "on", "inverse", "value", "of", "each", "number", "in", "a", "list", "." ]
train
https://github.com/diirt/util/blob/24aca0a173a635aaf0b78d213a3fee8d4f91c077/src/main/java/org/epics/util/array/ListMath.java#L125-L138
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/microdom/serialize/MicroWriter.java
MicroWriter.writeToFile
@Nonnull public static ESuccess writeToFile (@Nonnull final IMicroNode aNode, @Nonnull final Path aPath) { return writeToFile (aNode, aPath, XMLWriterSettings.DEFAULT_XML_SETTINGS); }
java
@Nonnull public static ESuccess writeToFile (@Nonnull final IMicroNode aNode, @Nonnull final Path aPath) { return writeToFile (aNode, aPath, XMLWriterSettings.DEFAULT_XML_SETTINGS); }
[ "@", "Nonnull", "public", "static", "ESuccess", "writeToFile", "(", "@", "Nonnull", "final", "IMicroNode", "aNode", ",", "@", "Nonnull", "final", "Path", "aPath", ")", "{", "return", "writeToFile", "(", "aNode", ",", "aPath", ",", "XMLWriterSettings", ".", "DEFAULT_XML_SETTINGS", ")", ";", "}" ]
Write a Micro Node to a file using the default settings. @param aNode The node to be serialized. May be any kind of node (incl. documents). May not be <code>null</code>. @param aPath The file to write to. May not be <code>null</code>. @return {@link ESuccess}
[ "Write", "a", "Micro", "Node", "to", "a", "file", "using", "the", "default", "settings", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/microdom/serialize/MicroWriter.java#L115-L119
kiegroup/drools
drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/parser/JavaParser.java
JavaParser.primitiveType
public final void primitiveType() throws RecognitionException { int primitiveType_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 51) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:537:5: ( 'boolean' | 'char' | 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g: { if ( input.LA(1)==65||input.LA(1)==67||input.LA(1)==71||input.LA(1)==77||input.LA(1)==85||input.LA(1)==92||input.LA(1)==94||input.LA(1)==105 ) { 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, 51, primitiveType_StartIndex); } } }
java
public final void primitiveType() throws RecognitionException { int primitiveType_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 51) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:537:5: ( 'boolean' | 'char' | 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g: { if ( input.LA(1)==65||input.LA(1)==67||input.LA(1)==71||input.LA(1)==77||input.LA(1)==85||input.LA(1)==92||input.LA(1)==94||input.LA(1)==105 ) { 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, 51, primitiveType_StartIndex); } } }
[ "public", "final", "void", "primitiveType", "(", ")", "throws", "RecognitionException", "{", "int", "primitiveType_StartIndex", "=", "input", ".", "index", "(", ")", ";", "try", "{", "if", "(", "state", ".", "backtracking", ">", "0", "&&", "alreadyParsedRule", "(", "input", ",", "51", ")", ")", "{", "return", ";", "}", "// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:537:5: ( 'boolean' | 'char' | 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' )", "// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:", "{", "if", "(", "input", ".", "LA", "(", "1", ")", "==", "65", "||", "input", ".", "LA", "(", "1", ")", "==", "67", "||", "input", ".", "LA", "(", "1", ")", "==", "71", "||", "input", ".", "LA", "(", "1", ")", "==", "77", "||", "input", ".", "LA", "(", "1", ")", "==", "85", "||", "input", ".", "LA", "(", "1", ")", "==", "92", "||", "input", ".", "LA", "(", "1", ")", "==", "94", "||", "input", ".", "LA", "(", "1", ")", "==", "105", ")", "{", "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", ",", "51", ",", "primitiveType_StartIndex", ")", ";", "}", "}", "}" ]
src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:536:1: primitiveType : ( 'boolean' | 'char' | 'byte' | 'short' | 'int' | 'long' | 'float' | 'double' );
[ "src", "/", "main", "/", "resources", "/", "org", "/", "drools", "/", "compiler", "/", "semantics", "/", "java", "/", "parser", "/", "Java", ".", "g", ":", "536", ":", "1", ":", "primitiveType", ":", "(", "boolean", "|", "char", "|", "byte", "|", "short", "|", "int", "|", "long", "|", "float", "|", "double", ")", ";" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-compiler/src/main/java/org/drools/compiler/rule/builder/dialect/java/parser/JavaParser.java#L4413-L4444
synchronoss/cpo-api
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
CassandraCpoAdapter.getInstance
public static CassandraCpoAdapter getInstance(CassandraCpoMetaDescriptor metaDescriptor, DataSourceInfo<ClusterDataSource> cdsiWrite, DataSourceInfo<ClusterDataSource> cdsiRead) throws CpoException { String adapterKey = metaDescriptor + ":" + cdsiWrite.getDataSourceName() + ":" + cdsiRead.getDataSourceName(); CassandraCpoAdapter adapter = (CassandraCpoAdapter) findCpoAdapter(adapterKey); if (adapter == null) { adapter = new CassandraCpoAdapter(metaDescriptor, cdsiWrite, cdsiRead); addCpoAdapter(adapterKey, adapter); } return adapter; }
java
public static CassandraCpoAdapter getInstance(CassandraCpoMetaDescriptor metaDescriptor, DataSourceInfo<ClusterDataSource> cdsiWrite, DataSourceInfo<ClusterDataSource> cdsiRead) throws CpoException { String adapterKey = metaDescriptor + ":" + cdsiWrite.getDataSourceName() + ":" + cdsiRead.getDataSourceName(); CassandraCpoAdapter adapter = (CassandraCpoAdapter) findCpoAdapter(adapterKey); if (adapter == null) { adapter = new CassandraCpoAdapter(metaDescriptor, cdsiWrite, cdsiRead); addCpoAdapter(adapterKey, adapter); } return adapter; }
[ "public", "static", "CassandraCpoAdapter", "getInstance", "(", "CassandraCpoMetaDescriptor", "metaDescriptor", ",", "DataSourceInfo", "<", "ClusterDataSource", ">", "cdsiWrite", ",", "DataSourceInfo", "<", "ClusterDataSource", ">", "cdsiRead", ")", "throws", "CpoException", "{", "String", "adapterKey", "=", "metaDescriptor", "+", "\":\"", "+", "cdsiWrite", ".", "getDataSourceName", "(", ")", "+", "\":\"", "+", "cdsiRead", ".", "getDataSourceName", "(", ")", ";", "CassandraCpoAdapter", "adapter", "=", "(", "CassandraCpoAdapter", ")", "findCpoAdapter", "(", "adapterKey", ")", ";", "if", "(", "adapter", "==", "null", ")", "{", "adapter", "=", "new", "CassandraCpoAdapter", "(", "metaDescriptor", ",", "cdsiWrite", ",", "cdsiRead", ")", ";", "addCpoAdapter", "(", "adapterKey", ",", "adapter", ")", ";", "}", "return", "adapter", ";", "}" ]
Creates a CassandraCpoAdapter. @param metaDescriptor This datasource that identifies the cpo metadata datasource @param cdsiWrite The datasource that identifies the transaction database for write transactions. @param cdsiRead The datasource that identifies the transaction database for read-only transactions. @throws org.synchronoss.cpo.CpoException exception
[ "Creates", "a", "CassandraCpoAdapter", "." ]
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L112-L120
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.getBeanForMethodArgument
@Internal @SuppressWarnings("WeakerAccess") @UsedByGeneratedCode protected final Object getBeanForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, int methodIndex, int argIndex) { MethodInjectionPoint injectionPoint = methodInjectionPoints.get(methodIndex); Argument argument = injectionPoint.getArguments()[argIndex]; if (argument instanceof DefaultArgument) { argument = new EnvironmentAwareArgument((DefaultArgument) argument); instrumentAnnotationMetadata(context, argument); } return getBeanForMethodArgument(resolutionContext, context, injectionPoint, argument); }
java
@Internal @SuppressWarnings("WeakerAccess") @UsedByGeneratedCode protected final Object getBeanForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, int methodIndex, int argIndex) { MethodInjectionPoint injectionPoint = methodInjectionPoints.get(methodIndex); Argument argument = injectionPoint.getArguments()[argIndex]; if (argument instanceof DefaultArgument) { argument = new EnvironmentAwareArgument((DefaultArgument) argument); instrumentAnnotationMetadata(context, argument); } return getBeanForMethodArgument(resolutionContext, context, injectionPoint, argument); }
[ "@", "Internal", "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "@", "UsedByGeneratedCode", "protected", "final", "Object", "getBeanForMethodArgument", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "int", "methodIndex", ",", "int", "argIndex", ")", "{", "MethodInjectionPoint", "injectionPoint", "=", "methodInjectionPoints", ".", "get", "(", "methodIndex", ")", ";", "Argument", "argument", "=", "injectionPoint", ".", "getArguments", "(", ")", "[", "argIndex", "]", ";", "if", "(", "argument", "instanceof", "DefaultArgument", ")", "{", "argument", "=", "new", "EnvironmentAwareArgument", "(", "(", "DefaultArgument", ")", "argument", ")", ";", "instrumentAnnotationMetadata", "(", "context", ",", "argument", ")", ";", "}", "return", "getBeanForMethodArgument", "(", "resolutionContext", ",", "context", ",", "injectionPoint", ",", "argument", ")", ";", "}" ]
Obtains a bean definition for the method at the given index and the argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param methodIndex The method index @param argIndex The argument index @return The resolved bean
[ "Obtains", "a", "bean", "definition", "for", "the", "method", "at", "the", "given", "index", "and", "the", "argument", "at", "the", "given", "index", "<p", ">", "Warning", ":", "this", "method", "is", "used", "by", "internal", "generated", "code", "and", "should", "not", "be", "called", "by", "user", "code", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L839-L850
UrielCh/ovh-java-sdk
ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java
ApiOvhDbaaslogs.serviceName_output_graylog_dashboard_POST
public OvhOperation serviceName_output_graylog_dashboard_POST(String serviceName, Boolean autoSelectOption, String description, String optionId, String title) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/graylog/dashboard"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "autoSelectOption", autoSelectOption); addBody(o, "description", description); addBody(o, "optionId", optionId); addBody(o, "title", title); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
java
public OvhOperation serviceName_output_graylog_dashboard_POST(String serviceName, Boolean autoSelectOption, String description, String optionId, String title) throws IOException { String qPath = "/dbaas/logs/{serviceName}/output/graylog/dashboard"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "autoSelectOption", autoSelectOption); addBody(o, "description", description); addBody(o, "optionId", optionId); addBody(o, "title", title); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOperation.class); }
[ "public", "OvhOperation", "serviceName_output_graylog_dashboard_POST", "(", "String", "serviceName", ",", "Boolean", "autoSelectOption", ",", "String", "description", ",", "String", "optionId", ",", "String", "title", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dbaas/logs/{serviceName}/output/graylog/dashboard\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"autoSelectOption\"", ",", "autoSelectOption", ")", ";", "addBody", "(", "o", ",", "\"description\"", ",", "description", ")", ";", "addBody", "(", "o", ",", "\"optionId\"", ",", "optionId", ")", ";", "addBody", "(", "o", ",", "\"title\"", ",", "title", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOperation", ".", "class", ")", ";", "}" ]
Register a new graylog dashboard REST: POST /dbaas/logs/{serviceName}/output/graylog/dashboard @param serviceName [required] Service name @param optionId [required] Option ID @param title [required] Title @param description [required] Description @param autoSelectOption [required] If set, automatically selects a compatible option
[ "Register", "a", "new", "graylog", "dashboard" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java#L1116-L1126
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Checker.java
Checker.isButtonChecked
public <T extends CompoundButton> boolean isButtonChecked(Class<T> expectedClass, String text) { T button = waiter.waitForText(expectedClass, text, 0, Timeout.getSmallTimeout(), true); if(button != null && button.isChecked()){ return true; } return false; }
java
public <T extends CompoundButton> boolean isButtonChecked(Class<T> expectedClass, String text) { T button = waiter.waitForText(expectedClass, text, 0, Timeout.getSmallTimeout(), true); if(button != null && button.isChecked()){ return true; } return false; }
[ "public", "<", "T", "extends", "CompoundButton", ">", "boolean", "isButtonChecked", "(", "Class", "<", "T", ">", "expectedClass", ",", "String", "text", ")", "{", "T", "button", "=", "waiter", ".", "waitForText", "(", "expectedClass", ",", "text", ",", "0", ",", "Timeout", ".", "getSmallTimeout", "(", ")", ",", "true", ")", ";", "if", "(", "button", "!=", "null", "&&", "button", ".", "isChecked", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if a {@link CompoundButton} with a given text is checked. @param expectedClass the expected class, e.g. {@code CheckBox.class} or {@code RadioButton.class} @param text the text that is expected to be checked @return {@code true} if {@code CompoundButton} is checked and {@code false} if it is not checked
[ "Checks", "if", "a", "{", "@link", "CompoundButton", "}", "with", "a", "given", "text", "is", "checked", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Checker.java#L57-L65
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java
FileUtilities.getFilesListByExtention
public static File[] getFilesListByExtention( String folderPath, final String ext ) { File[] files = new File(folderPath).listFiles(new FilenameFilter(){ public boolean accept( File dir, String name ) { return name.endsWith(ext); } }); return files; }
java
public static File[] getFilesListByExtention( String folderPath, final String ext ) { File[] files = new File(folderPath).listFiles(new FilenameFilter(){ public boolean accept( File dir, String name ) { return name.endsWith(ext); } }); return files; }
[ "public", "static", "File", "[", "]", "getFilesListByExtention", "(", "String", "folderPath", ",", "final", "String", "ext", ")", "{", "File", "[", "]", "files", "=", "new", "File", "(", "folderPath", ")", ".", "listFiles", "(", "new", "FilenameFilter", "(", ")", "{", "public", "boolean", "accept", "(", "File", "dir", ",", "String", "name", ")", "{", "return", "name", ".", "endsWith", "(", "ext", ")", ";", "}", "}", ")", ";", "return", "files", ";", "}" ]
Get the list of files in a folder by its extension. @param folderPath the folder path. @param ext the extension without the dot. @return the list of files patching.
[ "Get", "the", "list", "of", "files", "in", "a", "folder", "by", "its", "extension", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java#L447-L454
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java
StreamExecutionEnvironment.generateSequence
public DataStreamSource<Long> generateSequence(long from, long to) { if (from > to) { throw new IllegalArgumentException("Start of sequence must not be greater than the end"); } return addSource(new StatefulSequenceSource(from, to), "Sequence Source"); }
java
public DataStreamSource<Long> generateSequence(long from, long to) { if (from > to) { throw new IllegalArgumentException("Start of sequence must not be greater than the end"); } return addSource(new StatefulSequenceSource(from, to), "Sequence Source"); }
[ "public", "DataStreamSource", "<", "Long", ">", "generateSequence", "(", "long", "from", ",", "long", "to", ")", "{", "if", "(", "from", ">", "to", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Start of sequence must not be greater than the end\"", ")", ";", "}", "return", "addSource", "(", "new", "StatefulSequenceSource", "(", "from", ",", "to", ")", ",", "\"Sequence Source\"", ")", ";", "}" ]
Creates a new data stream that contains a sequence of numbers. This is a parallel source, if you manually set the parallelism to {@code 1} (using {@link org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator#setParallelism(int)}) the generated sequence of elements is in order. @param from The number to start at (inclusive) @param to The number to stop at (inclusive) @return A data stream, containing all number in the [from, to] interval
[ "Creates", "a", "new", "data", "stream", "that", "contains", "a", "sequence", "of", "numbers", ".", "This", "is", "a", "parallel", "source", "if", "you", "manually", "set", "the", "parallelism", "to", "{", "@code", "1", "}", "(", "using", "{", "@link", "org", ".", "apache", ".", "flink", ".", "streaming", ".", "api", ".", "datastream", ".", "SingleOutputStreamOperator#setParallelism", "(", "int", ")", "}", ")", "the", "generated", "sequence", "of", "elements", "is", "in", "order", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java#L675-L680
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/Configuration.java
Configuration.setDouble
@PublicEvolving public void setDouble(ConfigOption<Double> key, double value) { setValueInternal(key.key(), value); }
java
@PublicEvolving public void setDouble(ConfigOption<Double> key, double value) { setValueInternal(key.key(), value); }
[ "@", "PublicEvolving", "public", "void", "setDouble", "(", "ConfigOption", "<", "Double", ">", "key", ",", "double", "value", ")", "{", "setValueInternal", "(", "key", ".", "key", "(", ")", ",", "value", ")", ";", "}" ]
Adds the given value to the configuration object. The main key of the config option will be used to map the value. @param key the option specifying the key to be added @param value the value of the key/value pair to be added
[ "Adds", "the", "given", "value", "to", "the", "configuration", "object", ".", "The", "main", "key", "of", "the", "config", "option", "will", "be", "used", "to", "map", "the", "value", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L560-L563
OpenLiberty/open-liberty
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java
Util.decodeLTPAToken
@Sensitive public static byte[] decodeLTPAToken(Codec codec, @Sensitive byte[] token_arr) throws SASException { byte[] ltpaTokenBytes = null; try { byte[] data = readGSSTokenData(LTPAMech.LTPA_OID.substring(4), token_arr); if (data != null) { // Check if it is double-encoded WAS classic token and get the encoded ltpa token bytes if (isGSSToken(LTPAMech.LTPA_OID.substring(4), data)) { data = readGSSTokenData(LTPAMech.LTPA_OID.substring(4), data); } Any any = codec.decode_value(data, org.omg.Security.OpaqueHelper.type()); ltpaTokenBytes = org.omg.Security.OpaqueHelper.extract(any); } } catch (Exception ex) { // TODO: Modify SASException to take a message? throw new SASException(2, ex); } if (ltpaTokenBytes == null || ltpaTokenBytes.length == 0) { throw new SASException(2); } return ltpaTokenBytes; }
java
@Sensitive public static byte[] decodeLTPAToken(Codec codec, @Sensitive byte[] token_arr) throws SASException { byte[] ltpaTokenBytes = null; try { byte[] data = readGSSTokenData(LTPAMech.LTPA_OID.substring(4), token_arr); if (data != null) { // Check if it is double-encoded WAS classic token and get the encoded ltpa token bytes if (isGSSToken(LTPAMech.LTPA_OID.substring(4), data)) { data = readGSSTokenData(LTPAMech.LTPA_OID.substring(4), data); } Any any = codec.decode_value(data, org.omg.Security.OpaqueHelper.type()); ltpaTokenBytes = org.omg.Security.OpaqueHelper.extract(any); } } catch (Exception ex) { // TODO: Modify SASException to take a message? throw new SASException(2, ex); } if (ltpaTokenBytes == null || ltpaTokenBytes.length == 0) { throw new SASException(2); } return ltpaTokenBytes; }
[ "@", "Sensitive", "public", "static", "byte", "[", "]", "decodeLTPAToken", "(", "Codec", "codec", ",", "@", "Sensitive", "byte", "[", "]", "token_arr", ")", "throws", "SASException", "{", "byte", "[", "]", "ltpaTokenBytes", "=", "null", ";", "try", "{", "byte", "[", "]", "data", "=", "readGSSTokenData", "(", "LTPAMech", ".", "LTPA_OID", ".", "substring", "(", "4", ")", ",", "token_arr", ")", ";", "if", "(", "data", "!=", "null", ")", "{", "// Check if it is double-encoded WAS classic token and get the encoded ltpa token bytes", "if", "(", "isGSSToken", "(", "LTPAMech", ".", "LTPA_OID", ".", "substring", "(", "4", ")", ",", "data", ")", ")", "{", "data", "=", "readGSSTokenData", "(", "LTPAMech", ".", "LTPA_OID", ".", "substring", "(", "4", ")", ",", "data", ")", ";", "}", "Any", "any", "=", "codec", ".", "decode_value", "(", "data", ",", "org", ".", "omg", ".", "Security", ".", "OpaqueHelper", ".", "type", "(", ")", ")", ";", "ltpaTokenBytes", "=", "org", ".", "omg", ".", "Security", ".", "OpaqueHelper", ".", "extract", "(", "any", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "// TODO: Modify SASException to take a message?", "throw", "new", "SASException", "(", "2", ",", "ex", ")", ";", "}", "if", "(", "ltpaTokenBytes", "==", "null", "||", "ltpaTokenBytes", ".", "length", "==", "0", ")", "{", "throw", "new", "SASException", "(", "2", ")", ";", "}", "return", "ltpaTokenBytes", ";", "}" ]
WAS classic encodes the GSSToken containing the encoded LTPA token inside another GSSToken. This code detects if there is another GSSToken inside the GSSToken, obtains the internal LTPA token bytes, and decodes them. @param codec The codec to do the encoding of the Any. @param token_arr the bytes of the GSS token to decode. @return the LTPA token bytes.
[ "WAS", "classic", "encodes", "the", "GSSToken", "containing", "the", "encoded", "LTPA", "token", "inside", "another", "GSSToken", ".", "This", "code", "detects", "if", "there", "is", "another", "GSSToken", "inside", "the", "GSSToken", "obtains", "the", "internal", "LTPA", "token", "bytes", "and", "decodes", "them", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java#L556-L579
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/source/MultipleIdsMessageAcknowledgingSourceBase.java
MultipleIdsMessageAcknowledgingSourceBase.acknowledgeIDs
@Override protected final void acknowledgeIDs(long checkpointId, Set<UId> uniqueIds) { LOG.debug("Acknowledging ids for checkpoint {}", checkpointId); Iterator<Tuple2<Long, List<SessionId>>> iterator = sessionIdsPerSnapshot.iterator(); while (iterator.hasNext()) { final Tuple2<Long, List<SessionId>> next = iterator.next(); long id = next.f0; if (id <= checkpointId) { acknowledgeSessionIDs(next.f1); // remove ids for this session iterator.remove(); } } }
java
@Override protected final void acknowledgeIDs(long checkpointId, Set<UId> uniqueIds) { LOG.debug("Acknowledging ids for checkpoint {}", checkpointId); Iterator<Tuple2<Long, List<SessionId>>> iterator = sessionIdsPerSnapshot.iterator(); while (iterator.hasNext()) { final Tuple2<Long, List<SessionId>> next = iterator.next(); long id = next.f0; if (id <= checkpointId) { acknowledgeSessionIDs(next.f1); // remove ids for this session iterator.remove(); } } }
[ "@", "Override", "protected", "final", "void", "acknowledgeIDs", "(", "long", "checkpointId", ",", "Set", "<", "UId", ">", "uniqueIds", ")", "{", "LOG", ".", "debug", "(", "\"Acknowledging ids for checkpoint {}\"", ",", "checkpointId", ")", ";", "Iterator", "<", "Tuple2", "<", "Long", ",", "List", "<", "SessionId", ">", ">", ">", "iterator", "=", "sessionIdsPerSnapshot", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "final", "Tuple2", "<", "Long", ",", "List", "<", "SessionId", ">", ">", "next", "=", "iterator", ".", "next", "(", ")", ";", "long", "id", "=", "next", ".", "f0", ";", "if", "(", "id", "<=", "checkpointId", ")", "{", "acknowledgeSessionIDs", "(", "next", ".", "f1", ")", ";", "// remove ids for this session", "iterator", ".", "remove", "(", ")", ";", "}", "}", "}" ]
Acknowledges the session ids. @param checkpointId The id of the current checkout to acknowledge ids for. @param uniqueIds The checkpointed unique ids which are ignored here. They only serve as a means of de-duplicating messages when the acknowledgment after a checkpoint fails.
[ "Acknowledges", "the", "session", "ids", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/source/MultipleIdsMessageAcknowledgingSourceBase.java#L114-L127
joniles/mpxj
src/main/java/net/sf/mpxj/planner/PlannerReader.java
PlannerReader.setWorkingDay
private void setWorkingDay(ProjectCalendar mpxjCalendar, Day mpxjDay, String plannerDay) { DayType dayType = DayType.DEFAULT; if (plannerDay != null) { switch (getInt(plannerDay)) { case 0: { dayType = DayType.WORKING; break; } case 1: { dayType = DayType.NON_WORKING; break; } } } mpxjCalendar.setWorkingDay(mpxjDay, dayType); }
java
private void setWorkingDay(ProjectCalendar mpxjCalendar, Day mpxjDay, String plannerDay) { DayType dayType = DayType.DEFAULT; if (plannerDay != null) { switch (getInt(plannerDay)) { case 0: { dayType = DayType.WORKING; break; } case 1: { dayType = DayType.NON_WORKING; break; } } } mpxjCalendar.setWorkingDay(mpxjDay, dayType); }
[ "private", "void", "setWorkingDay", "(", "ProjectCalendar", "mpxjCalendar", ",", "Day", "mpxjDay", ",", "String", "plannerDay", ")", "{", "DayType", "dayType", "=", "DayType", ".", "DEFAULT", ";", "if", "(", "plannerDay", "!=", "null", ")", "{", "switch", "(", "getInt", "(", "plannerDay", ")", ")", "{", "case", "0", ":", "{", "dayType", "=", "DayType", ".", "WORKING", ";", "break", ";", "}", "case", "1", ":", "{", "dayType", "=", "DayType", ".", "NON_WORKING", ";", "break", ";", "}", "}", "}", "mpxjCalendar", ".", "setWorkingDay", "(", "mpxjDay", ",", "dayType", ")", ";", "}" ]
Set the working/non-working status of a weekday. @param mpxjCalendar MPXJ calendar @param mpxjDay day of the week @param plannerDay planner day type
[ "Set", "the", "working", "/", "non", "-", "working", "status", "of", "a", "weekday", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/planner/PlannerReader.java#L284-L307
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java
SpecializedOps_DDRM.createReflector
public static DMatrixRMaj createReflector(DMatrixRMaj u , double gamma) { if( !MatrixFeatures_DDRM.isVector(u)) throw new IllegalArgumentException("u must be a vector"); DMatrixRMaj Q = CommonOps_DDRM.identity(u.getNumElements()); CommonOps_DDRM.multAddTransB(-gamma,u,u,Q); return Q; }
java
public static DMatrixRMaj createReflector(DMatrixRMaj u , double gamma) { if( !MatrixFeatures_DDRM.isVector(u)) throw new IllegalArgumentException("u must be a vector"); DMatrixRMaj Q = CommonOps_DDRM.identity(u.getNumElements()); CommonOps_DDRM.multAddTransB(-gamma,u,u,Q); return Q; }
[ "public", "static", "DMatrixRMaj", "createReflector", "(", "DMatrixRMaj", "u", ",", "double", "gamma", ")", "{", "if", "(", "!", "MatrixFeatures_DDRM", ".", "isVector", "(", "u", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"u must be a vector\"", ")", ";", "DMatrixRMaj", "Q", "=", "CommonOps_DDRM", ".", "identity", "(", "u", ".", "getNumElements", "(", ")", ")", ";", "CommonOps_DDRM", ".", "multAddTransB", "(", "-", "gamma", ",", "u", ",", "u", ",", "Q", ")", ";", "return", "Q", ";", "}" ]
<p> Creates a reflector from the provided vector and gamma.<br> <br> Q = I - &gamma; u u<sup>T</sup><br> </p> <p> In practice {@link VectorVectorMult_DDRM#householder(double, DMatrixD1, DMatrixD1, DMatrixD1)} multHouseholder} should be used for performance reasons since there is no need to calculate Q explicitly. </p> @param u A vector. Not modified. @param gamma To produce a reflector gamma needs to be equal to 2/||u||. @return An orthogonal reflector.
[ "<p", ">", "Creates", "a", "reflector", "from", "the", "provided", "vector", "and", "gamma", ".", "<br", ">", "<br", ">", "Q", "=", "I", "-", "&gamma", ";", "u", "u<sup", ">", "T<", "/", "sup", ">", "<br", ">", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/SpecializedOps_DDRM.java#L80-L88
classgraph/classgraph
src/main/java/io/github/classgraph/ResourceList.java
ResourceList.forEachInputStream
public void forEachInputStream(final InputStreamConsumer inputStreamConsumer, final boolean ignoreIOExceptions) { for (final Resource resource : this) { try { inputStreamConsumer.accept(resource, resource.open()); } catch (final IOException e) { if (!ignoreIOExceptions) { throw new IllegalArgumentException("Could not load resource " + resource, e); } } finally { resource.close(); } } }
java
public void forEachInputStream(final InputStreamConsumer inputStreamConsumer, final boolean ignoreIOExceptions) { for (final Resource resource : this) { try { inputStreamConsumer.accept(resource, resource.open()); } catch (final IOException e) { if (!ignoreIOExceptions) { throw new IllegalArgumentException("Could not load resource " + resource, e); } } finally { resource.close(); } } }
[ "public", "void", "forEachInputStream", "(", "final", "InputStreamConsumer", "inputStreamConsumer", ",", "final", "boolean", "ignoreIOExceptions", ")", "{", "for", "(", "final", "Resource", "resource", ":", "this", ")", "{", "try", "{", "inputStreamConsumer", ".", "accept", "(", "resource", ",", "resource", ".", "open", "(", ")", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "if", "(", "!", "ignoreIOExceptions", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Could not load resource \"", "+", "resource", ",", "e", ")", ";", "}", "}", "finally", "{", "resource", ".", "close", "(", ")", ";", "}", "}", "}" ]
Fetch an {@link InputStream} for each {@link Resource} in this {@link ResourceList}, pass the {@link InputStream} to the given {@link InputStreamConsumer}, then close the {@link InputStream} after the {@link InputStreamConsumer} returns, by calling {@link Resource#close()}. @param inputStreamConsumer The {@link InputStreamConsumer}. @param ignoreIOExceptions if true, any {@link IOException} thrown while trying to load any of the resources will be silently ignored. @throws IllegalArgumentException if ignoreExceptions is false, and an {@link IOException} is thrown while trying to open any of the resources.
[ "Fetch", "an", "{", "@link", "InputStream", "}", "for", "each", "{", "@link", "Resource", "}", "in", "this", "{", "@link", "ResourceList", "}", "pass", "the", "{", "@link", "InputStream", "}", "to", "the", "given", "{", "@link", "InputStreamConsumer", "}", "then", "close", "the", "{", "@link", "InputStream", "}", "after", "the", "{", "@link", "InputStreamConsumer", "}", "returns", "by", "calling", "{", "@link", "Resource#close", "()", "}", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ResourceList.java#L388-L401
BlueBrain/bluima
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/FileEventStream.java
FileEventStream.main
public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Usage: FileEventStream eventfile [iterations cutoff]"); System.exit(1); } int ai=0; String eventFile = args[ai++]; EventStream es = new FileEventStream(eventFile); int iterations = 100; int cutoff = 5; if (ai < args.length) { iterations = Integer.parseInt(args[ai++]); cutoff = Integer.parseInt(args[ai++]); } GISModel model = GIS.trainModel(es,iterations,cutoff); new SuffixSensitiveGISModelWriter(model, new File(eventFile+".bin.gz")).persist(); }
java
public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Usage: FileEventStream eventfile [iterations cutoff]"); System.exit(1); } int ai=0; String eventFile = args[ai++]; EventStream es = new FileEventStream(eventFile); int iterations = 100; int cutoff = 5; if (ai < args.length) { iterations = Integer.parseInt(args[ai++]); cutoff = Integer.parseInt(args[ai++]); } GISModel model = GIS.trainModel(es,iterations,cutoff); new SuffixSensitiveGISModelWriter(model, new File(eventFile+".bin.gz")).persist(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "if", "(", "args", ".", "length", "==", "0", ")", "{", "System", ".", "err", ".", "println", "(", "\"Usage: FileEventStream eventfile [iterations cutoff]\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "int", "ai", "=", "0", ";", "String", "eventFile", "=", "args", "[", "ai", "++", "]", ";", "EventStream", "es", "=", "new", "FileEventStream", "(", "eventFile", ")", ";", "int", "iterations", "=", "100", ";", "int", "cutoff", "=", "5", ";", "if", "(", "ai", "<", "args", ".", "length", ")", "{", "iterations", "=", "Integer", ".", "parseInt", "(", "args", "[", "ai", "++", "]", ")", ";", "cutoff", "=", "Integer", ".", "parseInt", "(", "args", "[", "ai", "++", "]", ")", ";", "}", "GISModel", "model", "=", "GIS", ".", "trainModel", "(", "es", ",", "iterations", ",", "cutoff", ")", ";", "new", "SuffixSensitiveGISModelWriter", "(", "model", ",", "new", "File", "(", "eventFile", "+", "\".bin.gz\"", ")", ")", ".", "persist", "(", ")", ";", "}" ]
Trains and writes a model based on the events in the specified event file. the name of the model created is based on the event file name. @param args eventfile [iterations cuttoff] @throws IOException when the eventfile can not be read or the model file can not be written.
[ "Trains", "and", "writes", "a", "model", "based", "on", "the", "events", "in", "the", "specified", "event", "file", ".", "the", "name", "of", "the", "model", "created", "is", "based", "on", "the", "event", "file", "name", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/FileEventStream.java#L101-L117
javagl/ND
nd-distance/src/main/java/de/javagl/nd/distance/tuples/d/DoubleTupleDistanceFunctions.java
DoubleTupleDistanceFunctions.byDistanceComparator
public static Comparator<DoubleTuple> byDistanceComparator( DoubleTuple reference, final ToDoubleBiFunction<? super DoubleTuple, ? super DoubleTuple> distanceFunction) { final DoubleTuple fReference = DoubleTuples.copy(reference); return new Comparator<DoubleTuple>() { @Override public int compare(DoubleTuple t0, DoubleTuple t1) { double d0 = distanceFunction.applyAsDouble(fReference, t0); double d1 = distanceFunction.applyAsDouble(fReference, t1); return Double.compare(d0, d1); } }; }
java
public static Comparator<DoubleTuple> byDistanceComparator( DoubleTuple reference, final ToDoubleBiFunction<? super DoubleTuple, ? super DoubleTuple> distanceFunction) { final DoubleTuple fReference = DoubleTuples.copy(reference); return new Comparator<DoubleTuple>() { @Override public int compare(DoubleTuple t0, DoubleTuple t1) { double d0 = distanceFunction.applyAsDouble(fReference, t0); double d1 = distanceFunction.applyAsDouble(fReference, t1); return Double.compare(d0, d1); } }; }
[ "public", "static", "Comparator", "<", "DoubleTuple", ">", "byDistanceComparator", "(", "DoubleTuple", "reference", ",", "final", "ToDoubleBiFunction", "<", "?", "super", "DoubleTuple", ",", "?", "super", "DoubleTuple", ">", "distanceFunction", ")", "{", "final", "DoubleTuple", "fReference", "=", "DoubleTuples", ".", "copy", "(", "reference", ")", ";", "return", "new", "Comparator", "<", "DoubleTuple", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "DoubleTuple", "t0", ",", "DoubleTuple", "t1", ")", "{", "double", "d0", "=", "distanceFunction", ".", "applyAsDouble", "(", "fReference", ",", "t0", ")", ";", "double", "d1", "=", "distanceFunction", ".", "applyAsDouble", "(", "fReference", ",", "t1", ")", ";", "return", "Double", ".", "compare", "(", "d0", ",", "d1", ")", ";", "}", "}", ";", "}" ]
Returns a new comparator that compares {@link DoubleTuple} instances by their distance to the given reference, according to the given distance function. A copy of the given reference point will be stored, so that changes in the given point will not affect the returned comparator. @param reference The reference point @param distanceFunction The distance function @return The comparator
[ "Returns", "a", "new", "comparator", "that", "compares", "{", "@link", "DoubleTuple", "}", "instances", "by", "their", "distance", "to", "the", "given", "reference", "according", "to", "the", "given", "distance", "function", ".", "A", "copy", "of", "the", "given", "reference", "point", "will", "be", "stored", "so", "that", "changes", "in", "the", "given", "point", "will", "not", "affect", "the", "returned", "comparator", "." ]
train
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-distance/src/main/java/de/javagl/nd/distance/tuples/d/DoubleTupleDistanceFunctions.java#L55-L71
Netflix/netflix-graph
src/main/java/com/netflix/nfgraph/NFGraph.java
NFGraph.getConnectionSet
public OrdinalSet getConnectionSet(String connectionModel, String nodeType, int ordinal, String propertyName) { int connectionModelIndex = modelHolder.getModelIndex(connectionModel); return getConnectionSet(connectionModelIndex, nodeType, ordinal, propertyName); }
java
public OrdinalSet getConnectionSet(String connectionModel, String nodeType, int ordinal, String propertyName) { int connectionModelIndex = modelHolder.getModelIndex(connectionModel); return getConnectionSet(connectionModelIndex, nodeType, ordinal, propertyName); }
[ "public", "OrdinalSet", "getConnectionSet", "(", "String", "connectionModel", ",", "String", "nodeType", ",", "int", "ordinal", ",", "String", "propertyName", ")", "{", "int", "connectionModelIndex", "=", "modelHolder", ".", "getModelIndex", "(", "connectionModel", ")", ";", "return", "getConnectionSet", "(", "connectionModelIndex", ",", "nodeType", ",", "ordinal", ",", "propertyName", ")", ";", "}" ]
Retrieve an {@link OrdinalSet} over all connected ordinals in a given connection model, given the type and ordinal of the originating node, and the property by which this node is connected. @return an {@link OrdinalSet} over all connected ordinals
[ "Retrieve", "an", "{", "@link", "OrdinalSet", "}", "over", "all", "connected", "ordinals", "in", "a", "given", "connection", "model", "given", "the", "type", "and", "ordinal", "of", "the", "originating", "node", "and", "the", "property", "by", "which", "this", "node", "is", "connected", "." ]
train
https://github.com/Netflix/netflix-graph/blob/ee129252a08a9f51dd296d6fca2f0b28b7be284e/src/main/java/com/netflix/nfgraph/NFGraph.java#L153-L156
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/UnsavedRevision.java
UnsavedRevision.setAttachment
@InterfaceAudience.Public public void setAttachment(String name, String contentType, URL contentStreamURL) { try { InputStream inputStream = contentStreamURL.openStream(); setAttachment(name, contentType, inputStream); } catch (IOException e) { Log.e(Database.TAG, "Error opening stream for url: %s", contentStreamURL); throw new RuntimeException(e); } }
java
@InterfaceAudience.Public public void setAttachment(String name, String contentType, URL contentStreamURL) { try { InputStream inputStream = contentStreamURL.openStream(); setAttachment(name, contentType, inputStream); } catch (IOException e) { Log.e(Database.TAG, "Error opening stream for url: %s", contentStreamURL); throw new RuntimeException(e); } }
[ "@", "InterfaceAudience", ".", "Public", "public", "void", "setAttachment", "(", "String", "name", ",", "String", "contentType", ",", "URL", "contentStreamURL", ")", "{", "try", "{", "InputStream", "inputStream", "=", "contentStreamURL", ".", "openStream", "(", ")", ";", "setAttachment", "(", "name", ",", "contentType", ",", "inputStream", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Log", ".", "e", "(", "Database", ".", "TAG", ",", "\"Error opening stream for url: %s\"", ",", "contentStreamURL", ")", ";", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Sets the attachment with the given name. The Attachment data will be written to the Database when the Revision is saved. @param name The name of the Attachment to set. @param contentType The content-type of the Attachment. @param contentStreamURL The URL that contains the Attachment content.
[ "Sets", "the", "attachment", "with", "the", "given", "name", ".", "The", "Attachment", "data", "will", "be", "written", "to", "the", "Database", "when", "the", "Revision", "is", "saved", "." ]
train
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/UnsavedRevision.java#L183-L192
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfChunk.java
PdfChunk.getWidthCorrected
public float getWidthCorrected(float charSpacing, float wordSpacing) { if (image != null) { return image.getScaledWidth() + charSpacing; } int numberOfSpaces = 0; int idx = -1; while ((idx = value.indexOf(' ', idx + 1)) >= 0) ++numberOfSpaces; return width() + (value.length() * charSpacing + numberOfSpaces * wordSpacing); }
java
public float getWidthCorrected(float charSpacing, float wordSpacing) { if (image != null) { return image.getScaledWidth() + charSpacing; } int numberOfSpaces = 0; int idx = -1; while ((idx = value.indexOf(' ', idx + 1)) >= 0) ++numberOfSpaces; return width() + (value.length() * charSpacing + numberOfSpaces * wordSpacing); }
[ "public", "float", "getWidthCorrected", "(", "float", "charSpacing", ",", "float", "wordSpacing", ")", "{", "if", "(", "image", "!=", "null", ")", "{", "return", "image", ".", "getScaledWidth", "(", ")", "+", "charSpacing", ";", "}", "int", "numberOfSpaces", "=", "0", ";", "int", "idx", "=", "-", "1", ";", "while", "(", "(", "idx", "=", "value", ".", "indexOf", "(", "'", "'", ",", "idx", "+", "1", ")", ")", ">=", "0", ")", "++", "numberOfSpaces", ";", "return", "width", "(", ")", "+", "(", "value", ".", "length", "(", ")", "*", "charSpacing", "+", "numberOfSpaces", "*", "wordSpacing", ")", ";", "}" ]
Gets the width of the <CODE>PdfChunk</CODE> taking into account the extra character and word spacing. @param charSpacing the extra character spacing @param wordSpacing the extra word spacing @return the calculated width
[ "Gets", "the", "width", "of", "the", "<CODE", ">", "PdfChunk<", "/", "CODE", ">", "taking", "into", "account", "the", "extra", "character", "and", "word", "spacing", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfChunk.java#L548-L558
apache/incubator-atlas
webapp/src/main/java/org/apache/atlas/web/listeners/LoginProcessor.java
LoginProcessor.getServerPrincipal
private String getServerPrincipal(String principal, String host) throws IOException { return SecurityUtil.getServerPrincipal(principal, host); }
java
private String getServerPrincipal(String principal, String host) throws IOException { return SecurityUtil.getServerPrincipal(principal, host); }
[ "private", "String", "getServerPrincipal", "(", "String", "principal", ",", "String", "host", ")", "throws", "IOException", "{", "return", "SecurityUtil", ".", "getServerPrincipal", "(", "principal", ",", "host", ")", ";", "}" ]
Return a server (service) principal. The token "_HOST" in the principal will be replaced with the local host name (e.g. dgi/_HOST will be changed to dgi/localHostName) @param principal the input principal containing an option "_HOST" token @return the service principal. @throws IOException
[ "Return", "a", "server", "(", "service", ")", "principal", ".", "The", "token", "_HOST", "in", "the", "principal", "will", "be", "replaced", "with", "the", "local", "host", "name", "(", "e", ".", "g", ".", "dgi", "/", "_HOST", "will", "be", "changed", "to", "dgi", "/", "localHostName", ")" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/webapp/src/main/java/org/apache/atlas/web/listeners/LoginProcessor.java#L119-L121
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.fromClassPath
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
java
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
[ "public", "static", "Chainr", "fromClassPath", "(", "String", "chainrSpecClassPath", ",", "ChainrInstantiator", "chainrInstantiator", ")", "{", "Object", "chainrSpec", "=", "JsonUtils", ".", "classpathToObject", "(", "chainrSpecClassPath", ")", ";", "return", "getChainr", "(", "chainrInstantiator", ",", "chainrSpec", ")", ";", "}" ]
Builds a Chainr instance using the spec described in the data via the class path that is passed in. @param chainrSpecClassPath The class path that points to the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance
[ "Builds", "a", "Chainr", "instance", "using", "the", "spec", "described", "in", "the", "data", "via", "the", "class", "path", "that", "is", "passed", "in", "." ]
train
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L45-L48
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
CommonOps_DDF2.multAddOuter
public static void multAddOuter( double alpha , DMatrix2x2 A , double beta , DMatrix2 u , DMatrix2 v , DMatrix2x2 C ) { C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a21 = alpha*A.a21 + beta*u.a2*v.a1; C.a22 = alpha*A.a22 + beta*u.a2*v.a2; }
java
public static void multAddOuter( double alpha , DMatrix2x2 A , double beta , DMatrix2 u , DMatrix2 v , DMatrix2x2 C ) { C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a21 = alpha*A.a21 + beta*u.a2*v.a1; C.a22 = alpha*A.a22 + beta*u.a2*v.a2; }
[ "public", "static", "void", "multAddOuter", "(", "double", "alpha", ",", "DMatrix2x2", "A", ",", "double", "beta", ",", "DMatrix2", "u", ",", "DMatrix2", "v", ",", "DMatrix2x2", "C", ")", "{", "C", ".", "a11", "=", "alpha", "*", "A", ".", "a11", "+", "beta", "*", "u", ".", "a1", "*", "v", ".", "a1", ";", "C", ".", "a12", "=", "alpha", "*", "A", ".", "a12", "+", "beta", "*", "u", ".", "a1", "*", "v", ".", "a2", ";", "C", ".", "a21", "=", "alpha", "*", "A", ".", "a21", "+", "beta", "*", "u", ".", "a2", "*", "v", ".", "a1", ";", "C", ".", "a22", "=", "alpha", "*", "A", ".", "a22", "+", "beta", "*", "u", ".", "a2", "*", "v", ".", "a2", ";", "}" ]
C = &alpha;A + &beta;u*v<sup>T</sup> @param alpha scale factor applied to A @param A matrix @param beta scale factor applies to outer product @param u vector @param v vector @param C Storage for solution. Can be same instance as A.
[ "C", "=", "&alpha", ";", "A", "+", "&beta", ";", "u", "*", "v<sup", ">", "T<", "/", "sup", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L537-L542
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataPng.java
CoverageDataPng.getPixelValue
public short getPixelValue(WritableRaster raster, int x, int y) { Object pixelData = raster.getDataElements(x, y, null); short sdata[] = (short[]) pixelData; if (sdata.length != 1) { throw new UnsupportedOperationException( "This method is not supported by this color model"); } short pixelValue = sdata[0]; return pixelValue; }
java
public short getPixelValue(WritableRaster raster, int x, int y) { Object pixelData = raster.getDataElements(x, y, null); short sdata[] = (short[]) pixelData; if (sdata.length != 1) { throw new UnsupportedOperationException( "This method is not supported by this color model"); } short pixelValue = sdata[0]; return pixelValue; }
[ "public", "short", "getPixelValue", "(", "WritableRaster", "raster", ",", "int", "x", ",", "int", "y", ")", "{", "Object", "pixelData", "=", "raster", ".", "getDataElements", "(", "x", ",", "y", ",", "null", ")", ";", "short", "sdata", "[", "]", "=", "(", "short", "[", "]", ")", "pixelData", ";", "if", "(", "sdata", ".", "length", "!=", "1", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"This method is not supported by this color model\"", ")", ";", "}", "short", "pixelValue", "=", "sdata", "[", "0", "]", ";", "return", "pixelValue", ";", "}" ]
Get the pixel value as an "unsigned short" from the raster and the coordinate @param raster image raster @param x x coordinate @param y y coordinate @return "unsigned short" pixel value
[ "Get", "the", "pixel", "value", "as", "an", "unsigned", "short", "from", "the", "raster", "and", "the", "coordinate" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/extension/coverage/CoverageDataPng.java#L154-L164
signit-wesign/java-sdk
src/main/java/cn/signit/sdk/util/FastjsonEncoder.java
FastjsonEncoder.encodeAsString
public static String encodeAsString(Object obj,NamingStyle namingStyle,boolean useUnicode){ SerializeConfig config = SerializeConfig.getGlobalInstance(); config.propertyNamingStrategy = getNamingStrategy(namingStyle); if(useUnicode){ return JSON.toJSONString(obj,config, SerializerFeature.BrowserCompatible, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.NotWriteDefaultValue ); } return JSON.toJSONString(obj,config); }
java
public static String encodeAsString(Object obj,NamingStyle namingStyle,boolean useUnicode){ SerializeConfig config = SerializeConfig.getGlobalInstance(); config.propertyNamingStrategy = getNamingStrategy(namingStyle); if(useUnicode){ return JSON.toJSONString(obj,config, SerializerFeature.BrowserCompatible, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.NotWriteDefaultValue ); } return JSON.toJSONString(obj,config); }
[ "public", "static", "String", "encodeAsString", "(", "Object", "obj", ",", "NamingStyle", "namingStyle", ",", "boolean", "useUnicode", ")", "{", "SerializeConfig", "config", "=", "SerializeConfig", ".", "getGlobalInstance", "(", ")", ";", "config", ".", "propertyNamingStrategy", "=", "getNamingStrategy", "(", "namingStyle", ")", ";", "if", "(", "useUnicode", ")", "{", "return", "JSON", ".", "toJSONString", "(", "obj", ",", "config", ",", "SerializerFeature", ".", "BrowserCompatible", ",", "SerializerFeature", ".", "WriteNullListAsEmpty", ",", "SerializerFeature", ".", "NotWriteDefaultValue", ")", ";", "}", "return", "JSON", ".", "toJSONString", "(", "obj", ",", "config", ")", ";", "}" ]
将指定java对象序列化成相应字符串 @param obj java对象 @param namingStyle 命名风格 @param useUnicode 是否使用unicode编码(当有中文字段时) @return 序列化后的json字符串 @author Zhanghongdong
[ "将指定java对象序列化成相应字符串" ]
train
https://github.com/signit-wesign/java-sdk/blob/6f3196c9d444818a953396fdaa8ffed9794d9530/src/main/java/cn/signit/sdk/util/FastjsonEncoder.java#L20-L31
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/Environment.java
Environment.doDelete
public void doDelete(String url, HttpResponse response, Map<String, Object> headers) { response.setRequest(url); httpClient.delete(url, response, headers); }
java
public void doDelete(String url, HttpResponse response, Map<String, Object> headers) { response.setRequest(url); httpClient.delete(url, response, headers); }
[ "public", "void", "doDelete", "(", "String", "url", ",", "HttpResponse", "response", ",", "Map", "<", "String", ",", "Object", ">", "headers", ")", "{", "response", ".", "setRequest", "(", "url", ")", ";", "httpClient", ".", "delete", "(", "url", ",", "response", ",", "headers", ")", ";", "}" ]
DELETEs content at URL. @param url url to send delete to. @param response response to store url and response value in. @param headers http headers to add.
[ "DELETEs", "content", "at", "URL", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/Environment.java#L427-L430
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/ApkParser.java
ApkParser.LEW
private int LEW(byte[] arr, int off) { return arr[off + 3] << 24 & 0xff000000 | arr[off + 2] << 16 & 0xff0000 | arr[off + 1] << 8 & 0xff00 | arr[off] & 0xFF; }
java
private int LEW(byte[] arr, int off) { return arr[off + 3] << 24 & 0xff000000 | arr[off + 2] << 16 & 0xff0000 | arr[off + 1] << 8 & 0xff00 | arr[off] & 0xFF; }
[ "private", "int", "LEW", "(", "byte", "[", "]", "arr", ",", "int", "off", ")", "{", "return", "arr", "[", "off", "+", "3", "]", "<<", "24", "&", "0xff000000", "|", "arr", "[", "off", "+", "2", "]", "<<", "16", "&", "0xff0000", "|", "arr", "[", "off", "+", "1", "]", "<<", "8", "&", "0xff00", "|", "arr", "[", "off", "]", "&", "0xFF", ";", "}" ]
Gets the LEW (Little-Endian Word) from a {@link Byte} array, at the position defined by the offset {@link Integer} provided. @param arr The {@link Byte} array to process. @param off An {@link int} value indicating the offset from which the return value should be taken. @return The {@link Integer} Little Endian 32 bit word taken from the input {@link Byte} array at the offset supplied as a parameter.
[ "Gets", "the", "LEW", "(", "Little", "-", "Endian", "Word", ")", "from", "a", "{", "@link", "Byte", "}", "array", "at", "the", "position", "defined", "by", "the", "offset", "{", "@link", "Integer", "}", "provided", "." ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/ApkParser.java#L280-L282
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/ProjectApi.java
ProjectApi.deleteHook
public void deleteHook(Object projectIdOrPath, Integer hookId) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "hooks", hookId); }
java
public void deleteHook(Object projectIdOrPath, Integer hookId) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "hooks", hookId); }
[ "public", "void", "deleteHook", "(", "Object", "projectIdOrPath", ",", "Integer", "hookId", ")", "throws", "GitLabApiException", "{", "Response", ".", "Status", "expectedStatus", "=", "(", "isApiVersion", "(", "ApiVersion", ".", "V3", ")", "?", "Response", ".", "Status", ".", "OK", ":", "Response", ".", "Status", ".", "NO_CONTENT", ")", ";", "delete", "(", "expectedStatus", ",", "null", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"hooks\"", ",", "hookId", ")", ";", "}" ]
Deletes a hook from the project. <pre><code>DELETE /projects/:id/hooks/:hook_id</code></pre> @param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required @param hookId the project hook ID to delete @throws GitLabApiException if any exception occurs
[ "Deletes", "a", "hook", "from", "the", "project", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProjectApi.java#L1738-L1741
UrielCh/ovh-java-sdk
ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java
ApiOvhPrice.hosting_web_extraSqlPerso_extraSqlPersoName_GET
public OvhPrice hosting_web_extraSqlPerso_extraSqlPersoName_GET(net.minidev.ovh.api.price.hosting.web.OvhExtraSqlPersoEnum extraSqlPersoName) throws IOException { String qPath = "/price/hosting/web/extraSqlPerso/{extraSqlPersoName}"; StringBuilder sb = path(qPath, extraSqlPersoName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
java
public OvhPrice hosting_web_extraSqlPerso_extraSqlPersoName_GET(net.minidev.ovh.api.price.hosting.web.OvhExtraSqlPersoEnum extraSqlPersoName) throws IOException { String qPath = "/price/hosting/web/extraSqlPerso/{extraSqlPersoName}"; StringBuilder sb = path(qPath, extraSqlPersoName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
[ "public", "OvhPrice", "hosting_web_extraSqlPerso_extraSqlPersoName_GET", "(", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "price", ".", "hosting", ".", "web", ".", "OvhExtraSqlPersoEnum", "extraSqlPersoName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/price/hosting/web/extraSqlPerso/{extraSqlPersoName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "extraSqlPersoName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhPrice", ".", "class", ")", ";", "}" ]
Get the price for extra sql perso option REST: GET /price/hosting/web/extraSqlPerso/{extraSqlPersoName} @param extraSqlPersoName [required] ExtraSqlPerso
[ "Get", "the", "price", "for", "extra", "sql", "perso", "option" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L258-L263
PinaeOS/nala
src/main/java/org/pinae/nala/xb/Xml.java
Xml.toObject
public static Object toObject(String xml, String encoding, Class<?> cls) throws UnmarshalException { if (xml == null || xml.trim().equals("")) { throw new UnmarshalException("XML String is Empty"); } Object object = null; Unmarshaller bind = null; try { bind = new XmlUnmarshaller(new ByteArrayInputStream(xml.getBytes(encoding))); } catch (UnsupportedEncodingException e) { throw new UnmarshalException(e); } if (bind != null) { bind.setRootClass(cls); object = bind.unmarshal(); } return object; }
java
public static Object toObject(String xml, String encoding, Class<?> cls) throws UnmarshalException { if (xml == null || xml.trim().equals("")) { throw new UnmarshalException("XML String is Empty"); } Object object = null; Unmarshaller bind = null; try { bind = new XmlUnmarshaller(new ByteArrayInputStream(xml.getBytes(encoding))); } catch (UnsupportedEncodingException e) { throw new UnmarshalException(e); } if (bind != null) { bind.setRootClass(cls); object = bind.unmarshal(); } return object; }
[ "public", "static", "Object", "toObject", "(", "String", "xml", ",", "String", "encoding", ",", "Class", "<", "?", ">", "cls", ")", "throws", "UnmarshalException", "{", "if", "(", "xml", "==", "null", "||", "xml", ".", "trim", "(", ")", ".", "equals", "(", "\"\"", ")", ")", "{", "throw", "new", "UnmarshalException", "(", "\"XML String is Empty\"", ")", ";", "}", "Object", "object", "=", "null", ";", "Unmarshaller", "bind", "=", "null", ";", "try", "{", "bind", "=", "new", "XmlUnmarshaller", "(", "new", "ByteArrayInputStream", "(", "xml", ".", "getBytes", "(", "encoding", ")", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "UnmarshalException", "(", "e", ")", ";", "}", "if", "(", "bind", "!=", "null", ")", "{", "bind", ".", "setRootClass", "(", "cls", ")", ";", "object", "=", "bind", ".", "unmarshal", "(", ")", ";", "}", "return", "object", ";", "}" ]
将XML文件绑定为对象 @param xml XML字符串 @param encoding XML文件编码, 例如UTF-8, GBK @param cls 绑定目标类 @return 绑定后的对象 @throws UnmarshalException 解组异常
[ "将XML文件绑定为对象" ]
train
https://github.com/PinaeOS/nala/blob/2047ade4af197cec938278d300d111ea94af6fbf/src/main/java/org/pinae/nala/xb/Xml.java#L53-L75
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ModifyingCollectionWithItself.java
ModifyingCollectionWithItself.matchMethodInvocation
@Override public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) { if (IS_COLLECTION_MODIFIED_WITH_ITSELF.matches(t, state)) { return describe(t, state); } return Description.NO_MATCH; }
java
@Override public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) { if (IS_COLLECTION_MODIFIED_WITH_ITSELF.matches(t, state)) { return describe(t, state); } return Description.NO_MATCH; }
[ "@", "Override", "public", "Description", "matchMethodInvocation", "(", "MethodInvocationTree", "t", ",", "VisitorState", "state", ")", "{", "if", "(", "IS_COLLECTION_MODIFIED_WITH_ITSELF", ".", "matches", "(", "t", ",", "state", ")", ")", "{", "return", "describe", "(", "t", ",", "state", ")", ";", "}", "return", "Description", ".", "NO_MATCH", ";", "}" ]
Matches calls to addAll, containsAll, removeAll, and retainAll on itself
[ "Matches", "calls", "to", "addAll", "containsAll", "removeAll", "and", "retainAll", "on", "itself" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ModifyingCollectionWithItself.java#L78-L84
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/runtime/cli/PublicMethodsCliObjectFactory.java
PublicMethodsCliObjectFactory.applyCommandLineOptions
public void applyCommandLineOptions(CommandLine cli, T embeddedGobblin) { try { for (Option option : cli.getOptions()) { if (!this.methodsMap.containsKey(option.getOpt())) { // Option added by cli driver itself. continue; } if (option.hasArg()) { this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin, option.getValue()); } else { this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin); } } } catch (IllegalAccessException | InvocationTargetException exc) { throw new RuntimeException("Could not apply options to " + embeddedGobblin.getClass().getName(), exc); } }
java
public void applyCommandLineOptions(CommandLine cli, T embeddedGobblin) { try { for (Option option : cli.getOptions()) { if (!this.methodsMap.containsKey(option.getOpt())) { // Option added by cli driver itself. continue; } if (option.hasArg()) { this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin, option.getValue()); } else { this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin); } } } catch (IllegalAccessException | InvocationTargetException exc) { throw new RuntimeException("Could not apply options to " + embeddedGobblin.getClass().getName(), exc); } }
[ "public", "void", "applyCommandLineOptions", "(", "CommandLine", "cli", ",", "T", "embeddedGobblin", ")", "{", "try", "{", "for", "(", "Option", "option", ":", "cli", ".", "getOptions", "(", ")", ")", "{", "if", "(", "!", "this", ".", "methodsMap", ".", "containsKey", "(", "option", ".", "getOpt", "(", ")", ")", ")", "{", "// Option added by cli driver itself.", "continue", ";", "}", "if", "(", "option", ".", "hasArg", "(", ")", ")", "{", "this", ".", "methodsMap", ".", "get", "(", "option", ".", "getOpt", "(", ")", ")", ".", "invoke", "(", "embeddedGobblin", ",", "option", ".", "getValue", "(", ")", ")", ";", "}", "else", "{", "this", ".", "methodsMap", ".", "get", "(", "option", ".", "getOpt", "(", ")", ")", ".", "invoke", "(", "embeddedGobblin", ")", ";", "}", "}", "}", "catch", "(", "IllegalAccessException", "|", "InvocationTargetException", "exc", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not apply options to \"", "+", "embeddedGobblin", ".", "getClass", "(", ")", ".", "getName", "(", ")", ",", "exc", ")", ";", "}", "}" ]
For each method for which the helper created an {@link Option} and for which the input {@link CommandLine} contains that option, this method will automatically call the method on the input object with the correct arguments.
[ "For", "each", "method", "for", "which", "the", "helper", "created", "an", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/runtime/cli/PublicMethodsCliObjectFactory.java#L140-L156
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/MustBeClosedChecker.java
MustBeClosedChecker.matchMethod
@Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) { // Ignore methods and constructors that are not annotated with {@link MustBeClosed}. return NO_MATCH; } boolean isAConstructor = methodIsConstructor().matches(tree, state); if (isAConstructor && !AUTO_CLOSEABLE_CONSTRUCTOR_MATCHER.matches(tree, state)) { return buildDescription(tree) .setMessage("MustBeClosed should only annotate constructors of AutoCloseables.") .build(); } if (!isAConstructor && !METHOD_RETURNS_AUTO_CLOSEABLE_MATCHER.matches(tree, state)) { return buildDescription(tree) .setMessage("MustBeClosed should only annotate methods that return an AutoCloseable.") .build(); } return NO_MATCH; }
java
@Override public Description matchMethod(MethodTree tree, VisitorState state) { if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) { // Ignore methods and constructors that are not annotated with {@link MustBeClosed}. return NO_MATCH; } boolean isAConstructor = methodIsConstructor().matches(tree, state); if (isAConstructor && !AUTO_CLOSEABLE_CONSTRUCTOR_MATCHER.matches(tree, state)) { return buildDescription(tree) .setMessage("MustBeClosed should only annotate constructors of AutoCloseables.") .build(); } if (!isAConstructor && !METHOD_RETURNS_AUTO_CLOSEABLE_MATCHER.matches(tree, state)) { return buildDescription(tree) .setMessage("MustBeClosed should only annotate methods that return an AutoCloseable.") .build(); } return NO_MATCH; }
[ "@", "Override", "public", "Description", "matchMethod", "(", "MethodTree", "tree", ",", "VisitorState", "state", ")", "{", "if", "(", "!", "HAS_MUST_BE_CLOSED_ANNOTATION", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "// Ignore methods and constructors that are not annotated with {@link MustBeClosed}.", "return", "NO_MATCH", ";", "}", "boolean", "isAConstructor", "=", "methodIsConstructor", "(", ")", ".", "matches", "(", "tree", ",", "state", ")", ";", "if", "(", "isAConstructor", "&&", "!", "AUTO_CLOSEABLE_CONSTRUCTOR_MATCHER", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "return", "buildDescription", "(", "tree", ")", ".", "setMessage", "(", "\"MustBeClosed should only annotate constructors of AutoCloseables.\"", ")", ".", "build", "(", ")", ";", "}", "if", "(", "!", "isAConstructor", "&&", "!", "METHOD_RETURNS_AUTO_CLOSEABLE_MATCHER", ".", "matches", "(", "tree", ",", "state", ")", ")", "{", "return", "buildDescription", "(", "tree", ")", ".", "setMessage", "(", "\"MustBeClosed should only annotate methods that return an AutoCloseable.\"", ")", ".", "build", "(", ")", ";", "}", "return", "NO_MATCH", ";", "}" ]
Check that the {@link MustBeClosed} annotation is only used for constructors of AutoCloseables and methods that return an AutoCloseable.
[ "Check", "that", "the", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/MustBeClosedChecker.java#L82-L102
apereo/cas
support/cas-server-support-saml/src/main/java/org/apereo/cas/support/saml/authentication/SamlResponseBuilder.java
SamlResponseBuilder.setStatusRequestDenied
public void setStatusRequestDenied(final Response response, final String description) { response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.REQUEST_DENIED, description)); }
java
public void setStatusRequestDenied(final Response response, final String description) { response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.REQUEST_DENIED, description)); }
[ "public", "void", "setStatusRequestDenied", "(", "final", "Response", "response", ",", "final", "String", "description", ")", "{", "response", ".", "setStatus", "(", "this", ".", "samlObjectBuilder", ".", "newStatus", "(", "StatusCode", ".", "REQUEST_DENIED", ",", "description", ")", ")", ";", "}" ]
Sets status request denied. @param response the response @param description the description
[ "Sets", "status", "request", "denied", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml/src/main/java/org/apereo/cas/support/saml/authentication/SamlResponseBuilder.java#L64-L66
andi12/msbuild-maven-plugin
msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/VersionInfoMojo.java
VersionInfoMojo.writeVersionInfoTemplateToTempFile
private File writeVersionInfoTemplateToTempFile() throws MojoExecutionException { try { final File versionInfoSrc = File.createTempFile( "msbuild-maven-plugin_" + MOJO_NAME, null ); InputStream is = getClass().getResourceAsStream( DEFAULT_VERSION_INFO_TEMPLATE ); FileOutputStream dest = new FileOutputStream( versionInfoSrc ); byte[] buffer = new byte[1024]; int read = -1; while ( ( read = is.read( buffer ) ) != -1 ) { dest.write( buffer, 0, read ); } dest.close(); return versionInfoSrc; } catch ( IOException ioe ) { String msg = "Failed to create temporary version file"; getLog().error( msg, ioe ); throw new MojoExecutionException( msg, ioe ); } }
java
private File writeVersionInfoTemplateToTempFile() throws MojoExecutionException { try { final File versionInfoSrc = File.createTempFile( "msbuild-maven-plugin_" + MOJO_NAME, null ); InputStream is = getClass().getResourceAsStream( DEFAULT_VERSION_INFO_TEMPLATE ); FileOutputStream dest = new FileOutputStream( versionInfoSrc ); byte[] buffer = new byte[1024]; int read = -1; while ( ( read = is.read( buffer ) ) != -1 ) { dest.write( buffer, 0, read ); } dest.close(); return versionInfoSrc; } catch ( IOException ioe ) { String msg = "Failed to create temporary version file"; getLog().error( msg, ioe ); throw new MojoExecutionException( msg, ioe ); } }
[ "private", "File", "writeVersionInfoTemplateToTempFile", "(", ")", "throws", "MojoExecutionException", "{", "try", "{", "final", "File", "versionInfoSrc", "=", "File", ".", "createTempFile", "(", "\"msbuild-maven-plugin_\"", "+", "MOJO_NAME", ",", "null", ")", ";", "InputStream", "is", "=", "getClass", "(", ")", ".", "getResourceAsStream", "(", "DEFAULT_VERSION_INFO_TEMPLATE", ")", ";", "FileOutputStream", "dest", "=", "new", "FileOutputStream", "(", "versionInfoSrc", ")", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "1024", "]", ";", "int", "read", "=", "-", "1", ";", "while", "(", "(", "read", "=", "is", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "dest", ".", "write", "(", "buffer", ",", "0", ",", "read", ")", ";", "}", "dest", ".", "close", "(", ")", ";", "return", "versionInfoSrc", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "String", "msg", "=", "\"Failed to create temporary version file\"", ";", "getLog", "(", ")", ".", "error", "(", "msg", ",", "ioe", ")", ";", "throw", "new", "MojoExecutionException", "(", "msg", ",", "ioe", ")", ";", "}", "}" ]
Write the default .rc template file to a temporary file and return it @return a File pointing to the temporary file @throws MojoExecutionException if there is an IOException
[ "Write", "the", "default", ".", "rc", "template", "file", "to", "a", "temporary", "file", "and", "return", "it" ]
train
https://github.com/andi12/msbuild-maven-plugin/blob/224159c15efba20d482f8c630f7947339b1a1b86/msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/VersionInfoMojo.java#L167-L191
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/AbstractHttpTransport.java
AbstractHttpTransport.createFeatureListResource
protected IResource createFeatureListResource(List<String> list, URI uri, long lastmod) { JSONArray json; try { json = new JSONArray(new ArrayList<String>(dependentFeatures)); } catch (JSONException ex) { return new ExceptionResource(uri, lastmod, new IOException(ex)); } StringBuffer sb = new StringBuffer(); sb.append(FEATURE_LIST_PRELUDE).append(json).append(FEATURE_LIST_PROLOGUE); IResource result = new StringResource(sb.toString(), uri, lastmod); return result; }
java
protected IResource createFeatureListResource(List<String> list, URI uri, long lastmod) { JSONArray json; try { json = new JSONArray(new ArrayList<String>(dependentFeatures)); } catch (JSONException ex) { return new ExceptionResource(uri, lastmod, new IOException(ex)); } StringBuffer sb = new StringBuffer(); sb.append(FEATURE_LIST_PRELUDE).append(json).append(FEATURE_LIST_PROLOGUE); IResource result = new StringResource(sb.toString(), uri, lastmod); return result; }
[ "protected", "IResource", "createFeatureListResource", "(", "List", "<", "String", ">", "list", ",", "URI", "uri", ",", "long", "lastmod", ")", "{", "JSONArray", "json", ";", "try", "{", "json", "=", "new", "JSONArray", "(", "new", "ArrayList", "<", "String", ">", "(", "dependentFeatures", ")", ")", ";", "}", "catch", "(", "JSONException", "ex", ")", "{", "return", "new", "ExceptionResource", "(", "uri", ",", "lastmod", ",", "new", "IOException", "(", "ex", ")", ")", ";", "}", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "sb", ".", "append", "(", "FEATURE_LIST_PRELUDE", ")", ".", "append", "(", "json", ")", ".", "append", "(", "FEATURE_LIST_PROLOGUE", ")", ";", "IResource", "result", "=", "new", "StringResource", "(", "sb", ".", "toString", "(", ")", ",", "uri", ",", "lastmod", ")", ";", "return", "result", ";", "}" ]
Creates an {@link IResource} object for the dependent feature list AMD module @param list the dependent features list @param uri the resource URI @param lastmod the last modified time of the resource @return the {@link IResource} object for the module
[ "Creates", "an", "{", "@link", "IResource", "}", "object", "for", "the", "dependent", "feature", "list", "AMD", "module" ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/transport/AbstractHttpTransport.java#L1090-L1101
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java
BaseSparseNDArrayCOO.checkBufferCoherence
protected void checkBufferCoherence(){ if (values.length() < length){ throw new IllegalStateException("nnz is larger than capacity of buffers"); } if (values.length() * rank() != indices.length()){ throw new IllegalArgumentException("Sizes of values, indices and shape are incoherent."); } }
java
protected void checkBufferCoherence(){ if (values.length() < length){ throw new IllegalStateException("nnz is larger than capacity of buffers"); } if (values.length() * rank() != indices.length()){ throw new IllegalArgumentException("Sizes of values, indices and shape are incoherent."); } }
[ "protected", "void", "checkBufferCoherence", "(", ")", "{", "if", "(", "values", ".", "length", "(", ")", "<", "length", ")", "{", "throw", "new", "IllegalStateException", "(", "\"nnz is larger than capacity of buffers\"", ")", ";", "}", "if", "(", "values", ".", "length", "(", ")", "*", "rank", "(", ")", "!=", "indices", ".", "length", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Sizes of values, indices and shape are incoherent.\"", ")", ";", "}", "}" ]
Check that the length of indices and values are coherent and matches the rank of the matrix.
[ "Check", "that", "the", "length", "of", "indices", "and", "values", "are", "coherent", "and", "matches", "the", "rank", "of", "the", "matrix", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java#L143-L151
camunda/camunda-commons
logging/src/main/java/org/camunda/commons/logging/BaseLogger.java
BaseLogger.logError
protected void logError(String id, String messageTemplate, Object... parameters) { if(delegateLogger.isErrorEnabled()) { String msg = formatMessageTemplate(id, messageTemplate); delegateLogger.error(msg, parameters); } }
java
protected void logError(String id, String messageTemplate, Object... parameters) { if(delegateLogger.isErrorEnabled()) { String msg = formatMessageTemplate(id, messageTemplate); delegateLogger.error(msg, parameters); } }
[ "protected", "void", "logError", "(", "String", "id", ",", "String", "messageTemplate", ",", "Object", "...", "parameters", ")", "{", "if", "(", "delegateLogger", ".", "isErrorEnabled", "(", ")", ")", "{", "String", "msg", "=", "formatMessageTemplate", "(", "id", ",", "messageTemplate", ")", ";", "delegateLogger", ".", "error", "(", "msg", ",", "parameters", ")", ";", "}", "}" ]
Logs an 'ERROR' message @param id the unique id of this log message @param messageTemplate the message template to use @param parameters a list of optional parameters
[ "Logs", "an", "ERROR", "message" ]
train
https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/logging/src/main/java/org/camunda/commons/logging/BaseLogger.java#L157-L162
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/transform/TransformersLogger.java
TransformersLogger.logAttributeWarning
public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, null, message, attributes)); }
java
public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, null, message, attributes)); }
[ "public", "void", "logAttributeWarning", "(", "PathAddress", "address", ",", "String", "message", ",", "Set", "<", "String", ">", "attributes", ")", "{", "messageQueue", ".", "add", "(", "new", "AttributeLogEntry", "(", "address", ",", "null", ",", "message", ",", "attributes", ")", ")", ";", "}" ]
Log a warning for the resource at the provided address and the given attributes, using the provided detail message. @param address where warning occurred @param message custom error message to append @param attributes attributes we that have problems about
[ "Log", "a", "warning", "for", "the", "resource", "at", "the", "provided", "address", "and", "the", "given", "attributes", "using", "the", "provided", "detail", "message", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformersLogger.java#L133-L135
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.openOutgoingConnection
public void openOutgoingConnection (Connection conn, String hostname, int port) throws IOException { // create a socket channel to use for this connection, initialize it and queue it up to // have the non-blocking connect process started SocketChannel sockchan = SocketChannel.open(); sockchan.configureBlocking(false); conn.init(this, sockchan, System.currentTimeMillis()); _connectq.append(Tuple.newTuple(conn, new InetSocketAddress(hostname, port))); }
java
public void openOutgoingConnection (Connection conn, String hostname, int port) throws IOException { // create a socket channel to use for this connection, initialize it and queue it up to // have the non-blocking connect process started SocketChannel sockchan = SocketChannel.open(); sockchan.configureBlocking(false); conn.init(this, sockchan, System.currentTimeMillis()); _connectq.append(Tuple.newTuple(conn, new InetSocketAddress(hostname, port))); }
[ "public", "void", "openOutgoingConnection", "(", "Connection", "conn", ",", "String", "hostname", ",", "int", "port", ")", "throws", "IOException", "{", "// create a socket channel to use for this connection, initialize it and queue it up to", "// have the non-blocking connect process started", "SocketChannel", "sockchan", "=", "SocketChannel", ".", "open", "(", ")", ";", "sockchan", ".", "configureBlocking", "(", "false", ")", ";", "conn", ".", "init", "(", "this", ",", "sockchan", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "_connectq", ".", "append", "(", "Tuple", ".", "newTuple", "(", "conn", ",", "new", "InetSocketAddress", "(", "hostname", ",", "port", ")", ")", ")", ";", "}" ]
Opens an outgoing connection to the supplied address. The connection will be opened in a non-blocking manner and added to the connection manager's select set. Messages posted to the connection prior to it being actually connected to its destination will remain in the queue. If the connection fails those messages will be dropped. @param conn the connection to be initialized and opened. Callers may want to provide a {@link Connection} derived class so that they may intercept calldown methods. @param hostname the hostname of the server to which to connect. @param port the port on which to connect to the server. @exception IOException thrown if an error occurs creating our socket. Everything else happens asynchronously. If the connection attempt fails, the Connection will be notified via {@link Connection#networkFailure}.
[ "Opens", "an", "outgoing", "connection", "to", "the", "supplied", "address", ".", "The", "connection", "will", "be", "opened", "in", "a", "non", "-", "blocking", "manner", "and", "added", "to", "the", "connection", "manager", "s", "select", "set", ".", "Messages", "posted", "to", "the", "connection", "prior", "to", "it", "being", "actually", "connected", "to", "its", "destination", "will", "remain", "in", "the", "queue", ".", "If", "the", "connection", "fails", "those", "messages", "will", "be", "dropped", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L369-L378
baidubce/bce-sdk-java
src/main/java/com/baidubce/util/JsonUtils.java
JsonUtils.fromJsonString
public static <T> T fromJsonString(String json, Class<T> clazz) { if (json == null) { return null; } try { return JsonUtils.objectMapper.readValue(json, clazz); } catch (Exception e) { throw new BceClientException("Unable to parse Json String.", e); } }
java
public static <T> T fromJsonString(String json, Class<T> clazz) { if (json == null) { return null; } try { return JsonUtils.objectMapper.readValue(json, clazz); } catch (Exception e) { throw new BceClientException("Unable to parse Json String.", e); } }
[ "public", "static", "<", "T", ">", "T", "fromJsonString", "(", "String", "json", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "json", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "return", "JsonUtils", ".", "objectMapper", ".", "readValue", "(", "json", ",", "clazz", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "BceClientException", "(", "\"Unable to parse Json String.\"", ",", "e", ")", ";", "}", "}" ]
Returns the deserialized object from the given json string and target class; or null if the given json string is null.
[ "Returns", "the", "deserialized", "object", "from", "the", "given", "json", "string", "and", "target", "class", ";", "or", "null", "if", "the", "given", "json", "string", "is", "null", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/util/JsonUtils.java#L63-L72
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/map/AbstractIntObjectMap.java
AbstractIntObjectMap.pairsMatching
public void pairsMatching(final IntObjectProcedure condition, final IntArrayList keyList, final ObjectArrayList valueList) { keyList.clear(); valueList.clear(); forEachPair( new IntObjectProcedure() { public boolean apply(int key, Object value) { if (condition.apply(key,value)) { keyList.add(key); valueList.add(value); } return true; } } ); }
java
public void pairsMatching(final IntObjectProcedure condition, final IntArrayList keyList, final ObjectArrayList valueList) { keyList.clear(); valueList.clear(); forEachPair( new IntObjectProcedure() { public boolean apply(int key, Object value) { if (condition.apply(key,value)) { keyList.add(key); valueList.add(value); } return true; } } ); }
[ "public", "void", "pairsMatching", "(", "final", "IntObjectProcedure", "condition", ",", "final", "IntArrayList", "keyList", ",", "final", "ObjectArrayList", "valueList", ")", "{", "keyList", ".", "clear", "(", ")", ";", "valueList", ".", "clear", "(", ")", ";", "forEachPair", "(", "new", "IntObjectProcedure", "(", ")", "{", "public", "boolean", "apply", "(", "int", "key", ",", "Object", "value", ")", "{", "if", "(", "condition", ".", "apply", "(", "key", ",", "value", ")", ")", "{", "keyList", ".", "add", "(", "key", ")", ";", "valueList", ".", "add", "(", "value", ")", ";", "}", "return", "true", ";", "}", "}", ")", ";", "}" ]
Fills all pairs satisfying a given condition into the specified lists. Fills into the lists, starting at index 0. After this call returns the specified lists both have a new size, the number of pairs satisfying the condition. Iteration order is guaranteed to be <i>identical</i> to the order used by method {@link #forEachKey(IntProcedure)}. <p> <b>Example:</b> <br> <pre> IntObjectProcedure condition = new IntObjectProcedure() { // match even keys only public boolean apply(int key, Object value) { return key%2==0; } } keys = (8,7,6), values = (1,2,2) --> keyList = (6,8), valueList = (2,1)</tt> </pre> @param condition the condition to be matched. Takes the current key as first and the current value as second argument. @param keyList the list to be filled with keys, can have any size. @param valueList the list to be filled with values, can have any size.
[ "Fills", "all", "pairs", "satisfying", "a", "given", "condition", "into", "the", "specified", "lists", ".", "Fills", "into", "the", "lists", "starting", "at", "index", "0", ".", "After", "this", "call", "returns", "the", "specified", "lists", "both", "have", "a", "new", "size", "the", "number", "of", "pairs", "satisfying", "the", "condition", ".", "Iteration", "order", "is", "guaranteed", "to", "be", "<i", ">", "identical<", "/", "i", ">", "to", "the", "order", "used", "by", "method", "{", "@link", "#forEachKey", "(", "IntProcedure", ")", "}", ".", "<p", ">", "<b", ">", "Example", ":", "<", "/", "b", ">", "<br", ">", "<pre", ">", "IntObjectProcedure", "condition", "=", "new", "IntObjectProcedure", "()", "{", "//", "match", "even", "keys", "only", "public", "boolean", "apply", "(", "int", "key", "Object", "value", ")", "{", "return", "key%2", "==", "0", ";", "}", "}", "keys", "=", "(", "8", "7", "6", ")", "values", "=", "(", "1", "2", "2", ")", "--", ">", "keyList", "=", "(", "6", "8", ")", "valueList", "=", "(", "2", "1", ")", "<", "/", "tt", ">", "<", "/", "pre", ">" ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractIntObjectMap.java#L254-L269
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/Invalidator.java
Invalidator.invalidateKey
public final void invalidateKey(Data key, String dataStructureName, String sourceUuid) { checkNotNull(key, "key cannot be null"); checkNotNull(sourceUuid, "sourceUuid cannot be null"); Invalidation invalidation = newKeyInvalidation(key, dataStructureName, sourceUuid); invalidateInternal(invalidation, getPartitionId(key)); }
java
public final void invalidateKey(Data key, String dataStructureName, String sourceUuid) { checkNotNull(key, "key cannot be null"); checkNotNull(sourceUuid, "sourceUuid cannot be null"); Invalidation invalidation = newKeyInvalidation(key, dataStructureName, sourceUuid); invalidateInternal(invalidation, getPartitionId(key)); }
[ "public", "final", "void", "invalidateKey", "(", "Data", "key", ",", "String", "dataStructureName", ",", "String", "sourceUuid", ")", "{", "checkNotNull", "(", "key", ",", "\"key cannot be null\"", ")", ";", "checkNotNull", "(", "sourceUuid", ",", "\"sourceUuid cannot be null\"", ")", ";", "Invalidation", "invalidation", "=", "newKeyInvalidation", "(", "key", ",", "dataStructureName", ",", "sourceUuid", ")", ";", "invalidateInternal", "(", "invalidation", ",", "getPartitionId", "(", "key", ")", ")", ";", "}" ]
Invalidates supplied key from Near Caches of supplied data structure name. @param key key of the entry to be removed from Near Cache @param dataStructureName name of the data structure to be invalidated
[ "Invalidates", "supplied", "key", "from", "Near", "Caches", "of", "supplied", "data", "structure", "name", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/Invalidator.java#L67-L73
qspin/qtaste
plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/TreeNodeSelector.java
TreeNodeSelector.prepareActions
protected void prepareActions() throws QTasteTestFailException { if (mSelectorIdentifier == SelectorIdentifier.CLEAR_SELECTION) { // nothing special to do for CLEAR_SELECTION action return; } String nodePath = mData[0].toString(); String nodePathSeparator = mData[1].toString(); // Split node path into an array of node path elements // Be careful that String.split() method takes a regex as argument. // Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method. String[] nodePathElements = nodePath.split(Pattern.quote(nodePathSeparator)); if (nodePathElements.length == 0) { throw new QTasteTestFailException( "Unable to split the node path in elements (nodePath: '" + nodePath + "' separator: '" + nodePathSeparator + "')"); } LOGGER.trace("nodePath: " + nodePath + " separator: " + nodePathSeparator + " splitted in " + nodePathElements.length + " element(s)."); if (component instanceof JTree) { JTree tree = (JTree) component; } else { throw new QTasteTestFailException( "Invalid component class (expected: JTree, got: " + component.getClass().getName() + ")."); } }
java
protected void prepareActions() throws QTasteTestFailException { if (mSelectorIdentifier == SelectorIdentifier.CLEAR_SELECTION) { // nothing special to do for CLEAR_SELECTION action return; } String nodePath = mData[0].toString(); String nodePathSeparator = mData[1].toString(); // Split node path into an array of node path elements // Be careful that String.split() method takes a regex as argument. // Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method. String[] nodePathElements = nodePath.split(Pattern.quote(nodePathSeparator)); if (nodePathElements.length == 0) { throw new QTasteTestFailException( "Unable to split the node path in elements (nodePath: '" + nodePath + "' separator: '" + nodePathSeparator + "')"); } LOGGER.trace("nodePath: " + nodePath + " separator: " + nodePathSeparator + " splitted in " + nodePathElements.length + " element(s)."); if (component instanceof JTree) { JTree tree = (JTree) component; } else { throw new QTasteTestFailException( "Invalid component class (expected: JTree, got: " + component.getClass().getName() + ")."); } }
[ "protected", "void", "prepareActions", "(", ")", "throws", "QTasteTestFailException", "{", "if", "(", "mSelectorIdentifier", "==", "SelectorIdentifier", ".", "CLEAR_SELECTION", ")", "{", "// nothing special to do for CLEAR_SELECTION action", "return", ";", "}", "String", "nodePath", "=", "mData", "[", "0", "]", ".", "toString", "(", ")", ";", "String", "nodePathSeparator", "=", "mData", "[", "1", "]", ".", "toString", "(", ")", ";", "// Split node path into an array of node path elements", "// Be careful that String.split() method takes a regex as argument.", "// Here, the token 'nodePathSeparator' is escaped using the Pattern.quote() method.", "String", "[", "]", "nodePathElements", "=", "nodePath", ".", "split", "(", "Pattern", ".", "quote", "(", "nodePathSeparator", ")", ")", ";", "if", "(", "nodePathElements", ".", "length", "==", "0", ")", "{", "throw", "new", "QTasteTestFailException", "(", "\"Unable to split the node path in elements (nodePath: '\"", "+", "nodePath", "+", "\"' separator: '\"", "+", "nodePathSeparator", "+", "\"')\"", ")", ";", "}", "LOGGER", ".", "trace", "(", "\"nodePath: \"", "+", "nodePath", "+", "\" separator: \"", "+", "nodePathSeparator", "+", "\" splitted in \"", "+", "nodePathElements", ".", "length", "+", "\" element(s).\"", ")", ";", "if", "(", "component", "instanceof", "JTree", ")", "{", "JTree", "tree", "=", "(", "JTree", ")", "component", ";", "}", "else", "{", "throw", "new", "QTasteTestFailException", "(", "\"Invalid component class (expected: JTree, got: \"", "+", "component", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\").\"", ")", ";", "}", "}" ]
Build a tree path (an array of objects) from a node path string and a node path separator. @throws QTasteTestFailException
[ "Build", "a", "tree", "path", "(", "an", "array", "of", "objects", ")", "from", "a", "node", "path", "string", "and", "a", "node", "path", "separator", "." ]
train
https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/TreeNodeSelector.java#L78-L108
xerial/larray
larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
LBufferAPI.readFrom
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
java
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return readLen; }
[ "public", "int", "readFrom", "(", "ByteBuffer", "src", ",", "long", "destOffset", ")", "{", "if", "(", "src", ".", "remaining", "(", ")", "+", "destOffset", ">=", "size", "(", ")", ")", "throw", "new", "BufferOverflowException", "(", ")", ";", "int", "readLen", "=", "src", ".", "remaining", "(", ")", ";", "ByteBuffer", "b", "=", "toDirectByteBuffer", "(", "destOffset", ",", "readLen", ")", ";", "b", ".", "position", "(", "0", ")", ";", "b", ".", "put", "(", "src", ")", ";", "return", "readLen", ";", "}" ]
Reads the given source byte buffer into this buffer at the given offset @param src source byte buffer @param destOffset offset in this buffer to read to @return the number of bytes read
[ "Reads", "the", "given", "source", "byte", "buffer", "into", "this", "buffer", "at", "the", "given", "offset" ]
train
https://github.com/xerial/larray/blob/9a1462623c0e56ca67c5341ea29832963c29479f/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java#L385-L393
Stratio/cassandra-lucene-index
plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaBuilder.java
SchemaBuilder.fromJson
public static SchemaBuilder fromJson(String json) { try { return JsonSerializer.fromString(json, SchemaBuilder.class); } catch (IOException e) { throw new IndexException(e, "Unparseable JSON schema: {}: {}", e.getMessage(), json); } }
java
public static SchemaBuilder fromJson(String json) { try { return JsonSerializer.fromString(json, SchemaBuilder.class); } catch (IOException e) { throw new IndexException(e, "Unparseable JSON schema: {}: {}", e.getMessage(), json); } }
[ "public", "static", "SchemaBuilder", "fromJson", "(", "String", "json", ")", "{", "try", "{", "return", "JsonSerializer", ".", "fromString", "(", "json", ",", "SchemaBuilder", ".", "class", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IndexException", "(", "e", ",", "\"Unparseable JSON schema: {}: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "json", ")", ";", "}", "}" ]
Returns the {@link Schema} contained in the specified JSON {@code String}. @param json a {@code String} containing the JSON representation of the {@link Schema} to be parsed @return the schema contained in the specified JSON {@code String}
[ "Returns", "the", "{", "@link", "Schema", "}", "contained", "in", "the", "specified", "JSON", "{", "@code", "String", "}", "." ]
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/schema/SchemaBuilder.java#L154-L160
osmdroid/osmdroid
OSMMapTilePackager/src/main/java/org/osmdroid/mtp/util/Util.java
Util.getMapTileFromCoordinates
public static OSMTileInfo getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) { final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)); final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom)); return new OSMTileInfo(x, y, zoom); }
java
public static OSMTileInfo getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) { final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)); final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom)); return new OSMTileInfo(x, y, zoom); }
[ "public", "static", "OSMTileInfo", "getMapTileFromCoordinates", "(", "final", "double", "aLat", ",", "final", "double", "aLon", ",", "final", "int", "zoom", ")", "{", "final", "int", "y", "=", "(", "int", ")", "Math", ".", "floor", "(", "(", "1", "-", "Math", ".", "log", "(", "Math", ".", "tan", "(", "aLat", "*", "Math", ".", "PI", "/", "180", ")", "+", "1", "/", "Math", ".", "cos", "(", "aLat", "*", "Math", ".", "PI", "/", "180", ")", ")", "/", "Math", ".", "PI", ")", "/", "2", "*", "(", "1", "<<", "zoom", ")", ")", ";", "final", "int", "x", "=", "(", "int", ")", "Math", ".", "floor", "(", "(", "aLon", "+", "180", ")", "/", "360", "*", "(", "1", "<<", "zoom", ")", ")", ";", "return", "new", "OSMTileInfo", "(", "x", ",", "y", ",", "zoom", ")", ";", "}" ]
For a description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames</a> For a code-description see: see <a href="http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number">http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames#compute_bounding_box_for_tile_number</a> @param aLat latitude to get the {@link OSMTileInfo} for. @param aLon longitude to get the {@link OSMTileInfo} for. @return The {@link OSMTileInfo} providing 'x' 'y' and 'z'(oom) for the coordinates passed.
[ "For", "a", "description", "see", ":", "see", "<a", "href", "=", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames", ">", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames<", "/", "a", ">", "For", "a", "code", "-", "description", "see", ":", "see", "<a", "href", "=", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames#compute_bounding_box_for_tile_number", ">", "http", ":", "//", "wiki", ".", "openstreetmap", ".", "org", "/", "index", ".", "php", "/", "Slippy_map_tilenames#compute_bounding_box_for_tile_number<", "/", "a", ">" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OSMMapTilePackager/src/main/java/org/osmdroid/mtp/util/Util.java#L40-L45
czyzby/gdx-lml
lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java
LmlApplicationListener.saveDtdSchema
public void saveDtdSchema(final FileHandle file) { try { final Writer appendable = file.writer(false, "UTF-8"); final boolean strict = lmlParser.isStrict(); lmlParser.setStrict(false); // Temporary setting to non-strict to generate as much tags as possible. createDtdSchema(lmlParser, appendable); appendable.close(); lmlParser.setStrict(strict); } catch (final Exception exception) { throw new GdxRuntimeException("Unable to save DTD schema.", exception); } }
java
public void saveDtdSchema(final FileHandle file) { try { final Writer appendable = file.writer(false, "UTF-8"); final boolean strict = lmlParser.isStrict(); lmlParser.setStrict(false); // Temporary setting to non-strict to generate as much tags as possible. createDtdSchema(lmlParser, appendable); appendable.close(); lmlParser.setStrict(strict); } catch (final Exception exception) { throw new GdxRuntimeException("Unable to save DTD schema.", exception); } }
[ "public", "void", "saveDtdSchema", "(", "final", "FileHandle", "file", ")", "{", "try", "{", "final", "Writer", "appendable", "=", "file", ".", "writer", "(", "false", ",", "\"UTF-8\"", ")", ";", "final", "boolean", "strict", "=", "lmlParser", ".", "isStrict", "(", ")", ";", "lmlParser", ".", "setStrict", "(", "false", ")", ";", "// Temporary setting to non-strict to generate as much tags as possible.", "createDtdSchema", "(", "lmlParser", ",", "appendable", ")", ";", "appendable", ".", "close", "(", ")", ";", "lmlParser", ".", "setStrict", "(", "strict", ")", ";", "}", "catch", "(", "final", "Exception", "exception", ")", "{", "throw", "new", "GdxRuntimeException", "(", "\"Unable to save DTD schema.\"", ",", "exception", ")", ";", "}", "}" ]
Uses current {@link LmlParser} to generate a DTD schema file with all supported tags, macros and attributes. Should be used only during development: DTD allows to validate LML templates during creation (and add content assist thanks to XML support in your IDE), but is not used in any way by the {@link LmlParser} in runtime. @param file path to the file where DTD schema should be saved. Advised to be local or absolute. Note that some platforms (GWT) do not support file saving - this method should be used on desktop platform and only during development. @throws GdxRuntimeException when unable to save DTD schema. @see Dtd
[ "Uses", "current", "{", "@link", "LmlParser", "}", "to", "generate", "a", "DTD", "schema", "file", "with", "all", "supported", "tags", "macros", "and", "attributes", ".", "Should", "be", "used", "only", "during", "development", ":", "DTD", "allows", "to", "validate", "LML", "templates", "during", "creation", "(", "and", "add", "content", "assist", "thanks", "to", "XML", "support", "in", "your", "IDE", ")", "but", "is", "not", "used", "in", "any", "way", "by", "the", "{", "@link", "LmlParser", "}", "in", "runtime", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/lml/src/main/java/com/github/czyzby/lml/util/LmlApplicationListener.java#L104-L115
apache/incubator-shardingsphere
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java
ShardingRule.getTableRule
public TableRule getTableRule(final String logicTableName) { Optional<TableRule> tableRule = findTableRule(logicTableName); if (tableRule.isPresent()) { return tableRule.get(); } if (isBroadcastTable(logicTableName)) { return new TableRule(shardingDataSourceNames.getDataSourceNames(), logicTableName); } if (!Strings.isNullOrEmpty(shardingDataSourceNames.getDefaultDataSourceName())) { return new TableRule(shardingDataSourceNames.getDefaultDataSourceName(), logicTableName); } throw new ShardingConfigurationException("Cannot find table rule and default data source with logic table: '%s'", logicTableName); }
java
public TableRule getTableRule(final String logicTableName) { Optional<TableRule> tableRule = findTableRule(logicTableName); if (tableRule.isPresent()) { return tableRule.get(); } if (isBroadcastTable(logicTableName)) { return new TableRule(shardingDataSourceNames.getDataSourceNames(), logicTableName); } if (!Strings.isNullOrEmpty(shardingDataSourceNames.getDefaultDataSourceName())) { return new TableRule(shardingDataSourceNames.getDefaultDataSourceName(), logicTableName); } throw new ShardingConfigurationException("Cannot find table rule and default data source with logic table: '%s'", logicTableName); }
[ "public", "TableRule", "getTableRule", "(", "final", "String", "logicTableName", ")", "{", "Optional", "<", "TableRule", ">", "tableRule", "=", "findTableRule", "(", "logicTableName", ")", ";", "if", "(", "tableRule", ".", "isPresent", "(", ")", ")", "{", "return", "tableRule", ".", "get", "(", ")", ";", "}", "if", "(", "isBroadcastTable", "(", "logicTableName", ")", ")", "{", "return", "new", "TableRule", "(", "shardingDataSourceNames", ".", "getDataSourceNames", "(", ")", ",", "logicTableName", ")", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "shardingDataSourceNames", ".", "getDefaultDataSourceName", "(", ")", ")", ")", "{", "return", "new", "TableRule", "(", "shardingDataSourceNames", ".", "getDefaultDataSourceName", "(", ")", ",", "logicTableName", ")", ";", "}", "throw", "new", "ShardingConfigurationException", "(", "\"Cannot find table rule and default data source with logic table: '%s'\"", ",", "logicTableName", ")", ";", "}" ]
Get table rule. @param logicTableName logic table name @return table rule
[ "Get", "table", "rule", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java#L182-L194
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.beginCreateOrUpdateSecuritySettingsAsync
public Observable<Void> beginCreateOrUpdateSecuritySettingsAsync(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) { return beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginCreateOrUpdateSecuritySettingsAsync(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) { return beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginCreateOrUpdateSecuritySettingsAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ",", "AsymmetricEncryptedSecret", "deviceAdminPassword", ")", "{", "return", "beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ",", "deviceAdminPassword", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates the security settings on a data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @param deviceAdminPassword Device administrator password as an encrypted string (encrypted using RSA PKCS #1) is used to sign into the local web UI of the device. The Actual password should have at least 8 characters that are a combination of uppercase, lowercase, numeric, and special characters. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Updates", "the", "security", "settings", "on", "a", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1942-L1949
ehcache/ehcache3
core/src/main/java/org/ehcache/core/exceptions/ExceptionFactory.java
ExceptionFactory.newCacheLoadingException
public static CacheLoadingException newCacheLoadingException(Exception e, Exception suppressed) { CacheLoadingException ne = new CacheLoadingException(e); ne.addSuppressed(e); return ne; }
java
public static CacheLoadingException newCacheLoadingException(Exception e, Exception suppressed) { CacheLoadingException ne = new CacheLoadingException(e); ne.addSuppressed(e); return ne; }
[ "public", "static", "CacheLoadingException", "newCacheLoadingException", "(", "Exception", "e", ",", "Exception", "suppressed", ")", "{", "CacheLoadingException", "ne", "=", "new", "CacheLoadingException", "(", "e", ")", ";", "ne", ".", "addSuppressed", "(", "e", ")", ";", "return", "ne", ";", "}" ]
Creates a new {@code CacheLoadingException} with the provided exception as cause and a suppressed one. @param e the cause @param suppressed the suppressed exception to add to the new exception @return a cache loading exception
[ "Creates", "a", "new", "{", "@code", "CacheLoadingException", "}", "with", "the", "provided", "exception", "as", "cause", "and", "a", "suppressed", "one", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/exceptions/ExceptionFactory.java#L71-L75
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/handlers/DefaultFilenameTabCompleter.java
DefaultFilenameTabCompleter.completeCandidates
@Override void completeCandidates(CommandContext ctx, String buffer, int cursor, List<String> candidates) { boolean quoted = buffer.startsWith("\""); if (candidates.size() == 1) { // Escaping must occur in all cases. // if quoted, only " will be escaped. EscapeSelector escSelector = quoted ? QUOTES_ONLY_ESCAPE_SELECTOR : ESCAPE_SELECTOR; candidates.set(0, Util.escapeString(candidates.get(0), escSelector)); } }
java
@Override void completeCandidates(CommandContext ctx, String buffer, int cursor, List<String> candidates) { boolean quoted = buffer.startsWith("\""); if (candidates.size() == 1) { // Escaping must occur in all cases. // if quoted, only " will be escaped. EscapeSelector escSelector = quoted ? QUOTES_ONLY_ESCAPE_SELECTOR : ESCAPE_SELECTOR; candidates.set(0, Util.escapeString(candidates.get(0), escSelector)); } }
[ "@", "Override", "void", "completeCandidates", "(", "CommandContext", "ctx", ",", "String", "buffer", ",", "int", "cursor", ",", "List", "<", "String", ">", "candidates", ")", "{", "boolean", "quoted", "=", "buffer", ".", "startsWith", "(", "\"\\\"\"", ")", ";", "if", "(", "candidates", ".", "size", "(", ")", "==", "1", ")", "{", "// Escaping must occur in all cases.", "// if quoted, only \" will be escaped.", "EscapeSelector", "escSelector", "=", "quoted", "?", "QUOTES_ONLY_ESCAPE_SELECTOR", ":", "ESCAPE_SELECTOR", ";", "candidates", ".", "set", "(", "0", ",", "Util", ".", "escapeString", "(", "candidates", ".", "get", "(", "0", ")", ",", "escSelector", ")", ")", ";", "}", "}" ]
The only supported syntax at command execution is fully quoted, e.g.: "/My Files\..." or not quoted at all. Completion supports only these 2 syntaxes.
[ "The", "only", "supported", "syntax", "at", "command", "execution", "is", "fully", "quoted", "e", ".", "g", ".", ":", "/", "My", "Files", "\\", "...", "or", "not", "quoted", "at", "all", ".", "Completion", "supports", "only", "these", "2", "syntaxes", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/handlers/DefaultFilenameTabCompleter.java#L59-L69
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/line/GridRansacLineDetector.java
GridRansacLineDetector.process
public void process( D derivX , D derivY , GrayU8 binaryEdges ) { InputSanityCheck.checkSameShape(derivX,derivY,binaryEdges); int w = derivX.width-regionSize+1; int h = derivY.height-regionSize+1; foundLines.reshape(derivX.width / regionSize, derivX.height / regionSize); foundLines.reset(); // avoid partial regions/other image edge conditions by being at least the region's radius away for( int y = 0; y < h; y += regionSize) { int gridY = y/regionSize; // index of the top left pixel in the region being considered // possible over optimization int index = binaryEdges.startIndex + y*binaryEdges.stride; for( int x = 0; x < w; x+= regionSize , index += regionSize) { int gridX = x/regionSize; // detects edgels inside the region detectEdgels(index,x,y,derivX,derivY,binaryEdges); // find lines inside the region using RANSAC findLinesInRegion(foundLines.get(gridX,gridY)); } } }
java
public void process( D derivX , D derivY , GrayU8 binaryEdges ) { InputSanityCheck.checkSameShape(derivX,derivY,binaryEdges); int w = derivX.width-regionSize+1; int h = derivY.height-regionSize+1; foundLines.reshape(derivX.width / regionSize, derivX.height / regionSize); foundLines.reset(); // avoid partial regions/other image edge conditions by being at least the region's radius away for( int y = 0; y < h; y += regionSize) { int gridY = y/regionSize; // index of the top left pixel in the region being considered // possible over optimization int index = binaryEdges.startIndex + y*binaryEdges.stride; for( int x = 0; x < w; x+= regionSize , index += regionSize) { int gridX = x/regionSize; // detects edgels inside the region detectEdgels(index,x,y,derivX,derivY,binaryEdges); // find lines inside the region using RANSAC findLinesInRegion(foundLines.get(gridX,gridY)); } } }
[ "public", "void", "process", "(", "D", "derivX", ",", "D", "derivY", ",", "GrayU8", "binaryEdges", ")", "{", "InputSanityCheck", ".", "checkSameShape", "(", "derivX", ",", "derivY", ",", "binaryEdges", ")", ";", "int", "w", "=", "derivX", ".", "width", "-", "regionSize", "+", "1", ";", "int", "h", "=", "derivY", ".", "height", "-", "regionSize", "+", "1", ";", "foundLines", ".", "reshape", "(", "derivX", ".", "width", "/", "regionSize", ",", "derivX", ".", "height", "/", "regionSize", ")", ";", "foundLines", ".", "reset", "(", ")", ";", "// avoid partial regions/other image edge conditions by being at least the region's radius away", "for", "(", "int", "y", "=", "0", ";", "y", "<", "h", ";", "y", "+=", "regionSize", ")", "{", "int", "gridY", "=", "y", "/", "regionSize", ";", "// index of the top left pixel in the region being considered", "// possible over optimization", "int", "index", "=", "binaryEdges", ".", "startIndex", "+", "y", "*", "binaryEdges", ".", "stride", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "w", ";", "x", "+=", "regionSize", ",", "index", "+=", "regionSize", ")", "{", "int", "gridX", "=", "x", "/", "regionSize", ";", "// detects edgels inside the region", "detectEdgels", "(", "index", ",", "x", ",", "y", ",", "derivX", ",", "derivY", ",", "binaryEdges", ")", ";", "// find lines inside the region using RANSAC", "findLinesInRegion", "(", "foundLines", ".", "get", "(", "gridX", ",", "gridY", ")", ")", ";", "}", "}", "}" ]
Detects line segments through the image inside of grids. @param derivX Image derivative along x-axis. Not modified. @param derivY Image derivative along x-axis. Not modified. @param binaryEdges True values indicate that a pixel is an edge pixel. Not modified.
[ "Detects", "line", "segments", "through", "the", "image", "inside", "of", "grids", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/line/GridRansacLineDetector.java#L104-L129
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java
XmlResponsesSaxParser.parseListBucketObjectsResponse
public ListBucketHandler parseListBucketObjectsResponse(InputStream inputStream, final boolean shouldSDKDecodeResponse) throws IOException { ListBucketHandler handler = new ListBucketHandler(shouldSDKDecodeResponse); parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream)); return handler; }
java
public ListBucketHandler parseListBucketObjectsResponse(InputStream inputStream, final boolean shouldSDKDecodeResponse) throws IOException { ListBucketHandler handler = new ListBucketHandler(shouldSDKDecodeResponse); parseXmlInputStream(handler, sanitizeXmlDocument(handler, inputStream)); return handler; }
[ "public", "ListBucketHandler", "parseListBucketObjectsResponse", "(", "InputStream", "inputStream", ",", "final", "boolean", "shouldSDKDecodeResponse", ")", "throws", "IOException", "{", "ListBucketHandler", "handler", "=", "new", "ListBucketHandler", "(", "shouldSDKDecodeResponse", ")", ";", "parseXmlInputStream", "(", "handler", ",", "sanitizeXmlDocument", "(", "handler", ",", "inputStream", ")", ")", ";", "return", "handler", ";", "}" ]
Parses a ListBucket response XML document from an input stream. @param inputStream XML data input stream. @return the XML handler object populated with data parsed from the XML stream. @throws SdkClientException
[ "Parses", "a", "ListBucket", "response", "XML", "document", "from", "an", "input", "stream", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/transform/XmlResponsesSaxParser.java#L319-L325
mozilla/rhino
src/org/mozilla/javascript/ScriptRuntime.java
ScriptRuntime.toObjectOrNull
@Deprecated public static Scriptable toObjectOrNull(Context cx, Object obj) { if (obj instanceof Scriptable) { return (Scriptable)obj; } else if (obj != null && obj != Undefined.instance) { return toObject(cx, getTopCallScope(cx), obj); } return null; }
java
@Deprecated public static Scriptable toObjectOrNull(Context cx, Object obj) { if (obj instanceof Scriptable) { return (Scriptable)obj; } else if (obj != null && obj != Undefined.instance) { return toObject(cx, getTopCallScope(cx), obj); } return null; }
[ "@", "Deprecated", "public", "static", "Scriptable", "toObjectOrNull", "(", "Context", "cx", ",", "Object", "obj", ")", "{", "if", "(", "obj", "instanceof", "Scriptable", ")", "{", "return", "(", "Scriptable", ")", "obj", ";", "}", "else", "if", "(", "obj", "!=", "null", "&&", "obj", "!=", "Undefined", ".", "instance", ")", "{", "return", "toObject", "(", "cx", ",", "getTopCallScope", "(", "cx", ")", ",", "obj", ")", ";", "}", "return", "null", ";", "}" ]
<strong>Warning</strong>: This doesn't allow to resolve primitive prototype properly when many top scopes are involved @deprecated Use {@link #toObjectOrNull(Context, Object, Scriptable)} instead
[ "<strong", ">", "Warning<", "/", "strong", ">", ":", "This", "doesn", "t", "allow", "to", "resolve", "primitive", "prototype", "properly", "when", "many", "top", "scopes", "are", "involved" ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptRuntime.java#L1068-L1077
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.getRepeated
@Nonnull public static String getRepeated (final char cElement, @Nonnegative final int nRepeats) { ValueEnforcer.isGE0 (nRepeats, "Repeats"); if (nRepeats == 0) return ""; if (nRepeats == 1) return Character.toString (cElement); final char [] aElement = new char [nRepeats]; Arrays.fill (aElement, cElement); return new String (aElement); }
java
@Nonnull public static String getRepeated (final char cElement, @Nonnegative final int nRepeats) { ValueEnforcer.isGE0 (nRepeats, "Repeats"); if (nRepeats == 0) return ""; if (nRepeats == 1) return Character.toString (cElement); final char [] aElement = new char [nRepeats]; Arrays.fill (aElement, cElement); return new String (aElement); }
[ "@", "Nonnull", "public", "static", "String", "getRepeated", "(", "final", "char", "cElement", ",", "@", "Nonnegative", "final", "int", "nRepeats", ")", "{", "ValueEnforcer", ".", "isGE0", "(", "nRepeats", ",", "\"Repeats\"", ")", ";", "if", "(", "nRepeats", "==", "0", ")", "return", "\"\"", ";", "if", "(", "nRepeats", "==", "1", ")", "return", "Character", ".", "toString", "(", "cElement", ")", ";", "final", "char", "[", "]", "aElement", "=", "new", "char", "[", "nRepeats", "]", ";", "Arrays", ".", "fill", "(", "aElement", ",", "cElement", ")", ";", "return", "new", "String", "(", "aElement", ")", ";", "}" ]
Get the passed string element repeated for a certain number of times. Each string element is simply appended at the end of the string. @param cElement The character to get repeated. @param nRepeats The number of repetitions to retrieve. May not be &lt; 0. @return A non-<code>null</code> string containing the string element for the given number of times.
[ "Get", "the", "passed", "string", "element", "repeated", "for", "a", "certain", "number", "of", "times", ".", "Each", "string", "element", "is", "simply", "appended", "at", "the", "end", "of", "the", "string", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2353-L2366
sagiegurari/fax4j
src/main/java/org/fax4j/spi/vbs/VBSFaxClientSpi.java
VBSFaxClientSpi.invokeScript
protected FaxJobStatus invokeScript(FaxJob faxJob,String name,Object[] input,FaxActionType faxActionType) { //generate script String script=this.generateScript(name,input); //invoke script ProcessOutput processOutput=this.invokeScript(script); //validate output this.processOutputValidator.validateProcessOutput(this,processOutput,faxActionType); //handle output FaxJobStatus output=null; switch(faxActionType) { case SUBMIT_FAX_JOB: this.processOutputHandler.updateFaxJob(this,faxJob,processOutput,faxActionType); break; case GET_FAX_JOB_STATUS: output=this.processOutputHandler.getFaxJobStatus(this,processOutput); break; default: //do nothing break; } return output; }
java
protected FaxJobStatus invokeScript(FaxJob faxJob,String name,Object[] input,FaxActionType faxActionType) { //generate script String script=this.generateScript(name,input); //invoke script ProcessOutput processOutput=this.invokeScript(script); //validate output this.processOutputValidator.validateProcessOutput(this,processOutput,faxActionType); //handle output FaxJobStatus output=null; switch(faxActionType) { case SUBMIT_FAX_JOB: this.processOutputHandler.updateFaxJob(this,faxJob,processOutput,faxActionType); break; case GET_FAX_JOB_STATUS: output=this.processOutputHandler.getFaxJobStatus(this,processOutput); break; default: //do nothing break; } return output; }
[ "protected", "FaxJobStatus", "invokeScript", "(", "FaxJob", "faxJob", ",", "String", "name", ",", "Object", "[", "]", "input", ",", "FaxActionType", "faxActionType", ")", "{", "//generate script", "String", "script", "=", "this", ".", "generateScript", "(", "name", ",", "input", ")", ";", "//invoke script", "ProcessOutput", "processOutput", "=", "this", ".", "invokeScript", "(", "script", ")", ";", "//validate output", "this", ".", "processOutputValidator", ".", "validateProcessOutput", "(", "this", ",", "processOutput", ",", "faxActionType", ")", ";", "//handle output", "FaxJobStatus", "output", "=", "null", ";", "switch", "(", "faxActionType", ")", "{", "case", "SUBMIT_FAX_JOB", ":", "this", ".", "processOutputHandler", ".", "updateFaxJob", "(", "this", ",", "faxJob", ",", "processOutput", ",", "faxActionType", ")", ";", "break", ";", "case", "GET_FAX_JOB_STATUS", ":", "output", "=", "this", ".", "processOutputHandler", ".", "getFaxJobStatus", "(", "this", ",", "processOutput", ")", ";", "break", ";", "default", ":", "//do nothing", "break", ";", "}", "return", "output", ";", "}" ]
Invokes the VB script and returns its output. @param faxJob The fax job object containing the needed information @param name The script name @param input The script input @param faxActionType The fax action type @return The fax job status (only for get fax job status action, for others null will be returned)
[ "Invokes", "the", "VB", "script", "and", "returns", "its", "output", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/vbs/VBSFaxClientSpi.java#L620-L647
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
StandardBullhornData.handleDeleteFile
protected FileApiResponse handleDeleteFile(Class<? extends FileEntity> type, Integer entityId, Integer fileId) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesDeleteFile(BullhornEntityInfo.getTypesRestEntityName(type), entityId, fileId); String url = restUrlFactory.assembleDeleteFileUrl(); StandardFileApiResponse fileApiResponse = this.performCustomRequest(url, null, StandardFileApiResponse.class, uriVariables, HttpMethod.DELETE, null); return fileApiResponse; }
java
protected FileApiResponse handleDeleteFile(Class<? extends FileEntity> type, Integer entityId, Integer fileId) { Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesDeleteFile(BullhornEntityInfo.getTypesRestEntityName(type), entityId, fileId); String url = restUrlFactory.assembleDeleteFileUrl(); StandardFileApiResponse fileApiResponse = this.performCustomRequest(url, null, StandardFileApiResponse.class, uriVariables, HttpMethod.DELETE, null); return fileApiResponse; }
[ "protected", "FileApiResponse", "handleDeleteFile", "(", "Class", "<", "?", "extends", "FileEntity", ">", "type", ",", "Integer", "entityId", ",", "Integer", "fileId", ")", "{", "Map", "<", "String", ",", "String", ">", "uriVariables", "=", "restUriVariablesFactory", ".", "getUriVariablesDeleteFile", "(", "BullhornEntityInfo", ".", "getTypesRestEntityName", "(", "type", ")", ",", "entityId", ",", "fileId", ")", ";", "String", "url", "=", "restUrlFactory", ".", "assembleDeleteFileUrl", "(", ")", ";", "StandardFileApiResponse", "fileApiResponse", "=", "this", ".", "performCustomRequest", "(", "url", ",", "null", ",", "StandardFileApiResponse", ".", "class", ",", "uriVariables", ",", "HttpMethod", ".", "DELETE", ",", "null", ")", ";", "return", "fileApiResponse", ";", "}" ]
Makes the api call to delete a file attached to an entity. @param type @param entityId @param fileId @return
[ "Makes", "the", "api", "call", "to", "delete", "a", "file", "attached", "to", "an", "entity", "." ]
train
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L1746-L1754
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/BundlesHandlerFactory.java
BundlesHandlerFactory.getBundleFromName
private JoinableResourceBundle getBundleFromName(String name, List<JoinableResourceBundle> bundles) { JoinableResourceBundle bundle = null; for (JoinableResourceBundle aBundle : bundles) { if (aBundle.getName().equals(name)) { bundle = aBundle; break; } } return bundle; }
java
private JoinableResourceBundle getBundleFromName(String name, List<JoinableResourceBundle> bundles) { JoinableResourceBundle bundle = null; for (JoinableResourceBundle aBundle : bundles) { if (aBundle.getName().equals(name)) { bundle = aBundle; break; } } return bundle; }
[ "private", "JoinableResourceBundle", "getBundleFromName", "(", "String", "name", ",", "List", "<", "JoinableResourceBundle", ">", "bundles", ")", "{", "JoinableResourceBundle", "bundle", "=", "null", ";", "for", "(", "JoinableResourceBundle", "aBundle", ":", "bundles", ")", "{", "if", "(", "aBundle", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "bundle", "=", "aBundle", ";", "break", ";", "}", "}", "return", "bundle", ";", "}" ]
Returns a bundle from its name @param name the bundle name @param bundles the list of bundle @return a bundle from its name
[ "Returns", "a", "bundle", "from", "its", "name" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/BundlesHandlerFactory.java#L453-L464
resilience4j/resilience4j
resilience4j-metrics/src/main/java/io/github/resilience4j/metrics/RateLimiterMetrics.java
RateLimiterMetrics.ofRateLimiterRegistry
public static RateLimiterMetrics ofRateLimiterRegistry(String prefix, RateLimiterRegistry rateLimiterRegistry) { return new RateLimiterMetrics(prefix, rateLimiterRegistry.getAllRateLimiters()); }
java
public static RateLimiterMetrics ofRateLimiterRegistry(String prefix, RateLimiterRegistry rateLimiterRegistry) { return new RateLimiterMetrics(prefix, rateLimiterRegistry.getAllRateLimiters()); }
[ "public", "static", "RateLimiterMetrics", "ofRateLimiterRegistry", "(", "String", "prefix", ",", "RateLimiterRegistry", "rateLimiterRegistry", ")", "{", "return", "new", "RateLimiterMetrics", "(", "prefix", ",", "rateLimiterRegistry", ".", "getAllRateLimiters", "(", ")", ")", ";", "}" ]
Creates a new instance {@link RateLimiterMetrics} with specified metrics names prefix and a {@link RateLimiterRegistry} as a source. @param prefix the prefix of metrics names @param rateLimiterRegistry the registry of rate limiters
[ "Creates", "a", "new", "instance", "{", "@link", "RateLimiterMetrics", "}", "with", "specified", "metrics", "names", "prefix", "and", "a", "{", "@link", "RateLimiterRegistry", "}", "as", "a", "source", "." ]
train
https://github.com/resilience4j/resilience4j/blob/fa843d30f531c00f0c3dc218b65a7f2bb51af336/resilience4j-metrics/src/main/java/io/github/resilience4j/metrics/RateLimiterMetrics.java#L72-L74
foundation-runtime/logging
logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java
TransactionLogger.writePropertiesToLog
protected void writePropertiesToLog(Logger logger, Level level) { writeToLog(logger, level, getMapAsString(this.properties, separator), null); if (this.exception != null) { writeToLog(this.logger, Level.ERROR, "Error:", this.exception); } }
java
protected void writePropertiesToLog(Logger logger, Level level) { writeToLog(logger, level, getMapAsString(this.properties, separator), null); if (this.exception != null) { writeToLog(this.logger, Level.ERROR, "Error:", this.exception); } }
[ "protected", "void", "writePropertiesToLog", "(", "Logger", "logger", ",", "Level", "level", ")", "{", "writeToLog", "(", "logger", ",", "level", ",", "getMapAsString", "(", "this", ".", "properties", ",", "separator", ")", ",", "null", ")", ";", "if", "(", "this", ".", "exception", "!=", "null", ")", "{", "writeToLog", "(", "this", ".", "logger", ",", "Level", ".", "ERROR", ",", "\"Error:\"", ",", "this", ".", "exception", ")", ";", "}", "}" ]
Write 'properties' map to given log in given level - with pipe separator between each entry Write exception stack trace to 'logger' in 'error' level, if not empty @param logger @param level - of logging
[ "Write", "properties", "map", "to", "given", "log", "in", "given", "level", "-", "with", "pipe", "separator", "between", "each", "entry", "Write", "exception", "stack", "trace", "to", "logger", "in", "error", "level", "if", "not", "empty" ]
train
https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-api/src/main/java/com/cisco/oss/foundation/logging/transactions/TransactionLogger.java#L363-L369
protostuff/protostuff
protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java
JsonIOUtil.writeTo
public static <T> void writeTo(JsonGenerator generator, T message, Schema<T> schema, boolean numeric) throws IOException { generator.writeStartObject(); final JsonOutput output = new JsonOutput(generator, numeric, schema); schema.writeTo(output, message); if (output.isLastRepeated()) generator.writeEndArray(); generator.writeEndObject(); }
java
public static <T> void writeTo(JsonGenerator generator, T message, Schema<T> schema, boolean numeric) throws IOException { generator.writeStartObject(); final JsonOutput output = new JsonOutput(generator, numeric, schema); schema.writeTo(output, message); if (output.isLastRepeated()) generator.writeEndArray(); generator.writeEndObject(); }
[ "public", "static", "<", "T", ">", "void", "writeTo", "(", "JsonGenerator", "generator", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ",", "boolean", "numeric", ")", "throws", "IOException", "{", "generator", ".", "writeStartObject", "(", ")", ";", "final", "JsonOutput", "output", "=", "new", "JsonOutput", "(", "generator", ",", "numeric", ",", "schema", ")", ";", "schema", ".", "writeTo", "(", "output", ",", "message", ")", ";", "if", "(", "output", ".", "isLastRepeated", "(", ")", ")", "generator", ".", "writeEndArray", "(", ")", ";", "generator", ".", "writeEndObject", "(", ")", ";", "}" ]
Serializes the {@code message} into a JsonGenerator using the given {@code schema}.
[ "Serializes", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java#L454-L465
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/JobApi.java
JobApi.downloadArtifactsFile
public File downloadArtifactsFile(Object projectIdOrPath, Integer jobId, File directory) throws GitLabApiException { Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts"); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = "job-" + jobId + "-artifacts.zip"; File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }
java
public File downloadArtifactsFile(Object projectIdOrPath, Integer jobId, File directory) throws GitLabApiException { Response response = getWithAccepts(Response.Status.OK, null, MediaType.MEDIA_TYPE_WILDCARD, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts"); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = "job-" + jobId + "-artifacts.zip"; File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }
[ "public", "File", "downloadArtifactsFile", "(", "Object", "projectIdOrPath", ",", "Integer", "jobId", ",", "File", "directory", ")", "throws", "GitLabApiException", "{", "Response", "response", "=", "getWithAccepts", "(", "Response", ".", "Status", ".", "OK", ",", "null", ",", "MediaType", ".", "MEDIA_TYPE_WILDCARD", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"jobs\"", ",", "jobId", ",", "\"artifacts\"", ")", ";", "try", "{", "if", "(", "directory", "==", "null", ")", "directory", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"java.io.tmpdir\"", ")", ")", ";", "String", "filename", "=", "\"job-\"", "+", "jobId", "+", "\"-artifacts.zip\"", ";", "File", "file", "=", "new", "File", "(", "directory", ",", "filename", ")", ";", "InputStream", "in", "=", "response", ".", "readEntity", "(", "InputStream", ".", "class", ")", ";", "Files", ".", "copy", "(", "in", ",", "file", ".", "toPath", "(", ")", ",", "StandardCopyOption", ".", "REPLACE_EXISTING", ")", ";", "return", "(", "file", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "new", "GitLabApiException", "(", "ioe", ")", ";", "}", "}" ]
Download the job artifacts file for the specified job ID. The artifacts file will be saved in the specified directory with the following name pattern: job-{jobid}-artifacts.zip. If the file already exists in the directory it will be overwritten. <pre><code>GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts</code></pre> @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path @param jobId the job ID to get the artifacts for @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" @return a File instance pointing to the download of the specified job artifacts file @throws GitLabApiException if any exception occurs
[ "Download", "the", "job", "artifacts", "file", "for", "the", "specified", "job", "ID", ".", "The", "artifacts", "file", "will", "be", "saved", "in", "the", "specified", "directory", "with", "the", "following", "name", "pattern", ":", "job", "-", "{", "jobid", "}", "-", "artifacts", ".", "zip", ".", "If", "the", "file", "already", "exists", "in", "the", "directory", "it", "will", "be", "overwritten", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/JobApi.java#L267-L286
looly/hutool
hutool-setting/src/main/java/cn/hutool/setting/AbsSetting.java
AbsSetting.getLong
public Long getLong(String key, String group, Long defaultValue) { return Convert.toLong(getByGroup(key, group), defaultValue); }
java
public Long getLong(String key, String group, Long defaultValue) { return Convert.toLong(getByGroup(key, group), defaultValue); }
[ "public", "Long", "getLong", "(", "String", "key", ",", "String", "group", ",", "Long", "defaultValue", ")", "{", "return", "Convert", ".", "toLong", "(", "getByGroup", "(", "key", ",", "group", ")", ",", "defaultValue", ")", ";", "}" ]
获取long类型属性值 @param key 属性名 @param group 分组名 @param defaultValue 默认值 @return 属性值
[ "获取long类型属性值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-setting/src/main/java/cn/hutool/setting/AbsSetting.java#L212-L214
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java
BoxApiFile.getDownloadRequest
public BoxRequestsFile.DownloadFile getDownloadRequest(OutputStream outputStream, String fileId) { BoxRequestsFile.DownloadFile request = new BoxRequestsFile.DownloadFile(fileId, outputStream, getFileDownloadUrl(fileId),mSession); return request; }
java
public BoxRequestsFile.DownloadFile getDownloadRequest(OutputStream outputStream, String fileId) { BoxRequestsFile.DownloadFile request = new BoxRequestsFile.DownloadFile(fileId, outputStream, getFileDownloadUrl(fileId),mSession); return request; }
[ "public", "BoxRequestsFile", ".", "DownloadFile", "getDownloadRequest", "(", "OutputStream", "outputStream", ",", "String", "fileId", ")", "{", "BoxRequestsFile", ".", "DownloadFile", "request", "=", "new", "BoxRequestsFile", ".", "DownloadFile", "(", "fileId", ",", "outputStream", ",", "getFileDownloadUrl", "(", "fileId", ")", ",", "mSession", ")", ";", "return", "request", ";", "}" ]
Gets a request that downloads the given file to the provided outputStream. Developer is responsible for closing the outputStream provided. @param outputStream outputStream to write file contents to. @param fileId the file id to download. @return request to download a file to an output stream
[ "Gets", "a", "request", "that", "downloads", "the", "given", "file", "to", "the", "provided", "outputStream", ".", "Developer", "is", "responsible", "for", "closing", "the", "outputStream", "provided", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L398-L401
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
RedisInner.getByResourceGroupAsync
public Observable<RedisResourceInner> getByResourceGroupAsync(String resourceGroupName, String name) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() { @Override public RedisResourceInner call(ServiceResponse<RedisResourceInner> response) { return response.body(); } }); }
java
public Observable<RedisResourceInner> getByResourceGroupAsync(String resourceGroupName, String name) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() { @Override public RedisResourceInner call(ServiceResponse<RedisResourceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RedisResourceInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "name", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RedisResourceInner", ">", ",", "RedisResourceInner", ">", "(", ")", "{", "@", "Override", "public", "RedisResourceInner", "call", "(", "ServiceResponse", "<", "RedisResourceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets a Redis cache (resource description). @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the RedisResourceInner object
[ "Gets", "a", "Redis", "cache", "(", "resource", "description", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L779-L786
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java
CoronaTaskLauncher.killTasks
public void killTasks( String trackerName, InetAddress addr, List<KillTaskAction> killActions) { for (KillTaskAction killAction : killActions) { String description = "KillTaskAction " + killAction.getTaskID(); LOG.info("Queueing " + description + " to worker " + trackerName + "(" + addr.host + ":" + addr.port + ")"); allWorkQueues.enqueueAction( new ActionToSend(trackerName, addr, killAction, description)); } }
java
public void killTasks( String trackerName, InetAddress addr, List<KillTaskAction> killActions) { for (KillTaskAction killAction : killActions) { String description = "KillTaskAction " + killAction.getTaskID(); LOG.info("Queueing " + description + " to worker " + trackerName + "(" + addr.host + ":" + addr.port + ")"); allWorkQueues.enqueueAction( new ActionToSend(trackerName, addr, killAction, description)); } }
[ "public", "void", "killTasks", "(", "String", "trackerName", ",", "InetAddress", "addr", ",", "List", "<", "KillTaskAction", ">", "killActions", ")", "{", "for", "(", "KillTaskAction", "killAction", ":", "killActions", ")", "{", "String", "description", "=", "\"KillTaskAction \"", "+", "killAction", ".", "getTaskID", "(", ")", ";", "LOG", ".", "info", "(", "\"Queueing \"", "+", "description", "+", "\" to worker \"", "+", "trackerName", "+", "\"(\"", "+", "addr", ".", "host", "+", "\":\"", "+", "addr", ".", "port", "+", "\")\"", ")", ";", "allWorkQueues", ".", "enqueueAction", "(", "new", "ActionToSend", "(", "trackerName", ",", "addr", ",", "killAction", ",", "description", ")", ")", ";", "}", "}" ]
Enqueue kill tasks actions. @param trackerName The name of the tracker to send the kill actions to. @param addr The address of the tracker to send the kill actions to. @param killActions The kill actions to send.
[ "Enqueue", "kill", "tasks", "actions", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/CoronaTaskLauncher.java#L112-L121
stripe/stripe-java
src/main/java/com/stripe/model/Order.java
Order.returnOrder
public OrderReturn returnOrder(Map<String, Object> params) throws StripeException { return returnOrder(params, (RequestOptions) null); }
java
public OrderReturn returnOrder(Map<String, Object> params) throws StripeException { return returnOrder(params, (RequestOptions) null); }
[ "public", "OrderReturn", "returnOrder", "(", "Map", "<", "String", ",", "Object", ">", "params", ")", "throws", "StripeException", "{", "return", "returnOrder", "(", "params", ",", "(", "RequestOptions", ")", "null", ")", ";", "}" ]
Return all or part of an order. The order must have a status of <code>paid</code> or <code> fulfilled</code> before it can be returned. Once all items have been returned, the order will become <code>canceled</code> or <code>returned</code> depending on which status the order started in.
[ "Return", "all", "or", "part", "of", "an", "order", ".", "The", "order", "must", "have", "a", "status", "of", "<code", ">", "paid<", "/", "code", ">", "or", "<code", ">", "fulfilled<", "/", "code", ">", "before", "it", "can", "be", "returned", ".", "Once", "all", "items", "have", "been", "returned", "the", "order", "will", "become", "<code", ">", "canceled<", "/", "code", ">", "or", "<code", ">", "returned<", "/", "code", ">", "depending", "on", "which", "status", "the", "order", "started", "in", "." ]
train
https://github.com/stripe/stripe-java/blob/acfa8becef3e73bfe3e9d8880bea3f3f30dadeac/src/main/java/com/stripe/model/Order.java#L394-L396
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
StrBuilder.appendPadding
public StrBuilder appendPadding(final int length, final char padChar) { if (length >= 0) { ensureCapacity(size + length); for (int i = 0; i < length; i++) { buffer[size++] = padChar; } } return this; }
java
public StrBuilder appendPadding(final int length, final char padChar) { if (length >= 0) { ensureCapacity(size + length); for (int i = 0; i < length; i++) { buffer[size++] = padChar; } } return this; }
[ "public", "StrBuilder", "appendPadding", "(", "final", "int", "length", ",", "final", "char", "padChar", ")", "{", "if", "(", "length", ">=", "0", ")", "{", "ensureCapacity", "(", "size", "+", "length", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "buffer", "[", "size", "++", "]", "=", "padChar", ";", "}", "}", "return", "this", ";", "}" ]
Appends the pad character to the builder the specified number of times. @param length the length to append, negative means no append @param padChar the character to append @return this, to enable chaining
[ "Appends", "the", "pad", "character", "to", "the", "builder", "the", "specified", "number", "of", "times", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L1480-L1488
unbescape/unbescape
src/main/java/org/unbescape/xml/XmlEscape.java
XmlEscape.escapeXml11AttributeMinimal
public static void escapeXml11AttributeMinimal(final Reader reader, final Writer writer) throws IOException { escapeXml(reader, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_1_ONLY_MARKUP_SIGNIFICANT); }
java
public static void escapeXml11AttributeMinimal(final Reader reader, final Writer writer) throws IOException { escapeXml(reader, writer, XmlEscapeSymbols.XML11_ATTRIBUTE_SYMBOLS, XmlEscapeType.CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA, XmlEscapeLevel.LEVEL_1_ONLY_MARKUP_SIGNIFICANT); }
[ "public", "static", "void", "escapeXml11AttributeMinimal", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeXml", "(", "reader", ",", "writer", ",", "XmlEscapeSymbols", ".", "XML11_ATTRIBUTE_SYMBOLS", ",", "XmlEscapeType", ".", "CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA", ",", "XmlEscapeLevel", ".", "LEVEL_1_ONLY_MARKUP_SIGNIFICANT", ")", ";", "}" ]
<p> Perform an XML 1.1 level 1 (only markup-significant chars) <strong>escape</strong> operation on a <tt>Reader</tt> input meant to be an XML attribute value, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 1</em> means this method will only escape the five markup-significant characters which are <em>predefined</em> as Character Entity References in XML: <tt>&lt;</tt>, <tt>&gt;</tt>, <tt>&amp;</tt>, <tt>&quot;</tt> and <tt>&#39;</tt>. </p> <p> Besides, being an attribute value also <tt>&#92;t</tt>, <tt>&#92;n</tt> and <tt>&#92;r</tt> will be escaped to avoid white-space normalization from removing line feeds (turning them into white spaces) during future parsing operations. </p> <p> This method calls {@link #escapeXml11(Reader, Writer, XmlEscapeType, XmlEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link org.unbescape.xml.XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA}</li> <li><tt>level</tt>: {@link org.unbescape.xml.XmlEscapeLevel#LEVEL_1_ONLY_MARKUP_SIGNIFICANT}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.5
[ "<p", ">", "Perform", "an", "XML", "1", ".", "1", "level", "1", "(", "only", "markup", "-", "significant", "chars", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "tt", ">", "input", "meant", "to", "be", "an", "XML", "attribute", "value", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "<em", ">", "Level", "1<", "/", "em", ">", "means", "this", "method", "will", "only", "escape", "the", "five", "markup", "-", "significant", "characters", "which", "are", "<em", ">", "predefined<", "/", "em", ">", "as", "Character", "Entity", "References", "in", "XML", ":", "<tt", ">", "&lt", ";", "<", "/", "tt", ">", "<tt", ">", "&gt", ";", "<", "/", "tt", ">", "<tt", ">", "&amp", ";", "<", "/", "tt", ">", "<tt", ">", "&quot", ";", "<", "/", "tt", ">", "and", "<tt", ">", "&#39", ";", "<", "/", "tt", ">", ".", "<", "/", "p", ">", "<p", ">", "Besides", "being", "an", "attribute", "value", "also", "<tt", ">", "&#92", ";", "t<", "/", "tt", ">", "<tt", ">", "&#92", ";", "n<", "/", "tt", ">", "and", "<tt", ">", "&#92", ";", "r<", "/", "tt", ">", "will", "be", "escaped", "to", "avoid", "white", "-", "space", "normalization", "from", "removing", "line", "feeds", "(", "turning", "them", "into", "white", "spaces", ")", "during", "future", "parsing", "operations", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "calls", "{", "@link", "#escapeXml11", "(", "Reader", "Writer", "XmlEscapeType", "XmlEscapeLevel", ")", "}", "with", "the", "following", "preconfigured", "values", ":", "<", "/", "p", ">", "<ul", ">", "<li", ">", "<tt", ">", "type<", "/", "tt", ">", ":", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeType#CHARACTER_ENTITY_REFERENCES_DEFAULT_TO_HEXA", "}", "<", "/", "li", ">", "<li", ">", "<tt", ">", "level<", "/", "tt", ">", ":", "{", "@link", "org", ".", "unbescape", ".", "xml", ".", "XmlEscapeLevel#LEVEL_1_ONLY_MARKUP_SIGNIFICANT", "}", "<", "/", "li", ">", "<", "/", "ul", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread", "-", "safe<", "/", "strong", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/xml/XmlEscape.java#L1356-L1361
alkacon/opencms-core
src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorModel.java
CmsMessageBundleEditorModel.saveToPropertyVfsBundle
private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, f.getEncoding()); props.store(writer, null); byte[] contentBytes = outputStream.toByteArray(); CmsFile file = f.getFile(); file.setContents(contentBytes); String contentEncodingProperty = m_cms.readPropertyObject( file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(); if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) { m_cms.writePropertyObject( m_cms.getSitePath(file), new CmsProperty( CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, f.getEncoding(), f.getEncoding())); } m_cms.writeFile(file); } catch (IOException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2, f.getFile().getRootPath(), f.getEncoding()), e); } } } }
java
private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, f.getEncoding()); props.store(writer, null); byte[] contentBytes = outputStream.toByteArray(); CmsFile file = f.getFile(); file.setContents(contentBytes); String contentEncodingProperty = m_cms.readPropertyObject( file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(); if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) { m_cms.writePropertyObject( m_cms.getSitePath(file), new CmsProperty( CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, f.getEncoding(), f.getEncoding())); } m_cms.writeFile(file); } catch (IOException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2, f.getFile().getRootPath(), f.getEncoding()), e); } } } }
[ "private", "void", "saveToPropertyVfsBundle", "(", ")", "throws", "CmsException", "{", "for", "(", "Locale", "l", ":", "m_changedTranslations", ")", "{", "SortedProperties", "props", "=", "m_localizations", ".", "get", "(", "l", ")", ";", "LockedFile", "f", "=", "m_lockedBundleFiles", ".", "get", "(", "l", ")", ";", "if", "(", "(", "null", "!=", "props", ")", "&&", "(", "null", "!=", "f", ")", ")", "{", "try", "{", "ByteArrayOutputStream", "outputStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "Writer", "writer", "=", "new", "OutputStreamWriter", "(", "outputStream", ",", "f", ".", "getEncoding", "(", ")", ")", ";", "props", ".", "store", "(", "writer", ",", "null", ")", ";", "byte", "[", "]", "contentBytes", "=", "outputStream", ".", "toByteArray", "(", ")", ";", "CmsFile", "file", "=", "f", ".", "getFile", "(", ")", ";", "file", ".", "setContents", "(", "contentBytes", ")", ";", "String", "contentEncodingProperty", "=", "m_cms", ".", "readPropertyObject", "(", "file", ",", "CmsPropertyDefinition", ".", "PROPERTY_CONTENT_ENCODING", ",", "false", ")", ".", "getValue", "(", ")", ";", "if", "(", "(", "null", "==", "contentEncodingProperty", ")", "||", "!", "contentEncodingProperty", ".", "equals", "(", "f", ".", "getEncoding", "(", ")", ")", ")", "{", "m_cms", ".", "writePropertyObject", "(", "m_cms", ".", "getSitePath", "(", "file", ")", ",", "new", "CmsProperty", "(", "CmsPropertyDefinition", ".", "PROPERTY_CONTENT_ENCODING", ",", "f", ".", "getEncoding", "(", ")", ",", "f", ".", "getEncoding", "(", ")", ")", ")", ";", "}", "m_cms", ".", "writeFile", "(", "file", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "ERR_READING_FILE_UNSUPPORTED_ENCODING_2", ",", "f", ".", "getFile", "(", ")", ".", "getRootPath", "(", ")", ",", "f", ".", "getEncoding", "(", ")", ")", ",", "e", ")", ";", "}", "}", "}", "}" ]
Saves messages to a propertyvfsbundle file. @throws CmsException thrown if writing to the file fails.
[ "Saves", "messages", "to", "a", "propertyvfsbundle", "file", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/editors/messagebundle/CmsMessageBundleEditorModel.java#L1830-L1867
blackfizz/EazeGraph
EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/BaseBarChart.java
BaseBarChart.calculateBarPositions
protected void calculateBarPositions(int _DataSize) { int dataSize = mScrollEnabled ? mVisibleBars : _DataSize; float barWidth = mBarWidth; float margin = mBarMargin; if (!mFixedBarWidth) { // calculate the bar width if the bars should be dynamically displayed barWidth = (mAvailableScreenSize / _DataSize) - margin; } else { if(_DataSize < mVisibleBars) { dataSize = _DataSize; } // calculate margin between bars if the bars have a fixed width float cumulatedBarWidths = barWidth * dataSize; float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths; margin = remainingScreenSize / dataSize; } boolean isVertical = this instanceof VerticalBarChart; int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize)); int contentWidth = isVertical ? mGraphWidth : calculatedSize; int contentHeight = isVertical ? calculatedSize : mGraphHeight; mContentRect = new Rect(0, 0, contentWidth, contentHeight); mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight); calculateBounds(barWidth, margin); mLegend.invalidate(); mGraph.invalidate(); }
java
protected void calculateBarPositions(int _DataSize) { int dataSize = mScrollEnabled ? mVisibleBars : _DataSize; float barWidth = mBarWidth; float margin = mBarMargin; if (!mFixedBarWidth) { // calculate the bar width if the bars should be dynamically displayed barWidth = (mAvailableScreenSize / _DataSize) - margin; } else { if(_DataSize < mVisibleBars) { dataSize = _DataSize; } // calculate margin between bars if the bars have a fixed width float cumulatedBarWidths = barWidth * dataSize; float remainingScreenSize = mAvailableScreenSize - cumulatedBarWidths; margin = remainingScreenSize / dataSize; } boolean isVertical = this instanceof VerticalBarChart; int calculatedSize = (int) ((barWidth * _DataSize) + (margin * _DataSize)); int contentWidth = isVertical ? mGraphWidth : calculatedSize; int contentHeight = isVertical ? calculatedSize : mGraphHeight; mContentRect = new Rect(0, 0, contentWidth, contentHeight); mCurrentViewport = new RectF(0, 0, mGraphWidth, mGraphHeight); calculateBounds(barWidth, margin); mLegend.invalidate(); mGraph.invalidate(); }
[ "protected", "void", "calculateBarPositions", "(", "int", "_DataSize", ")", "{", "int", "dataSize", "=", "mScrollEnabled", "?", "mVisibleBars", ":", "_DataSize", ";", "float", "barWidth", "=", "mBarWidth", ";", "float", "margin", "=", "mBarMargin", ";", "if", "(", "!", "mFixedBarWidth", ")", "{", "// calculate the bar width if the bars should be dynamically displayed", "barWidth", "=", "(", "mAvailableScreenSize", "/", "_DataSize", ")", "-", "margin", ";", "}", "else", "{", "if", "(", "_DataSize", "<", "mVisibleBars", ")", "{", "dataSize", "=", "_DataSize", ";", "}", "// calculate margin between bars if the bars have a fixed width", "float", "cumulatedBarWidths", "=", "barWidth", "*", "dataSize", ";", "float", "remainingScreenSize", "=", "mAvailableScreenSize", "-", "cumulatedBarWidths", ";", "margin", "=", "remainingScreenSize", "/", "dataSize", ";", "}", "boolean", "isVertical", "=", "this", "instanceof", "VerticalBarChart", ";", "int", "calculatedSize", "=", "(", "int", ")", "(", "(", "barWidth", "*", "_DataSize", ")", "+", "(", "margin", "*", "_DataSize", ")", ")", ";", "int", "contentWidth", "=", "isVertical", "?", "mGraphWidth", ":", "calculatedSize", ";", "int", "contentHeight", "=", "isVertical", "?", "calculatedSize", ":", "mGraphHeight", ";", "mContentRect", "=", "new", "Rect", "(", "0", ",", "0", ",", "contentWidth", ",", "contentHeight", ")", ";", "mCurrentViewport", "=", "new", "RectF", "(", "0", ",", "0", ",", "mGraphWidth", ",", "mGraphHeight", ")", ";", "calculateBounds", "(", "barWidth", ",", "margin", ")", ";", "mLegend", ".", "invalidate", "(", ")", ";", "mGraph", ".", "invalidate", "(", ")", ";", "}" ]
Calculates the bar width and bar margin based on the _DataSize and settings and starts the boundary calculation in child classes. @param _DataSize Amount of data sets
[ "Calculates", "the", "bar", "width", "and", "bar", "margin", "based", "on", "the", "_DataSize", "and", "settings", "and", "starts", "the", "boundary", "calculation", "in", "child", "classes", "." ]
train
https://github.com/blackfizz/EazeGraph/blob/ce5e68ecc70e154f83bbb2fcce1a970db125c1e6/EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/BaseBarChart.java#L322-L356
ggrandes/packer
src/main/java/org/javastack/packer/Packer.java
Packer.useRSA
public Packer useRSA(final Key rsaKeyForEncrypt, final Key rsaKeyForDecrypt) throws NoSuchAlgorithmException, NoSuchPaddingException { this.rsaCipher = Cipher.getInstance(ASYM_CIPHER_CHAIN_PADDING); this.rsaKeyForEncrypt = rsaKeyForEncrypt; this.rsaKeyForDecrypt = rsaKeyForDecrypt; return this; }
java
public Packer useRSA(final Key rsaKeyForEncrypt, final Key rsaKeyForDecrypt) throws NoSuchAlgorithmException, NoSuchPaddingException { this.rsaCipher = Cipher.getInstance(ASYM_CIPHER_CHAIN_PADDING); this.rsaKeyForEncrypt = rsaKeyForEncrypt; this.rsaKeyForDecrypt = rsaKeyForDecrypt; return this; }
[ "public", "Packer", "useRSA", "(", "final", "Key", "rsaKeyForEncrypt", ",", "final", "Key", "rsaKeyForDecrypt", ")", "throws", "NoSuchAlgorithmException", ",", "NoSuchPaddingException", "{", "this", ".", "rsaCipher", "=", "Cipher", ".", "getInstance", "(", "ASYM_CIPHER_CHAIN_PADDING", ")", ";", "this", ".", "rsaKeyForEncrypt", "=", "rsaKeyForEncrypt", ";", "this", ".", "rsaKeyForDecrypt", "=", "rsaKeyForDecrypt", ";", "return", "this", ";", "}" ]
Sets he usage of "RSA/ECB/PKCS1Padding" for encryption (default no) @param rsaKeyForEncrypt @param rsaKeyForDecrypt @return @throws NoSuchPaddingException @throws NoSuchAlgorithmException
[ "Sets", "he", "usage", "of", "RSA", "/", "ECB", "/", "PKCS1Padding", "for", "encryption", "(", "default", "no", ")" ]
train
https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L476-L482
visenze/visearch-sdk-java
src/main/java/com/visenze/visearch/ViSearch.java
ViSearch.insertStatus
@Override public InsertStatus insertStatus(String transId, Map<String, String> customParams) { return dataOperations.insertStatus(transId, customParams); }
java
@Override public InsertStatus insertStatus(String transId, Map<String, String> customParams) { return dataOperations.insertStatus(transId, customParams); }
[ "@", "Override", "public", "InsertStatus", "insertStatus", "(", "String", "transId", ",", "Map", "<", "String", ",", "String", ">", "customParams", ")", "{", "return", "dataOperations", ".", "insertStatus", "(", "transId", ",", "customParams", ")", ";", "}" ]
(For testing) Get insert status by insert trans id. @param transId the id of the insert trans. @return the insert trans
[ "(", "For", "testing", ")", "Get", "insert", "status", "by", "insert", "trans", "id", "." ]
train
https://github.com/visenze/visearch-sdk-java/blob/133611b84a7489f08bf40b55912ccd2acc7f002c/src/main/java/com/visenze/visearch/ViSearch.java#L171-L174
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbBlob.java
MariaDbBlob.setBytes
public int setBytes(final long pos, final byte[] bytes) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("pos should be > 0, first position is 1."); } final int arrayPos = (int) pos - 1; if (length > arrayPos + bytes.length) { System.arraycopy(bytes, 0, data, offset + arrayPos, bytes.length); } else { byte[] newContent = new byte[arrayPos + bytes.length]; if (Math.min(arrayPos, length) > 0) { System.arraycopy(data, this.offset, newContent, 0, Math.min(arrayPos, length)); } System.arraycopy(bytes, 0, newContent, arrayPos, bytes.length); data = newContent; length = arrayPos + bytes.length; offset = 0; } return bytes.length; }
java
public int setBytes(final long pos, final byte[] bytes) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("pos should be > 0, first position is 1."); } final int arrayPos = (int) pos - 1; if (length > arrayPos + bytes.length) { System.arraycopy(bytes, 0, data, offset + arrayPos, bytes.length); } else { byte[] newContent = new byte[arrayPos + bytes.length]; if (Math.min(arrayPos, length) > 0) { System.arraycopy(data, this.offset, newContent, 0, Math.min(arrayPos, length)); } System.arraycopy(bytes, 0, newContent, arrayPos, bytes.length); data = newContent; length = arrayPos + bytes.length; offset = 0; } return bytes.length; }
[ "public", "int", "setBytes", "(", "final", "long", "pos", ",", "final", "byte", "[", "]", "bytes", ")", "throws", "SQLException", "{", "if", "(", "pos", "<", "1", ")", "{", "throw", "ExceptionMapper", ".", "getSqlException", "(", "\"pos should be > 0, first position is 1.\"", ")", ";", "}", "final", "int", "arrayPos", "=", "(", "int", ")", "pos", "-", "1", ";", "if", "(", "length", ">", "arrayPos", "+", "bytes", ".", "length", ")", "{", "System", ".", "arraycopy", "(", "bytes", ",", "0", ",", "data", ",", "offset", "+", "arrayPos", ",", "bytes", ".", "length", ")", ";", "}", "else", "{", "byte", "[", "]", "newContent", "=", "new", "byte", "[", "arrayPos", "+", "bytes", ".", "length", "]", ";", "if", "(", "Math", ".", "min", "(", "arrayPos", ",", "length", ")", ">", "0", ")", "{", "System", ".", "arraycopy", "(", "data", ",", "this", ".", "offset", ",", "newContent", ",", "0", ",", "Math", ".", "min", "(", "arrayPos", ",", "length", ")", ")", ";", "}", "System", ".", "arraycopy", "(", "bytes", ",", "0", ",", "newContent", ",", "arrayPos", ",", "bytes", ".", "length", ")", ";", "data", "=", "newContent", ";", "length", "=", "arrayPos", "+", "bytes", ".", "length", ";", "offset", "=", "0", ";", "}", "return", "bytes", ".", "length", ";", "}" ]
Writes the given array of bytes to the <code>BLOB</code> value that this <code>Blob</code> object represents, starting at position <code>pos</code>, and returns the number of bytes written. The array of bytes will overwrite the existing bytes in the <code>Blob</code> object starting at the position <code>pos</code>. If the end of the <code>Blob</code> value is reached while writing the array of bytes, then the length of the <code>Blob</code> value will be increased to accommodate the extra bytes. @param pos the position in the <code>BLOB</code> object at which to start writing; the first position is 1 @param bytes the array of bytes to be written to the <code>BLOB</code> value that this <code>Blob</code> object represents @return the number of bytes written @see #getBytes
[ "Writes", "the", "given", "array", "of", "bytes", "to", "the", "<code", ">", "BLOB<", "/", "code", ">", "value", "that", "this", "<code", ">", "Blob<", "/", "code", ">", "object", "represents", "starting", "at", "position", "<code", ">", "pos<", "/", "code", ">", "and", "returns", "the", "number", "of", "bytes", "written", ".", "The", "array", "of", "bytes", "will", "overwrite", "the", "existing", "bytes", "in", "the", "<code", ">", "Blob<", "/", "code", ">", "object", "starting", "at", "the", "position", "<code", ">", "pos<", "/", "code", ">", ".", "If", "the", "end", "of", "the", "<code", ">", "Blob<", "/", "code", ">", "value", "is", "reached", "while", "writing", "the", "array", "of", "bytes", "then", "the", "length", "of", "the", "<code", ">", "Blob<", "/", "code", ">", "value", "will", "be", "increased", "to", "accommodate", "the", "extra", "bytes", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbBlob.java#L279-L303
amzn/ion-java
src/com/amazon/ion/impl/UnifiedInputStreamX.java
UnifiedInputStreamX.read
public final int read(byte[] dst, int offset, int length) throws IOException { if (!is_byte_data()) { throw new IOException("byte read is not support over character sources"); } int remaining = length; while (remaining > 0 && !isEOF()) { int ready = _limit - _pos; if (ready > remaining) { ready = remaining; } System.arraycopy(_bytes, _pos, dst, offset, ready); _pos += ready; offset += ready; remaining -= ready; if (remaining == 0 || _pos < _limit || refill_helper()) { break; } } return length - remaining; }
java
public final int read(byte[] dst, int offset, int length) throws IOException { if (!is_byte_data()) { throw new IOException("byte read is not support over character sources"); } int remaining = length; while (remaining > 0 && !isEOF()) { int ready = _limit - _pos; if (ready > remaining) { ready = remaining; } System.arraycopy(_bytes, _pos, dst, offset, ready); _pos += ready; offset += ready; remaining -= ready; if (remaining == 0 || _pos < _limit || refill_helper()) { break; } } return length - remaining; }
[ "public", "final", "int", "read", "(", "byte", "[", "]", "dst", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "if", "(", "!", "is_byte_data", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"byte read is not support over character sources\"", ")", ";", "}", "int", "remaining", "=", "length", ";", "while", "(", "remaining", ">", "0", "&&", "!", "isEOF", "(", ")", ")", "{", "int", "ready", "=", "_limit", "-", "_pos", ";", "if", "(", "ready", ">", "remaining", ")", "{", "ready", "=", "remaining", ";", "}", "System", ".", "arraycopy", "(", "_bytes", ",", "_pos", ",", "dst", ",", "offset", ",", "ready", ")", ";", "_pos", "+=", "ready", ";", "offset", "+=", "ready", ";", "remaining", "-=", "ready", ";", "if", "(", "remaining", "==", "0", "||", "_pos", "<", "_limit", "||", "refill_helper", "(", ")", ")", "{", "break", ";", "}", "}", "return", "length", "-", "remaining", ";", "}" ]
It is unclear what the implication to the rest of the system to make it 'conform'
[ "It", "is", "unclear", "what", "the", "implication", "to", "the", "rest", "of", "the", "system", "to", "make", "it", "conform" ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/UnifiedInputStreamX.java#L365-L385
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.setTimePicker
public void setTimePicker(TimePicker timePicker, int hour, int minute) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "setTimePicker("+timePicker+", "+hour+", "+minute+")"); } timePicker = (TimePicker) waiter.waitForView(timePicker, Timeout.getSmallTimeout()); setter.setTimePicker(timePicker, hour, minute); }
java
public void setTimePicker(TimePicker timePicker, int hour, int minute) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "setTimePicker("+timePicker+", "+hour+", "+minute+")"); } timePicker = (TimePicker) waiter.waitForView(timePicker, Timeout.getSmallTimeout()); setter.setTimePicker(timePicker, hour, minute); }
[ "public", "void", "setTimePicker", "(", "TimePicker", "timePicker", ",", "int", "hour", ",", "int", "minute", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"setTimePicker(\"", "+", "timePicker", "+", "\", \"", "+", "hour", "+", "\", \"", "+", "minute", "+", "\")\"", ")", ";", "}", "timePicker", "=", "(", "TimePicker", ")", "waiter", ".", "waitForView", "(", "timePicker", ",", "Timeout", ".", "getSmallTimeout", "(", ")", ")", ";", "setter", ".", "setTimePicker", "(", "timePicker", ",", "hour", ",", "minute", ")", ";", "}" ]
Sets the time in the specified TimePicker. @param timePicker the {@link TimePicker} object @param hour the hour e.g. 15 @param minute the minute e.g. 30
[ "Sets", "the", "time", "in", "the", "specified", "TimePicker", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2571-L2578
hltcoe/annotated-nyt
src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java
NYTCorpusDocumentParser.getDOMObject
private Document getDOMObject(InputStream is, boolean validating) throws SAXException, IOException, ParserConfigurationException { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (!validating) { factory.setValidating(validating); factory.setSchema(null); factory.setNamespaceAware(false); } DocumentBuilder builder = factory.newDocumentBuilder(); // Create the builder and parse the file Document doc = builder.parse(is); return doc; }
java
private Document getDOMObject(InputStream is, boolean validating) throws SAXException, IOException, ParserConfigurationException { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (!validating) { factory.setValidating(validating); factory.setSchema(null); factory.setNamespaceAware(false); } DocumentBuilder builder = factory.newDocumentBuilder(); // Create the builder and parse the file Document doc = builder.parse(is); return doc; }
[ "private", "Document", "getDOMObject", "(", "InputStream", "is", ",", "boolean", "validating", ")", "throws", "SAXException", ",", "IOException", ",", "ParserConfigurationException", "{", "// Create a builder factory", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "if", "(", "!", "validating", ")", "{", "factory", ".", "setValidating", "(", "validating", ")", ";", "factory", ".", "setSchema", "(", "null", ")", ";", "factory", ".", "setNamespaceAware", "(", "false", ")", ";", "}", "DocumentBuilder", "builder", "=", "factory", ".", "newDocumentBuilder", "(", ")", ";", "// Create the builder and parse the file", "Document", "doc", "=", "builder", ".", "parse", "(", "is", ")", ";", "return", "doc", ";", "}" ]
Parse an {@link InputStream} containing an XML document, into a DOM object. @param is An {@link InputStream} representing an xml file. @param validating True iff validating should be turned on. @return A DOM Object containing a parsed XML document or a null value if there is an error in parsing. @throws ParserConfigurationException @throws IOException @throws SAXException
[ "Parse", "an", "{", "@link", "InputStream", "}", "containing", "an", "XML", "document", "into", "a", "DOM", "object", "." ]
train
https://github.com/hltcoe/annotated-nyt/blob/0a4daa97705591cefea9de61614770ae2665a48e/src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java#L464-L480
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/FirewallRulesInner.java
FirewallRulesInner.createOrUpdate
public FirewallRuleInner createOrUpdate(String resourceGroupName, String serverName, String firewallRuleName, FirewallRuleInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, firewallRuleName, parameters).toBlocking().single().body(); }
java
public FirewallRuleInner createOrUpdate(String resourceGroupName, String serverName, String firewallRuleName, FirewallRuleInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, firewallRuleName, parameters).toBlocking().single().body(); }
[ "public", "FirewallRuleInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "firewallRuleName", ",", "FirewallRuleInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "firewallRuleName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a firewall rule. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param firewallRuleName The name of the firewall rule. @param parameters The required parameters for creating or updating a firewall rule. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the FirewallRuleInner object if successful.
[ "Creates", "or", "updates", "a", "firewall", "rule", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/FirewallRulesInner.java#L89-L91
opentelecoms-org/jsmpp
jsmpp-examples/src/main/java/org/jsmpp/examples/gateway/AutoReconnectGateway.java
AutoReconnectGateway.newSession
private SMPPSession newSession() throws IOException { SMPPSession tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam); tmpSession.addSessionStateListener(new SessionStateListenerImpl()); return tmpSession; }
java
private SMPPSession newSession() throws IOException { SMPPSession tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam); tmpSession.addSessionStateListener(new SessionStateListenerImpl()); return tmpSession; }
[ "private", "SMPPSession", "newSession", "(", ")", "throws", "IOException", "{", "SMPPSession", "tmpSession", "=", "new", "SMPPSession", "(", "remoteIpAddress", ",", "remotePort", ",", "bindParam", ")", ";", "tmpSession", ".", "addSessionStateListener", "(", "new", "SessionStateListenerImpl", "(", ")", ")", ";", "return", "tmpSession", ";", "}" ]
Create new {@link SMPPSession} complete with the {@link SessionStateListenerImpl}. @return the {@link SMPPSession}. @throws IOException if the creation of new session failed.
[ "Create", "new", "{", "@link", "SMPPSession", "}", "complete", "with", "the", "{", "@link", "SessionStateListenerImpl", "}", "." ]
train
https://github.com/opentelecoms-org/jsmpp/blob/acc15e73e7431deabc803731971b15323315baaf/jsmpp-examples/src/main/java/org/jsmpp/examples/gateway/AutoReconnectGateway.java#L110-L114
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/network/NetworkCache.java
NetworkCache.writeTempCacheFile
File writeTempCacheFile(InputStream stream, FileExtension extension) throws IOException { String fileName = filenameForUrl(url, extension, true); File file = new File(appContext.getCacheDir(), fileName); try { OutputStream output = new FileOutputStream(file); //noinspection TryFinallyCanBeTryWithResources try { byte[] buffer = new byte[1024]; int read; while ((read = stream.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); } } finally { stream.close(); } return file; }
java
File writeTempCacheFile(InputStream stream, FileExtension extension) throws IOException { String fileName = filenameForUrl(url, extension, true); File file = new File(appContext.getCacheDir(), fileName); try { OutputStream output = new FileOutputStream(file); //noinspection TryFinallyCanBeTryWithResources try { byte[] buffer = new byte[1024]; int read; while ((read = stream.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); } } finally { stream.close(); } return file; }
[ "File", "writeTempCacheFile", "(", "InputStream", "stream", ",", "FileExtension", "extension", ")", "throws", "IOException", "{", "String", "fileName", "=", "filenameForUrl", "(", "url", ",", "extension", ",", "true", ")", ";", "File", "file", "=", "new", "File", "(", "appContext", ".", "getCacheDir", "(", ")", ",", "fileName", ")", ";", "try", "{", "OutputStream", "output", "=", "new", "FileOutputStream", "(", "file", ")", ";", "//noinspection TryFinallyCanBeTryWithResources", "try", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "1024", "]", ";", "int", "read", ";", "while", "(", "(", "read", "=", "stream", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "output", ".", "write", "(", "buffer", ",", "0", ",", "read", ")", ";", "}", "output", ".", "flush", "(", ")", ";", "}", "finally", "{", "output", ".", "close", "(", ")", ";", "}", "}", "finally", "{", "stream", ".", "close", "(", ")", ";", "}", "return", "file", ";", "}" ]
Writes an InputStream from a network response to a temporary file. If the file successfully parses to an composition, {@link #renameTempFile(FileExtension)} should be called to move the file to its final location for future cache hits.
[ "Writes", "an", "InputStream", "from", "a", "network", "response", "to", "a", "temporary", "file", ".", "If", "the", "file", "successfully", "parses", "to", "an", "composition", "{" ]
train
https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/network/NetworkCache.java#L73-L95
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendClose
public static <T> void sendClose(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { CloseMessage sm = new CloseMessage(data); sendClose(sm, wsChannel, callback, context); }
java
public static <T> void sendClose(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) { CloseMessage sm = new CloseMessage(data); sendClose(sm, wsChannel, callback, context); }
[ "public", "static", "<", "T", ">", "void", "sendClose", "(", "final", "ByteBuffer", "data", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "T", ">", "callback", ",", "T", "context", ")", "{", "CloseMessage", "sm", "=", "new", "CloseMessage", "(", "data", ")", ";", "sendClose", "(", "sm", ",", "wsChannel", ",", "callback", ",", "context", ")", ";", "}" ]
Sends a complete close message, invoking the callback when complete @param data The data to send @param wsChannel The web socket channel @param callback The callback to invoke on completion @param context The context object that will be passed to the callback on completion
[ "Sends", "a", "complete", "close", "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#L781-L784
jbundle/webapp
base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java
BaseOsgiServlet.sendResourceFile
public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException { URL url = null; try { url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader()); } catch (RuntimeException e) { e.printStackTrace(); // ??? } if (url == null) return false; // Not found InputStream inStream = null; try { inStream = url.openStream(); } catch (Exception e) { return false; // Not found } // Todo may want to add cache info (using bundle lastModified). OutputStream writer = response.getOutputStream(); if (response.getContentType() == null) { if (httpContext != null) response.setContentType(httpContext.getMimeType(path)); else response.setContentType(FileHttpContext.getDefaultMimeType(path)); } copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things writer.close(); inStream.close(); return true; }
java
public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException { URL url = null; try { url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader()); } catch (RuntimeException e) { e.printStackTrace(); // ??? } if (url == null) return false; // Not found InputStream inStream = null; try { inStream = url.openStream(); } catch (Exception e) { return false; // Not found } // Todo may want to add cache info (using bundle lastModified). OutputStream writer = response.getOutputStream(); if (response.getContentType() == null) { if (httpContext != null) response.setContentType(httpContext.getMimeType(path)); else response.setContentType(FileHttpContext.getDefaultMimeType(path)); } copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things writer.close(); inStream.close(); return true; }
[ "public", "boolean", "sendResourceFile", "(", "String", "path", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "URL", "url", "=", "null", ";", "try", "{", "url", "=", "ClassServiceUtility", ".", "getClassService", "(", ")", ".", "getResourceURL", "(", "path", ",", "baseURL", ",", "null", ",", "this", ".", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "// ???", "}", "if", "(", "url", "==", "null", ")", "return", "false", ";", "// Not found", "InputStream", "inStream", "=", "null", ";", "try", "{", "inStream", "=", "url", ".", "openStream", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "// Not found", "}", "// Todo may want to add cache info (using bundle lastModified).", "OutputStream", "writer", "=", "response", ".", "getOutputStream", "(", ")", ";", "if", "(", "response", ".", "getContentType", "(", ")", "==", "null", ")", "{", "if", "(", "httpContext", "!=", "null", ")", "response", ".", "setContentType", "(", "httpContext", ".", "getMimeType", "(", "path", ")", ")", ";", "else", "response", ".", "setContentType", "(", "FileHttpContext", ".", "getDefaultMimeType", "(", "path", ")", ")", ";", "}", "copyStream", "(", "inStream", ",", "writer", ",", "true", ")", ";", "// Ignore errors, as browsers do weird things", "writer", ".", "close", "(", ")", ";", "inStream", ".", "close", "(", ")", ";", "return", "true", ";", "}" ]
Send this resource to the response stream. @param request @param response @return @throws IOException
[ "Send", "this", "resource", "to", "the", "response", "stream", "." ]
train
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java#L88-L118
HeidelTime/heideltime
src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java
HolidayProcessor.getEasterSunday
public String getEasterSunday(int year, int days) { int K = year / 100; int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 ); int S = 2 - ( (3 * K + 3) / 4 ); int A = year % 19; int D = ( 19 * A + M ) % 30; int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) ); int OG = 21 + D - R; int SZ = 7 - ( year + ( year / 4 ) + S ) % 7; int OE = 7 - ( OG - SZ ) % 7; int OS = OG + OE; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); String date; if( OS <= 31 ) { date = String.format("%04d-03-%02d", year, OS); } else{ date = String.format("%04d-04-%02d", year, ( OS - 31 ) ); } try{ c.setTime(formatter.parse(date)); c.add(Calendar.DAY_OF_MONTH, days); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; }
java
public String getEasterSunday(int year, int days) { int K = year / 100; int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 ); int S = 2 - ( (3 * K + 3) / 4 ); int A = year % 19; int D = ( 19 * A + M ) % 30; int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) ); int OG = 21 + D - R; int SZ = 7 - ( year + ( year / 4 ) + S ) % 7; int OE = 7 - ( OG - SZ ) % 7; int OS = OG + OE; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); String date; if( OS <= 31 ) { date = String.format("%04d-03-%02d", year, OS); } else{ date = String.format("%04d-04-%02d", year, ( OS - 31 ) ); } try{ c.setTime(formatter.parse(date)); c.add(Calendar.DAY_OF_MONTH, days); date = formatter.format(c.getTime()); } catch (ParseException e) { e.printStackTrace(); } return date; }
[ "public", "String", "getEasterSunday", "(", "int", "year", ",", "int", "days", ")", "{", "int", "K", "=", "year", "/", "100", ";", "int", "M", "=", "15", "+", "(", "(", "3", "*", "K", "+", "3", ")", "/", "4", ")", "-", "(", "(", "8", "*", "K", "+", "13", ")", "/", "25", ")", ";", "int", "S", "=", "2", "-", "(", "(", "3", "*", "K", "+", "3", ")", "/", "4", ")", ";", "int", "A", "=", "year", "%", "19", ";", "int", "D", "=", "(", "19", "*", "A", "+", "M", ")", "%", "30", ";", "int", "R", "=", "(", "D", "/", "29", ")", "+", "(", "(", "D", "/", "28", ")", "-", "(", "D", "/", "29", ")", "*", "(", "A", "/", "11", ")", ")", ";", "int", "OG", "=", "21", "+", "D", "-", "R", ";", "int", "SZ", "=", "7", "-", "(", "year", "+", "(", "year", "/", "4", ")", "+", "S", ")", "%", "7", ";", "int", "OE", "=", "7", "-", "(", "OG", "-", "SZ", ")", "%", "7", ";", "int", "OS", "=", "OG", "+", "OE", ";", "SimpleDateFormat", "formatter", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd\"", ")", ";", "Calendar", "c", "=", "Calendar", ".", "getInstance", "(", ")", ";", "String", "date", ";", "if", "(", "OS", "<=", "31", ")", "{", "date", "=", "String", ".", "format", "(", "\"%04d-03-%02d\"", ",", "year", ",", "OS", ")", ";", "}", "else", "{", "date", "=", "String", ".", "format", "(", "\"%04d-04-%02d\"", ",", "year", ",", "(", "OS", "-", "31", ")", ")", ";", "}", "try", "{", "c", ".", "setTime", "(", "formatter", ".", "parse", "(", "date", ")", ")", ";", "c", ".", "add", "(", "Calendar", ".", "DAY_OF_MONTH", ",", "days", ")", ";", "date", "=", "formatter", ".", "format", "(", "c", ".", "getTime", "(", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "date", ";", "}" ]
Get the date of a day relative to Easter Sunday in a given year. Algorithm used is from the "Physikalisch-Technische Bundesanstalt Braunschweig" PTB. @author Hans-Peter Pfeiffer @param year @param days @return date
[ "Get", "the", "date", "of", "a", "day", "relative", "to", "Easter", "Sunday", "in", "a", "given", "year", ".", "Algorithm", "used", "is", "from", "the", "Physikalisch", "-", "Technische", "Bundesanstalt", "Braunschweig", "PTB", "." ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java#L196-L226
albfernandez/itext2
src/main/java/com/lowagie/text/xml/XmlParser.java
XmlParser.go
public void go(DocListener document, InputSource is) { try { parser.parse(is, new SAXiTextHandler(document)); } catch(SAXException se) { throw new ExceptionConverter(se); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
java
public void go(DocListener document, InputSource is) { try { parser.parse(is, new SAXiTextHandler(document)); } catch(SAXException se) { throw new ExceptionConverter(se); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
[ "public", "void", "go", "(", "DocListener", "document", ",", "InputSource", "is", ")", "{", "try", "{", "parser", ".", "parse", "(", "is", ",", "new", "SAXiTextHandler", "(", "document", ")", ")", ";", "}", "catch", "(", "SAXException", "se", ")", "{", "throw", "new", "ExceptionConverter", "(", "se", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "new", "ExceptionConverter", "(", "ioe", ")", ";", "}", "}" ]
Parses a given file. @param document The document that will listen to the parser @param is The InputStream with the contents
[ "Parses", "a", "given", "file", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/xml/XmlParser.java#L98-L108
Netflix/Hystrix
hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MethodExecutionAction.java
MethodExecutionAction.executeWithArgs
@Override public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException { if(ExecutionType.ASYNCHRONOUS == executionType){ Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args); return executeClj(closure.getClosureObj(), closure.getClosureMethod()); } return execute(object, method, args); }
java
@Override public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException { if(ExecutionType.ASYNCHRONOUS == executionType){ Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args); return executeClj(closure.getClosureObj(), closure.getClosureMethod()); } return execute(object, method, args); }
[ "@", "Override", "public", "Object", "executeWithArgs", "(", "ExecutionType", "executionType", ",", "Object", "[", "]", "args", ")", "throws", "CommandActionExecutionException", "{", "if", "(", "ExecutionType", ".", "ASYNCHRONOUS", "==", "executionType", ")", "{", "Closure", "closure", "=", "AsyncClosureFactory", ".", "getInstance", "(", ")", ".", "createClosure", "(", "metaHolder", ",", "method", ",", "object", ",", "args", ")", ";", "return", "executeClj", "(", "closure", ".", "getClosureObj", "(", ")", ",", "closure", ".", "getClosureMethod", "(", ")", ")", ";", "}", "return", "execute", "(", "object", ",", "method", ",", "args", ")", ";", "}" ]
Invokes the method. Also private method also can be invoked. @return result of execution
[ "Invokes", "the", "method", ".", "Also", "private", "method", "also", "can", "be", "invoked", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MethodExecutionAction.java#L86-L94
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java
KeyVaultCredentials.buildAuthenticatedRequest
private Pair<Request, HttpMessageSecurity> buildAuthenticatedRequest(Request originalRequest, Response response) throws IOException { String authenticateHeader = response.header(WWW_AUTHENTICATE); Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX); challengeMap.put("x-ms-message-encryption-key", response.header("x-ms-message-encryption-key")); challengeMap.put("x-ms-message-signing-key", response.header("x-ms-message-signing-key")); // Cache the challenge cache.addCachedChallenge(originalRequest.url(), challengeMap); return buildAuthenticatedRequest(originalRequest, challengeMap); }
java
private Pair<Request, HttpMessageSecurity> buildAuthenticatedRequest(Request originalRequest, Response response) throws IOException { String authenticateHeader = response.header(WWW_AUTHENTICATE); Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX); challengeMap.put("x-ms-message-encryption-key", response.header("x-ms-message-encryption-key")); challengeMap.put("x-ms-message-signing-key", response.header("x-ms-message-signing-key")); // Cache the challenge cache.addCachedChallenge(originalRequest.url(), challengeMap); return buildAuthenticatedRequest(originalRequest, challengeMap); }
[ "private", "Pair", "<", "Request", ",", "HttpMessageSecurity", ">", "buildAuthenticatedRequest", "(", "Request", "originalRequest", ",", "Response", "response", ")", "throws", "IOException", "{", "String", "authenticateHeader", "=", "response", ".", "header", "(", "WWW_AUTHENTICATE", ")", ";", "Map", "<", "String", ",", "String", ">", "challengeMap", "=", "extractChallenge", "(", "authenticateHeader", ",", "BEARER_TOKEP_REFIX", ")", ";", "challengeMap", ".", "put", "(", "\"x-ms-message-encryption-key\"", ",", "response", ".", "header", "(", "\"x-ms-message-encryption-key\"", ")", ")", ";", "challengeMap", ".", "put", "(", "\"x-ms-message-signing-key\"", ",", "response", ".", "header", "(", "\"x-ms-message-signing-key\"", ")", ")", ";", "// Cache the challenge", "cache", ".", "addCachedChallenge", "(", "originalRequest", ".", "url", "(", ")", ",", "challengeMap", ")", ";", "return", "buildAuthenticatedRequest", "(", "originalRequest", ",", "challengeMap", ")", ";", "}" ]
Builds request with authenticated header. Protects request body if supported. @param originalRequest unprotected request without auth token. @param response response with unauthorized return code. @return Pair of protected request and HttpMessageSecurity used for encryption.
[ "Builds", "request", "with", "authenticated", "header", ".", "Protects", "request", "body", "if", "supported", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java#L146-L159
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java
WsTraceRouterImpl.routeTo
protected void routeTo(RoutedMessage routedTrace, String logHandlerId) { WsTraceHandler wsTraceHandler = wsTraceHandlerServices.get(logHandlerId); if (wsTraceHandler != null) { wsTraceHandler.publish(routedTrace); } }
java
protected void routeTo(RoutedMessage routedTrace, String logHandlerId) { WsTraceHandler wsTraceHandler = wsTraceHandlerServices.get(logHandlerId); if (wsTraceHandler != null) { wsTraceHandler.publish(routedTrace); } }
[ "protected", "void", "routeTo", "(", "RoutedMessage", "routedTrace", ",", "String", "logHandlerId", ")", "{", "WsTraceHandler", "wsTraceHandler", "=", "wsTraceHandlerServices", ".", "get", "(", "logHandlerId", ")", ";", "if", "(", "wsTraceHandler", "!=", "null", ")", "{", "wsTraceHandler", ".", "publish", "(", "routedTrace", ")", ";", "}", "}" ]
Route the traces to the LogHandler identified by the given logHandlerId. @param msg The fully formatted trace. @param logRecord The associated LogRecord, in case the LogHandler needs it. @param logHandlerId The LogHandler ID in which to route.
[ "Route", "the", "traces", "to", "the", "LogHandler", "identified", "by", "the", "given", "logHandlerId", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java#L152-L157
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java
CQJDBCStorageConnection.appendPattern
protected void appendPattern(StringBuilder sb, QPathEntry entry, boolean indexConstraint) { String pattern = entry.getAsString(false); sb.append("(I.NAME"); if (pattern.contains("*")) { sb.append(" LIKE '"); sb.append(escapeSpecialChars(pattern)); sb.append("' ESCAPE '"); sb.append(getLikeExpressionEscape()); sb.append("'"); } else { sb.append("='"); sb.append(escape(pattern)); sb.append("'"); } if (indexConstraint && entry.getIndex() != -1) { sb.append(" and I.I_INDEX="); sb.append(entry.getIndex()); } sb.append(")"); }
java
protected void appendPattern(StringBuilder sb, QPathEntry entry, boolean indexConstraint) { String pattern = entry.getAsString(false); sb.append("(I.NAME"); if (pattern.contains("*")) { sb.append(" LIKE '"); sb.append(escapeSpecialChars(pattern)); sb.append("' ESCAPE '"); sb.append(getLikeExpressionEscape()); sb.append("'"); } else { sb.append("='"); sb.append(escape(pattern)); sb.append("'"); } if (indexConstraint && entry.getIndex() != -1) { sb.append(" and I.I_INDEX="); sb.append(entry.getIndex()); } sb.append(")"); }
[ "protected", "void", "appendPattern", "(", "StringBuilder", "sb", ",", "QPathEntry", "entry", ",", "boolean", "indexConstraint", ")", "{", "String", "pattern", "=", "entry", ".", "getAsString", "(", "false", ")", ";", "sb", ".", "append", "(", "\"(I.NAME\"", ")", ";", "if", "(", "pattern", ".", "contains", "(", "\"*\"", ")", ")", "{", "sb", ".", "append", "(", "\" LIKE '\"", ")", ";", "sb", ".", "append", "(", "escapeSpecialChars", "(", "pattern", ")", ")", ";", "sb", ".", "append", "(", "\"' ESCAPE '\"", ")", ";", "sb", ".", "append", "(", "getLikeExpressionEscape", "(", ")", ")", ";", "sb", ".", "append", "(", "\"'\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"='\"", ")", ";", "sb", ".", "append", "(", "escape", "(", "pattern", ")", ")", ";", "sb", ".", "append", "(", "\"'\"", ")", ";", "}", "if", "(", "indexConstraint", "&&", "entry", ".", "getIndex", "(", ")", "!=", "-", "1", ")", "{", "sb", ".", "append", "(", "\" and I.I_INDEX=\"", ")", ";", "sb", ".", "append", "(", "entry", ".", "getIndex", "(", ")", ")", ";", "}", "sb", ".", "append", "(", "\")\"", ")", ";", "}" ]
Append pattern expression. Appends String "I.NAME LIKE 'escaped pattern' ESCAPE 'escapeString'" or "I.NAME='pattern'" to String builder sb. @param sb StringBuilder @param entry @param indexConstraint
[ "Append", "pattern", "expression", ".", "Appends", "String", "I", ".", "NAME", "LIKE", "escaped", "pattern", "ESCAPE", "escapeString", "or", "I", ".", "NAME", "=", "pattern", "to", "String", "builder", "sb", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java#L2239-L2264