repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.getAt
@SuppressWarnings("unchecked") public static List<Long> getAt(long[] array, IntRange range) { RangeInfo info = subListBorders(array.length, range); List<Long> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1)); return info.reverse ? reverse(answer) : answer; }
java
@SuppressWarnings("unchecked") public static List<Long> getAt(long[] array, IntRange range) { RangeInfo info = subListBorders(array.length, range); List<Long> answer = primitiveArrayGet(array, new IntRange(true, info.from, info.to - 1)); return info.reverse ? reverse(answer) : answer; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "List", "<", "Long", ">", "getAt", "(", "long", "[", "]", "array", ",", "IntRange", "range", ")", "{", "RangeInfo", "info", "=", "subListBorders", "(", "array", ".", "length", ",", "...
Support the subscript operator with an IntRange for a long array @param array a long array @param range an IntRange indicating the indices for the items to retrieve @return list of the retrieved longs @since 1.0
[ "Support", "the", "subscript", "operator", "with", "an", "IntRange", "for", "a", "long", "array" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13774-L13779
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlLikeUtils.java
SqlLikeUtils.sqlToRegexSimilar
static String sqlToRegexSimilar( String sqlPattern, CharSequence escapeStr) { final char escapeChar; if (escapeStr != null) { if (escapeStr.length() != 1) { throw invalidEscapeCharacter(escapeStr.toString()); } escapeChar = escapeStr.charAt(0); } else { escapeChar = 0; } return sqlToRegexSimilar(sqlPattern, escapeChar); }
java
static String sqlToRegexSimilar( String sqlPattern, CharSequence escapeStr) { final char escapeChar; if (escapeStr != null) { if (escapeStr.length() != 1) { throw invalidEscapeCharacter(escapeStr.toString()); } escapeChar = escapeStr.charAt(0); } else { escapeChar = 0; } return sqlToRegexSimilar(sqlPattern, escapeChar); }
[ "static", "String", "sqlToRegexSimilar", "(", "String", "sqlPattern", ",", "CharSequence", "escapeStr", ")", "{", "final", "char", "escapeChar", ";", "if", "(", "escapeStr", "!=", "null", ")", "{", "if", "(", "escapeStr", ".", "length", "(", ")", "!=", "1"...
Translates a SQL SIMILAR pattern to Java regex pattern, with optional escape string.
[ "Translates", "a", "SQL", "SIMILAR", "pattern", "to", "Java", "regex", "pattern", "with", "optional", "escape", "string", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlLikeUtils.java#L213-L226
protostuff/protostuff
protostuff-api/src/main/java/io/protostuff/UnsignedNumberUtil.java
UnsignedNumberUtil.overflowInParse
private static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; }
java
private static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; }
[ "private", "static", "boolean", "overflowInParse", "(", "long", "current", ",", "int", "digit", ",", "int", "radix", ")", "{", "if", "(", "current", ">=", "0", ")", "{", "if", "(", "current", "<", "maxValueDivs", "[", "radix", "]", ")", "{", "return", ...
Returns true if (current * radix) + digit is a number too large to be represented by an unsigned long. This is useful for detecting overflow while parsing a string representation of a number. Does not verify whether supplied radix is valid, passing an invalid radix will give undefined results or an ArrayIndexOutOfBoundsException.
[ "Returns", "true", "if", "(", "current", "*", "radix", ")", "+", "digit", "is", "a", "number", "too", "large", "to", "be", "represented", "by", "an", "unsigned", "long", ".", "This", "is", "useful", "for", "detecting", "overflow", "while", "parsing", "a"...
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-api/src/main/java/io/protostuff/UnsignedNumberUtil.java#L317-L335
assertthat/selenium-shutterbug
src/main/java/com/assertthat/selenium_shutterbug/core/Shutterbug.java
Shutterbug.shootElement
public static ElementSnapshot shootElement(WebDriver driver, WebElement element, boolean useDevicePixelRatio) { Browser browser = new Browser(driver, useDevicePixelRatio); ElementSnapshot elementSnapshot = new ElementSnapshot(driver, browser.getDevicePixelRatio()); browser.scrollToElement(element); elementSnapshot.setImage(browser.takeScreenshot(),browser.getBoundingClientRect(element)); return elementSnapshot; }
java
public static ElementSnapshot shootElement(WebDriver driver, WebElement element, boolean useDevicePixelRatio) { Browser browser = new Browser(driver, useDevicePixelRatio); ElementSnapshot elementSnapshot = new ElementSnapshot(driver, browser.getDevicePixelRatio()); browser.scrollToElement(element); elementSnapshot.setImage(browser.takeScreenshot(),browser.getBoundingClientRect(element)); return elementSnapshot; }
[ "public", "static", "ElementSnapshot", "shootElement", "(", "WebDriver", "driver", ",", "WebElement", "element", ",", "boolean", "useDevicePixelRatio", ")", "{", "Browser", "browser", "=", "new", "Browser", "(", "driver", ",", "useDevicePixelRatio", ")", ";", "Ele...
To be used when need to screenshot particular element. @param driver WebDriver instance @param element WebElement instance to be screen shot @param useDevicePixelRatio whether or not take into account device pixel ratio @return ElementSnapshot instance
[ "To", "be", "used", "when", "need", "to", "screenshot", "particular", "element", "." ]
train
https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/Shutterbug.java#L135-L141
Omertron/api-fanarttv
src/main/java/com/omertron/fanarttvapi/tools/ApiBuilder.java
ApiBuilder.getImageUrl
public URL getImageUrl(BaseType baseType, String id) throws FanartTvException { StringBuilder url = getBaseUrl(baseType); // Add the ID url.append(id); // Add the API Key url.append(DELIMITER_APIKEY).append(apiKey); // Add the client API Key if (StringUtils.isNotBlank(clientKey)) { url.append(DELIMITER_CLIENT_KEY).append(clientKey); } return convertUrl(url); }
java
public URL getImageUrl(BaseType baseType, String id) throws FanartTvException { StringBuilder url = getBaseUrl(baseType); // Add the ID url.append(id); // Add the API Key url.append(DELIMITER_APIKEY).append(apiKey); // Add the client API Key if (StringUtils.isNotBlank(clientKey)) { url.append(DELIMITER_CLIENT_KEY).append(clientKey); } return convertUrl(url); }
[ "public", "URL", "getImageUrl", "(", "BaseType", "baseType", ",", "String", "id", ")", "throws", "FanartTvException", "{", "StringBuilder", "url", "=", "getBaseUrl", "(", "baseType", ")", ";", "// Add the ID", "url", ".", "append", "(", "id", ")", ";", "// A...
Generate the URL for the artwork requests @param baseType @param id @return @throws FanartTvException
[ "Generate", "the", "URL", "for", "the", "artwork", "requests" ]
train
https://github.com/Omertron/api-fanarttv/blob/2a1854c840d8111935d0f6abe5232e2c3c3f318b/src/main/java/com/omertron/fanarttvapi/tools/ApiBuilder.java#L103-L118
alkacon/opencms-core
src/org/opencms/relations/CmsLink.java
CmsLink.setComponents
private void setComponents() { CmsUriSplitter splitter = new CmsUriSplitter(m_uri, true); m_target = splitter.getPrefix(); m_anchor = CmsLinkProcessor.unescapeLink(splitter.getAnchor()); setQuery(splitter.getQuery()); }
java
private void setComponents() { CmsUriSplitter splitter = new CmsUriSplitter(m_uri, true); m_target = splitter.getPrefix(); m_anchor = CmsLinkProcessor.unescapeLink(splitter.getAnchor()); setQuery(splitter.getQuery()); }
[ "private", "void", "setComponents", "(", ")", "{", "CmsUriSplitter", "splitter", "=", "new", "CmsUriSplitter", "(", "m_uri", ",", "true", ")", ";", "m_target", "=", "splitter", ".", "getPrefix", "(", ")", ";", "m_anchor", "=", "CmsLinkProcessor", ".", "unesc...
Sets the component member variables (target, anchor, query) by splitting the uri <code>scheme://authority/path#anchor?query</code>.<p>
[ "Sets", "the", "component", "member", "variables", "(", "target", "anchor", "query", ")", "by", "splitting", "the", "uri", "<code", ">", "scheme", ":", "//", "authority", "/", "path#anchor?query<", "/", "code", ">", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsLink.java#L723-L729
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java
PassiveRole.appendEntry
private boolean appendEntry(long index, RaftLogEntry entry, RaftLogWriter writer, CompletableFuture<AppendResponse> future) { try { Indexed<RaftLogEntry> indexed = writer.append(entry); log.trace("Appended {}", indexed); } catch (StorageException.TooLarge e) { log.warn("Entry size exceeds maximum allowed bytes. Ensure Raft storage configuration is consistent on all nodes!"); return false; } catch (StorageException.OutOfDiskSpace e) { log.trace("Append failed: {}", e); raft.getServiceManager().compact(); failAppend(index - 1, future); return false; } return true; }
java
private boolean appendEntry(long index, RaftLogEntry entry, RaftLogWriter writer, CompletableFuture<AppendResponse> future) { try { Indexed<RaftLogEntry> indexed = writer.append(entry); log.trace("Appended {}", indexed); } catch (StorageException.TooLarge e) { log.warn("Entry size exceeds maximum allowed bytes. Ensure Raft storage configuration is consistent on all nodes!"); return false; } catch (StorageException.OutOfDiskSpace e) { log.trace("Append failed: {}", e); raft.getServiceManager().compact(); failAppend(index - 1, future); return false; } return true; }
[ "private", "boolean", "appendEntry", "(", "long", "index", ",", "RaftLogEntry", "entry", ",", "RaftLogWriter", "writer", ",", "CompletableFuture", "<", "AppendResponse", ">", "future", ")", "{", "try", "{", "Indexed", "<", "RaftLogEntry", ">", "indexed", "=", ...
Attempts to append an entry, returning {@code false} if the append fails due to an {@link StorageException.OutOfDiskSpace} exception.
[ "Attempts", "to", "append", "an", "entry", "returning", "{" ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/roles/PassiveRole.java#L316-L330
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.takeWhile
public static CharSequence takeWhile(CharSequence self, @ClosureParams(value=SimpleType.class, options="char") Closure condition) { int num = 0; BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition); while (num < self.length()) { char value = self.charAt(num); if (bcw.call(value)) { num += 1; } else { break; } } return take(self, num); }
java
public static CharSequence takeWhile(CharSequence self, @ClosureParams(value=SimpleType.class, options="char") Closure condition) { int num = 0; BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition); while (num < self.length()) { char value = self.charAt(num); if (bcw.call(value)) { num += 1; } else { break; } } return take(self, num); }
[ "public", "static", "CharSequence", "takeWhile", "(", "CharSequence", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"char\"", ")", "Closure", "condition", ")", "{", "int", "num", "=", "0", ";", "Bo...
Returns the longest prefix of this CharSequence where each element passed to the given closure evaluates to true. <p> <pre class="groovyTestCase"> def text = "Groovy" assert text.takeWhile{ it < 'A' } == '' assert text.takeWhile{ it < 'Z' } == 'G' assert text.takeWhile{ it != 'v' } == 'Groo' assert text.takeWhile{ it < 'z' } == 'Groovy' </pre> @param self the original CharSequence @param condition the closure that must evaluate to true to continue taking elements @return a prefix of elements in the CharSequence where each element passed to the given closure evaluates to true @since 2.0.0
[ "Returns", "the", "longest", "prefix", "of", "this", "CharSequence", "where", "each", "element", "passed", "to", "the", "given", "closure", "evaluates", "to", "true", ".", "<p", ">", "<pre", "class", "=", "groovyTestCase", ">", "def", "text", "=", "Groovy", ...
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L3183-L3195
carewebframework/carewebframework-vista
org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java
PropertyCollection.getValue
public boolean getValue(String name, boolean dflt) { try { String val = getValue(name, Boolean.toString(dflt)).toLowerCase(); return val.startsWith("y") ? true : Boolean.parseBoolean(val); } catch (Exception e) { return false; } }
java
public boolean getValue(String name, boolean dflt) { try { String val = getValue(name, Boolean.toString(dflt)).toLowerCase(); return val.startsWith("y") ? true : Boolean.parseBoolean(val); } catch (Exception e) { return false; } }
[ "public", "boolean", "getValue", "(", "String", "name", ",", "boolean", "dflt", ")", "{", "try", "{", "String", "val", "=", "getValue", "(", "name", ",", "Boolean", ".", "toString", "(", "dflt", ")", ")", ".", "toLowerCase", "(", ")", ";", "return", ...
Returns a boolean property value. @param name Property name. @param dflt Default value if a property value is not found. @return Property value or default value if property value not found.
[ "Returns", "a", "boolean", "property", "value", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.api-parent/org.carewebframework.vista.api.core/src/main/java/org/carewebframework/vista/api/property/PropertyCollection.java#L146-L153
Alluxio/alluxio
minicluster/src/main/java/alluxio/multi/process/MultiProcessCluster.java
MultiProcessCluster.createWorker
private synchronized Worker createWorker(int i) throws IOException { Preconditions.checkState(mState == State.STARTED, "Must be in a started state to create workers"); File confDir = new File(mWorkDir, "conf-worker" + i); File logsDir = new File(mWorkDir, "logs-worker" + i); File ramdisk = new File(mWorkDir, "ramdisk" + i); logsDir.mkdirs(); ramdisk.mkdirs(); int rpcPort = getNewPort(); int dataPort = getNewPort(); int webPort = getNewPort(); Map<PropertyKey, String> conf = new HashMap<>(); conf.put(PropertyKey.LOGGER_TYPE, "WORKER_LOGGER"); conf.put(PropertyKey.CONF_DIR, confDir.getAbsolutePath()); conf.put(PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_DIRS_PATH.format(0), ramdisk.getAbsolutePath()); conf.put(PropertyKey.LOGS_DIR, logsDir.getAbsolutePath()); conf.put(PropertyKey.WORKER_RPC_PORT, Integer.toString(rpcPort)); conf.put(PropertyKey.WORKER_WEB_PORT, Integer.toString(webPort)); Worker worker = mCloser.register(new Worker(logsDir, conf)); mWorkers.add(worker); LOG.info("Created worker with (rpc, data, web) ports ({}, {}, {})", rpcPort, dataPort, webPort); return worker; }
java
private synchronized Worker createWorker(int i) throws IOException { Preconditions.checkState(mState == State.STARTED, "Must be in a started state to create workers"); File confDir = new File(mWorkDir, "conf-worker" + i); File logsDir = new File(mWorkDir, "logs-worker" + i); File ramdisk = new File(mWorkDir, "ramdisk" + i); logsDir.mkdirs(); ramdisk.mkdirs(); int rpcPort = getNewPort(); int dataPort = getNewPort(); int webPort = getNewPort(); Map<PropertyKey, String> conf = new HashMap<>(); conf.put(PropertyKey.LOGGER_TYPE, "WORKER_LOGGER"); conf.put(PropertyKey.CONF_DIR, confDir.getAbsolutePath()); conf.put(PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_DIRS_PATH.format(0), ramdisk.getAbsolutePath()); conf.put(PropertyKey.LOGS_DIR, logsDir.getAbsolutePath()); conf.put(PropertyKey.WORKER_RPC_PORT, Integer.toString(rpcPort)); conf.put(PropertyKey.WORKER_WEB_PORT, Integer.toString(webPort)); Worker worker = mCloser.register(new Worker(logsDir, conf)); mWorkers.add(worker); LOG.info("Created worker with (rpc, data, web) ports ({}, {}, {})", rpcPort, dataPort, webPort); return worker; }
[ "private", "synchronized", "Worker", "createWorker", "(", "int", "i", ")", "throws", "IOException", "{", "Preconditions", ".", "checkState", "(", "mState", "==", "State", ".", "STARTED", ",", "\"Must be in a started state to create workers\"", ")", ";", "File", "con...
Creates the specified worker without starting it. @param i the index of the worker to create
[ "Creates", "the", "specified", "worker", "without", "starting", "it", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/minicluster/src/main/java/alluxio/multi/process/MultiProcessCluster.java#L578-L604
Harium/keel
src/main/java/com/harium/keel/catalano/math/transform/FourierTransform.java
FourierTransform.convolve
private static void convolve(double[] x, double[] y, double[] out) { // if (x.length != y.length || x.length != out.length) // throw new IllegalArgumentException("Mismatched lengths"); int n = x.length; convolve(x, new double[n], y, new double[n], out, new double[n]); }
java
private static void convolve(double[] x, double[] y, double[] out) { // if (x.length != y.length || x.length != out.length) // throw new IllegalArgumentException("Mismatched lengths"); int n = x.length; convolve(x, new double[n], y, new double[n], out, new double[n]); }
[ "private", "static", "void", "convolve", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ",", "double", "[", "]", "out", ")", "{", "// if (x.length != y.length || x.length != out.length)\r", "// throw new IllegalArgumentException(\"Mismat...
/* Computes the circular convolution of the given real vectors. Each vector's length must be the same.
[ "/", "*", "Computes", "the", "circular", "convolution", "of", "the", "given", "real", "vectors", ".", "Each", "vector", "s", "length", "must", "be", "the", "same", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/transform/FourierTransform.java#L347-L352
google/closure-compiler
src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java
FeatureSet.with
@VisibleForTesting public FeatureSet with(Feature... newFeatures) { return new FeatureSet(union(features, ImmutableSet.copyOf(newFeatures))); }
java
@VisibleForTesting public FeatureSet with(Feature... newFeatures) { return new FeatureSet(union(features, ImmutableSet.copyOf(newFeatures))); }
[ "@", "VisibleForTesting", "public", "FeatureSet", "with", "(", "Feature", "...", "newFeatures", ")", "{", "return", "new", "FeatureSet", "(", "union", "(", "features", ",", "ImmutableSet", ".", "copyOf", "(", "newFeatures", ")", ")", ")", ";", "}" ]
Returns a feature set combining all the features from {@code this} and {@code newFeatures}.
[ "Returns", "a", "feature", "set", "combining", "all", "the", "features", "from", "{" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/parser/FeatureSet.java#L367-L370
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/DisparitySparseScoreSadRect.java
DisparitySparseScoreSadRect.setImages
public void setImages( Input left , Input right ) { InputSanityCheck.checkSameShape(left, right); this.left = left; this.right = right; }
java
public void setImages( Input left , Input right ) { InputSanityCheck.checkSameShape(left, right); this.left = left; this.right = right; }
[ "public", "void", "setImages", "(", "Input", "left", ",", "Input", "right", ")", "{", "InputSanityCheck", ".", "checkSameShape", "(", "left", ",", "right", ")", ";", "this", ".", "left", "=", "left", ";", "this", ".", "right", "=", "right", ";", "}" ]
Specify inputs for left and right camera images. @param left Rectified left camera image. @param right Rectified right camera image.
[ "Specify", "inputs", "for", "left", "and", "right", "camera", "images", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/DisparitySparseScoreSadRect.java#L72-L77
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java
BigDecimalUtil.roundTo
public static BigDecimal roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale) { return setScale(setScale(bd, numberOfDecPlaces, BigDecimal.ROUND_HALF_UP), finalScale); }
java
public static BigDecimal roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale) { return setScale(setScale(bd, numberOfDecPlaces, BigDecimal.ROUND_HALF_UP), finalScale); }
[ "public", "static", "BigDecimal", "roundTo", "(", "final", "BigDecimal", "bd", ",", "final", "int", "numberOfDecPlaces", ",", "final", "int", "finalScale", ")", "{", "return", "setScale", "(", "setScale", "(", "bd", ",", "numberOfDecPlaces", ",", "BigDecimal", ...
returns a new BigDecimal with correct scale after being round to n dec places. @param bd value @param numberOfDecPlaces number of dec place to round to @param finalScale final scale of result (typically numberOfDecPlaces &lt; finalScale); @return new bd or null
[ "returns", "a", "new", "BigDecimal", "with", "correct", "scale", "after", "being", "round", "to", "n", "dec", "places", "." ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/BigDecimalUtil.java#L397-L399
openwms/org.openwms
org.openwms.core.util/src/main/java/org/openwms/core/http/AbstractWebController.java
AbstractWebController.buildNOKResponse
protected <T extends AbstractBase> ResponseEntity<Response<T>> buildNOKResponse(HttpStatus code, String msg, T... params) { return buildResponse(code, msg, "", params); }
java
protected <T extends AbstractBase> ResponseEntity<Response<T>> buildNOKResponse(HttpStatus code, String msg, T... params) { return buildResponse(code, msg, "", params); }
[ "protected", "<", "T", "extends", "AbstractBase", ">", "ResponseEntity", "<", "Response", "<", "T", ">", ">", "buildNOKResponse", "(", "HttpStatus", "code", ",", "String", "msg", ",", "T", "...", "params", ")", "{", "return", "buildResponse", "(", "code", ...
Build a response object that signals a not-okay response with a given status {@code code}. @param <T> Some type extending the AbstractBase entity @param code The status code to set as response code @param msg The error message passed to the caller @param params A set of Serializable objects that are passed to the caller @return A ResponseEntity with status {@code code}
[ "Build", "a", "response", "object", "that", "signals", "a", "not", "-", "okay", "response", "with", "a", "given", "status", "{", "@code", "code", "}", "." ]
train
https://github.com/openwms/org.openwms/blob/b24a95c5d09a7ec3c723d7e107d1cb0039d06a7e/org.openwms.core.util/src/main/java/org/openwms/core/http/AbstractWebController.java#L200-L202
apache/spark
common/network-common/src/main/java/org/apache/spark/network/client/TransportClientFactory.java
TransportClientFactory.createUnmanagedClient
public TransportClient createUnmanagedClient(String remoteHost, int remotePort) throws IOException, InterruptedException { final InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort); return createClient(address); }
java
public TransportClient createUnmanagedClient(String remoteHost, int remotePort) throws IOException, InterruptedException { final InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort); return createClient(address); }
[ "public", "TransportClient", "createUnmanagedClient", "(", "String", "remoteHost", ",", "int", "remotePort", ")", "throws", "IOException", ",", "InterruptedException", "{", "final", "InetSocketAddress", "address", "=", "new", "InetSocketAddress", "(", "remoteHost", ",",...
Create a completely new {@link TransportClient} to the given remote host / port. This connection is not pooled. As with {@link #createClient(String, int)}, this method is blocking.
[ "Create", "a", "completely", "new", "{", "@link", "TransportClient", "}", "to", "the", "given", "remote", "host", "/", "port", ".", "This", "connection", "is", "not", "pooled", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-common/src/main/java/org/apache/spark/network/client/TransportClientFactory.java#L203-L207
buschmais/jqa-java-plugin
src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java
VisitorHelper.addWrites
void addWrites(MethodDescriptor methodDescriptor, final Integer lineNumber, FieldDescriptor fieldDescriptor) { WritesDescriptor writesDescriptor = scannerContext.getStore().create(methodDescriptor, WritesDescriptor.class, fieldDescriptor); writesDescriptor.setLineNumber(lineNumber); }
java
void addWrites(MethodDescriptor methodDescriptor, final Integer lineNumber, FieldDescriptor fieldDescriptor) { WritesDescriptor writesDescriptor = scannerContext.getStore().create(methodDescriptor, WritesDescriptor.class, fieldDescriptor); writesDescriptor.setLineNumber(lineNumber); }
[ "void", "addWrites", "(", "MethodDescriptor", "methodDescriptor", ",", "final", "Integer", "lineNumber", ",", "FieldDescriptor", "fieldDescriptor", ")", "{", "WritesDescriptor", "writesDescriptor", "=", "scannerContext", ".", "getStore", "(", ")", ".", "create", "(", ...
Add a writes relation between a method and a field. @param methodDescriptor The method. @param lineNumber The line number. @param fieldDescriptor The field.
[ "Add", "a", "writes", "relation", "between", "a", "method", "and", "a", "field", "." ]
train
https://github.com/buschmais/jqa-java-plugin/blob/4c050943e9c28cf1c4a08aa962d5b5bf03c4fe54/src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java#L166-L169
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/cache/CmsFlexCacheClearDialog.java
CmsFlexCacheClearDialog.actionClearCaches
public void actionClearCaches() throws JspException { OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, null)); setAction(CmsDialog.ACTION_CANCEL); actionCloseDialog(); }
java
public void actionClearCaches() throws JspException { OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_CLEAR_CACHES, null)); setAction(CmsDialog.ACTION_CANCEL); actionCloseDialog(); }
[ "public", "void", "actionClearCaches", "(", ")", "throws", "JspException", "{", "OpenCms", ".", "fireCmsEvent", "(", "new", "CmsEvent", "(", "I_CmsEventListener", ".", "EVENT_CLEAR_CACHES", ",", "null", ")", ")", ";", "setAction", "(", "CmsDialog", ".", "ACTION_...
Sends a clear caches event.<p> @throws JspException if something goes wrong
[ "Sends", "a", "clear", "caches", "event", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/cache/CmsFlexCacheClearDialog.java#L108-L114
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/EmailApi.java
EmailApi.cancelEmail
public ApiSuccessResponse cancelEmail(String id, CancelData cancelData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = cancelEmailWithHttpInfo(id, cancelData); return resp.getData(); }
java
public ApiSuccessResponse cancelEmail(String id, CancelData cancelData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = cancelEmailWithHttpInfo(id, cancelData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "cancelEmail", "(", "String", "id", ",", "CancelData", "cancelData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "cancelEmailWithHttpInfo", "(", "id", ",", "cancelData", ")", ";", ...
cancel the outbound email interaction Cancel the interaction specified in the id path parameter @param id id of interaction to cancel (required) @param cancelData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "cancel", "the", "outbound", "email", "interaction", "Cancel", "the", "interaction", "specified", "in", "the", "id", "path", "parameter" ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/EmailApi.java#L265-L268
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.feedHandler
protected boolean feedHandler(IFacebookMethod feedMethod, CharSequence title, CharSequence body, Collection<IFeedImage> images, Integer priority) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(feedMethod.numParams()); params.add(new Pair<String, CharSequence>("title", title)); if (null != body) params.add(new Pair<String, CharSequence>("body", body)); if (null != priority) params.add(new Pair<String, CharSequence>("priority", priority.toString())); handleFeedImages(params, images); return extractBoolean(this.callMethod(feedMethod, params)); }
java
protected boolean feedHandler(IFacebookMethod feedMethod, CharSequence title, CharSequence body, Collection<IFeedImage> images, Integer priority) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(feedMethod.numParams()); params.add(new Pair<String, CharSequence>("title", title)); if (null != body) params.add(new Pair<String, CharSequence>("body", body)); if (null != priority) params.add(new Pair<String, CharSequence>("priority", priority.toString())); handleFeedImages(params, images); return extractBoolean(this.callMethod(feedMethod, params)); }
[ "protected", "boolean", "feedHandler", "(", "IFacebookMethod", "feedMethod", ",", "CharSequence", "title", ",", "CharSequence", "body", ",", "Collection", "<", "IFeedImage", ">", "images", ",", "Integer", "priority", ")", "throws", "FacebookException", ",", "IOExcep...
Helper function: assembles the parameters used by feed_publishActionOfUser and feed_publishStoryToUser @param feedMethod feed_publishStoryToUser / feed_publishActionOfUser @param title title of the story @param body body of the story @param images optional images to be included in he story @param priority @return whether the call to <code>feedMethod</code> was successful
[ "Helper", "function", ":", "assembles", "the", "parameters", "used", "by", "feed_publishActionOfUser", "and", "feed_publishStoryToUser" ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L234-L249
elki-project/elki
elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/IndexTree.java
IndexTree.initializeFromFile
public void initializeFromFile(TreeIndexHeader header, PageFile<N> file) { this.dirCapacity = header.getDirCapacity(); this.leafCapacity = header.getLeafCapacity(); this.dirMinimum = header.getDirMinimum(); this.leafMinimum = header.getLeafMinimum(); if(getLogger().isDebugging()) { StringBuilder msg = new StringBuilder(); msg.append(getClass()); msg.append("\n file = ").append(file.getClass()); getLogger().debugFine(msg.toString()); } this.initialized = true; }
java
public void initializeFromFile(TreeIndexHeader header, PageFile<N> file) { this.dirCapacity = header.getDirCapacity(); this.leafCapacity = header.getLeafCapacity(); this.dirMinimum = header.getDirMinimum(); this.leafMinimum = header.getLeafMinimum(); if(getLogger().isDebugging()) { StringBuilder msg = new StringBuilder(); msg.append(getClass()); msg.append("\n file = ").append(file.getClass()); getLogger().debugFine(msg.toString()); } this.initialized = true; }
[ "public", "void", "initializeFromFile", "(", "TreeIndexHeader", "header", ",", "PageFile", "<", "N", ">", "file", ")", "{", "this", ".", "dirCapacity", "=", "header", ".", "getDirCapacity", "(", ")", ";", "this", ".", "leafCapacity", "=", "header", ".", "g...
Initializes this index from an existing persistent file. @param header File header @param file Page file
[ "Initializes", "this", "index", "from", "an", "existing", "persistent", "file", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index/src/main/java/de/lmu/ifi/dbs/elki/index/tree/IndexTree.java#L219-L233
openengsb/openengsb
components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java
EngineeringObjectEnhancer.reloadReferencesAndUpdateEO
private void reloadReferencesAndUpdateEO(ModelDiff diff, EngineeringObjectModelWrapper model) { for (ModelDiffEntry entry : diff.getDifferences().values()) { mergeEngineeringObjectWithReferencedModel(entry.getField(), model); } }
java
private void reloadReferencesAndUpdateEO(ModelDiff diff, EngineeringObjectModelWrapper model) { for (ModelDiffEntry entry : diff.getDifferences().values()) { mergeEngineeringObjectWithReferencedModel(entry.getField(), model); } }
[ "private", "void", "reloadReferencesAndUpdateEO", "(", "ModelDiff", "diff", ",", "EngineeringObjectModelWrapper", "model", ")", "{", "for", "(", "ModelDiffEntry", "entry", ":", "diff", ".", "getDifferences", "(", ")", ".", "values", "(", ")", ")", "{", "mergeEng...
Reload the references which have changed in the actual update and update the Engineering Object accordingly.
[ "Reload", "the", "references", "which", "have", "changed", "in", "the", "actual", "update", "and", "update", "the", "Engineering", "Object", "accordingly", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java#L204-L208
paypal/SeLion
client/src/main/java/com/paypal/selion/platform/html/DatePicker.java
DatePicker.datePickerInit
public void datePickerInit(String prevMonthLocator, String nextMonthLocator, String dateTextLocator) { this.prevMonthLocator = prevMonthLocator; this.nextMonthLocator = nextMonthLocator; this.dateTextLocator = dateTextLocator; }
java
public void datePickerInit(String prevMonthLocator, String nextMonthLocator, String dateTextLocator) { this.prevMonthLocator = prevMonthLocator; this.nextMonthLocator = nextMonthLocator; this.dateTextLocator = dateTextLocator; }
[ "public", "void", "datePickerInit", "(", "String", "prevMonthLocator", ",", "String", "nextMonthLocator", ",", "String", "dateTextLocator", ")", "{", "this", ".", "prevMonthLocator", "=", "prevMonthLocator", ";", "this", ".", "nextMonthLocator", "=", "nextMonthLocator...
DatePicker comes with default locators for widget controls previous button, next button, and date text. This method gives access to override these default locators. @param prevMonthLocator calendar widget prev month @param nextMonthLocator calendar widget next month @param dateTextLocator calendar widget month and year text
[ "DatePicker", "comes", "with", "default", "locators", "for", "widget", "controls", "previous", "button", "next", "button", "and", "date", "text", ".", "This", "method", "gives", "access", "to", "override", "these", "default", "locators", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/platform/html/DatePicker.java#L311-L315
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_server_PUT
public void organizationName_service_exchangeService_server_PUT(String organizationName, String exchangeService, OvhServer body) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/server"; StringBuilder sb = path(qPath, organizationName, exchangeService); exec(qPath, "PUT", sb.toString(), body); }
java
public void organizationName_service_exchangeService_server_PUT(String organizationName, String exchangeService, OvhServer body) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/server"; StringBuilder sb = path(qPath, organizationName, exchangeService); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "organizationName_service_exchangeService_server_PUT", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "OvhServer", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exch...
Alter this object properties REST: PUT /email/exchange/{organizationName}/service/{exchangeService}/server @param body [required] New object properties @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L407-L411
box/box-java-sdk
src/main/java/com/box/sdk/BoxFolder.java
BoxFolder.uploadLargeFile
public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize) throws InterruptedException, IOException { URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); return new LargeFileUpload(). upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); }
java
public BoxFile.Info uploadLargeFile(InputStream inputStream, String fileName, long fileSize) throws InterruptedException, IOException { URL url = UPLOAD_SESSION_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL()); return new LargeFileUpload(). upload(this.getAPI(), this.getID(), inputStream, url, fileName, fileSize); }
[ "public", "BoxFile", ".", "Info", "uploadLargeFile", "(", "InputStream", "inputStream", ",", "String", "fileName", ",", "long", "fileSize", ")", "throws", "InterruptedException", ",", "IOException", "{", "URL", "url", "=", "UPLOAD_SESSION_URL_TEMPLATE", ".", "build"...
Creates a new file. @param inputStream the stream instance that contains the data. @param fileName the name of the file to be created. @param fileSize the size of the file that will be uploaded. @return the created file instance. @throws InterruptedException when a thread execution is interrupted. @throws IOException when reading a stream throws exception.
[ "Creates", "a", "new", "file", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFolder.java#L1085-L1090
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.eachCombination
public static void eachCombination(Iterable self, Closure<?> function) { each(GroovyCollections.combinations(self), function); }
java
public static void eachCombination(Iterable self, Closure<?> function) { each(GroovyCollections.combinations(self), function); }
[ "public", "static", "void", "eachCombination", "(", "Iterable", "self", ",", "Closure", "<", "?", ">", "function", ")", "{", "each", "(", "GroovyCollections", ".", "combinations", "(", "self", ")", ",", "function", ")", ";", "}" ]
Applies a function on each combination of the input lists. <p> Example usage: <pre class="groovyTestCase">[[2, 3],[4, 5, 6]].eachCombination { println "Found $it" }</pre> @param self a Collection of lists @param function a closure to be called on each combination @see groovy.util.GroovyCollections#combinations(Iterable) @since 2.2.0
[ "Applies", "a", "function", "on", "each", "combination", "of", "the", "input", "lists", ".", "<p", ">", "Example", "usage", ":", "<pre", "class", "=", "groovyTestCase", ">", "[[", "2", "3", "]", "[", "4", "5", "6", "]]", ".", "eachCombination", "{", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L5324-L5326
jbundle/jbundle
thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java
BaseApplet.addSubPanels
public boolean addSubPanels(Container parent, int options) { if (parent == null) parent = m_parent; String strScreen = this.getProperty(Params.SCREEN); JBasePanel baseScreen = (JBasePanel)ClassServiceUtility.getClassService().makeObjectFromClassName(strScreen); if (baseScreen != null) { FieldList record = null; baseScreen.init(this, record); // test return this.changeSubScreen(parent, baseScreen, null, options); // You must manually push the history command } else Util.getLogger().warning("Screen class not found " + strScreen); return false; // Nothing happened }
java
public boolean addSubPanels(Container parent, int options) { if (parent == null) parent = m_parent; String strScreen = this.getProperty(Params.SCREEN); JBasePanel baseScreen = (JBasePanel)ClassServiceUtility.getClassService().makeObjectFromClassName(strScreen); if (baseScreen != null) { FieldList record = null; baseScreen.init(this, record); // test return this.changeSubScreen(parent, baseScreen, null, options); // You must manually push the history command } else Util.getLogger().warning("Screen class not found " + strScreen); return false; // Nothing happened }
[ "public", "boolean", "addSubPanels", "(", "Container", "parent", ",", "int", "options", ")", "{", "if", "(", "parent", "==", "null", ")", "parent", "=", "m_parent", ";", "String", "strScreen", "=", "this", ".", "getProperty", "(", "Params", ".", "SCREEN", ...
Add any applet sub-panel(s) now. Usually, you override this, although for a simple screen, just pass a screen=class param. @param parent The parent to add the new screen to. @param options options @return true if success
[ "Add", "any", "applet", "sub", "-", "panel", "(", "s", ")", "now", ".", "Usually", "you", "override", "this", "although", "for", "a", "simple", "screen", "just", "pass", "a", "screen", "=", "class", "param", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/BaseApplet.java#L328-L343
liferay/com-liferay-commerce
commerce-account-service/src/main/java/com/liferay/commerce/account/service/persistence/impl/CommerceAccountPersistenceImpl.java
CommerceAccountPersistenceImpl.filterFindByCompanyId
@Override public List<CommerceAccount> filterFindByCompanyId(long companyId, int start, int end) { return filterFindByCompanyId(companyId, start, end, null); }
java
@Override public List<CommerceAccount> filterFindByCompanyId(long companyId, int start, int end) { return filterFindByCompanyId(companyId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceAccount", ">", "filterFindByCompanyId", "(", "long", "companyId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "filterFindByCompanyId", "(", "companyId", ",", "start", ",", "end", ",", "null", "...
Returns a range of all the commerce accounts that the user has permission to view where companyId = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAccountModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param companyId the company ID @param start the lower bound of the range of commerce accounts @param end the upper bound of the range of commerce accounts (not inclusive) @return the range of matching commerce accounts that the user has permission to view
[ "Returns", "a", "range", "of", "all", "the", "commerce", "accounts", "that", "the", "user", "has", "permission", "to", "view", "where", "companyId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-account-service/src/main/java/com/liferay/commerce/account/service/persistence/impl/CommerceAccountPersistenceImpl.java#L568-L572
thorntail/thorntail
plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java
GradleDependencyResolutionHelper.getCachedReference
@SuppressWarnings("unchecked") private static <T> T getCachedReference(Project project, String key, Supplier<T> supplier) { if (project == null) { throw new IllegalArgumentException("Gradle project reference cannot be null."); } Project rootProject = project.getRootProject(); ExtraPropertiesExtension ext = rootProject.getExtensions().getExtraProperties(); T value; if (ext.has(key)) { value = (T) ext.get(key); } else { value = supplier.get(); ext.set(key, value); } return value; }
java
@SuppressWarnings("unchecked") private static <T> T getCachedReference(Project project, String key, Supplier<T> supplier) { if (project == null) { throw new IllegalArgumentException("Gradle project reference cannot be null."); } Project rootProject = project.getRootProject(); ExtraPropertiesExtension ext = rootProject.getExtensions().getExtraProperties(); T value; if (ext.has(key)) { value = (T) ext.get(key); } else { value = supplier.get(); ext.set(key, value); } return value; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "<", "T", ">", "T", "getCachedReference", "(", "Project", "project", ",", "String", "key", ",", "Supplier", "<", "T", ">", "supplier", ")", "{", "if", "(", "project", "==", "null", ...
Get data (identified by the given key) that has been cached on the given Gradle project reference. @param project the Gradle project reference. @param key the key used for caching the data. @param supplier the function that needs to be executed in the event of a cache-miss. @param <T> the type of the data stored on the project. @return data that has been cached on the given Gradle project reference.
[ "Get", "data", "(", "identified", "by", "the", "given", "key", ")", "that", "has", "been", "cached", "on", "the", "given", "Gradle", "project", "reference", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L382-L398
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/XMLWriter.java
XMLWriter.writeElement
public void writeElement(String name, int type) { StringBuffer nsdecl = new StringBuffer(); if (_isRootElement) { for (Iterator<String> iter = _namespaces.keySet().iterator(); iter .hasNext();) { String fullName = (String) iter.next(); String abbrev = (String) _namespaces.get(fullName); nsdecl.append(" xmlns:").append(abbrev).append("=\"").append( fullName).append("\""); } _isRootElement = false; } int pos = name.lastIndexOf(':'); if (pos >= 0) { // lookup prefix for namespace String fullns = name.substring(0, pos); String prefix = (String) _namespaces.get(fullns); if (prefix == null) { // there is no prefix for this namespace name = name.substring(pos + 1); nsdecl.append(" xmlns=\"").append(fullns).append("\""); } else { // there is a prefix name = prefix + ":" + name.substring(pos + 1); } } else { throw new IllegalArgumentException( "All XML elements must have a namespace"); } switch (type) { case OPENING: _buffer.append("<"); _buffer.append(name); _buffer.append( nsdecl); _buffer.append( ">"); break; case CLOSING: _buffer.append("</"); _buffer.append( name); _buffer.append( ">\n"); break; case NO_CONTENT: default: _buffer.append("<"); _buffer.append( name); _buffer.append( nsdecl); _buffer.append( "/>"); break; } }
java
public void writeElement(String name, int type) { StringBuffer nsdecl = new StringBuffer(); if (_isRootElement) { for (Iterator<String> iter = _namespaces.keySet().iterator(); iter .hasNext();) { String fullName = (String) iter.next(); String abbrev = (String) _namespaces.get(fullName); nsdecl.append(" xmlns:").append(abbrev).append("=\"").append( fullName).append("\""); } _isRootElement = false; } int pos = name.lastIndexOf(':'); if (pos >= 0) { // lookup prefix for namespace String fullns = name.substring(0, pos); String prefix = (String) _namespaces.get(fullns); if (prefix == null) { // there is no prefix for this namespace name = name.substring(pos + 1); nsdecl.append(" xmlns=\"").append(fullns).append("\""); } else { // there is a prefix name = prefix + ":" + name.substring(pos + 1); } } else { throw new IllegalArgumentException( "All XML elements must have a namespace"); } switch (type) { case OPENING: _buffer.append("<"); _buffer.append(name); _buffer.append( nsdecl); _buffer.append( ">"); break; case CLOSING: _buffer.append("</"); _buffer.append( name); _buffer.append( ">\n"); break; case NO_CONTENT: default: _buffer.append("<"); _buffer.append( name); _buffer.append( nsdecl); _buffer.append( "/>"); break; } }
[ "public", "void", "writeElement", "(", "String", "name", ",", "int", "type", ")", "{", "StringBuffer", "nsdecl", "=", "new", "StringBuffer", "(", ")", ";", "if", "(", "_isRootElement", ")", "{", "for", "(", "Iterator", "<", "String", ">", "iter", "=", ...
Write an element. @param name Element name @param type Element type
[ "Write", "an", "element", "." ]
train
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/XMLWriter.java#L130-L182
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/TransactionWriteRequest.java
TransactionWriteRequest.addPut
public TransactionWriteRequest addPut(Object object, DynamoDBTransactionWriteExpression transactionWriteExpression) { return addPut(object, transactionWriteExpression, null /* returnValuesOnConditionCheckFailure */); }
java
public TransactionWriteRequest addPut(Object object, DynamoDBTransactionWriteExpression transactionWriteExpression) { return addPut(object, transactionWriteExpression, null /* returnValuesOnConditionCheckFailure */); }
[ "public", "TransactionWriteRequest", "addPut", "(", "Object", "object", ",", "DynamoDBTransactionWriteExpression", "transactionWriteExpression", ")", "{", "return", "addPut", "(", "object", ",", "transactionWriteExpression", ",", "null", "/* returnValuesOnConditionCheckFailure ...
Adds put operation (to be executed on object) to the list of transaction write operations. transactionWriteExpression is used to conditionally put object.
[ "Adds", "put", "operation", "(", "to", "be", "executed", "on", "object", ")", "to", "the", "list", "of", "transaction", "write", "operations", ".", "transactionWriteExpression", "is", "used", "to", "conditionally", "put", "object", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/TransactionWriteRequest.java#L58-L60
gallandarakhneorg/afc
advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java
BusItinerary.getBusHalt
@Pure public BusItineraryHalt getBusHalt(String name, Comparator<String> nameComparator) { if (name == null) { return null; } final Comparator<String> cmp = nameComparator == null ? BusNetworkUtilities.NAME_COMPARATOR : nameComparator; for (final BusItineraryHalt bushalt : this.validHalts) { if (cmp.compare(name, bushalt.getName()) == 0) { return bushalt; } } for (final BusItineraryHalt bushalt : this.invalidHalts) { if (cmp.compare(name, bushalt.getName()) == 0) { return bushalt; } } return null; }
java
@Pure public BusItineraryHalt getBusHalt(String name, Comparator<String> nameComparator) { if (name == null) { return null; } final Comparator<String> cmp = nameComparator == null ? BusNetworkUtilities.NAME_COMPARATOR : nameComparator; for (final BusItineraryHalt bushalt : this.validHalts) { if (cmp.compare(name, bushalt.getName()) == 0) { return bushalt; } } for (final BusItineraryHalt bushalt : this.invalidHalts) { if (cmp.compare(name, bushalt.getName()) == 0) { return bushalt; } } return null; }
[ "@", "Pure", "public", "BusItineraryHalt", "getBusHalt", "(", "String", "name", ",", "Comparator", "<", "String", ">", "nameComparator", ")", "{", "if", "(", "name", "==", "null", ")", "{", "return", "null", ";", "}", "final", "Comparator", "<", "String", ...
Replies the bus halt with the specified name. @param name is the desired name @param nameComparator is used to compare the names. @return a bus halt or <code>null</code>
[ "Replies", "the", "bus", "halt", "with", "the", "specified", "name", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItinerary.java#L1583-L1600
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/write/WriteFileExtensions.java
WriteFileExtensions.writeProperties2File
public static void writeProperties2File(final String filename, final Properties properties) throws IOException { // Write properties to the file. try (FileOutputStream fos = new FileOutputStream(filename)) { properties.store(fos, null); } }
java
public static void writeProperties2File(final String filename, final Properties properties) throws IOException { // Write properties to the file. try (FileOutputStream fos = new FileOutputStream(filename)) { properties.store(fos, null); } }
[ "public", "static", "void", "writeProperties2File", "(", "final", "String", "filename", ",", "final", "Properties", "properties", ")", "throws", "IOException", "{", "// Write properties to the file.", "try", "(", "FileOutputStream", "fos", "=", "new", "FileOutputStream"...
The Method writeProperties2File(String, Properties) writes the Properties to the file. @param filename The filename from the file to write the properties. @param properties The properties. @throws IOException Signals that an I/O exception has occurred.
[ "The", "Method", "writeProperties2File", "(", "String", "Properties", ")", "writes", "the", "Properties", "to", "the", "file", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/write/WriteFileExtensions.java#L73-L81
alkacon/opencms-core
src/org/opencms/workplace/editors/CmsSimpleEditor.java
CmsSimpleEditor.decodeContentParameter
protected String decodeContentParameter(String encodedContent, String encoding, CmsFile originalFile) { return decodeContent(encodedContent); }
java
protected String decodeContentParameter(String encodedContent, String encoding, CmsFile originalFile) { return decodeContent(encodedContent); }
[ "protected", "String", "decodeContentParameter", "(", "String", "encodedContent", ",", "String", "encoding", ",", "CmsFile", "originalFile", ")", "{", "return", "decodeContent", "(", "encodedContent", ")", ";", "}" ]
Decodes the content from the content request parameter.<p> @param encodedContent the encoded content @param encoding the encoding to use @param originalFile the current file state @return the decoded content
[ "Decodes", "the", "content", "from", "the", "content", "request", "parameter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsSimpleEditor.java#L178-L181
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java
DateTimePatternGenerator.skeletonsAreSimilar
@Deprecated public boolean skeletonsAreSimilar(String id, String skeleton) { if (id.equals(skeleton)) { return true; // fast path } // must clone array, make sure items are in same order. TreeSet<String> parser1 = getSet(id); TreeSet<String> parser2 = getSet(skeleton); if (parser1.size() != parser2.size()) { return false; } Iterator<String> it2 = parser2.iterator(); for (String item : parser1) { int index1 = getCanonicalIndex(item, false); String item2 = it2.next(); // same length so safe int index2 = getCanonicalIndex(item2, false); if (types[index1][1] != types[index2][1]) { return false; } } return true; }
java
@Deprecated public boolean skeletonsAreSimilar(String id, String skeleton) { if (id.equals(skeleton)) { return true; // fast path } // must clone array, make sure items are in same order. TreeSet<String> parser1 = getSet(id); TreeSet<String> parser2 = getSet(skeleton); if (parser1.size() != parser2.size()) { return false; } Iterator<String> it2 = parser2.iterator(); for (String item : parser1) { int index1 = getCanonicalIndex(item, false); String item2 = it2.next(); // same length so safe int index2 = getCanonicalIndex(item2, false); if (types[index1][1] != types[index2][1]) { return false; } } return true; }
[ "@", "Deprecated", "public", "boolean", "skeletonsAreSimilar", "(", "String", "id", ",", "String", "skeleton", ")", "{", "if", "(", "id", ".", "equals", "(", "skeleton", ")", ")", "{", "return", "true", ";", "// fast path", "}", "// must clone array, make sure...
Used by CLDR tooling; not in ICU4C. Note, this will not work correctly with normal skeletons, since fields that should be related in the two skeletons being compared - like EEE and ccc, or y and U - will not be sorted in the same relative place as each other when iterating over both TreeSets being compare, using TreeSet's "natural" code point ordering (this could be addressed by initializing the TreeSet with a comparator that compares fields first by their index from getCanonicalIndex()). However if comparing canonical skeletons from getCanonicalSkeletonAllowingDuplicates it will be OK regardless, since in these skeletons all fields are normalized to the canonical pattern char for those fields - M or L to M, E or c to E, y or U to y, etc. - so corresponding fields will sort in the same way for both TreeMaps. @deprecated This API is ICU internal only. @hide original deprecated declaration @hide draft / provisional / internal are hidden on Android
[ "Used", "by", "CLDR", "tooling", ";", "not", "in", "ICU4C", ".", "Note", "this", "will", "not", "work", "correctly", "with", "normal", "skeletons", "since", "fields", "that", "should", "be", "related", "in", "the", "two", "skeletons", "being", "compared", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java#L1668-L1689
WASdev/tool.accelerate.core
liberty-starter-application/src/main/java/com/ibm/liberty/starter/build/maven/DomUtil.java
DomUtil.getGrandchildNode
public static Node getGrandchildNode(Node parentNode, String childNodeName, String grandChildNodeName, String grandChildNodeValue){ List<Node> matchingChildren = getChildren(parentNode, childNodeName, null); for(Node child : matchingChildren){ Node matchingGrandChild = getChildNode(child, grandChildNodeName, grandChildNodeValue); if(matchingGrandChild != null){ return matchingGrandChild; } } return null; }
java
public static Node getGrandchildNode(Node parentNode, String childNodeName, String grandChildNodeName, String grandChildNodeValue){ List<Node> matchingChildren = getChildren(parentNode, childNodeName, null); for(Node child : matchingChildren){ Node matchingGrandChild = getChildNode(child, grandChildNodeName, grandChildNodeValue); if(matchingGrandChild != null){ return matchingGrandChild; } } return null; }
[ "public", "static", "Node", "getGrandchildNode", "(", "Node", "parentNode", ",", "String", "childNodeName", ",", "String", "grandChildNodeName", ",", "String", "grandChildNodeValue", ")", "{", "List", "<", "Node", ">", "matchingChildren", "=", "getChildren", "(", ...
Get the matching grand child node @param parentNode - the parent node @param childNodeName - name of child node to match @param grandChildNodeName - name of grand child node to match @param grandChildNodeValue - value of grand child node to match @return the grand child node if a match was found, null otherwise
[ "Get", "the", "matching", "grand", "child", "node" ]
train
https://github.com/WASdev/tool.accelerate.core/blob/6511da654a69a25a76573eb76eefff349d9c4d80/liberty-starter-application/src/main/java/com/ibm/liberty/starter/build/maven/DomUtil.java#L63-L72
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/Compare.java
Compare.movies
public static boolean movies(final MovieInfo moviedb, final String title, final String year, int maxDistance, boolean caseSensitive) { if ((moviedb == null) || (StringUtils.isBlank(title))) { return false; } String primaryTitle, firstCompareTitle, secondCompareTitle; if (caseSensitive) { primaryTitle = title; firstCompareTitle = moviedb.getOriginalTitle(); secondCompareTitle = moviedb.getTitle(); } else { primaryTitle = title.toLowerCase(); firstCompareTitle = moviedb.getTitle().toLowerCase(); secondCompareTitle = moviedb.getOriginalTitle().toLowerCase(); } if (isValidYear(year) && isValidYear(moviedb.getReleaseDate())) { // Compare with year String movieYear = moviedb.getReleaseDate().substring(0, YEAR_LENGTH); return movieYear.equals(year) && compareTitles(primaryTitle, firstCompareTitle, secondCompareTitle, maxDistance); } // Compare without year return compareTitles(primaryTitle, firstCompareTitle, secondCompareTitle, maxDistance); }
java
public static boolean movies(final MovieInfo moviedb, final String title, final String year, int maxDistance, boolean caseSensitive) { if ((moviedb == null) || (StringUtils.isBlank(title))) { return false; } String primaryTitle, firstCompareTitle, secondCompareTitle; if (caseSensitive) { primaryTitle = title; firstCompareTitle = moviedb.getOriginalTitle(); secondCompareTitle = moviedb.getTitle(); } else { primaryTitle = title.toLowerCase(); firstCompareTitle = moviedb.getTitle().toLowerCase(); secondCompareTitle = moviedb.getOriginalTitle().toLowerCase(); } if (isValidYear(year) && isValidYear(moviedb.getReleaseDate())) { // Compare with year String movieYear = moviedb.getReleaseDate().substring(0, YEAR_LENGTH); return movieYear.equals(year) && compareTitles(primaryTitle, firstCompareTitle, secondCompareTitle, maxDistance); } // Compare without year return compareTitles(primaryTitle, firstCompareTitle, secondCompareTitle, maxDistance); }
[ "public", "static", "boolean", "movies", "(", "final", "MovieInfo", "moviedb", ",", "final", "String", "title", ",", "final", "String", "year", ",", "int", "maxDistance", ",", "boolean", "caseSensitive", ")", "{", "if", "(", "(", "moviedb", "==", "null", "...
Compare the MovieDB object with a title and year @param moviedb The moviedb object to compare too @param title The title of the movie to compare @param year The year of the movie to compare @param maxDistance The Levenshtein Distance between the two titles. 0 = exact match @param caseSensitive true if the comparison is to be case sensitive @return True if there is a match, False otherwise.
[ "Compare", "the", "MovieDB", "object", "with", "a", "title", "and", "year" ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/Compare.java#L64-L88
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java
QueueContainer.addAllBackup
public void addAllBackup(Map<Long, Data> dataMap) { for (Map.Entry<Long, Data> entry : dataMap.entrySet()) { QueueItem item = new QueueItem(this, entry.getKey(), null); if (!store.isEnabled() || store.getMemoryLimit() > getItemQueue().size()) { item.setData(entry.getValue()); } getBackupMap().put(item.getItemId(), item); } }
java
public void addAllBackup(Map<Long, Data> dataMap) { for (Map.Entry<Long, Data> entry : dataMap.entrySet()) { QueueItem item = new QueueItem(this, entry.getKey(), null); if (!store.isEnabled() || store.getMemoryLimit() > getItemQueue().size()) { item.setData(entry.getValue()); } getBackupMap().put(item.getItemId(), item); } }
[ "public", "void", "addAllBackup", "(", "Map", "<", "Long", ",", "Data", ">", "dataMap", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Long", ",", "Data", ">", "entry", ":", "dataMap", ".", "entrySet", "(", ")", ")", "{", "QueueItem", "item", "="...
Offers the items to the backup map in bulk. If the memory limit has been achieved the item data will not be kept in-memory. Executed on the backup replica @param dataMap the map from item ID to queue item @see #offerBackup(Data, long)
[ "Offers", "the", "items", "to", "the", "backup", "map", "in", "bulk", ".", "If", "the", "memory", "limit", "has", "been", "achieved", "the", "item", "data", "will", "not", "be", "kept", "in", "-", "memory", ".", "Executed", "on", "the", "backup", "repl...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java#L512-L520
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java
ExecutionConfig.addDefaultKryoSerializer
public <T extends Serializer<?> & Serializable>void addDefaultKryoSerializer(Class<?> type, T serializer) { if (type == null || serializer == null) { throw new NullPointerException("Cannot register null class or serializer."); } defaultKryoSerializers.put(type, new SerializableSerializer<>(serializer)); }
java
public <T extends Serializer<?> & Serializable>void addDefaultKryoSerializer(Class<?> type, T serializer) { if (type == null || serializer == null) { throw new NullPointerException("Cannot register null class or serializer."); } defaultKryoSerializers.put(type, new SerializableSerializer<>(serializer)); }
[ "public", "<", "T", "extends", "Serializer", "<", "?", ">", "&", "Serializable", ">", "void", "addDefaultKryoSerializer", "(", "Class", "<", "?", ">", "type", ",", "T", "serializer", ")", "{", "if", "(", "type", "==", "null", "||", "serializer", "==", ...
Adds a new Kryo default serializer to the Runtime. Note that the serializer instance must be serializable (as defined by java.io.Serializable), because it may be distributed to the worker nodes by java serialization. @param type The class of the types serialized with the given serializer. @param serializer The serializer to use.
[ "Adds", "a", "new", "Kryo", "default", "serializer", "to", "the", "Runtime", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java#L768-L774
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java
CassandraDataHandlerBase.getColumnValue
private Object getColumnValue(EntityMetadata m, Object e, Attribute attribute) { Field field = (Field) ((Attribute) attribute).getJavaMember(); Object value; if (!m.isCounterColumnType()) { value = getThriftColumnValue(e, attribute); } else { value = PropertyAccessorHelper.getString(e, field); } return value; }
java
private Object getColumnValue(EntityMetadata m, Object e, Attribute attribute) { Field field = (Field) ((Attribute) attribute).getJavaMember(); Object value; if (!m.isCounterColumnType()) { value = getThriftColumnValue(e, attribute); } else { value = PropertyAccessorHelper.getString(e, field); } return value; }
[ "private", "Object", "getColumnValue", "(", "EntityMetadata", "m", ",", "Object", "e", ",", "Attribute", "attribute", ")", "{", "Field", "field", "=", "(", "Field", ")", "(", "(", "Attribute", ")", "attribute", ")", ".", "getJavaMember", "(", ")", ";", "...
Gets the column value. @param m the m @param e the e @param attribute the attribute @return the column value
[ "Gets", "the", "column", "value", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java#L2001-L2014
lucee/Lucee
core/src/main/java/lucee/runtime/functions/conversion/SerializeJSON.java
SerializeJSON.call
public static String call(PageContext pc, Object var, boolean serializeQueryByColumns, String strCharset) throws PageException { Charset cs = StringUtil.isEmpty(strCharset) ? pc.getWebCharset() : CharsetUtil.toCharset(strCharset); return _call(pc, var, serializeQueryByColumns, cs); }
java
public static String call(PageContext pc, Object var, boolean serializeQueryByColumns, String strCharset) throws PageException { Charset cs = StringUtil.isEmpty(strCharset) ? pc.getWebCharset() : CharsetUtil.toCharset(strCharset); return _call(pc, var, serializeQueryByColumns, cs); }
[ "public", "static", "String", "call", "(", "PageContext", "pc", ",", "Object", "var", ",", "boolean", "serializeQueryByColumns", ",", "String", "strCharset", ")", "throws", "PageException", "{", "Charset", "cs", "=", "StringUtil", ".", "isEmpty", "(", "strCharse...
FUTURE remove, this methods are only used by compiled code in archives older than 5.2.3
[ "FUTURE", "remove", "this", "methods", "are", "only", "used", "by", "compiled", "code", "in", "archives", "older", "than", "5", ".", "2", ".", "3" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/functions/conversion/SerializeJSON.java#L61-L64
atomix/catalyst
serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java
SerializerRegistry.registerAbstract
public SerializerRegistry registerAbstract(Class<?> abstractType, Class<? extends TypeSerializer> serializer) { return registerAbstract(abstractType, calculateTypeId(abstractType), new DefaultTypeSerializerFactory(serializer)); }
java
public SerializerRegistry registerAbstract(Class<?> abstractType, Class<? extends TypeSerializer> serializer) { return registerAbstract(abstractType, calculateTypeId(abstractType), new DefaultTypeSerializerFactory(serializer)); }
[ "public", "SerializerRegistry", "registerAbstract", "(", "Class", "<", "?", ">", "abstractType", ",", "Class", "<", "?", "extends", "TypeSerializer", ">", "serializer", ")", "{", "return", "registerAbstract", "(", "abstractType", ",", "calculateTypeId", "(", "abst...
Registers the given class as an abstract serializer for the given abstract type. @param abstractType The abstract type for which to register the serializer. @param serializer The serializer class. @return The serializer registry.
[ "Registers", "the", "given", "class", "as", "an", "abstract", "serializer", "for", "the", "given", "abstract", "type", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java#L208-L210
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Counters.java
Counters.dotProductInPlace
public static <E> void dotProductInPlace(Counter<E> target, Counter<E> term) { for (E key : target.keySet()) { target.setCount(key, target.getCount(key) * term.getCount(key)); } }
java
public static <E> void dotProductInPlace(Counter<E> target, Counter<E> term) { for (E key : target.keySet()) { target.setCount(key, target.getCount(key) * term.getCount(key)); } }
[ "public", "static", "<", "E", ">", "void", "dotProductInPlace", "(", "Counter", "<", "E", ">", "target", ",", "Counter", "<", "E", ">", "term", ")", "{", "for", "(", "E", "key", ":", "target", ".", "keySet", "(", ")", ")", "{", "target", ".", "se...
Multiplies every count in target by the corresponding value in the term Counter.
[ "Multiplies", "every", "count", "in", "target", "by", "the", "corresponding", "value", "in", "the", "term", "Counter", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L423-L427
ops4j/org.ops4j.base
ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java
Resources.getTime
public Date getTime( String key, Date defaultValue ) throws MissingResourceException { try { return getTime( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
java
public Date getTime( String key, Date defaultValue ) throws MissingResourceException { try { return getTime( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
[ "public", "Date", "getTime", "(", "String", "key", ",", "Date", "defaultValue", ")", "throws", "MissingResourceException", "{", "try", "{", "return", "getTime", "(", "key", ")", ";", "}", "catch", "(", "MissingResourceException", "mre", ")", "{", "return", "...
Retrieve a time from bundle. @param key the key of resource @param defaultValue the default value if key is missing @return the resource time @throws MissingResourceException if the requested key is unknown
[ "Retrieve", "a", "time", "from", "bundle", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/Resources.java#L579-L590
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/query/engine/ScanningQueryEngine.java
ScanningQueryEngine.executeOptimizedQuery
protected QueryResults executeOptimizedQuery( final ScanQueryContext context, QueryCommand command, Statistics statistics, PlanNode plan ) { long nanos = System.nanoTime(); Columns columns = null; NodeSequence rows = null; final String workspaceName = context.getWorkspaceNames().iterator().next(); try { // Find the topmost PROJECT node and build the Columns ... PlanNode project = plan.findAtOrBelow(Type.PROJECT); assert project != null; columns = context.columnsFor(plan); assert columns != null; boolean trace = LOGGER.isTraceEnabled(); if (context.getHints().planOnly) { if (trace) { LOGGER.trace("Request for only query plan when executing query {0}", context.id()); } rows = NodeSequence.emptySequence(columns.getColumns().size()); } else { boolean includeSystemContent = context.getHints().includeSystemContent; final QuerySources sources = new QuerySources(context.getRepositoryCache(), context.getNodeTypes(), workspaceName, includeSystemContent); rows = createNodeSequence(command, context, plan, columns, sources); long nanos2 = System.nanoTime(); statistics = statistics.withResultsFormulationTime(Math.abs(nanos2 - nanos)); nanos = nanos2; if (rows == null) { // There must have been an error or was cancelled ... assert context.getProblems().hasErrors() || context.isCancelled(); rows = NodeSequence.emptySequence(columns.getColumns().size()); } if (trace) { LOGGER.trace("The execution function for {0}: {1}", context.id(), rows); } } } finally { statistics = statistics.withExecutionTime(Math.abs(System.nanoTime() - nanos)); } final String planDesc = context.getHints().showPlan ? plan.getString() : null; CachedNodeSupplier cachedNodes = context.getNodeCache(workspaceName); return new Results(columns, statistics, rows, cachedNodes, context.getProblems(), planDesc); }
java
protected QueryResults executeOptimizedQuery( final ScanQueryContext context, QueryCommand command, Statistics statistics, PlanNode plan ) { long nanos = System.nanoTime(); Columns columns = null; NodeSequence rows = null; final String workspaceName = context.getWorkspaceNames().iterator().next(); try { // Find the topmost PROJECT node and build the Columns ... PlanNode project = plan.findAtOrBelow(Type.PROJECT); assert project != null; columns = context.columnsFor(plan); assert columns != null; boolean trace = LOGGER.isTraceEnabled(); if (context.getHints().planOnly) { if (trace) { LOGGER.trace("Request for only query plan when executing query {0}", context.id()); } rows = NodeSequence.emptySequence(columns.getColumns().size()); } else { boolean includeSystemContent = context.getHints().includeSystemContent; final QuerySources sources = new QuerySources(context.getRepositoryCache(), context.getNodeTypes(), workspaceName, includeSystemContent); rows = createNodeSequence(command, context, plan, columns, sources); long nanos2 = System.nanoTime(); statistics = statistics.withResultsFormulationTime(Math.abs(nanos2 - nanos)); nanos = nanos2; if (rows == null) { // There must have been an error or was cancelled ... assert context.getProblems().hasErrors() || context.isCancelled(); rows = NodeSequence.emptySequence(columns.getColumns().size()); } if (trace) { LOGGER.trace("The execution function for {0}: {1}", context.id(), rows); } } } finally { statistics = statistics.withExecutionTime(Math.abs(System.nanoTime() - nanos)); } final String planDesc = context.getHints().showPlan ? plan.getString() : null; CachedNodeSupplier cachedNodes = context.getNodeCache(workspaceName); return new Results(columns, statistics, rows, cachedNodes, context.getProblems(), planDesc); }
[ "protected", "QueryResults", "executeOptimizedQuery", "(", "final", "ScanQueryContext", "context", ",", "QueryCommand", "command", ",", "Statistics", "statistics", ",", "PlanNode", "plan", ")", "{", "long", "nanos", "=", "System", ".", "nanoTime", "(", ")", ";", ...
Execute the optimized query defined by the supplied {@link PlanNode plan node}. @param context the context in which the query is to be executed; may not be null @param command the original query; may not be null @param statistics the statistics for the current query execution @param plan the optimized plan for the query; may not be null @return the query results; never null but possibly empty
[ "Execute", "the", "optimized", "query", "defined", "by", "the", "supplied", "{", "@link", "PlanNode", "plan", "node", "}", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/engine/ScanningQueryEngine.java#L481-L526
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/lib/RefCapablePropertyResourceBundle.java
RefCapablePropertyResourceBundle.getExpandedString
public String getExpandedString(String key, int behavior) { String s = getString(key); Matcher matcher = sysPropVarPattern.matcher(s); int previousEnd = 0; StringBuffer sb = new StringBuffer(); String varName, varValue; String condlVal; // Conditional : value while (matcher.find()) { varName = matcher.group(1); condlVal = ((matcher.groupCount() > 1) ? matcher.group(2) : null); varValue = System.getProperty(varName); if (condlVal != null) { // Replace varValue (the value to be substituted), with // the post-:+ portion of the expression. varValue = ((varValue == null) ? "" : condlVal.replaceAll("\\Q$" + varName + "\\E\\b", RefCapablePropertyResourceBundle.literalize( varValue))); } if (varValue == null) switch (behavior) { case THROW_BEHAVIOR: throw new RuntimeException( "No Sys Property set for variable '" + varName + "' in property value (" + s + ")."); case EMPTYSTRING_BEHAVIOR: varValue = ""; case NOOP_BEHAVIOR: break; default: throw new RuntimeException( "Undefined value for behavior: " + behavior); } sb.append(s.substring(previousEnd, matcher.start()) + ((varValue == null) ? matcher.group() : varValue)); previousEnd = matcher.end(); } return (previousEnd < 1) ? s : (sb.toString() + s.substring(previousEnd)); }
java
public String getExpandedString(String key, int behavior) { String s = getString(key); Matcher matcher = sysPropVarPattern.matcher(s); int previousEnd = 0; StringBuffer sb = new StringBuffer(); String varName, varValue; String condlVal; // Conditional : value while (matcher.find()) { varName = matcher.group(1); condlVal = ((matcher.groupCount() > 1) ? matcher.group(2) : null); varValue = System.getProperty(varName); if (condlVal != null) { // Replace varValue (the value to be substituted), with // the post-:+ portion of the expression. varValue = ((varValue == null) ? "" : condlVal.replaceAll("\\Q$" + varName + "\\E\\b", RefCapablePropertyResourceBundle.literalize( varValue))); } if (varValue == null) switch (behavior) { case THROW_BEHAVIOR: throw new RuntimeException( "No Sys Property set for variable '" + varName + "' in property value (" + s + ")."); case EMPTYSTRING_BEHAVIOR: varValue = ""; case NOOP_BEHAVIOR: break; default: throw new RuntimeException( "Undefined value for behavior: " + behavior); } sb.append(s.substring(previousEnd, matcher.start()) + ((varValue == null) ? matcher.group() : varValue)); previousEnd = matcher.end(); } return (previousEnd < 1) ? s : (sb.toString() + s.substring(previousEnd)); }
[ "public", "String", "getExpandedString", "(", "String", "key", ",", "int", "behavior", ")", "{", "String", "s", "=", "getString", "(", "key", ")", ";", "Matcher", "matcher", "=", "sysPropVarPattern", ".", "matcher", "(", "s", ")", ";", "int", "previousEnd"...
Same as getString(), but expands System Variables specified in property values like ${sysvarname}.
[ "Same", "as", "getString", "()", "but", "expands", "System", "Variables", "specified", "in", "property", "values", "like", "$", "{", "sysvarname", "}", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/RefCapablePropertyResourceBundle.java#L194-L234
agmip/dome
src/main/java/org/agmip/dome/Engine.java
Engine.runGenerators
public ArrayList<HashMap<String, Object>> runGenerators(HashMap<String, Object> data) { return runGenerators(data, false); }
java
public ArrayList<HashMap<String, Object>> runGenerators(HashMap<String, Object> data) { return runGenerators(data, false); }
[ "public", "ArrayList", "<", "HashMap", "<", "String", ",", "Object", ">", ">", "runGenerators", "(", "HashMap", "<", "String", ",", "Object", ">", "data", ")", "{", "return", "runGenerators", "(", "data", ",", "false", ")", ";", "}" ]
Run the generators on the dataset passed in. This will generate a number of additional datasets based on the original dataset. @param data A dataset to run the generators on @return A {@code HashMap} of just the exported keys.
[ "Run", "the", "generators", "on", "the", "dataset", "passed", "in", ".", "This", "will", "generate", "a", "number", "of", "additional", "datasets", "based", "on", "the", "original", "dataset", "." ]
train
https://github.com/agmip/dome/blob/ca7c15bf2bae09bb7e8d51160e77592bbda9343d/src/main/java/org/agmip/dome/Engine.java#L301-L303
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java
ST_Drape.drapeMultiPolygon
public static Geometry drapeMultiPolygon(MultiPolygon polygons, Geometry triangles, STRtree sTRtree) { GeometryFactory factory = polygons.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); int nbPolygons = polygons.getNumGeometries(); Polygon[] polygonsDiff = new Polygon[nbPolygons]; for (int i = 0; i < nbPolygons; i++) { polygonsDiff[i] = processPolygon((Polygon) polygons.getGeometryN(i), triangleLines, factory); } Geometry diffExt = factory.createMultiPolygon(polygonsDiff); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); diffExt.apply(drapeFilter); return diffExt; }
java
public static Geometry drapeMultiPolygon(MultiPolygon polygons, Geometry triangles, STRtree sTRtree) { GeometryFactory factory = polygons.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); int nbPolygons = polygons.getNumGeometries(); Polygon[] polygonsDiff = new Polygon[nbPolygons]; for (int i = 0; i < nbPolygons; i++) { polygonsDiff[i] = processPolygon((Polygon) polygons.getGeometryN(i), triangleLines, factory); } Geometry diffExt = factory.createMultiPolygon(polygonsDiff); CoordinateSequenceFilter drapeFilter = new DrapeFilter(sTRtree); diffExt.apply(drapeFilter); return diffExt; }
[ "public", "static", "Geometry", "drapeMultiPolygon", "(", "MultiPolygon", "polygons", ",", "Geometry", "triangles", ",", "STRtree", "sTRtree", ")", "{", "GeometryFactory", "factory", "=", "polygons", ".", "getFactory", "(", ")", ";", "//Split the triangles in lines to...
Drape a multilinestring to a set of triangles @param polygons @param triangles @param sTRtree @return
[ "Drape", "a", "multilinestring", "to", "a", "set", "of", "triangles" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/topography/ST_Drape.java#L106-L119
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java
WebDriverHelper.waitForElementToContainSpecificText
public void waitForElementToContainSpecificText(final By by, final String text, final int maximumSeconds) { WebDriverWait wait = new WebDriverWait(driver, maximumSeconds); wait.until(ExpectedConditions.textToBePresentInElement(by, text)); }
java
public void waitForElementToContainSpecificText(final By by, final String text, final int maximumSeconds) { WebDriverWait wait = new WebDriverWait(driver, maximumSeconds); wait.until(ExpectedConditions.textToBePresentInElement(by, text)); }
[ "public", "void", "waitForElementToContainSpecificText", "(", "final", "By", "by", ",", "final", "String", "text", ",", "final", "int", "maximumSeconds", ")", "{", "WebDriverWait", "wait", "=", "new", "WebDriverWait", "(", "driver", ",", "maximumSeconds", ")", "...
Waits until an element contains a specific text. @param by method of identifying the element @param text the element text to wait for @param maximumSeconds the maximum number of seconds to wait for
[ "Waits", "until", "an", "element", "contains", "a", "specific", "text", "." ]
train
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java#L531-L535
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java
ComputerVisionImpl.analyzeImageInStream
public ImageAnalysis analyzeImageInStream(byte[] image, AnalyzeImageInStreamOptionalParameter analyzeImageInStreamOptionalParameter) { return analyzeImageInStreamWithServiceResponseAsync(image, analyzeImageInStreamOptionalParameter).toBlocking().single().body(); }
java
public ImageAnalysis analyzeImageInStream(byte[] image, AnalyzeImageInStreamOptionalParameter analyzeImageInStreamOptionalParameter) { return analyzeImageInStreamWithServiceResponseAsync(image, analyzeImageInStreamOptionalParameter).toBlocking().single().body(); }
[ "public", "ImageAnalysis", "analyzeImageInStream", "(", "byte", "[", "]", "image", ",", "AnalyzeImageInStreamOptionalParameter", "analyzeImageInStreamOptionalParameter", ")", "{", "return", "analyzeImageInStreamWithServiceResponseAsync", "(", "image", ",", "analyzeImageInStreamOp...
This operation extracts a rich set of visual features based on the image content. @param image An image stream. @param analyzeImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ComputerVisionErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ImageAnalysis object if successful.
[ "This", "operation", "extracts", "a", "rich", "set", "of", "visual", "features", "based", "on", "the", "image", "content", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L1079-L1081
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java
KiteRequestHandler.getCSVRequest
public String getCSVRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { Request request = new Request.Builder().url(url).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); Response response = client.newCall(request).execute(); String body = response.body().string(); return new KiteResponseHandler().handle(response, body, "csv"); }
java
public String getCSVRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException { Request request = new Request.Builder().url(url).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); Response response = client.newCall(request).execute(); String body = response.body().string(); return new KiteResponseHandler().handle(response, body, "csv"); }
[ "public", "String", "getCSVRequest", "(", "String", "url", ",", "String", "apiKey", ",", "String", "accessToken", ")", "throws", "IOException", ",", "KiteException", ",", "JSONException", "{", "Request", "request", "=", "new", "Request", ".", "Builder", "(", "...
Makes GET request to fetch CSV dump. @return String which is received from server. @param url is the endpoint to which request has to be done. @param apiKey is the api key of the Kite Connect app. @param accessToken is the access token obtained after successful login process. @throws IOException is thrown when there is a connection related error. @throws KiteException is thrown for all Kite Trade related errors.
[ "Makes", "GET", "request", "to", "fetch", "CSV", "dump", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java#L146-L151
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/XlsLoader.java
XlsLoader.load
public <P> P load(final InputStream xlsIn, final Class<P> clazz) throws XlsMapperException, IOException { ArgUtils.notNull(xlsIn, "xlsIn"); ArgUtils.notNull(clazz, "clazz"); return loadDetail(xlsIn, clazz).getTarget(); }
java
public <P> P load(final InputStream xlsIn, final Class<P> clazz) throws XlsMapperException, IOException { ArgUtils.notNull(xlsIn, "xlsIn"); ArgUtils.notNull(clazz, "clazz"); return loadDetail(xlsIn, clazz).getTarget(); }
[ "public", "<", "P", ">", "P", "load", "(", "final", "InputStream", "xlsIn", ",", "final", "Class", "<", "P", ">", "clazz", ")", "throws", "XlsMapperException", ",", "IOException", "{", "ArgUtils", ".", "notNull", "(", "xlsIn", ",", "\"xlsIn\"", ")", ";",...
Excelファイルの1シートを読み込み、任意のクラスにマッピングする。 @param <P> シートをマッピングするクラスタイプ @param xlsIn 読み込みもとのExcelファイルのストリーム。 @param clazz マッピング先のクラスタイプ。 @return シートをマッピングしたオブジェクト。 {@link Configuration#isIgnoreSheetNotFound()}の値がtrueで、シートが見つからない場合、nullを返します。 @throws IllegalArgumentException {@literal xlsIn == null or clazz == null} @throws XlsMapperException Excelファイルのマッピングに失敗した場合 @throws IOException ファイルの読み込みに失敗した場合
[ "Excelファイルの1シートを読み込み、任意のクラスにマッピングする。" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/XlsLoader.java#L81-L87
jenkinsci/support-core-plugin
src/main/java/com/cloudbees/jenkins/support/impl/SlaveLogs.java
SlaveLogs.addSlaveJulLogRecords
private void addSlaveJulLogRecords(Container result, List<java.util.concurrent.Callable<List<FileContent>>> tasks, final Node node, final SmartLogFetcher logFetcher) { final FilePath rootPath = node.getRootPath(); if (rootPath != null) { // rotated log files stored on the disk tasks.add(new java.util.concurrent.Callable<List<FileContent>>(){ public List<FileContent> call() throws Exception { List<FileContent> result = new ArrayList<FileContent>(); FilePath supportPath = rootPath.child(SUPPORT_DIRECTORY_NAME); if (supportPath.isDirectory()) { final Map<String, File> logFiles = logFetcher.forNode(node).getLogFiles(supportPath); for (Map.Entry<String, File> entry : logFiles.entrySet()) { result.add(new FileContent( "nodes/slave/{0}/logs/{1}", new String[]{node.getNodeName(), entry.getKey()}, entry.getValue()) ); } } return result; } }); } // this file captures the most recent of those that are still kept around in memory. // this overlaps with Jenkins.logRecords, and also overlaps with what's written in files, // but added nonetheless just in case. // // should be ignorable. result.add(new LogRecordContent("nodes/slave/{0}/logs/all_memory_buffer.log", node.getNodeName()) { @Override public Iterable<LogRecord> getLogRecords() throws IOException { try { return SupportPlugin.getInstance().getAllLogRecords(node); } catch (InterruptedException e) { throw (IOException)new InterruptedIOException().initCause(e); } } }); }
java
private void addSlaveJulLogRecords(Container result, List<java.util.concurrent.Callable<List<FileContent>>> tasks, final Node node, final SmartLogFetcher logFetcher) { final FilePath rootPath = node.getRootPath(); if (rootPath != null) { // rotated log files stored on the disk tasks.add(new java.util.concurrent.Callable<List<FileContent>>(){ public List<FileContent> call() throws Exception { List<FileContent> result = new ArrayList<FileContent>(); FilePath supportPath = rootPath.child(SUPPORT_DIRECTORY_NAME); if (supportPath.isDirectory()) { final Map<String, File> logFiles = logFetcher.forNode(node).getLogFiles(supportPath); for (Map.Entry<String, File> entry : logFiles.entrySet()) { result.add(new FileContent( "nodes/slave/{0}/logs/{1}", new String[]{node.getNodeName(), entry.getKey()}, entry.getValue()) ); } } return result; } }); } // this file captures the most recent of those that are still kept around in memory. // this overlaps with Jenkins.logRecords, and also overlaps with what's written in files, // but added nonetheless just in case. // // should be ignorable. result.add(new LogRecordContent("nodes/slave/{0}/logs/all_memory_buffer.log", node.getNodeName()) { @Override public Iterable<LogRecord> getLogRecords() throws IOException { try { return SupportPlugin.getInstance().getAllLogRecords(node); } catch (InterruptedException e) { throw (IOException)new InterruptedIOException().initCause(e); } } }); }
[ "private", "void", "addSlaveJulLogRecords", "(", "Container", "result", ",", "List", "<", "java", ".", "util", ".", "concurrent", ".", "Callable", "<", "List", "<", "FileContent", ">", ">", ">", "tasks", ",", "final", "Node", "node", ",", "final", "SmartLo...
Captures a "recent" (but still fairly large number of) j.u.l entries written on this agent. @see JenkinsLogs#addMasterJulLogRecords(Container)
[ "Captures", "a", "recent", "(", "but", "still", "fairly", "large", "number", "of", ")", "j", ".", "u", ".", "l", "entries", "written", "on", "this", "agent", "." ]
train
https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/SlaveLogs.java#L169-L206
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.permutationInverse
public static void permutationInverse( int []original , int []inverse , int length ) { for (int i = 0; i < length; i++) { inverse[original[i]] = i; } }
java
public static void permutationInverse( int []original , int []inverse , int length ) { for (int i = 0; i < length; i++) { inverse[original[i]] = i; } }
[ "public", "static", "void", "permutationInverse", "(", "int", "[", "]", "original", ",", "int", "[", "]", "inverse", ",", "int", "length", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "inverse", "...
Computes the inverse permutation vector @param original Original permutation vector @param inverse It's inverse
[ "Computes", "the", "inverse", "permutation", "vector" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L867-L871
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.beginGetTroubleshootingResult
public TroubleshootingResultInner beginGetTroubleshootingResult(String resourceGroupName, String networkWatcherName, String targetResourceId) { return beginGetTroubleshootingResultWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().single().body(); }
java
public TroubleshootingResultInner beginGetTroubleshootingResult(String resourceGroupName, String networkWatcherName, String targetResourceId) { return beginGetTroubleshootingResultWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().single().body(); }
[ "public", "TroubleshootingResultInner", "beginGetTroubleshootingResult", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "targetResourceId", ")", "{", "return", "beginGetTroubleshootingResultWithServiceResponseAsync", "(", "resourceGroupName"...
Get the last completed troubleshooting result on a specified resource. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher resource. @param targetResourceId The target resource ID to query the troubleshooting result. @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 TroubleshootingResultInner object if successful.
[ "Get", "the", "last", "completed", "troubleshooting", "result", "on", "a", "specified", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1708-L1710
Mthwate/DatLib
src/main/java/com/mthwate/datlib/PropertyUtils.java
PropertyUtils.getProperty
public static String getProperty(File file, String key, String defaultValue) { String property = null; try { property = PropertiesFactory.load(file).getProperty(key); } catch (IOException e) {} return property == null ? defaultValue : property; }
java
public static String getProperty(File file, String key, String defaultValue) { String property = null; try { property = PropertiesFactory.load(file).getProperty(key); } catch (IOException e) {} return property == null ? defaultValue : property; }
[ "public", "static", "String", "getProperty", "(", "File", "file", ",", "String", "key", ",", "String", "defaultValue", ")", "{", "String", "property", "=", "null", ";", "try", "{", "property", "=", "PropertiesFactory", ".", "load", "(", "file", ")", ".", ...
Retrieves a value from a properties file. @since 1.2 @param file the properties file @param key the property key @param defaultValue the fallback value to use @return the value retrieved with the supplied key
[ "Retrieves", "a", "value", "from", "a", "properties", "file", "." ]
train
https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/PropertyUtils.java#L63-L69
JodaOrg/joda-beans
src/main/java/org/joda/beans/impl/flexi/FlexiBean.java
FlexiBean.putAll
public void putAll(Map<String, ? extends Object> map) { if (map.size() > 0) { for (String key : map.keySet()) { if (VALID_KEY.matcher(key).matches() == false) { throw new IllegalArgumentException("Invalid key for FlexiBean: " + key); } } if (data == Collections.EMPTY_MAP) { data = new LinkedHashMap<>(map); } else { data.putAll(map); } } }
java
public void putAll(Map<String, ? extends Object> map) { if (map.size() > 0) { for (String key : map.keySet()) { if (VALID_KEY.matcher(key).matches() == false) { throw new IllegalArgumentException("Invalid key for FlexiBean: " + key); } } if (data == Collections.EMPTY_MAP) { data = new LinkedHashMap<>(map); } else { data.putAll(map); } } }
[ "public", "void", "putAll", "(", "Map", "<", "String", ",", "?", "extends", "Object", ">", "map", ")", "{", "if", "(", "map", ".", "size", "(", ")", ">", "0", ")", "{", "for", "(", "String", "key", ":", "map", ".", "keySet", "(", ")", ")", "{...
Puts the properties in the specified map into this bean. <p> This creates properties if they do not exist. @param map the map of properties to add, not null
[ "Puts", "the", "properties", "in", "the", "specified", "map", "into", "this", "bean", ".", "<p", ">", "This", "creates", "properties", "if", "they", "do", "not", "exist", "." ]
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/impl/flexi/FlexiBean.java#L302-L315
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java
SegmentedBucketLocker.lockBucketsWrite
void lockBucketsWrite(long i1, long i2) { int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always lock segments in same order to avoid deadlocks if (bucket1LockIdx < bucket2LockIdx) { lockAry[bucket1LockIdx].writeLock(); lockAry[bucket2LockIdx].writeLock(); } else if (bucket1LockIdx > bucket2LockIdx) { lockAry[bucket2LockIdx].writeLock(); lockAry[bucket1LockIdx].writeLock(); } // if we get here both indexes are on same segment so only lock once!!! else { lockAry[bucket1LockIdx].writeLock(); } }
java
void lockBucketsWrite(long i1, long i2) { int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always lock segments in same order to avoid deadlocks if (bucket1LockIdx < bucket2LockIdx) { lockAry[bucket1LockIdx].writeLock(); lockAry[bucket2LockIdx].writeLock(); } else if (bucket1LockIdx > bucket2LockIdx) { lockAry[bucket2LockIdx].writeLock(); lockAry[bucket1LockIdx].writeLock(); } // if we get here both indexes are on same segment so only lock once!!! else { lockAry[bucket1LockIdx].writeLock(); } }
[ "void", "lockBucketsWrite", "(", "long", "i1", ",", "long", "i2", ")", "{", "int", "bucket1LockIdx", "=", "getBucketLock", "(", "i1", ")", ";", "int", "bucket2LockIdx", "=", "getBucketLock", "(", "i2", ")", ";", "// always lock segments in same order to avoid dead...
Locks segments corresponding to bucket indexes in specific order to prevent deadlocks
[ "Locks", "segments", "corresponding", "to", "bucket", "indexes", "in", "specific", "order", "to", "prevent", "deadlocks" ]
train
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java#L64-L79
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.multRows
public static void multRows(double[] diag, int offset, DMatrixSparseCSC A) { if( diag.length < A.numRows ) throw new IllegalArgumentException("Array is too small. "+diag.length+" < "+A.numCols); for (int i = 0; i < A.nz_length; i++) { A.nz_values[i] *= diag[A.nz_rows[i+offset]]; } }
java
public static void multRows(double[] diag, int offset, DMatrixSparseCSC A) { if( diag.length < A.numRows ) throw new IllegalArgumentException("Array is too small. "+diag.length+" < "+A.numCols); for (int i = 0; i < A.nz_length; i++) { A.nz_values[i] *= diag[A.nz_rows[i+offset]]; } }
[ "public", "static", "void", "multRows", "(", "double", "[", "]", "diag", ",", "int", "offset", ",", "DMatrixSparseCSC", "A", ")", "{", "if", "(", "diag", ".", "length", "<", "A", ".", "numRows", ")", "throw", "new", "IllegalArgumentException", "(", "\"Ar...
Multiply all elements of row 'i' by value[i]. A[i,:] *= values[i] @param diag (Input) multiplication factors @param offset (Input) First index in values @param A (Input/Output) Matrix. Modified.
[ "Multiply", "all", "elements", "of", "row", "i", "by", "value", "[", "i", "]", ".", "A", "[", "i", ":", "]", "*", "=", "values", "[", "i", "]" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L1783-L1790
JadiraOrg/jadira
cloning/src/main/java/org/jadira/reflection/access/classloader/AccessClassLoader.java
AccessClassLoader.registerClass
public void registerClass(String name, byte[] bytes) { if (registeredClasses.containsKey(name)) { throw new IllegalStateException("Attempted to register a class that has been registered already: " + name); } registeredClasses.put(name, bytes); }
java
public void registerClass(String name, byte[] bytes) { if (registeredClasses.containsKey(name)) { throw new IllegalStateException("Attempted to register a class that has been registered already: " + name); } registeredClasses.put(name, bytes); }
[ "public", "void", "registerClass", "(", "String", "name", ",", "byte", "[", "]", "bytes", ")", "{", "if", "(", "registeredClasses", ".", "containsKey", "(", "name", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Attempted to register a class tha...
Registers a class by its name @param name The name of the class to be registered @param bytes An array of bytes containing the class
[ "Registers", "a", "class", "by", "its", "name" ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/classloader/AccessClassLoader.java#L101-L107
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/av/CameraEncoder.java
CameraEncoder.prepareEncoder
private void prepareEncoder(EGLContext sharedContext, int width, int height, int bitRate, Muxer muxer) throws IOException { mVideoEncoder = new VideoEncoderCore(width, height, bitRate, muxer); if (mEglCore == null) { // This is the first prepare called for this CameraEncoder instance mEglCore = new EglCore(sharedContext, EglCore.FLAG_RECORDABLE); } if (mInputWindowSurface != null) mInputWindowSurface.release(); mInputWindowSurface = new WindowSurface(mEglCore, mVideoEncoder.getInputSurface()); mInputWindowSurface.makeCurrent(); if (mFullScreen != null) mFullScreen.release(); mFullScreen = new FullFrameRect( new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT)); mFullScreen.getProgram().setTexSize(width, height); mIncomingSizeUpdated = true; }
java
private void prepareEncoder(EGLContext sharedContext, int width, int height, int bitRate, Muxer muxer) throws IOException { mVideoEncoder = new VideoEncoderCore(width, height, bitRate, muxer); if (mEglCore == null) { // This is the first prepare called for this CameraEncoder instance mEglCore = new EglCore(sharedContext, EglCore.FLAG_RECORDABLE); } if (mInputWindowSurface != null) mInputWindowSurface.release(); mInputWindowSurface = new WindowSurface(mEglCore, mVideoEncoder.getInputSurface()); mInputWindowSurface.makeCurrent(); if (mFullScreen != null) mFullScreen.release(); mFullScreen = new FullFrameRect( new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT)); mFullScreen.getProgram().setTexSize(width, height); mIncomingSizeUpdated = true; }
[ "private", "void", "prepareEncoder", "(", "EGLContext", "sharedContext", ",", "int", "width", ",", "int", "height", ",", "int", "bitRate", ",", "Muxer", "muxer", ")", "throws", "IOException", "{", "mVideoEncoder", "=", "new", "VideoEncoderCore", "(", "width", ...
Called with the display EGLContext current, on Encoder thread @param sharedContext The display EGLContext to be shared with the Encoder Surface's context. @param width the desired width of the encoder's video output @param height the desired height of the encoder's video output @param bitRate the desired bitrate of the video encoder @param muxer the desired output muxer
[ "Called", "with", "the", "display", "EGLContext", "current", "on", "Encoder", "thread" ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/CameraEncoder.java#L692-L708
ThreeTen/threetenbp
src/main/java/org/threeten/bp/format/DateTimeFormatterBuilder.java
DateTimeFormatterBuilder.toFormatter
public DateTimeFormatter toFormatter(Locale locale) { Jdk8Methods.requireNonNull(locale, "locale"); while (active.parent != null) { optionalEnd(); } CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false); return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD, ResolverStyle.SMART, null, null, null); }
java
public DateTimeFormatter toFormatter(Locale locale) { Jdk8Methods.requireNonNull(locale, "locale"); while (active.parent != null) { optionalEnd(); } CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false); return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD, ResolverStyle.SMART, null, null, null); }
[ "public", "DateTimeFormatter", "toFormatter", "(", "Locale", "locale", ")", "{", "Jdk8Methods", ".", "requireNonNull", "(", "locale", ",", "\"locale\"", ")", ";", "while", "(", "active", ".", "parent", "!=", "null", ")", "{", "optionalEnd", "(", ")", ";", ...
Completes this builder by creating the DateTimeFormatter using the specified locale. <p> This will create a formatter with the specified locale. Numbers will be printed and parsed using the standard non-localized set of symbols. <p> Calling this method will end any open optional sections by repeatedly calling {@link #optionalEnd()} before creating the formatter. <p> This builder can still be used after creating the formatter if desired, although the state may have been changed by calls to {@code optionalEnd}. @param locale the locale to use for formatting, not null @return the created formatter, not null
[ "Completes", "this", "builder", "by", "creating", "the", "DateTimeFormatter", "using", "the", "specified", "locale", ".", "<p", ">", "This", "will", "create", "a", "formatter", "with", "the", "specified", "locale", ".", "Numbers", "will", "be", "printed", "and...
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/format/DateTimeFormatterBuilder.java#L1882-L1889
m-m-m/util
gwt/src/main/java/net/sf/mmm/util/gwt/base/rebind/AbstractIncrementalGenerator.java
AbstractIncrementalGenerator.generateDefaultConstructor
protected void generateDefaultConstructor(SourceWriter sourceWriter, String simpleName) { generateSourcePublicConstructorDeclaration(sourceWriter, simpleName); sourceWriter.println("super();"); generateSourceCloseBlock(sourceWriter); }
java
protected void generateDefaultConstructor(SourceWriter sourceWriter, String simpleName) { generateSourcePublicConstructorDeclaration(sourceWriter, simpleName); sourceWriter.println("super();"); generateSourceCloseBlock(sourceWriter); }
[ "protected", "void", "generateDefaultConstructor", "(", "SourceWriter", "sourceWriter", ",", "String", "simpleName", ")", "{", "generateSourcePublicConstructorDeclaration", "(", "sourceWriter", ",", "simpleName", ")", ";", "sourceWriter", ".", "println", "(", "\"super();\...
Generates the the default constructor. @param sourceWriter is the {@link SourceWriter}. @param simpleName is the {@link Class#getSimpleName() simple name}.
[ "Generates", "the", "the", "default", "constructor", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/java/net/sf/mmm/util/gwt/base/rebind/AbstractIncrementalGenerator.java#L167-L172
ttddyy/datasource-proxy
src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java
ProxyDataSourceBuilder.logSlowQueryByCommons
public ProxyDataSourceBuilder logSlowQueryByCommons(long thresholdTime, TimeUnit timeUnit) { return logSlowQueryByCommons(thresholdTime, timeUnit, null, null); }
java
public ProxyDataSourceBuilder logSlowQueryByCommons(long thresholdTime, TimeUnit timeUnit) { return logSlowQueryByCommons(thresholdTime, timeUnit, null, null); }
[ "public", "ProxyDataSourceBuilder", "logSlowQueryByCommons", "(", "long", "thresholdTime", ",", "TimeUnit", "timeUnit", ")", "{", "return", "logSlowQueryByCommons", "(", "thresholdTime", ",", "timeUnit", ",", "null", ",", "null", ")", ";", "}" ]
Register {@link CommonsSlowQueryListener}. @param thresholdTime slow query threshold time @param timeUnit slow query threshold time unit @return builder @since 1.4.1
[ "Register", "{", "@link", "CommonsSlowQueryListener", "}", "." ]
train
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java#L233-L235
google/closure-compiler
src/com/google/javascript/jscomp/NodeUtil.java
NodeUtil.newCallNode
static Node newCallNode(Node callTarget, Node... parameters) { boolean isFreeCall = !isGet(callTarget); Node call = IR.call(callTarget); call.putBooleanProp(Node.FREE_CALL, isFreeCall); for (Node parameter : parameters) { call.addChildToBack(parameter); } return call; }
java
static Node newCallNode(Node callTarget, Node... parameters) { boolean isFreeCall = !isGet(callTarget); Node call = IR.call(callTarget); call.putBooleanProp(Node.FREE_CALL, isFreeCall); for (Node parameter : parameters) { call.addChildToBack(parameter); } return call; }
[ "static", "Node", "newCallNode", "(", "Node", "callTarget", ",", "Node", "...", "parameters", ")", "{", "boolean", "isFreeCall", "=", "!", "isGet", "(", "callTarget", ")", ";", "Node", "call", "=", "IR", ".", "call", "(", "callTarget", ")", ";", "call", ...
A new CALL node with the "FREE_CALL" set based on call target.
[ "A", "new", "CALL", "node", "with", "the", "FREE_CALL", "set", "based", "on", "call", "target", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/NodeUtil.java#L5014-L5022
sannies/mp4parser
isoparser/src/main/java/org/mp4parser/boxes/microsoft/XtraBox.java
XtraBox.setTagValue
public void setTagValue(String name, long value) { removeTag(name); XtraTag tag = new XtraTag(name); tag.values.addElement(new XtraValue(value)); tags.addElement(tag); }
java
public void setTagValue(String name, long value) { removeTag(name); XtraTag tag = new XtraTag(name); tag.values.addElement(new XtraValue(value)); tags.addElement(tag); }
[ "public", "void", "setTagValue", "(", "String", "name", ",", "long", "value", ")", "{", "removeTag", "(", "name", ")", ";", "XtraTag", "tag", "=", "new", "XtraTag", "(", "name", ")", ";", "tag", ".", "values", ".", "addElement", "(", "new", "XtraValue"...
Removes and recreates tag using specified Long value @param name Tag name to replace @param value New Long value
[ "Removes", "and", "recreates", "tag", "using", "specified", "Long", "value" ]
train
https://github.com/sannies/mp4parser/blob/3382ff5d489363900f352a8da0f794a20ad3b063/isoparser/src/main/java/org/mp4parser/boxes/microsoft/XtraBox.java#L329-L334
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Utilities.java
Utilities.newLibraryEntry
public static IClasspathEntry newLibraryEntry(Bundle bundle, IPath precomputedBundlePath, BundleURLMappings javadocURLs) { assert bundle != null; final IPath bundlePath; if (precomputedBundlePath == null) { bundlePath = BundleUtil.getBundlePath(bundle); } else { bundlePath = precomputedBundlePath; } final IPath sourceBundlePath = BundleUtil.getSourceBundlePath(bundle, bundlePath); final IPath javadocPath = BundleUtil.getJavadocBundlePath(bundle, bundlePath); final IClasspathAttribute[] extraAttributes; if (javadocPath == null) { if (javadocURLs != null) { final String url = javadocURLs.getURLForBundle(bundle); if (!Strings.isNullOrEmpty(url)) { final IClasspathAttribute attr = JavaCore.newClasspathAttribute( IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, url); extraAttributes = new IClasspathAttribute[] {attr}; } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } } else { final IClasspathAttribute attr = JavaCore.newClasspathAttribute( IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, javadocPath.makeAbsolute().toOSString()); extraAttributes = new IClasspathAttribute[] {attr}; } return JavaCore.newLibraryEntry( bundlePath, sourceBundlePath, null, null, extraAttributes, false); }
java
public static IClasspathEntry newLibraryEntry(Bundle bundle, IPath precomputedBundlePath, BundleURLMappings javadocURLs) { assert bundle != null; final IPath bundlePath; if (precomputedBundlePath == null) { bundlePath = BundleUtil.getBundlePath(bundle); } else { bundlePath = precomputedBundlePath; } final IPath sourceBundlePath = BundleUtil.getSourceBundlePath(bundle, bundlePath); final IPath javadocPath = BundleUtil.getJavadocBundlePath(bundle, bundlePath); final IClasspathAttribute[] extraAttributes; if (javadocPath == null) { if (javadocURLs != null) { final String url = javadocURLs.getURLForBundle(bundle); if (!Strings.isNullOrEmpty(url)) { final IClasspathAttribute attr = JavaCore.newClasspathAttribute( IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, url); extraAttributes = new IClasspathAttribute[] {attr}; } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } } else { final IClasspathAttribute attr = JavaCore.newClasspathAttribute( IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, javadocPath.makeAbsolute().toOSString()); extraAttributes = new IClasspathAttribute[] {attr}; } return JavaCore.newLibraryEntry( bundlePath, sourceBundlePath, null, null, extraAttributes, false); }
[ "public", "static", "IClasspathEntry", "newLibraryEntry", "(", "Bundle", "bundle", ",", "IPath", "precomputedBundlePath", ",", "BundleURLMappings", "javadocURLs", ")", "{", "assert", "bundle", "!=", "null", ";", "final", "IPath", "bundlePath", ";", "if", "(", "pre...
Create the classpath library linked to the bundle with the given name. @param bundle the bundle to point to. Never <code>null</code>. @param precomputedBundlePath the path to the bundle that is already available. If <code>null</code>, the path is computed from the bundle with {@link BundleUtil}. @param javadocURLs the mappings from the bundle to the javadoc URL. It is used for linking the javadoc to the bundle if the bundle platform does not know the Javadoc file. If <code>null</code>, no mapping is defined. @return the classpath entry.
[ "Create", "the", "classpath", "library", "linked", "to", "the", "bundle", "with", "the", "given", "name", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Utilities.java#L181-L221
dmak/jaxb-xew-plugin
src/main/java/com/sun/tools/xjc/addon/xew/CommonUtils.java
CommonUtils.getAnnotationMemberExpression
public static JExpression getAnnotationMemberExpression(JAnnotationUse annotation, String annotationMember) { JAnnotationValue annotationValue = getAnnotationMember(annotation, annotationMember); if (annotationValue == null) { return null; } // FIXME: Pending for https://java.net/jira/browse/JAXB-878 try { // In most cases the value is some expression... return (JExpression) getPrivateField(annotationValue, "value"); } catch (IllegalArgumentException e) { // ... and in some cases (like enum) do the conversion from JGenerable to JExpression // (a bit unoptimal, since this expression is going to be converted back to string) return JExpr.lit(generableToString(annotationValue)); } }
java
public static JExpression getAnnotationMemberExpression(JAnnotationUse annotation, String annotationMember) { JAnnotationValue annotationValue = getAnnotationMember(annotation, annotationMember); if (annotationValue == null) { return null; } // FIXME: Pending for https://java.net/jira/browse/JAXB-878 try { // In most cases the value is some expression... return (JExpression) getPrivateField(annotationValue, "value"); } catch (IllegalArgumentException e) { // ... and in some cases (like enum) do the conversion from JGenerable to JExpression // (a bit unoptimal, since this expression is going to be converted back to string) return JExpr.lit(generableToString(annotationValue)); } }
[ "public", "static", "JExpression", "getAnnotationMemberExpression", "(", "JAnnotationUse", "annotation", ",", "String", "annotationMember", ")", "{", "JAnnotationValue", "annotationValue", "=", "getAnnotationMember", "(", "annotation", ",", "annotationMember", ")", ";", "...
Returns the value of annotation element as {@link JExpression}. For example, for annotation <code>@XmlElementRef(name = "last-name", namespace = "http://mycompany.org/exchange", type = JAXBElement.class)</code> for member <code>name</code> the value <code>last-name</code> will be returned.
[ "Returns", "the", "value", "of", "annotation", "element", "as", "{" ]
train
https://github.com/dmak/jaxb-xew-plugin/blob/d564d6bf8e50c46b056cdb4b46d1d4bee4adfbe3/src/main/java/com/sun/tools/xjc/addon/xew/CommonUtils.java#L94-L111
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java
MapConverter.getBool
public boolean getBool(Map<String, Object> data, String name) { Boolean value = getBoolean(data, name); return (null == value) ? false : value.booleanValue(); }
java
public boolean getBool(Map<String, Object> data, String name) { Boolean value = getBoolean(data, name); return (null == value) ? false : value.booleanValue(); }
[ "public", "boolean", "getBool", "(", "Map", "<", "String", ",", "Object", ">", "data", ",", "String", "name", ")", "{", "Boolean", "value", "=", "getBoolean", "(", "data", ",", "name", ")", ";", "return", "(", "null", "==", "value", ")", "?", "false"...
<p> getBool. </p> @param data a {@link java.util.Map} object. @param name a {@link java.lang.String} object. @return a boolean.
[ "<p", ">", "getBool", ".", "<", "/", "p", ">" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java#L204-L207
thelinmichael/spotify-web-api-java
src/main/java/com/wrapper/spotify/SpotifyApi.java
SpotifyApi.authorizationCodeRefresh
public AuthorizationCodeRefreshRequest.Builder authorizationCodeRefresh(String client_id, String client_secret, String refresh_token) { return new AuthorizationCodeRefreshRequest.Builder(client_id, client_secret) .setDefaults(httpManager, scheme, host, port) .grant_type("refresh_token") .refresh_token(refresh_token); }
java
public AuthorizationCodeRefreshRequest.Builder authorizationCodeRefresh(String client_id, String client_secret, String refresh_token) { return new AuthorizationCodeRefreshRequest.Builder(client_id, client_secret) .setDefaults(httpManager, scheme, host, port) .grant_type("refresh_token") .refresh_token(refresh_token); }
[ "public", "AuthorizationCodeRefreshRequest", ".", "Builder", "authorizationCodeRefresh", "(", "String", "client_id", ",", "String", "client_secret", ",", "String", "refresh_token", ")", "{", "return", "new", "AuthorizationCodeRefreshRequest", ".", "Builder", "(", "client_...
Refresh the access token by using authorization code grant. <br> Requires client ID, client secret, and refresh token to be set. @param client_id When you register your application, Spotify provides you a Client ID. @param client_secret When you register your application, Spotify provides you a Client Secret. @param refresh_token The refresh token returned from the authorization code exchange. @return An {@link AuthorizationCodeRequest.Builder}.
[ "Refresh", "the", "access", "token", "by", "using", "authorization", "code", "grant", ".", "<br", ">", "Requires", "client", "ID", "client", "secret", "and", "refresh", "token", "to", "be", "set", "." ]
train
https://github.com/thelinmichael/spotify-web-api-java/blob/c06b8512344c0310d0c1df362fa267879021da2e/src/main/java/com/wrapper/spotify/SpotifyApi.java#L325-L330
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.createGroup
public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); result = m_driverManager.createGroup(dbc, new CmsUUID(), name, description, flags, parent); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_GROUP_1, name), e); } finally { dbc.clear(); } return result; }
java
public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); result = m_driverManager.createGroup(dbc, new CmsUUID(), name, description, flags, parent); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_GROUP_1, name), e); } finally { dbc.clear(); } return result; }
[ "public", "CmsGroup", "createGroup", "(", "CmsRequestContext", "context", ",", "String", "name", ",", "String", "description", ",", "int", "flags", ",", "String", "parent", ")", "throws", "CmsException", ",", "CmsRoleViolationException", "{", "CmsDbContext", "dbc", ...
Creates a new user group.<p> @param context the current request context @param name the name of the new group @param description the description for the new group @param flags the flags for the new group @param parent the name of the parent group (or <code>null</code>) @return a <code>{@link CmsGroup}</code> object representing the newly created group @throws CmsException if operation was not successful. @throws CmsRoleViolationException if the role {@link CmsRole#ACCOUNT_MANAGER} is not owned by the current user
[ "Creates", "a", "new", "user", "group", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L915-L930
knowm/XChart
xchart/src/main/java/org/knowm/xchart/QuickChart.java
QuickChart.getChart
public static XYChart getChart( String chartTitle, String xTitle, String yTitle, String seriesName, List<? extends Number> xData, List<? extends Number> yData) { // Create Chart XYChart chart = new XYChart(WIDTH, HEIGHT); // Customize Chart chart.setTitle(chartTitle); chart.setXAxisTitle(xTitle); chart.setYAxisTitle(yTitle); XYSeries series = chart.addSeries(seriesName, xData, yData); series.setMarker(SeriesMarkers.NONE); return chart; }
java
public static XYChart getChart( String chartTitle, String xTitle, String yTitle, String seriesName, List<? extends Number> xData, List<? extends Number> yData) { // Create Chart XYChart chart = new XYChart(WIDTH, HEIGHT); // Customize Chart chart.setTitle(chartTitle); chart.setXAxisTitle(xTitle); chart.setYAxisTitle(yTitle); XYSeries series = chart.addSeries(seriesName, xData, yData); series.setMarker(SeriesMarkers.NONE); return chart; }
[ "public", "static", "XYChart", "getChart", "(", "String", "chartTitle", ",", "String", "xTitle", ",", "String", "yTitle", ",", "String", "seriesName", ",", "List", "<", "?", "extends", "Number", ">", "xData", ",", "List", "<", "?", "extends", "Number", ">"...
Creates a Chart with default style @param chartTitle the Chart title @param xTitle The X-Axis title @param yTitle The Y-Axis title @param seriesName The name of the series @param xData A Collection containing the X-Axis data @param yData A Collection containing Y-Axis data @return a Chart Object
[ "Creates", "a", "Chart", "with", "default", "style" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/QuickChart.java#L98-L118
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RunReflectiveCall.java
RunReflectiveCall.fireBeforeInvocation
private static boolean fireBeforeInvocation(Object runner, Object target, FrameworkMethod method, Object... params) { if ((runner != null) && (method != null)) { DepthGauge depthGauge = LifecycleHooks.computeIfAbsent(methodDepth.get(), methodHash(runner, method), newInstance); if (0 == depthGauge.increaseDepth()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("beforeInvocation: {}", LifecycleHooks.invoke(runner, "describeChild", method)); } synchronized(methodWatcherLoader) { for (MethodWatcher watcher : methodWatcherLoader) { watcher.beforeInvocation(runner, target, method, params); } } return true; } } return false; }
java
private static boolean fireBeforeInvocation(Object runner, Object target, FrameworkMethod method, Object... params) { if ((runner != null) && (method != null)) { DepthGauge depthGauge = LifecycleHooks.computeIfAbsent(methodDepth.get(), methodHash(runner, method), newInstance); if (0 == depthGauge.increaseDepth()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("beforeInvocation: {}", LifecycleHooks.invoke(runner, "describeChild", method)); } synchronized(methodWatcherLoader) { for (MethodWatcher watcher : methodWatcherLoader) { watcher.beforeInvocation(runner, target, method, params); } } return true; } } return false; }
[ "private", "static", "boolean", "fireBeforeInvocation", "(", "Object", "runner", ",", "Object", "target", ",", "FrameworkMethod", "method", ",", "Object", "...", "params", ")", "{", "if", "(", "(", "runner", "!=", "null", ")", "&&", "(", "method", "!=", "n...
Fire the {@link MethodWatcher#beforeInvocation(Object, Object, FrameworkMethod, Object...) event. <p> If the {@code beforeInvocation} event for the specified method has already been fired, do nothing. @param runner JUnit test runner @param target "enhanced" object upon which the method was invoked @param method {@link FrameworkMethod} object for the invoked method @param params method invocation parameters @return {@code true} if event the {@code beforeInvocation} was fired; otherwise {@code false}
[ "Fire", "the", "{", "@link", "MethodWatcher#beforeInvocation", "(", "Object", "Object", "FrameworkMethod", "Object", "...", ")", "event", ".", "<p", ">", "If", "the", "{", "@code", "beforeInvocation", "}", "event", "for", "the", "specified", "method", "has", "...
train
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RunReflectiveCall.java#L163-L179
UrielCh/ovh-java-sdk
ovh-java-sdk-connectivity/src/main/java/net/minidev/ovh/api/ApiOvhConnectivity.java
ApiOvhConnectivity.eligibility_search_streets_POST
public OvhAsyncTaskArray<OvhStreet> eligibility_search_streets_POST(String inseeCode) throws IOException { String qPath = "/connectivity/eligibility/search/streets"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "inseeCode", inseeCode); String resp = execN(qPath, "POST", sb.toString(), o); return convertTo(resp, t3); }
java
public OvhAsyncTaskArray<OvhStreet> eligibility_search_streets_POST(String inseeCode) throws IOException { String qPath = "/connectivity/eligibility/search/streets"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "inseeCode", inseeCode); String resp = execN(qPath, "POST", sb.toString(), o); return convertTo(resp, t3); }
[ "public", "OvhAsyncTaskArray", "<", "OvhStreet", ">", "eligibility_search_streets_POST", "(", "String", "inseeCode", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/connectivity/eligibility/search/streets\"", ";", "StringBuilder", "sb", "=", "path", "(", ...
Get all street linked to a locality REST: POST /connectivity/eligibility/search/streets @param inseeCode [required] French INSEE identifier (you can get it with POST /connectivity/eligibility/search/cities)
[ "Get", "all", "street", "linked", "to", "a", "locality" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-connectivity/src/main/java/net/minidev/ovh/api/ApiOvhConnectivity.java#L72-L79
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/context/RpcRuntimeContext.java
RpcRuntimeContext.putIfAbsent
public static Object putIfAbsent(String key, Object value) { return value == null ? CONTEXT.remove(key) : CONTEXT.putIfAbsent(key, value); }
java
public static Object putIfAbsent(String key, Object value) { return value == null ? CONTEXT.remove(key) : CONTEXT.putIfAbsent(key, value); }
[ "public", "static", "Object", "putIfAbsent", "(", "String", "key", ",", "Object", "value", ")", "{", "return", "value", "==", "null", "?", "CONTEXT", ".", "remove", "(", "key", ")", ":", "CONTEXT", ".", "putIfAbsent", "(", "key", ",", "value", ")", ";"...
设置上下文信息(不存在才设置成功) @param key the key @param value the value @return the object @see ConcurrentHashMap#putIfAbsent(Object, Object)
[ "设置上下文信息(不存在才设置成功)" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/context/RpcRuntimeContext.java#L278-L280
alkacon/opencms-core
src/org/opencms/file/wrapper/CmsObjectWrapper.java
CmsObjectWrapper.readPropertyObject
public CmsProperty readPropertyObject(CmsResource resource, String property, boolean search) throws CmsException { return m_cms.readPropertyObject(resource, property, search); }
java
public CmsProperty readPropertyObject(CmsResource resource, String property, boolean search) throws CmsException { return m_cms.readPropertyObject(resource, property, search); }
[ "public", "CmsProperty", "readPropertyObject", "(", "CmsResource", "resource", ",", "String", "property", ",", "boolean", "search", ")", "throws", "CmsException", "{", "return", "m_cms", ".", "readPropertyObject", "(", "resource", ",", "property", ",", "search", "...
Delegate method for {@link CmsObject#readPropertyObject(CmsResource, String, boolean)}.<p> @see CmsObject#readPropertyObject(CmsResource, String, boolean) @param resource the resource where the property is attached to @param property the property name @param search if true, the property is searched on all parent folders of the resource, if it's not found attached directly to the resource @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found @throws CmsException if something goes wrong
[ "Delegate", "method", "for", "{", "@link", "CmsObject#readPropertyObject", "(", "CmsResource", "String", "boolean", ")", "}", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsObjectWrapper.java#L597-L600
greengerong/prerender-java
src/main/java/com/github/greengerong/PrerenderSeoService.java
PrerenderSeoService.copyRequestHeaders
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) throws URISyntaxException { // Get an Enumeration of all of the header names sent by the client Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) { Enumeration<?> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HOST)) { HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl())); headerValue = host.getHostName(); if (host.getPort() != -1) { headerValue += ":" + host.getPort(); } } proxyRequest.addHeader(headerName, headerValue); } } } }
java
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) throws URISyntaxException { // Get an Enumeration of all of the header names sent by the client Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) { Enumeration<?> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HOST)) { HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl())); headerValue = host.getHostName(); if (host.getPort() != -1) { headerValue += ":" + host.getPort(); } } proxyRequest.addHeader(headerName, headerValue); } } } }
[ "private", "void", "copyRequestHeaders", "(", "HttpServletRequest", "servletRequest", ",", "HttpRequest", "proxyRequest", ")", "throws", "URISyntaxException", "{", "// Get an Enumeration of all of the header names sent by the client", "Enumeration", "<", "?", ">", "enumerationOfH...
Copy request headers from the servlet client to the proxy request. @throws java.net.URISyntaxException
[ "Copy", "request", "headers", "from", "the", "servlet", "client", "to", "the", "proxy", "request", "." ]
train
https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L159-L184
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFSubstitution.java
NumeratorSubstitution.doSubstitution
public void doSubstitution(double number, StringBuilder toInsertInto, int position, int recursionCount) { // perform a transformation on the number being formatted that // is dependent on the type of substitution this is //String s = toInsertInto.toString(); double numberToFormat = transformNumber(number); if (withZeros && ruleSet != null) { // if there are leading zeros in the decimal expansion then emit them long nf = (long)numberToFormat; int len = toInsertInto.length(); while ((nf *= 10) < denominator) { toInsertInto.insert(position + pos, ' '); ruleSet.format(0, toInsertInto, position + pos, recursionCount); } position += toInsertInto.length() - len; } // if the result is an integer, from here on out we work in integer // space (saving time and memory and preserving accuracy) if (numberToFormat == Math.floor(numberToFormat) && ruleSet != null) { ruleSet.format((long)numberToFormat, toInsertInto, position + pos, recursionCount); // if the result isn't an integer, then call either our rule set's // format() method or our DecimalFormat's format() method to // format the result } else { if (ruleSet != null) { ruleSet.format(numberToFormat, toInsertInto, position + pos, recursionCount); } else { toInsertInto.insert(position + pos, numberFormat.format(numberToFormat)); } } }
java
public void doSubstitution(double number, StringBuilder toInsertInto, int position, int recursionCount) { // perform a transformation on the number being formatted that // is dependent on the type of substitution this is //String s = toInsertInto.toString(); double numberToFormat = transformNumber(number); if (withZeros && ruleSet != null) { // if there are leading zeros in the decimal expansion then emit them long nf = (long)numberToFormat; int len = toInsertInto.length(); while ((nf *= 10) < denominator) { toInsertInto.insert(position + pos, ' '); ruleSet.format(0, toInsertInto, position + pos, recursionCount); } position += toInsertInto.length() - len; } // if the result is an integer, from here on out we work in integer // space (saving time and memory and preserving accuracy) if (numberToFormat == Math.floor(numberToFormat) && ruleSet != null) { ruleSet.format((long)numberToFormat, toInsertInto, position + pos, recursionCount); // if the result isn't an integer, then call either our rule set's // format() method or our DecimalFormat's format() method to // format the result } else { if (ruleSet != null) { ruleSet.format(numberToFormat, toInsertInto, position + pos, recursionCount); } else { toInsertInto.insert(position + pos, numberFormat.format(numberToFormat)); } } }
[ "public", "void", "doSubstitution", "(", "double", "number", ",", "StringBuilder", "toInsertInto", ",", "int", "position", ",", "int", "recursionCount", ")", "{", "// perform a transformation on the number being formatted that", "// is dependent on the type of substitution this i...
Performs a mathematical operation on the number, formats it using either ruleSet or decimalFormat, and inserts the result into toInsertInto. @param number The number being formatted. @param toInsertInto The string we insert the result into @param position The position in toInsertInto where the owning rule's rule text begins (this value is added to this substitution's position to determine exactly where to insert the new text)
[ "Performs", "a", "mathematical", "operation", "on", "the", "number", "formats", "it", "using", "either", "ruleSet", "or", "decimalFormat", "and", "inserts", "the", "result", "into", "toInsertInto", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NFSubstitution.java#L1499-L1531
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionListener.java
RaftSessionListener.addEventListener
public void addEventListener(EventType eventType, Consumer<PrimitiveEvent> listener) { executor.execute(() -> eventListeners.computeIfAbsent(eventType.canonicalize(), e -> Sets.newLinkedHashSet()).add(listener)); }
java
public void addEventListener(EventType eventType, Consumer<PrimitiveEvent> listener) { executor.execute(() -> eventListeners.computeIfAbsent(eventType.canonicalize(), e -> Sets.newLinkedHashSet()).add(listener)); }
[ "public", "void", "addEventListener", "(", "EventType", "eventType", ",", "Consumer", "<", "PrimitiveEvent", ">", "listener", ")", "{", "executor", ".", "execute", "(", "(", ")", "->", "eventListeners", ".", "computeIfAbsent", "(", "eventType", ".", "canonicaliz...
Adds an event listener to the session. @param listener the event listener callback
[ "Adds", "an", "event", "listener", "to", "the", "session", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/RaftSessionListener.java#L69-L71
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginUpdateTagsAsync
public Observable<VirtualNetworkGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayInner>, VirtualNetworkGatewayInner>() { @Override public VirtualNetworkGatewayInner call(ServiceResponse<VirtualNetworkGatewayInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkGatewayInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayName, Map<String, String> tags) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayInner>, VirtualNetworkGatewayInner>() { @Override public VirtualNetworkGatewayInner call(ServiceResponse<VirtualNetworkGatewayInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkGatewayInner", ">", "beginUpdateTagsAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateTagsWithService...
Updates a virtual network gateway tags. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkGatewayInner object
[ "Updates", "a", "virtual", "network", "gateway", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L862-L869
JodaOrg/joda-time
src/main/java/org/joda/time/LocalDateTime.java
LocalDateTime.toDate
public Date toDate(final TimeZone timeZone) { final Calendar calendar = Calendar.getInstance(timeZone); calendar.clear(); calendar.set(getYear(), getMonthOfYear() - 1, getDayOfMonth(), getHourOfDay(), getMinuteOfHour(), getSecondOfMinute()); Date date = calendar.getTime(); date.setTime(date.getTime() + getMillisOfSecond()); return correctDstTransition(date, timeZone); }
java
public Date toDate(final TimeZone timeZone) { final Calendar calendar = Calendar.getInstance(timeZone); calendar.clear(); calendar.set(getYear(), getMonthOfYear() - 1, getDayOfMonth(), getHourOfDay(), getMinuteOfHour(), getSecondOfMinute()); Date date = calendar.getTime(); date.setTime(date.getTime() + getMillisOfSecond()); return correctDstTransition(date, timeZone); }
[ "public", "Date", "toDate", "(", "final", "TimeZone", "timeZone", ")", "{", "final", "Calendar", "calendar", "=", "Calendar", ".", "getInstance", "(", "timeZone", ")", ";", "calendar", ".", "clear", "(", ")", ";", "calendar", ".", "set", "(", "getYear", ...
Get the date time as a <code>java.util.Date</code> using the specified time zone. <p> The <code>Date</code> object created has exactly the same fields as this date-time, except when the time would be invalid due to a daylight savings gap. In that case, the time will be set to the earliest valid time after the gap. <p> In the case of a daylight savings overlap, the earlier instant is selected. <p> Converting to a JDK Date is full of complications as the JDK Date constructor doesn't behave as you might expect around DST transitions. This method works by taking a first guess and then adjusting. This also handles the situation where the JDK time zone data differs from the Joda-Time time zone data. <p> Unlike {@link #toDate()}, this implementation does not rely on Java's synchronized time zone initialization logic, and should demonstrate better concurrent performance characteristics. @return a Date initialised with this date-time, never null @since 2.3
[ "Get", "the", "date", "time", "as", "a", "<code", ">", "java", ".", "util", ".", "Date<", "/", "code", ">", "using", "the", "specified", "time", "zone", ".", "<p", ">", "The", "<code", ">", "Date<", "/", "code", ">", "object", "created", "has", "ex...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/LocalDateTime.java#L823-L831
gresrun/jesque
src/main/java/net/greghaines/jesque/utils/JedisUtils.java
JedisUtils.canUseAsDelayedQueue
public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) { final String type = jedis.type(key); return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type)); }
java
public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) { final String type = jedis.type(key); return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type)); }
[ "public", "static", "boolean", "canUseAsDelayedQueue", "(", "final", "Jedis", "jedis", ",", "final", "String", "key", ")", "{", "final", "String", "type", "=", "jedis", ".", "type", "(", "key", ")", ";", "return", "(", "ZSET", ".", "equalsIgnoreCase", "(",...
Determines if the queue identified by the given key can be used as a delayed queue. @param jedis connection to Redis @param key the key that identifies a queue @return true if the key already is a delayed queue or is not currently used, false otherwise
[ "Determines", "if", "the", "queue", "identified", "by", "the", "given", "key", "can", "be", "used", "as", "a", "delayed", "queue", "." ]
train
https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/utils/JedisUtils.java#L163-L166
Alexey1Gavrilov/ExpectIt
expectit-ant/src/main/java/net/sf/expectit/ant/matcher/AbstractMatcherElement.java
AbstractMatcherElement.exportSuccessfulResult
protected void exportSuccessfulResult(String prefix, R result) { if (prefix == null) { return; } setPropertyIfNoNull(prefix, "input", result.getInput()); if (!result.isSuccessful()) { return; } setPropertyIfNoNull(prefix, "input", result.getInput()); setPropertyIfNoNull(prefix, "before", result.getBefore()); setPropertyIfNoNull(prefix, "group", result.group()); setPropertyIfNoNull(prefix, "success", "true"); for (int i = 1; i <= result.groupCount(); i++) { setPropertyIfNoNull(prefix, "group." + i, result.group(i)); } }
java
protected void exportSuccessfulResult(String prefix, R result) { if (prefix == null) { return; } setPropertyIfNoNull(prefix, "input", result.getInput()); if (!result.isSuccessful()) { return; } setPropertyIfNoNull(prefix, "input", result.getInput()); setPropertyIfNoNull(prefix, "before", result.getBefore()); setPropertyIfNoNull(prefix, "group", result.group()); setPropertyIfNoNull(prefix, "success", "true"); for (int i = 1; i <= result.groupCount(); i++) { setPropertyIfNoNull(prefix, "group." + i, result.group(i)); } }
[ "protected", "void", "exportSuccessfulResult", "(", "String", "prefix", ",", "R", "result", ")", "{", "if", "(", "prefix", "==", "null", ")", "{", "return", ";", "}", "setPropertyIfNoNull", "(", "prefix", ",", "\"input\"", ",", "result", ".", "getInput", "...
Exports the successful result of the match as a set of properties with the given prefix. The properties key/value format is as follows: <ul> <li>{@code prefix + ".before" = result.getBefore()}</li> <li>{@code prefix + ".group" = result.group()}</li> <li>{@code prefix + ".success" = true}</li> <li>{@code prefix + ".group." + &lt;number&gt; = result.group(&lt;number&gt;)}, where the {@code number} is between 1 and {@code result.groupCount()}</li> </ul> If the {@code prefix} is {@code null}, or the {@code result} is not successful, then this method does nothing. @param prefix the property prefix @param result the result
[ "Exports", "the", "successful", "result", "of", "the", "match", "as", "a", "set", "of", "properties", "with", "the", "given", "prefix", ".", "The", "properties", "key", "/", "value", "format", "is", "as", "follows", ":", "<ul", ">", "<li", ">", "{", "@...
train
https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-ant/src/main/java/net/sf/expectit/ant/matcher/AbstractMatcherElement.java#L85-L100
alkacon/opencms-core
src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java
CmsDefaultXmlContentHandler.initSynchronizations
protected void initSynchronizations(Element root, CmsXmlContentDefinition contentDefinition) { List<Element> elements = new ArrayList<Element>(CmsXmlGenericWrapper.elements(root, APPINFO_SYNCHRONIZATION)); for (Element element : elements) { String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT); m_synchronizations.add(elementName); } }
java
protected void initSynchronizations(Element root, CmsXmlContentDefinition contentDefinition) { List<Element> elements = new ArrayList<Element>(CmsXmlGenericWrapper.elements(root, APPINFO_SYNCHRONIZATION)); for (Element element : elements) { String elementName = element.attributeValue(APPINFO_ATTR_ELEMENT); m_synchronizations.add(elementName); } }
[ "protected", "void", "initSynchronizations", "(", "Element", "root", ",", "CmsXmlContentDefinition", "contentDefinition", ")", "{", "List", "<", "Element", ">", "elements", "=", "new", "ArrayList", "<", "Element", ">", "(", "CmsXmlGenericWrapper", ".", "elements", ...
Initializes the locale synchronizations elements.<p> @param root the synchronizations element of the content schema appinfo. @param contentDefinition the content definition
[ "Initializes", "the", "locale", "synchronizations", "elements", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L3101-L3108
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/lang/BooleanHelper.java
BooleanHelper.getBooleanValue
public static boolean getBooleanValue (@Nullable final Boolean aObj, final boolean bDefault) { return aObj == null ? bDefault : aObj.booleanValue (); }
java
public static boolean getBooleanValue (@Nullable final Boolean aObj, final boolean bDefault) { return aObj == null ? bDefault : aObj.booleanValue (); }
[ "public", "static", "boolean", "getBooleanValue", "(", "@", "Nullable", "final", "Boolean", "aObj", ",", "final", "boolean", "bDefault", ")", "{", "return", "aObj", "==", "null", "?", "bDefault", ":", "aObj", ".", "booleanValue", "(", ")", ";", "}" ]
Get the primitive value of the passed object value. @param aObj The Boolean value to be converted @param bDefault The default value to be returned, if the passed obj is <code>null</code>. @return Either the primitive boolean value or the default value
[ "Get", "the", "primitive", "value", "of", "the", "passed", "object", "value", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/lang/BooleanHelper.java#L48-L51
kefirfromperm/kefirbb
src/org/kefirsf/bb/proc/ProcBol.java
ProcBol.skipLineBreak
private int skipLineBreak(Source source, final int offset) { char p; char c; int index = offset; p = source.charAt(index); index++; if (index < source.length()) { c = source.charAt(index); if ((c == '\n' || c == '\r') && c != p) { index++; } } return index; }
java
private int skipLineBreak(Source source, final int offset) { char p; char c; int index = offset; p = source.charAt(index); index++; if (index < source.length()) { c = source.charAt(index); if ((c == '\n' || c == '\r') && c != p) { index++; } } return index; }
[ "private", "int", "skipLineBreak", "(", "Source", "source", ",", "final", "int", "offset", ")", "{", "char", "p", ";", "char", "c", ";", "int", "index", "=", "offset", ";", "p", "=", "source", ".", "charAt", "(", "index", ")", ";", "index", "++", "...
Skip line break characters. '\r\n' for example @param source text source @param offset current index @return new index
[ "Skip", "line", "break", "characters", ".", "\\", "r", "\\", "n", "for", "example" ]
train
https://github.com/kefirfromperm/kefirbb/blob/8c36fc3d3dc27459b0cdc179b87582df30420856/src/org/kefirsf/bb/proc/ProcBol.java#L94-L107
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java
GoogleCloudStorageFileSystem.renameInternal
private void renameInternal(FileInfo srcInfo, URI dst) throws IOException { if (srcInfo.isDirectory()) { renameDirectoryInternal(srcInfo, dst); } else { URI src = srcInfo.getPath(); StorageResourceId srcResourceId = pathCodec.validatePathAndGetId(src, true); StorageResourceId dstResourceId = pathCodec.validatePathAndGetId(dst, true); gcs.copy( srcResourceId.getBucketName(), ImmutableList.of(srcResourceId.getObjectName()), dstResourceId.getBucketName(), ImmutableList.of(dstResourceId.getObjectName())); tryUpdateTimestampsForParentDirectories(ImmutableList.of(dst), ImmutableList.<URI>of()); // TODO(b/110833109): populate generation ID in StorageResourceId when getting info gcs.deleteObjects( ImmutableList.of( new StorageResourceId( srcInfo.getItemInfo().getBucketName(), srcInfo.getItemInfo().getObjectName(), srcInfo.getItemInfo().getContentGeneration()))); // Any path that was deleted, we should update the parent except for parents we also deleted tryUpdateTimestampsForParentDirectories(ImmutableList.of(src), ImmutableList.<URI>of()); } }
java
private void renameInternal(FileInfo srcInfo, URI dst) throws IOException { if (srcInfo.isDirectory()) { renameDirectoryInternal(srcInfo, dst); } else { URI src = srcInfo.getPath(); StorageResourceId srcResourceId = pathCodec.validatePathAndGetId(src, true); StorageResourceId dstResourceId = pathCodec.validatePathAndGetId(dst, true); gcs.copy( srcResourceId.getBucketName(), ImmutableList.of(srcResourceId.getObjectName()), dstResourceId.getBucketName(), ImmutableList.of(dstResourceId.getObjectName())); tryUpdateTimestampsForParentDirectories(ImmutableList.of(dst), ImmutableList.<URI>of()); // TODO(b/110833109): populate generation ID in StorageResourceId when getting info gcs.deleteObjects( ImmutableList.of( new StorageResourceId( srcInfo.getItemInfo().getBucketName(), srcInfo.getItemInfo().getObjectName(), srcInfo.getItemInfo().getContentGeneration()))); // Any path that was deleted, we should update the parent except for parents we also deleted tryUpdateTimestampsForParentDirectories(ImmutableList.of(src), ImmutableList.<URI>of()); } }
[ "private", "void", "renameInternal", "(", "FileInfo", "srcInfo", ",", "URI", "dst", ")", "throws", "IOException", "{", "if", "(", "srcInfo", ".", "isDirectory", "(", ")", ")", "{", "renameDirectoryInternal", "(", "srcInfo", ",", "dst", ")", ";", "}", "else...
Renames the given path without checking any parameters. <p>GCS does not support atomic renames therefore a rename is implemented as copying source metadata to destination and then deleting source metadata. Note that only the metadata is copied and not the content of any file.
[ "Renames", "the", "given", "path", "without", "checking", "any", "parameters", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java#L732-L757
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/UrlParser.java
UrlParser.parseInternal
private static void parseInternal(UrlParser urlParser, String url, Properties properties) throws SQLException { try { urlParser.initialUrl = url; int separator = url.indexOf("//"); if (separator == -1) { throw new IllegalArgumentException( "url parsing error : '//' is not present in the url " + url); } urlParser.haMode = parseHaMode(url, separator); String urlSecondPart = url.substring(separator + 2); int dbIndex = urlSecondPart.indexOf("/"); int paramIndex = urlSecondPart.indexOf("?"); String hostAddressesString; String additionalParameters; if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) { hostAddressesString = urlSecondPart.substring(0, paramIndex); additionalParameters = urlSecondPart.substring(paramIndex); } else if ((dbIndex < paramIndex && dbIndex > -1) || (dbIndex > paramIndex && paramIndex < 0)) { hostAddressesString = urlSecondPart.substring(0, dbIndex); additionalParameters = urlSecondPart.substring(dbIndex); } else { hostAddressesString = urlSecondPart; additionalParameters = null; } defineUrlParserParameters(urlParser, properties, hostAddressesString, additionalParameters); setDefaultHostAddressType(urlParser); urlParser.loadMultiMasterValue(); } catch (IllegalArgumentException i) { throw new SQLException("error parsing url : " + i.getMessage(), i); } }
java
private static void parseInternal(UrlParser urlParser, String url, Properties properties) throws SQLException { try { urlParser.initialUrl = url; int separator = url.indexOf("//"); if (separator == -1) { throw new IllegalArgumentException( "url parsing error : '//' is not present in the url " + url); } urlParser.haMode = parseHaMode(url, separator); String urlSecondPart = url.substring(separator + 2); int dbIndex = urlSecondPart.indexOf("/"); int paramIndex = urlSecondPart.indexOf("?"); String hostAddressesString; String additionalParameters; if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) { hostAddressesString = urlSecondPart.substring(0, paramIndex); additionalParameters = urlSecondPart.substring(paramIndex); } else if ((dbIndex < paramIndex && dbIndex > -1) || (dbIndex > paramIndex && paramIndex < 0)) { hostAddressesString = urlSecondPart.substring(0, dbIndex); additionalParameters = urlSecondPart.substring(dbIndex); } else { hostAddressesString = urlSecondPart; additionalParameters = null; } defineUrlParserParameters(urlParser, properties, hostAddressesString, additionalParameters); setDefaultHostAddressType(urlParser); urlParser.loadMultiMasterValue(); } catch (IllegalArgumentException i) { throw new SQLException("error parsing url : " + i.getMessage(), i); } }
[ "private", "static", "void", "parseInternal", "(", "UrlParser", "urlParser", ",", "String", "url", ",", "Properties", "properties", ")", "throws", "SQLException", "{", "try", "{", "urlParser", ".", "initialUrl", "=", "url", ";", "int", "separator", "=", "url",...
Parses the connection URL in order to set the UrlParser instance with all the information provided through the URL. @param urlParser object instance in which all data from the connection url is stored @param url connection URL @param properties properties @throws SQLException if format is incorrect
[ "Parses", "the", "connection", "URL", "in", "order", "to", "set", "the", "UrlParser", "instance", "with", "all", "the", "information", "provided", "through", "the", "URL", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/UrlParser.java#L175-L211
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.setEnterpriseText
public void setEnterpriseText(int index, String value) { set(selectField(TaskFieldLists.ENTERPRISE_TEXT, index), value); }
java
public void setEnterpriseText(int index, String value) { set(selectField(TaskFieldLists.ENTERPRISE_TEXT, index), value); }
[ "public", "void", "setEnterpriseText", "(", "int", "index", ",", "String", "value", ")", "{", "set", "(", "selectField", "(", "TaskFieldLists", ".", "ENTERPRISE_TEXT", ",", "index", ")", ",", "value", ")", ";", "}" ]
Set an enterprise field value. @param index field index @param value field value
[ "Set", "an", "enterprise", "field", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L3947-L3950
kaazing/java.client
ws/ws/src/main/java/org/kaazing/gateway/client/util/WrappedByteBuffer.java
WrappedByteBuffer.putPrefixedString
public WrappedByteBuffer putPrefixedString(int fieldSize, String v, Charset cs) { if (fieldSize == 0) { return this; } boolean utf16 = cs.name().startsWith("UTF-16"); if (utf16 && (fieldSize == 1)) { throw new IllegalArgumentException("fieldSize is not even for UTF-16 character set"); } java.nio.ByteBuffer strBuf = cs.encode(v); _autoExpand(fieldSize + strBuf.limit()); int len = strBuf.remaining(); switch (fieldSize) { case 1: put((byte) len); break; case 2: putShort((short) len); break; case 4: putInt(len); break; default: throw new IllegalArgumentException("Illegal argument, field size should be 1,2 or 4 and fieldSize is: " + fieldSize); } _buf.put(strBuf); return this; }
java
public WrappedByteBuffer putPrefixedString(int fieldSize, String v, Charset cs) { if (fieldSize == 0) { return this; } boolean utf16 = cs.name().startsWith("UTF-16"); if (utf16 && (fieldSize == 1)) { throw new IllegalArgumentException("fieldSize is not even for UTF-16 character set"); } java.nio.ByteBuffer strBuf = cs.encode(v); _autoExpand(fieldSize + strBuf.limit()); int len = strBuf.remaining(); switch (fieldSize) { case 1: put((byte) len); break; case 2: putShort((short) len); break; case 4: putInt(len); break; default: throw new IllegalArgumentException("Illegal argument, field size should be 1,2 or 4 and fieldSize is: " + fieldSize); } _buf.put(strBuf); return this; }
[ "public", "WrappedByteBuffer", "putPrefixedString", "(", "int", "fieldSize", ",", "String", "v", ",", "Charset", "cs", ")", "{", "if", "(", "fieldSize", "==", "0", ")", "{", "return", "this", ";", "}", "boolean", "utf16", "=", "cs", ".", "name", "(", "...
Puts a string into the buffer at the specified index, using the character set to encode the string as bytes. @param fieldSize the width in bytes of the prefixed length field @param v the string @param cs the character set @return the buffer
[ "Puts", "a", "string", "into", "the", "buffer", "at", "the", "specified", "index", "using", "the", "character", "set", "to", "encode", "the", "string", "as", "bytes", "." ]
train
https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/ws/ws/src/main/java/org/kaazing/gateway/client/util/WrappedByteBuffer.java#L581-L611
youseries/urule
urule-console/src/main/java/com/bstek/urule/console/repository/database/journal/DatabaseJournal.java
DatabaseJournal.doLock
protected void doLock() throws JournalException { ResultSet rs = null; boolean succeeded = false; try { startBatch(); } catch (SQLException e) { throw new JournalException("Unable to set autocommit to false.", e); } try { conHelper.exec(updateGlobalStmtSQL); rs = conHelper.exec(selectGlobalStmtSQL, null, false, 0); if (!rs.next()) { throw new JournalException("No revision available."); } lockedRevision = rs.getLong(1); succeeded = true; } catch (SQLException e) { throw new JournalException("Unable to lock global revision table.", e); } finally { DbUtility.close(rs); if (!succeeded) { doUnlock(false); } } }
java
protected void doLock() throws JournalException { ResultSet rs = null; boolean succeeded = false; try { startBatch(); } catch (SQLException e) { throw new JournalException("Unable to set autocommit to false.", e); } try { conHelper.exec(updateGlobalStmtSQL); rs = conHelper.exec(selectGlobalStmtSQL, null, false, 0); if (!rs.next()) { throw new JournalException("No revision available."); } lockedRevision = rs.getLong(1); succeeded = true; } catch (SQLException e) { throw new JournalException("Unable to lock global revision table.", e); } finally { DbUtility.close(rs); if (!succeeded) { doUnlock(false); } } }
[ "protected", "void", "doLock", "(", ")", "throws", "JournalException", "{", "ResultSet", "rs", "=", "null", ";", "boolean", "succeeded", "=", "false", ";", "try", "{", "startBatch", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw"...
<p> This journal is locked by incrementing the current value in the table named <code>GLOBAL_REVISION</code>, which effectively write-locks this table. The updated value is then saved away and remembered in the appended record, because a save may entail multiple appends (JCR-884).
[ "<p", ">", "This", "journal", "is", "locked", "by", "incrementing", "the", "current", "value", "in", "the", "table", "named", "<code", ">", "GLOBAL_REVISION<", "/", "code", ">", "which", "effectively", "write", "-", "locks", "this", "table", ".", "The", "u...
train
https://github.com/youseries/urule/blob/3fa0eb4439e97aa292e744bcbd88a9faa36661d8/urule-console/src/main/java/com/bstek/urule/console/repository/database/journal/DatabaseJournal.java#L401-L427
vipshop/vjtools
vjkit/src/main/java/com/vip/vjtools/vjkit/collection/ArrayUtil.java
ArrayUtil.toArray
@SuppressWarnings("unchecked") public static <T> T[] toArray(Collection<T> col, Class<T> type) { return col.toArray((T[]) Array.newInstance(type, 0)); }
java
@SuppressWarnings("unchecked") public static <T> T[] toArray(Collection<T> col, Class<T> type) { return col.toArray((T[]) Array.newInstance(type, 0)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "[", "]", "toArray", "(", "Collection", "<", "T", ">", "col", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "col", ".", "toArray", "(", "(", "T",...
从collection转为Array, 以 list.toArray(new String[0]); 最快 不需要创建list.size()的数组. 本函数等价于list.toArray(new String[0]); 用户也可以直接用后者. https://shipilev.net/blog/2016/arrays-wisdom-ancients/
[ "从collection转为Array", "以", "list", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "最快", "不需要创建list", ".", "size", "()", "的数组", "." ]
train
https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjkit/src/main/java/com/vip/vjtools/vjkit/collection/ArrayUtil.java#L47-L50
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/util/CharMap.java
CharMap.put
public V put(Character key, V value) { char k = checkKey(key); return put(k, value); }
java
public V put(Character key, V value) { char k = checkKey(key); return put(k, value); }
[ "public", "V", "put", "(", "Character", "key", ",", "V", "value", ")", "{", "char", "k", "=", "checkKey", "(", "key", ")", ";", "return", "put", "(", "k", ",", "value", ")", ";", "}" ]
Adds the mapping from the provided key to the value. @param key @param value @throws NullPointerException if the key is {@code null} @throws IllegalArgumentException if the key is not an instance of {@link Integer}
[ "Adds", "the", "mapping", "from", "the", "provided", "key", "to", "the", "value", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/util/CharMap.java#L197-L200
zaproxy/zaproxy
src/org/zaproxy/zap/extension/script/ExtensionScript.java
ExtensionScript.loadScriptTemplates
private void loadScriptTemplates(ScriptType type, ScriptEngineWrapper engine) { File locDir = new File(Constant.getZapHome() + File.separator + TEMPLATES_DIR + File.separator + type.getName()); File stdDir = new File(Constant.getZapInstall() + File.separator + TEMPLATES_DIR + File.separator + type.getName()); // Load local files first, as these override any one included in the release if (locDir.exists()) { for (File f : locDir.listFiles()) { loadTemplate(f, type, engine, false); } } if (stdDir.exists()) { for (File f : stdDir.listFiles()) { // Dont log errors on duplicates - 'local' templates should take presidence loadTemplate(f, type, engine, true); } } }
java
private void loadScriptTemplates(ScriptType type, ScriptEngineWrapper engine) { File locDir = new File(Constant.getZapHome() + File.separator + TEMPLATES_DIR + File.separator + type.getName()); File stdDir = new File(Constant.getZapInstall() + File.separator + TEMPLATES_DIR + File.separator + type.getName()); // Load local files first, as these override any one included in the release if (locDir.exists()) { for (File f : locDir.listFiles()) { loadTemplate(f, type, engine, false); } } if (stdDir.exists()) { for (File f : stdDir.listFiles()) { // Dont log errors on duplicates - 'local' templates should take presidence loadTemplate(f, type, engine, true); } } }
[ "private", "void", "loadScriptTemplates", "(", "ScriptType", "type", ",", "ScriptEngineWrapper", "engine", ")", "{", "File", "locDir", "=", "new", "File", "(", "Constant", ".", "getZapHome", "(", ")", "+", "File", ".", "separator", "+", "TEMPLATES_DIR", "+", ...
Loads script templates of the given {@code type} for the given {@code engine}. @param type the script type whose templates will be loaded @param engine the script engine whose templates will be loaded for the given {@code script} @since 2.4.0 @see #loadScriptTemplates(ScriptType)
[ "Loads", "script", "templates", "of", "the", "given", "{", "@code", "type", "}", "for", "the", "given", "{", "@code", "engine", "}", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/script/ExtensionScript.java#L1071-L1087
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/DataTracker.java
DataTracker.replaceEarlyOpenedFiles
public void replaceEarlyOpenedFiles(Collection<SSTableReader> toReplace, Collection<SSTableReader> replaceWith) { for (SSTableReader s : toReplace) assert s.openReason.equals(SSTableReader.OpenReason.EARLY); // note that we can replace an early opened file with a real one replaceReaders(toReplace, replaceWith, false); }
java
public void replaceEarlyOpenedFiles(Collection<SSTableReader> toReplace, Collection<SSTableReader> replaceWith) { for (SSTableReader s : toReplace) assert s.openReason.equals(SSTableReader.OpenReason.EARLY); // note that we can replace an early opened file with a real one replaceReaders(toReplace, replaceWith, false); }
[ "public", "void", "replaceEarlyOpenedFiles", "(", "Collection", "<", "SSTableReader", ">", "toReplace", ",", "Collection", "<", "SSTableReader", ">", "replaceWith", ")", "{", "for", "(", "SSTableReader", "s", ":", "toReplace", ")", "assert", "s", ".", "openReaso...
Adds the early opened files to the data tracker, but does not tell compaction strategies about it note that we dont track the live size of these sstables @param toReplace @param replaceWith
[ "Adds", "the", "early", "opened", "files", "to", "the", "data", "tracker", "but", "does", "not", "tell", "compaction", "strategies", "about", "it" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/DataTracker.java#L317-L323
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.intFunction
public static <R> IntFunction<R> intFunction(CheckedIntFunction<R> function, Consumer<Throwable> handler) { return t -> { try { return function.apply(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static <R> IntFunction<R> intFunction(CheckedIntFunction<R> function, Consumer<Throwable> handler) { return t -> { try { return function.apply(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "<", "R", ">", "IntFunction", "<", "R", ">", "intFunction", "(", "CheckedIntFunction", "<", "R", ">", "function", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "t", "->", "{", "try", "{", "return", "function",...
Wrap a {@link CheckedIntFunction} in a {@link IntFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> IntStream.of(1, 2, 3).mapToObj(Unchecked.intFunction( i -> { if (i &lt; 0) throw new Exception("Only positive numbers allowed"); return "" + i; }, e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedIntFunction", "}", "in", "a", "{", "@link", "IntFunction", "}", "with", "a", "custom", "handler", "for", "checked", "exceptions", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "IntStream", ".", "of", "(", ...
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1067-L1078
aws/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/OTAUpdateInfo.java
OTAUpdateInfo.withAdditionalParameters
public OTAUpdateInfo withAdditionalParameters(java.util.Map<String, String> additionalParameters) { setAdditionalParameters(additionalParameters); return this; }
java
public OTAUpdateInfo withAdditionalParameters(java.util.Map<String, String> additionalParameters) { setAdditionalParameters(additionalParameters); return this; }
[ "public", "OTAUpdateInfo", "withAdditionalParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "additionalParameters", ")", "{", "setAdditionalParameters", "(", "additionalParameters", ")", ";", "return", "this", ";", "}" ]
<p> A collection of name/value pairs </p> @param additionalParameters A collection of name/value pairs @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "collection", "of", "name", "/", "value", "pairs", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/OTAUpdateInfo.java#L797-L800
radkovo/jStyleParser
src/main/java/cz/vutbr/web/csskit/OutputUtil.java
OutputUtil.appendTimes
public static StringBuilder appendTimes(StringBuilder sb, String append, int times) { for(;times>0; times--) sb.append(append); return sb; }
java
public static StringBuilder appendTimes(StringBuilder sb, String append, int times) { for(;times>0; times--) sb.append(append); return sb; }
[ "public", "static", "StringBuilder", "appendTimes", "(", "StringBuilder", "sb", ",", "String", "append", ",", "int", "times", ")", "{", "for", "(", ";", "times", ">", "0", ";", "times", "--", ")", "sb", ".", "append", "(", "append", ")", ";", "return",...
Appends string multiple times to buffer @param sb StringBuilder to be modified @param append String to be added @param times Number of times <code>append</code> is added @return Modified StringBuilder <code>sb</code> to allow chaining
[ "Appends", "string", "multiple", "times", "to", "buffer" ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/csskit/OutputUtil.java#L68-L74
apache/reef
lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/remote/impl/RemoteSenderEventHandler.java
RemoteSenderEventHandler.onNext
@Override public void onNext(final RemoteEvent<T> value) { try { LOG.log(Level.FINEST, "Link: {0} event: {1}", new Object[] {linkRef, value}); if (linkRef.get() == null) { queue.add(value); final Link<byte[]> link = transport.get(value.remoteAddress()); if (link != null) { LOG.log(Level.FINEST, "transport get link: {0}", link); setLink(link); return; } final ConnectFutureTask<Link<byte[]>> cf = new ConnectFutureTask<>( new ConnectCallable(transport, value.localAddress(), value.remoteAddress()), new ConnectEventHandler<>(this)); executor.submit(cf); } else { // encode and write bytes // consumeQueue(); LOG.log(Level.FINEST, "Send: {0} event: {1}", new Object[] {linkRef, value}); linkRef.get().write(encoder.encode(value)); } } catch (final RemoteRuntimeException ex) { LOG.log(Level.SEVERE, "Remote Exception", ex); throw ex; } }
java
@Override public void onNext(final RemoteEvent<T> value) { try { LOG.log(Level.FINEST, "Link: {0} event: {1}", new Object[] {linkRef, value}); if (linkRef.get() == null) { queue.add(value); final Link<byte[]> link = transport.get(value.remoteAddress()); if (link != null) { LOG.log(Level.FINEST, "transport get link: {0}", link); setLink(link); return; } final ConnectFutureTask<Link<byte[]>> cf = new ConnectFutureTask<>( new ConnectCallable(transport, value.localAddress(), value.remoteAddress()), new ConnectEventHandler<>(this)); executor.submit(cf); } else { // encode and write bytes // consumeQueue(); LOG.log(Level.FINEST, "Send: {0} event: {1}", new Object[] {linkRef, value}); linkRef.get().write(encoder.encode(value)); } } catch (final RemoteRuntimeException ex) { LOG.log(Level.SEVERE, "Remote Exception", ex); throw ex; } }
[ "@", "Override", "public", "void", "onNext", "(", "final", "RemoteEvent", "<", "T", ">", "value", ")", "{", "try", "{", "LOG", ".", "log", "(", "Level", ".", "FINEST", ",", "\"Link: {0} event: {1}\"", ",", "new", "Object", "[", "]", "{", "linkRef", ","...
Handles the event to send to a remote node. @param value the event @throws RemoteRuntimeException
[ "Handles", "the", "event", "to", "send", "to", "a", "remote", "node", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/remote/impl/RemoteSenderEventHandler.java#L93-L125
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/factory/DecompositionFactory_ZDRM.java
DecompositionFactory_ZDRM.decomposeSafe
public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) { if( decomposition.inputModified() ) { a = a.copy(); } return decomposition.decompose(a); }
java
public static boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) { if( decomposition.inputModified() ) { a = a.copy(); } return decomposition.decompose(a); }
[ "public", "static", "boolean", "decomposeSafe", "(", "DecompositionInterface", "<", "ZMatrixRMaj", ">", "decomposition", ",", "ZMatrixRMaj", "a", ")", "{", "if", "(", "decomposition", ".", "inputModified", "(", ")", ")", "{", "a", "=", "a", ".", "copy", "(",...
Decomposes the input matrix 'a' and makes sure it isn't modified.
[ "Decomposes", "the", "input", "matrix", "a", "and", "makes", "sure", "it", "isn", "t", "modified", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/factory/DecompositionFactory_ZDRM.java#L83-L89