repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.countIgnoreCase
public static int countIgnoreCase(final String source, final String target) { if (isEmpty(source) || isEmpty(target)) { return 0; } return count(source.toLowerCase(), target.toLowerCase()); }
java
public static int countIgnoreCase(final String source, final String target) { if (isEmpty(source) || isEmpty(target)) { return 0; } return count(source.toLowerCase(), target.toLowerCase()); }
[ "public", "static", "int", "countIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "if", "(", "isEmpty", "(", "source", ")", "||", "isEmpty", "(", "target", ")", ")", "{", "return", "0", ";", "}", "return", "cou...
Count how much target in souce string.</br>统计target在source中出现的次数。 @param source source string @param target target string @return the count of target in source string.
[ "Count", "how", "much", "target", "in", "souce", "string", ".", "<", "/", "br", ">", "统计target在source中出现的次数。" ]
train
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L492-L498
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java
UnitResponse.createTimeout
public static UnitResponse createTimeout(Object dataOrException, String errMsg) { return new UnitResponse().setCode(Group.CODE_TIME_OUT).setData(dataOrException).setMessage(errMsg); }
java
public static UnitResponse createTimeout(Object dataOrException, String errMsg) { return new UnitResponse().setCode(Group.CODE_TIME_OUT).setData(dataOrException).setMessage(errMsg); }
[ "public", "static", "UnitResponse", "createTimeout", "(", "Object", "dataOrException", ",", "String", "errMsg", ")", "{", "return", "new", "UnitResponse", "(", ")", ".", "setCode", "(", "Group", ".", "CODE_TIME_OUT", ")", ".", "setData", "(", "dataOrException", ...
create a new timed out unit response. @param dataOrException the data or exception object. @param errMsg the error message. @return the newly created unit response object.
[ "create", "a", "new", "timed", "out", "unit", "response", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java#L188-L190
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java
DefaultElementProducer.notDelayedStyle
private boolean notDelayedStyle(Chunk c, String gt, Collection<? extends BaseStyler> stylers) { if (stylers == null) { return true; } try { Collection<Advanced> a = new ArrayList<>(stylers.size()); for (Advanced adv : StyleHelper.getStylers(stylers, Advanced.class)) { Advanced.EVENTMODE mode = adv.getEventmode(); if (Advanced.EVENTMODE.ALL.equals(mode) || Advanced.EVENTMODE.TEXT.equals(mode)) { // remember data and chunk adv.addDelayedData(gt, c); a.add(adv); } } if (a.size() > 0) { styleHelper.delayedStyle(c, gt, a, ph); return false; } } catch (VectorPrintException ex) { log.log(Level.SEVERE, null, ex); } return true; }
java
private boolean notDelayedStyle(Chunk c, String gt, Collection<? extends BaseStyler> stylers) { if (stylers == null) { return true; } try { Collection<Advanced> a = new ArrayList<>(stylers.size()); for (Advanced adv : StyleHelper.getStylers(stylers, Advanced.class)) { Advanced.EVENTMODE mode = adv.getEventmode(); if (Advanced.EVENTMODE.ALL.equals(mode) || Advanced.EVENTMODE.TEXT.equals(mode)) { // remember data and chunk adv.addDelayedData(gt, c); a.add(adv); } } if (a.size() > 0) { styleHelper.delayedStyle(c, gt, a, ph); return false; } } catch (VectorPrintException ex) { log.log(Level.SEVERE, null, ex); } return true; }
[ "private", "boolean", "notDelayedStyle", "(", "Chunk", "c", ",", "String", "gt", ",", "Collection", "<", "?", "extends", "BaseStyler", ">", "stylers", ")", "{", "if", "(", "stylers", "==", "null", ")", "{", "return", "true", ";", "}", "try", "{", "Coll...
register advanced stylers together with data(part) with the EventHelper to do the styling later @param c @param data @param stylers @return @see PageHelper#onGenericTag(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, com.itextpdf.text.Rectangle, java.lang.String)
[ "register", "advanced", "stylers", "together", "with", "data", "(", "part", ")", "with", "the", "EventHelper", "to", "do", "the", "styling", "later" ]
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/DefaultElementProducer.java#L305-L327
dita-ot/dita-ot
src/main/java/org/ditang/relaxng/defaults/Util.java
Util.clearUserInfo
private static URL clearUserInfo(String systemID) { try { URL url = new URL(systemID); // Do not clear user info on "file" urls 'cause on Windows the drive will // have no ":"... if (!"file".equals(url.getProtocol())) { return attachUserInfo(url, null, null); } return url; } catch (MalformedURLException e) { return null; } }
java
private static URL clearUserInfo(String systemID) { try { URL url = new URL(systemID); // Do not clear user info on "file" urls 'cause on Windows the drive will // have no ":"... if (!"file".equals(url.getProtocol())) { return attachUserInfo(url, null, null); } return url; } catch (MalformedURLException e) { return null; } }
[ "private", "static", "URL", "clearUserInfo", "(", "String", "systemID", ")", "{", "try", "{", "URL", "url", "=", "new", "URL", "(", "systemID", ")", ";", "// Do not clear user info on \"file\" urls 'cause on Windows the drive will", "// have no \":\"...", "if", "(", "...
Clears the user info from an url. @param systemID the url to be cleaned. @return the cleaned url, or null if the argument is not an URL.
[ "Clears", "the", "user", "info", "from", "an", "url", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/ditang/relaxng/defaults/Util.java#L362-L374
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpRequest.java
BoxHttpRequest.addHeader
public BoxHttpRequest addHeader(String key, String value) { mUrlConnection.addRequestProperty(key, value); return this; }
java
public BoxHttpRequest addHeader(String key, String value) { mUrlConnection.addRequestProperty(key, value); return this; }
[ "public", "BoxHttpRequest", "addHeader", "(", "String", "key", ",", "String", "value", ")", "{", "mUrlConnection", ".", "addRequestProperty", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds an HTTP header to the request. @param key the header key. @param value the header value. @return request with the updated header.
[ "Adds", "an", "HTTP", "header", "to", "the", "request", "." ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpRequest.java#L49-L52
thymeleaf/thymeleaf-spring
thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/view/AbstractThymeleafView.java
AbstractThymeleafView.setStaticVariables
public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); } this.staticVariables.putAll(variables); } }
java
public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); } this.staticVariables.putAll(variables); } }
[ "public", "void", "setStaticVariables", "(", "final", "Map", "<", "String", ",", "?", ">", "variables", ")", "{", "if", "(", "variables", "!=", "null", ")", "{", "if", "(", "this", ".", "staticVariables", "==", "null", ")", "{", "this", ".", "staticVar...
<p> Sets a set of static variables, which will be available at the context when this view is processed. </p> <p> This method <b>does not overwrite</b> the existing static variables, it simply adds the ones specify to any variables already registered. </p> <p> These static variables are added to the context before this view is processed, so that they can be referenced from the context like any other context variables, for example: {@code ${myStaticVar}}. </p> @param variables the set of variables to be added.
[ "<p", ">", "Sets", "a", "set", "of", "static", "variables", "which", "will", "be", "available", "at", "the", "context", "when", "this", "view", "is", "processed", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "<b", ">", "does", "not", "overwr...
train
https://github.com/thymeleaf/thymeleaf-spring/blob/9aa15a19017a0938e57646e3deefb8a90ab78dcb/thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/view/AbstractThymeleafView.java#L531-L538
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/COPACNeighborPredicate.java
COPACNeighborPredicate.instantiate
public COPACNeighborPredicate.Instance instantiate(Database database, Relation<V> relation) { DistanceQuery<V> dq = database.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC); KNNQuery<V> knnq = database.getKNNQuery(dq, settings.k); WritableDataStore<COPACModel> storage = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, COPACModel.class); Duration time = LOG.newDuration(this.getClass().getName() + ".preprocessing-time").begin(); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress(this.getClass().getName(), relation.size(), LOG) : null; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { DoubleDBIDList ref = knnq.getKNNForDBID(iditer, settings.k); storage.put(iditer, computeLocalModel(iditer, ref, relation)); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); LOG.statistics(time.end()); return new Instance(relation.getDBIDs(), storage); }
java
public COPACNeighborPredicate.Instance instantiate(Database database, Relation<V> relation) { DistanceQuery<V> dq = database.getDistanceQuery(relation, EuclideanDistanceFunction.STATIC); KNNQuery<V> knnq = database.getKNNQuery(dq, settings.k); WritableDataStore<COPACModel> storage = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, COPACModel.class); Duration time = LOG.newDuration(this.getClass().getName() + ".preprocessing-time").begin(); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress(this.getClass().getName(), relation.size(), LOG) : null; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { DoubleDBIDList ref = knnq.getKNNForDBID(iditer, settings.k); storage.put(iditer, computeLocalModel(iditer, ref, relation)); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); LOG.statistics(time.end()); return new Instance(relation.getDBIDs(), storage); }
[ "public", "COPACNeighborPredicate", ".", "Instance", "instantiate", "(", "Database", "database", ",", "Relation", "<", "V", ">", "relation", ")", "{", "DistanceQuery", "<", "V", ">", "dq", "=", "database", ".", "getDistanceQuery", "(", "relation", ",", "Euclid...
Full instantiation method. @param database Database @param relation Vector relation @return Instance
[ "Full", "instantiation", "method", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/gdbscan/COPACNeighborPredicate.java#L115-L131
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java
XPathUtils.evaluateAsNumber
public static Double evaluateAsNumber(Node node, String xPathExpression, NamespaceContext nsContext) { return (Double) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NUMBER); }
java
public static Double evaluateAsNumber(Node node, String xPathExpression, NamespaceContext nsContext) { return (Double) evaluateExpression(node, xPathExpression, nsContext, XPathConstants.NUMBER); }
[ "public", "static", "Double", "evaluateAsNumber", "(", "Node", "node", ",", "String", "xPathExpression", ",", "NamespaceContext", "nsContext", ")", "{", "return", "(", "Double", ")", "evaluateExpression", "(", "node", ",", "xPathExpression", ",", "nsContext", ",",...
Evaluate XPath expression with result type Number. @param node @param xPathExpression @param nsContext @return
[ "Evaluate", "XPath", "expression", "with", "result", "type", "Number", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/xpath/XPathUtils.java#L245-L247
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/protocol/version07/Base64.java
Base64.decodeFromFile
public static byte[] decodeFromFile(String filename) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables Path file = Paths.get(filename); byte[] buffer; int length = 0; int numBytes; // Check for size of file if (Files.size(file) > Integer.MAX_VALUE) { throw new java.io.IOException("File is too big for this convenience method (" + Files.size(file) + " bytes)."); } // end if: file too big for int index buffer = new byte[(int) Files.size(file)]; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(Files.newInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch (java.io.IOException e) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return decodedData; }
java
public static byte[] decodeFromFile(String filename) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables Path file = Paths.get(filename); byte[] buffer; int length = 0; int numBytes; // Check for size of file if (Files.size(file) > Integer.MAX_VALUE) { throw new java.io.IOException("File is too big for this convenience method (" + Files.size(file) + " bytes)."); } // end if: file too big for int index buffer = new byte[(int) Files.size(file)]; // Open a stream bis = new Base64.InputStream(new java.io.BufferedInputStream(Files.newInputStream(file)), Base64.DECODE); // Read until done while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[length]; System.arraycopy(buffer, 0, decodedData, 0, length); } // end try catch (java.io.IOException e) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try { bis.close(); } catch (Exception e) { } } // end finally return decodedData; }
[ "public", "static", "byte", "[", "]", "decodeFromFile", "(", "String", "filename", ")", "throws", "java", ".", "io", ".", "IOException", "{", "byte", "[", "]", "decodedData", "=", "null", ";", "Base64", ".", "InputStream", "bis", "=", "null", ";", "try",...
Convenience method for reading a base64-encoded file and decoding it. <p> As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it. </p> @param filename Filename for reading encoded data @return decoded byte array @throws java.io.IOException if there is an error @since 2.1
[ "Convenience", "method", "for", "reading", "a", "base64", "-", "encoded", "file", "and", "decoding", "it", "." ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/protocol/version07/Base64.java#L1355-L1396
googleapis/google-cloud-java
google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java
UnixPath.getParent
@Nullable public UnixPath getParent() { if (path.isEmpty() || isRoot()) { return null; } int index = hasTrailingSeparator() ? path.lastIndexOf(SEPARATOR, path.length() - 2) : path.lastIndexOf(SEPARATOR); if (index == -1) { return isAbsolute() ? ROOT_PATH : null; } else { return new UnixPath(permitEmptyComponents, path.substring(0, index + 1)); } }
java
@Nullable public UnixPath getParent() { if (path.isEmpty() || isRoot()) { return null; } int index = hasTrailingSeparator() ? path.lastIndexOf(SEPARATOR, path.length() - 2) : path.lastIndexOf(SEPARATOR); if (index == -1) { return isAbsolute() ? ROOT_PATH : null; } else { return new UnixPath(permitEmptyComponents, path.substring(0, index + 1)); } }
[ "@", "Nullable", "public", "UnixPath", "getParent", "(", ")", "{", "if", "(", "path", ".", "isEmpty", "(", ")", "||", "isRoot", "(", ")", ")", "{", "return", "null", ";", "}", "int", "index", "=", "hasTrailingSeparator", "(", ")", "?", "path", ".", ...
Returns parent directory (including trailing separator) or {@code null} if no parent remains. @see java.nio.file.Path#getParent()
[ "Returns", "parent", "directory", "(", "including", "trailing", "separator", ")", "or", "{", "@code", "null", "}", "if", "no", "parent", "remains", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/UnixPath.java#L177-L191
datumbox/lpsolve
src/main/java/lpsolve/LpSolve.java
LpSolve.putBbNodefunc
public void putBbNodefunc(BbListener listener, Object userhandle) throws LpSolveException { bbNodeListener = listener; bbNodeUserhandle = (listener != null) ? userhandle : null; addLp(this); registerBbNodefunc(); }
java
public void putBbNodefunc(BbListener listener, Object userhandle) throws LpSolveException { bbNodeListener = listener; bbNodeUserhandle = (listener != null) ? userhandle : null; addLp(this); registerBbNodefunc(); }
[ "public", "void", "putBbNodefunc", "(", "BbListener", "listener", ",", "Object", "userhandle", ")", "throws", "LpSolveException", "{", "bbNodeListener", "=", "listener", ";", "bbNodeUserhandle", "=", "(", "listener", "!=", "null", ")", "?", "userhandle", ":", "n...
Register an <code>BbNodeListener</code> for callback. @param listener the listener that should be called by lp_solve @param userhandle an arbitrary object that is passed to the listener on call
[ "Register", "an", "<code", ">", "BbNodeListener<", "/", "code", ">", "for", "callback", "." ]
train
https://github.com/datumbox/lpsolve/blob/201b3e99153d907bb99c189e5647bc71a3a1add6/src/main/java/lpsolve/LpSolve.java#L1667-L1672
apache/incubator-druid
sql/src/main/java/org/apache/druid/sql/calcite/rel/DruidQuery.java
DruidQuery.computeAggregations
private static List<Aggregation> computeAggregations( final PartialDruidQuery partialQuery, final PlannerContext plannerContext, final DruidQuerySignature querySignature, final RexBuilder rexBuilder, final boolean finalizeAggregations ) { final Aggregate aggregate = Preconditions.checkNotNull(partialQuery.getAggregate()); final List<Aggregation> aggregations = new ArrayList<>(); final String outputNamePrefix = Calcites.findUnusedPrefix( "a", new TreeSet<>(querySignature.getRowSignature().getRowOrder()) ); for (int i = 0; i < aggregate.getAggCallList().size(); i++) { final String aggName = outputNamePrefix + i; final AggregateCall aggCall = aggregate.getAggCallList().get(i); final Aggregation aggregation = GroupByRules.translateAggregateCall( plannerContext, querySignature, rexBuilder, partialQuery.getSelectProject(), aggregations, aggName, aggCall, finalizeAggregations ); if (aggregation == null) { throw new CannotBuildQueryException(aggregate, aggCall); } aggregations.add(aggregation); } return aggregations; }
java
private static List<Aggregation> computeAggregations( final PartialDruidQuery partialQuery, final PlannerContext plannerContext, final DruidQuerySignature querySignature, final RexBuilder rexBuilder, final boolean finalizeAggregations ) { final Aggregate aggregate = Preconditions.checkNotNull(partialQuery.getAggregate()); final List<Aggregation> aggregations = new ArrayList<>(); final String outputNamePrefix = Calcites.findUnusedPrefix( "a", new TreeSet<>(querySignature.getRowSignature().getRowOrder()) ); for (int i = 0; i < aggregate.getAggCallList().size(); i++) { final String aggName = outputNamePrefix + i; final AggregateCall aggCall = aggregate.getAggCallList().get(i); final Aggregation aggregation = GroupByRules.translateAggregateCall( plannerContext, querySignature, rexBuilder, partialQuery.getSelectProject(), aggregations, aggName, aggCall, finalizeAggregations ); if (aggregation == null) { throw new CannotBuildQueryException(aggregate, aggCall); } aggregations.add(aggregation); } return aggregations; }
[ "private", "static", "List", "<", "Aggregation", ">", "computeAggregations", "(", "final", "PartialDruidQuery", "partialQuery", ",", "final", "PlannerContext", "plannerContext", ",", "final", "DruidQuerySignature", "querySignature", ",", "final", "RexBuilder", "rexBuilder...
Returns aggregations corresponding to {@code aggregate.getAggCallList()}, in the same order. @param partialQuery partial query @param plannerContext planner context @param querySignature source row signature and re-usable virtual column references @param rexBuilder calcite RexBuilder @param finalizeAggregations true if this query should include explicit finalization for all of its aggregators, where required. Useful for subqueries where Druid's native query layer does not do this automatically. @return aggregations @throws CannotBuildQueryException if dimensions cannot be computed
[ "Returns", "aggregations", "corresponding", "to", "{", "@code", "aggregate", ".", "getAggCallList", "()", "}", "in", "the", "same", "order", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/sql/src/main/java/org/apache/druid/sql/calcite/rel/DruidQuery.java#L522-L559
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java
UfsJournalGarbageCollector.gcFileIfStale
private void gcFileIfStale(UfsJournalFile file, long checkpointSequenceNumber) { if (file.getEnd() > checkpointSequenceNumber && !file.isTmpCheckpoint()) { return; } long lastModifiedTimeMs; try { lastModifiedTimeMs = mUfs.getFileStatus(file.getLocation().toString()).getLastModifiedTime(); } catch (IOException e) { LOG.warn("Failed to get the last modified time for {}.", file.getLocation()); return; } long thresholdMs = file.isTmpCheckpoint() ? ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_TEMPORARY_FILE_GC_THRESHOLD_MS) : ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_GC_THRESHOLD_MS); if (System.currentTimeMillis() - lastModifiedTimeMs > thresholdMs) { deleteNoException(file.getLocation()); } }
java
private void gcFileIfStale(UfsJournalFile file, long checkpointSequenceNumber) { if (file.getEnd() > checkpointSequenceNumber && !file.isTmpCheckpoint()) { return; } long lastModifiedTimeMs; try { lastModifiedTimeMs = mUfs.getFileStatus(file.getLocation().toString()).getLastModifiedTime(); } catch (IOException e) { LOG.warn("Failed to get the last modified time for {}.", file.getLocation()); return; } long thresholdMs = file.isTmpCheckpoint() ? ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_TEMPORARY_FILE_GC_THRESHOLD_MS) : ServerConfiguration.getMs(PropertyKey.MASTER_JOURNAL_GC_THRESHOLD_MS); if (System.currentTimeMillis() - lastModifiedTimeMs > thresholdMs) { deleteNoException(file.getLocation()); } }
[ "private", "void", "gcFileIfStale", "(", "UfsJournalFile", "file", ",", "long", "checkpointSequenceNumber", ")", "{", "if", "(", "file", ".", "getEnd", "(", ")", ">", "checkpointSequenceNumber", "&&", "!", "file", ".", "isTmpCheckpoint", "(", ")", ")", "{", ...
Garbage collects a file if necessary. @param file the file @param checkpointSequenceNumber the first sequence number that has not been checkpointed
[ "Garbage", "collects", "a", "file", "if", "necessary", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournalGarbageCollector.java#L118-L138
andi12/msbuild-maven-plugin
msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MojoHelper.java
MojoHelper.validateToolPath
public static void validateToolPath( File toolPath, String toolName, Log logger ) throws FileNotFoundException { logger.debug( "Validating path for " + toolName ); if ( toolPath == null ) { logger.error( "Missing " + toolName + " path" ); throw new FileNotFoundException(); } if ( !toolPath.exists() || !toolPath.isFile() ) { logger.error( "Could not find " + toolName + " at " + toolPath ); throw new FileNotFoundException( toolPath.getAbsolutePath() ); } logger.debug( "Found " + toolName + " at " + toolPath ); }
java
public static void validateToolPath( File toolPath, String toolName, Log logger ) throws FileNotFoundException { logger.debug( "Validating path for " + toolName ); if ( toolPath == null ) { logger.error( "Missing " + toolName + " path" ); throw new FileNotFoundException(); } if ( !toolPath.exists() || !toolPath.isFile() ) { logger.error( "Could not find " + toolName + " at " + toolPath ); throw new FileNotFoundException( toolPath.getAbsolutePath() ); } logger.debug( "Found " + toolName + " at " + toolPath ); }
[ "public", "static", "void", "validateToolPath", "(", "File", "toolPath", ",", "String", "toolName", ",", "Log", "logger", ")", "throws", "FileNotFoundException", "{", "logger", ".", "debug", "(", "\"Validating path for \"", "+", "toolName", ")", ";", "if", "(", ...
Validates the path to a command-line tool. @param toolPath the configured tool path from the POM @param toolName the name of the tool, used for logging messages @param logger a Log to write messages to @throws FileNotFoundException if the tool cannot be found
[ "Validates", "the", "path", "to", "a", "command", "-", "line", "tool", "." ]
train
https://github.com/andi12/msbuild-maven-plugin/blob/224159c15efba20d482f8c630f7947339b1a1b86/msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/MojoHelper.java#L48-L66
zaproxy/zaproxy
src/org/apache/commons/httpclient/HttpMethodBase.java
HttpMethodBase.writeRequestHeaders
protected void writeRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState," + "HttpConnection)"); addRequestHeaders(state, conn); String charset = getParams().getHttpElementCharset(); Header[] headers = getRequestHeaders(); for (int i = 0; i < headers.length; i++) { String s = headers[i].toExternalForm(); if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output(s); } conn.print(s, charset); } }
java
protected void writeRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState," + "HttpConnection)"); addRequestHeaders(state, conn); String charset = getParams().getHttpElementCharset(); Header[] headers = getRequestHeaders(); for (int i = 0; i < headers.length; i++) { String s = headers[i].toExternalForm(); if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output(s); } conn.print(s, charset); } }
[ "protected", "void", "writeRequestHeaders", "(", "HttpState", "state", ",", "HttpConnection", "conn", ")", "throws", "IOException", ",", "HttpException", "{", "LOG", ".", "trace", "(", "\"enter HttpMethodBase.writeRequestHeaders(HttpState,\"", "+", "\"HttpConnection)\"", ...
Writes the request headers to the given {@link HttpConnection connection}. <p> This implementation invokes {@link #addRequestHeaders(HttpState,HttpConnection)}, and then writes each header to the request stream. </p> <p> Subclasses may want to override this method to to customize the processing. </p> @param state the {@link HttpState state} information associated with this method @param conn the {@link HttpConnection connection} used to execute this HTTP method @throws IOException if an I/O (transport) error occurs. Some transport exceptions can be recovered from. @throws HttpException if a protocol exception occurs. Usually protocol exceptions cannot be recovered from. @see #addRequestHeaders @see #getRequestHeaders
[ "Writes", "the", "request", "headers", "to", "the", "given", "{", "@link", "HttpConnection", "connection", "}", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/apache/commons/httpclient/HttpMethodBase.java#L2305-L2321
Azure/azure-sdk-for-java
servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java
ClientFactory.acceptSessionFromEntityPathAsync
public static CompletableFuture<IMessageSession> acceptSessionFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) { return acceptSessionFromEntityPathAsync(messagingFactory, entityPath, null, sessionId, receiveMode); }
java
public static CompletableFuture<IMessageSession> acceptSessionFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) { return acceptSessionFromEntityPathAsync(messagingFactory, entityPath, null, sessionId, receiveMode); }
[ "public", "static", "CompletableFuture", "<", "IMessageSession", ">", "acceptSessionFromEntityPathAsync", "(", "MessagingFactory", "messagingFactory", ",", "String", "entityPath", ",", "String", "sessionId", ",", "ReceiveMode", "receiveMode", ")", "{", "return", "acceptSe...
Asynchronously accepts a session from service bus using the client settings. Session Id can be null, if null, service will return the first available session. @param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created. @param entityPath path of entity @param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session @param receiveMode PeekLock or ReceiveAndDelete @return a CompletableFuture representing the pending session accepting
[ "Asynchronously", "accepts", "a", "session", "from", "service", "bus", "using", "the", "client", "settings", ".", "Session", "Id", "can", "be", "null", "if", "null", "service", "will", "return", "the", "first", "available", "session", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L736-L738
jbundle/jbundle
base/message/trx/src/main/java/org/jbundle/base/message/trx/transport/soap/SOAPMessageTransport.java
SOAPMessageTransport.setSOAPBody
public SOAPMessage setSOAPBody(SOAPMessage msg, BaseMessage message) { try { if (msg == null) msg = fac.createMessage(); // Message creation takes care of creating the SOAPPart - a // required part of the message as per the SOAP 1.1 // specification. SOAPPart soappart = msg.getSOAPPart(); // Retrieve the envelope from the soap part to start building // the soap message. SOAPEnvelope envelope = soappart.getEnvelope(); // Create a soap header from the envelope. //?SOAPHeader header = envelope.getHeader(); // Create a soap body from the envelope. SOAPBody body = envelope.getBody(); DOMResult result = new DOMResult(body); if (((BaseXmlTrxMessageOut)message.getExternalMessage()).copyMessageToResult(result)) { // Success // Note: For Jabx, I would have to fix the namespace of the message (so don't use JAXB) msg.saveChanges(); return msg; } } catch(Throwable e) { e.printStackTrace(); Utility.getLogger().warning("Error in constructing or sending message " +e.getMessage()); } return null; }
java
public SOAPMessage setSOAPBody(SOAPMessage msg, BaseMessage message) { try { if (msg == null) msg = fac.createMessage(); // Message creation takes care of creating the SOAPPart - a // required part of the message as per the SOAP 1.1 // specification. SOAPPart soappart = msg.getSOAPPart(); // Retrieve the envelope from the soap part to start building // the soap message. SOAPEnvelope envelope = soappart.getEnvelope(); // Create a soap header from the envelope. //?SOAPHeader header = envelope.getHeader(); // Create a soap body from the envelope. SOAPBody body = envelope.getBody(); DOMResult result = new DOMResult(body); if (((BaseXmlTrxMessageOut)message.getExternalMessage()).copyMessageToResult(result)) { // Success // Note: For Jabx, I would have to fix the namespace of the message (so don't use JAXB) msg.saveChanges(); return msg; } } catch(Throwable e) { e.printStackTrace(); Utility.getLogger().warning("Error in constructing or sending message " +e.getMessage()); } return null; }
[ "public", "SOAPMessage", "setSOAPBody", "(", "SOAPMessage", "msg", ",", "BaseMessage", "message", ")", "{", "try", "{", "if", "(", "msg", "==", "null", ")", "msg", "=", "fac", ".", "createMessage", "(", ")", ";", "// Message creation takes care of creating the S...
This utility method sticks this message into this soap message's body. @param msg The source message.
[ "This", "utility", "method", "sticks", "this", "message", "into", "this", "soap", "message", "s", "body", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/transport/soap/SOAPMessageTransport.java#L222-L255
shrinkwrap/shrinkwrap
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/importer/ExplodedImporterImpl.java
ExplodedImporterImpl.calculatePath
private ArchivePath calculatePath(File root, File child) { String rootPath = unifyPath(root.getPath()); String childPath = unifyPath(child.getPath()); String archiveChildPath = childPath.replaceFirst(Pattern.quote(rootPath), ""); return new BasicPath(archiveChildPath); }
java
private ArchivePath calculatePath(File root, File child) { String rootPath = unifyPath(root.getPath()); String childPath = unifyPath(child.getPath()); String archiveChildPath = childPath.replaceFirst(Pattern.quote(rootPath), ""); return new BasicPath(archiveChildPath); }
[ "private", "ArchivePath", "calculatePath", "(", "File", "root", ",", "File", "child", ")", "{", "String", "rootPath", "=", "unifyPath", "(", "root", ".", "getPath", "(", ")", ")", ";", "String", "childPath", "=", "unifyPath", "(", "child", ".", "getPath", ...
Calculate the relative child path. @param root The Archive root folder @param child The Child file @return a Path fort he child relative to root
[ "Calculate", "the", "relative", "child", "path", "." ]
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/importer/ExplodedImporterImpl.java#L142-L147
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/collection/Int2ObjectHashMap.java
Int2ObjectHashMap.computeIfAbsent
public V computeIfAbsent(final int key, final IntFunction<? extends V> mappingFunction) { checkNotNull(mappingFunction, "mappingFunction cannot be null"); V value = get(key); if (value == null) { value = mappingFunction.apply(key); if (value != null) { put(key, value); } } return value; }
java
public V computeIfAbsent(final int key, final IntFunction<? extends V> mappingFunction) { checkNotNull(mappingFunction, "mappingFunction cannot be null"); V value = get(key); if (value == null) { value = mappingFunction.apply(key); if (value != null) { put(key, value); } } return value; }
[ "public", "V", "computeIfAbsent", "(", "final", "int", "key", ",", "final", "IntFunction", "<", "?", "extends", "V", ">", "mappingFunction", ")", "{", "checkNotNull", "(", "mappingFunction", ",", "\"mappingFunction cannot be null\"", ")", ";", "V", "value", "=",...
Get a value for a given key, or if it does ot exist then default the value via a {@link IntFunction} and put it in the map. @param key to search on. @param mappingFunction to provide a value if the get returns null. @return the value if found otherwise the default.
[ "Get", "a", "value", "for", "a", "given", "key", "or", "if", "it", "does", "ot", "exist", "then", "default", "the", "value", "via", "a", "{", "@link", "IntFunction", "}", "and", "put", "it", "in", "the", "map", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/collection/Int2ObjectHashMap.java#L193-L203
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/markup/DamVideoMediaMarkupBuilder.java
DamVideoMediaMarkupBuilder.getVideoPlayerElement
protected Video getVideoPlayerElement(@NotNull Media media) { Dimension dimension = MediaMarkupBuilderUtil.getMediaformatDimension(media); Video video = new Video(); video.setWidth((int)dimension.getWidth()); video.setHeight((int)dimension.getHeight()); video.setControls(true); // add video sources for each video profile addSources(video, media); // add flash player as fallback video.addContent(getFlashPlayerElement(media, dimension)); return video; }
java
protected Video getVideoPlayerElement(@NotNull Media media) { Dimension dimension = MediaMarkupBuilderUtil.getMediaformatDimension(media); Video video = new Video(); video.setWidth((int)dimension.getWidth()); video.setHeight((int)dimension.getHeight()); video.setControls(true); // add video sources for each video profile addSources(video, media); // add flash player as fallback video.addContent(getFlashPlayerElement(media, dimension)); return video; }
[ "protected", "Video", "getVideoPlayerElement", "(", "@", "NotNull", "Media", "media", ")", "{", "Dimension", "dimension", "=", "MediaMarkupBuilderUtil", ".", "getMediaformatDimension", "(", "media", ")", ";", "Video", "video", "=", "new", "Video", "(", ")", ";",...
Build HTML5 video player element @param media Media metadata @return Media element
[ "Build", "HTML5", "video", "player", "element" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/markup/DamVideoMediaMarkupBuilder.java#L137-L152
pravega/pravega
segmentstore/contracts/src/main/java/io/pravega/segmentstore/contracts/tables/TableEntry.java
TableEntry.unversioned
public static TableEntry unversioned(@NonNull ArrayView key, @NonNull ArrayView value) { return new TableEntry(TableKey.unversioned(key), value); }
java
public static TableEntry unversioned(@NonNull ArrayView key, @NonNull ArrayView value) { return new TableEntry(TableKey.unversioned(key), value); }
[ "public", "static", "TableEntry", "unversioned", "(", "@", "NonNull", "ArrayView", "key", ",", "@", "NonNull", "ArrayView", "value", ")", "{", "return", "new", "TableEntry", "(", "TableKey", ".", "unversioned", "(", "key", ")", ",", "value", ")", ";", "}" ...
Creates a new instance of the TableEntry class with no desired version. @param key The Key. @param value The Value. @return the TableEntry that was created
[ "Creates", "a", "new", "instance", "of", "the", "TableEntry", "class", "with", "no", "desired", "version", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/contracts/src/main/java/io/pravega/segmentstore/contracts/tables/TableEntry.java#L42-L44
thinkaurelius/titan
titan-core/src/main/java/com/thinkaurelius/titan/graphdb/database/idassigner/placement/PartitionIDRange.java
PartitionIDRange.getGlobalRange
public static List<PartitionIDRange> getGlobalRange(final int partitionBits) { Preconditions.checkArgument(partitionBits>=0 && partitionBits<(Integer.SIZE-1),"Invalid partition bits: %s",partitionBits); final int partitionIdBound = (1 << (partitionBits)); return ImmutableList.of(new PartitionIDRange(0, partitionIdBound, partitionIdBound)); }
java
public static List<PartitionIDRange> getGlobalRange(final int partitionBits) { Preconditions.checkArgument(partitionBits>=0 && partitionBits<(Integer.SIZE-1),"Invalid partition bits: %s",partitionBits); final int partitionIdBound = (1 << (partitionBits)); return ImmutableList.of(new PartitionIDRange(0, partitionIdBound, partitionIdBound)); }
[ "public", "static", "List", "<", "PartitionIDRange", ">", "getGlobalRange", "(", "final", "int", "partitionBits", ")", "{", "Preconditions", ".", "checkArgument", "(", "partitionBits", ">=", "0", "&&", "partitionBits", "<", "(", "Integer", ".", "SIZE", "-", "1...
/* =========== Helper methods to generate PartitionIDRanges ============
[ "/", "*", "===========", "Helper", "methods", "to", "generate", "PartitionIDRanges", "============" ]
train
https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/database/idassigner/placement/PartitionIDRange.java#L120-L124
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/decomposition/eig/EigenPowerMethod_DDRM.java
EigenPowerMethod_DDRM.computeShiftInvert
public boolean computeShiftInvert(DMatrixRMaj A , double alpha ) { initPower(A); LinearSolverDense solver = LinearSolverFactory_DDRM.linear(A.numCols); SpecializedOps_DDRM.addIdentity(A,B,-alpha); solver.setA(B); boolean converged = false; for( int i = 0; i < maxIterations && !converged; i++ ) { solver.solve(q0,q1); double s = NormOps_DDRM.normPInf(q1); CommonOps_DDRM.divide(q1,s,q2); converged = checkConverged(A); } return converged; }
java
public boolean computeShiftInvert(DMatrixRMaj A , double alpha ) { initPower(A); LinearSolverDense solver = LinearSolverFactory_DDRM.linear(A.numCols); SpecializedOps_DDRM.addIdentity(A,B,-alpha); solver.setA(B); boolean converged = false; for( int i = 0; i < maxIterations && !converged; i++ ) { solver.solve(q0,q1); double s = NormOps_DDRM.normPInf(q1); CommonOps_DDRM.divide(q1,s,q2); converged = checkConverged(A); } return converged; }
[ "public", "boolean", "computeShiftInvert", "(", "DMatrixRMaj", "A", ",", "double", "alpha", ")", "{", "initPower", "(", "A", ")", ";", "LinearSolverDense", "solver", "=", "LinearSolverFactory_DDRM", ".", "linear", "(", "A", ".", "numCols", ")", ";", "Specializ...
Computes the most dominant eigen vector of A using an inverted shifted matrix. The inverted shifted matrix is defined as <b>B = (A - &alpha;I)<sup>-1</sup></b> and can converge faster if &alpha; is chosen wisely. @param A An invertible square matrix matrix. @param alpha Shifting factor. @return If it converged or not.
[ "Computes", "the", "most", "dominant", "eigen", "vector", "of", "A", "using", "an", "inverted", "shifted", "matrix", ".", "The", "inverted", "shifted", "matrix", "is", "defined", "as", "<b", ">", "B", "=", "(", "A", "-", "&alpha", ";", "I", ")", "<sup"...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/decomposition/eig/EigenPowerMethod_DDRM.java#L195-L214
jblas-project/jblas
src/main/java/org/jblas/util/LibraryLoader.java
LibraryLoader.loadLibraryFromStream
private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
java
private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
[ "private", "void", "loadLibraryFromStream", "(", "String", "libname", ",", "InputStream", "is", ")", "{", "try", "{", "File", "tempfile", "=", "createTempFile", "(", "libname", ")", ";", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "tempfile", ")...
Load a system library from a stream. Copies the library to a temp file and loads from there. @param libname name of the library (just used in constructing the library name) @param is InputStream pointing to the library
[ "Load", "a", "system", "library", "from", "a", "stream", ".", "Copies", "the", "library", "to", "a", "temp", "file", "and", "loads", "from", "there", "." ]
train
https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/util/LibraryLoader.java#L249-L282
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/transformer/AbstractObservableTransformerSource.java
AbstractObservableTransformerSource.onSourceErrorOccurred
protected void onSourceErrorOccurred(TransformerSourceErrorEvent event) { for (TransformerSourceEventListener listener : transformerSourceEventListeners) fireErrorEvent(listener, event); } /** * Fires the given event on the given listener. * @param listener The listener to fire the event to. * @param event The event to fire. */ private void fireErrorEvent(TransformerSourceEventListener listener, TransformerSourceErrorEvent event) { try { listener.ErrorOccurred(event); } catch (RuntimeException e) { // Log this somehow System.err.println("Exception thrown while trying to invoke event listener, removing bed behaved listener."); e.printStackTrace(); removeTransformerSourceEventListener(listener); } } }
java
protected void onSourceErrorOccurred(TransformerSourceErrorEvent event) { for (TransformerSourceEventListener listener : transformerSourceEventListeners) fireErrorEvent(listener, event); } /** * Fires the given event on the given listener. * @param listener The listener to fire the event to. * @param event The event to fire. */ private void fireErrorEvent(TransformerSourceEventListener listener, TransformerSourceErrorEvent event) { try { listener.ErrorOccurred(event); } catch (RuntimeException e) { // Log this somehow System.err.println("Exception thrown while trying to invoke event listener, removing bed behaved listener."); e.printStackTrace(); removeTransformerSourceEventListener(listener); } } }
[ "protected", "void", "onSourceErrorOccurred", "(", "TransformerSourceErrorEvent", "event", ")", "{", "for", "(", "TransformerSourceEventListener", "listener", ":", "transformerSourceEventListeners", ")", "fireErrorEvent", "(", "listener", ",", "event", ")", ";", "}", "/...
(Re)-fires a preconstructed event. @param event The event to fire
[ "(", "Re", ")", "-", "fires", "a", "preconstructed", "event", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/transformer/AbstractObservableTransformerSource.java#L79-L102
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/TSNE.java
TSNE.updateSolution
protected void updateSolution(double[][] sol, double[] meta, int it) { final double mom = (it < momentumSwitch && initialMomentum < finalMomentum) ? initialMomentum : finalMomentum; final int dim3 = dim * 3; for(int i = 0, off = 0; i < sol.length; i++, off += dim3) { final double[] sol_i = sol[i]; for(int k = 0; k < dim; k++) { // Indexes in meta array final int gradk = off + k, movk = gradk + dim, gaink = movk + dim; // Adjust learning rate: meta[gaink] = MathUtil.max(((meta[gradk] > 0) != (meta[movk] > 0)) ? (meta[gaink] + 0.2) : (meta[gaink] * 0.8), MIN_GAIN); meta[movk] *= mom; // Dampening the previous momentum meta[movk] -= learningRate * meta[gradk] * meta[gaink]; // Learn sol_i[k] += meta[movk]; } } }
java
protected void updateSolution(double[][] sol, double[] meta, int it) { final double mom = (it < momentumSwitch && initialMomentum < finalMomentum) ? initialMomentum : finalMomentum; final int dim3 = dim * 3; for(int i = 0, off = 0; i < sol.length; i++, off += dim3) { final double[] sol_i = sol[i]; for(int k = 0; k < dim; k++) { // Indexes in meta array final int gradk = off + k, movk = gradk + dim, gaink = movk + dim; // Adjust learning rate: meta[gaink] = MathUtil.max(((meta[gradk] > 0) != (meta[movk] > 0)) ? (meta[gaink] + 0.2) : (meta[gaink] * 0.8), MIN_GAIN); meta[movk] *= mom; // Dampening the previous momentum meta[movk] -= learningRate * meta[gradk] * meta[gaink]; // Learn sol_i[k] += meta[movk]; } } }
[ "protected", "void", "updateSolution", "(", "double", "[", "]", "[", "]", "sol", ",", "double", "[", "]", "meta", ",", "int", "it", ")", "{", "final", "double", "mom", "=", "(", "it", "<", "momentumSwitch", "&&", "initialMomentum", "<", "finalMomentum", ...
Update the current solution on iteration. @param sol Solution matrix @param meta Metadata array (gradient, momentum, learning rate) @param it Iteration number, to choose momentum factor.
[ "Update", "the", "current", "solution", "on", "iteration", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/TSNE.java#L345-L360
brianwhu/xillium
base/src/main/java/org/xillium/base/util/Mathematical.java
Mathematical.floor
public static int floor(int n, int m) { return n >= 0 ? (n / m) * m : ((n - m + 1) / m) * m; }
java
public static int floor(int n, int m) { return n >= 0 ? (n / m) * m : ((n - m + 1) / m) * m; }
[ "public", "static", "int", "floor", "(", "int", "n", ",", "int", "m", ")", "{", "return", "n", ">=", "0", "?", "(", "n", "/", "m", ")", "*", "m", ":", "(", "(", "n", "-", "m", "+", "1", ")", "/", "m", ")", "*", "m", ";", "}" ]
Rounds n down to the nearest multiple of m @param n an integer @param m an integer @return the value after rounding {@code n} down to the nearest multiple of {@code m}
[ "Rounds", "n", "down", "to", "the", "nearest", "multiple", "of", "m" ]
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/util/Mathematical.java#L15-L17
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java
ReUtil.extractMulti
public static String extractMulti(Pattern pattern, CharSequence content, String template) { if (null == content || null == pattern || null == template) { return null; } //提取模板中的编号 final TreeSet<Integer> varNums = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return ObjectUtil.compare(o2, o1); } }); final Matcher matcherForTemplate = PatternPool.GROUP_VAR.matcher(template); while (matcherForTemplate.find()) { varNums.add(Integer.parseInt(matcherForTemplate.group(1))); } final Matcher matcher = pattern.matcher(content); if (matcher.find()) { for (Integer group : varNums) { template = template.replace("$" + group, matcher.group(group)); } return template; } return null; }
java
public static String extractMulti(Pattern pattern, CharSequence content, String template) { if (null == content || null == pattern || null == template) { return null; } //提取模板中的编号 final TreeSet<Integer> varNums = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return ObjectUtil.compare(o2, o1); } }); final Matcher matcherForTemplate = PatternPool.GROUP_VAR.matcher(template); while (matcherForTemplate.find()) { varNums.add(Integer.parseInt(matcherForTemplate.group(1))); } final Matcher matcher = pattern.matcher(content); if (matcher.find()) { for (Integer group : varNums) { template = template.replace("$" + group, matcher.group(group)); } return template; } return null; }
[ "public", "static", "String", "extractMulti", "(", "Pattern", "pattern", ",", "CharSequence", "content", ",", "String", "template", ")", "{", "if", "(", "null", "==", "content", "||", "null", "==", "pattern", "||", "null", "==", "template", ")", "{", "retu...
从content中匹配出多个值并根据template生成新的字符串<br> 例如:<br> content 2013年5月 pattern (.*?)年(.*?)月 template: $1-$2 return 2013-5 @param pattern 匹配正则 @param content 被匹配的内容 @param template 生成内容模板,变量 $1 表示group1的内容,以此类推 @return 新字符串
[ "从content中匹配出多个值并根据template生成新的字符串<br", ">", "例如:<br", ">", "content", "2013年5月", "pattern", "(", ".", "*", "?", ")", "年", "(", ".", "*", "?", ")", "月", "template:", "$1", "-", "$2", "return", "2013", "-", "5" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L171-L196
jhalterman/failsafe
src/main/java/net/jodah/failsafe/FailsafeExecutor.java
FailsafeExecutor.getStageAsync
public <T extends R> CompletableFuture<T> getStageAsync(CheckedSupplier<? extends CompletionStage<T>> supplier) { return callAsync(execution -> Functions.promiseOfStage(supplier, execution), false); }
java
public <T extends R> CompletableFuture<T> getStageAsync(CheckedSupplier<? extends CompletionStage<T>> supplier) { return callAsync(execution -> Functions.promiseOfStage(supplier, execution), false); }
[ "public", "<", "T", "extends", "R", ">", "CompletableFuture", "<", "T", ">", "getStageAsync", "(", "CheckedSupplier", "<", "?", "extends", "CompletionStage", "<", "T", ">", ">", "supplier", ")", "{", "return", "callAsync", "(", "execution", "->", "Functions"...
Executes the {@code supplier} asynchronously until the resulting future is successfully completed or the configured policies are exceeded. <p> If a configured circuit breaker is open, the resulting future is completed exceptionally with {@link CircuitBreakerOpenException}. @throws NullPointerException if the {@code supplier} is null @throws RejectedExecutionException if the {@code supplier} cannot be scheduled for execution
[ "Executes", "the", "{", "@code", "supplier", "}", "asynchronously", "until", "the", "resulting", "future", "is", "successfully", "completed", "or", "the", "configured", "policies", "are", "exceeded", ".", "<p", ">", "If", "a", "configured", "circuit", "breaker",...
train
https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/FailsafeExecutor.java#L174-L176
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaMemcpyFromArray
public static int cudaMemcpyFromArray(Pointer dst, cudaArray src, long wOffset, long hOffset, long count, int cudaMemcpyKind_kind) { return checkResult(cudaMemcpyFromArrayNative(dst, src, wOffset, hOffset, count, cudaMemcpyKind_kind)); }
java
public static int cudaMemcpyFromArray(Pointer dst, cudaArray src, long wOffset, long hOffset, long count, int cudaMemcpyKind_kind) { return checkResult(cudaMemcpyFromArrayNative(dst, src, wOffset, hOffset, count, cudaMemcpyKind_kind)); }
[ "public", "static", "int", "cudaMemcpyFromArray", "(", "Pointer", "dst", ",", "cudaArray", "src", ",", "long", "wOffset", ",", "long", "hOffset", ",", "long", "count", ",", "int", "cudaMemcpyKind_kind", ")", "{", "return", "checkResult", "(", "cudaMemcpyFromArra...
Copies data between host and device. <pre> cudaError_t cudaMemcpyFromArray ( void* dst, cudaArray_const_t src, size_t wOffset, size_t hOffset, size_t count, cudaMemcpyKind kind ) </pre> <div> <p>Copies data between host and device. Copies <tt>count</tt> bytes from the CUDA array <tt>src</tt> starting at the upper left corner (<tt>wOffset</tt>, hOffset) to the memory area pointed to by <tt>dst</tt>, where <tt>kind</tt> is one of cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMemcpyDeviceToHost, or cudaMemcpyDeviceToDevice, and specifies the direction of the copy. </p> <div> <span>Note:</span> <ul> <li> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </li> <li> <p>This function exhibits synchronous behavior for most use cases. </p> </li> </ul> </div> </p> </div> @param dst Destination memory address @param src Source memory address @param wOffset Source starting X offset @param hOffset Source starting Y offset @param count Size in bytes to copy @param kind Type of transfer @return cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDevicePointer, cudaErrorInvalidMemcpyDirection @see JCuda#cudaMemcpy @see JCuda#cudaMemcpy2D @see JCuda#cudaMemcpyToArray @see JCuda#cudaMemcpy2DToArray @see JCuda#cudaMemcpy2DFromArray @see JCuda#cudaMemcpyArrayToArray @see JCuda#cudaMemcpy2DArrayToArray @see JCuda#cudaMemcpyToSymbol @see JCuda#cudaMemcpyFromSymbol @see JCuda#cudaMemcpyAsync @see JCuda#cudaMemcpy2DAsync @see JCuda#cudaMemcpyToArrayAsync @see JCuda#cudaMemcpy2DToArrayAsync @see JCuda#cudaMemcpyFromArrayAsync @see JCuda#cudaMemcpy2DFromArrayAsync @see JCuda#cudaMemcpyToSymbolAsync @see JCuda#cudaMemcpyFromSymbolAsync
[ "Copies", "data", "between", "host", "and", "device", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L4820-L4823
opsmatters/newrelic-api
src/main/java/com/opsmatters/newrelic/api/model/plugins/Component.java
Component.addMetric
public <T> void addMetric(String name, MetricTimeslice<T> timeslice) { metrics.put(name, timeslice); }
java
public <T> void addMetric(String name, MetricTimeslice<T> timeslice) { metrics.put(name, timeslice); }
[ "public", "<", "T", ">", "void", "addMetric", "(", "String", "name", ",", "MetricTimeslice", "<", "T", ">", "timeslice", ")", "{", "metrics", ".", "put", "(", "name", ",", "timeslice", ")", ";", "}" ]
Adds a metric to the set of metrics. @param <T> The type parameter used for the timeslice @param name The name of the metric @param timeslice The values representing the metric timeslice
[ "Adds", "a", "metric", "to", "the", "set", "of", "metrics", "." ]
train
https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/model/plugins/Component.java#L154-L157
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java
CSVParserBuilder.usingSeparatorWithNoQuotes
public CSVParserBuilder<T, K> usingSeparatorWithNoQuotes(char separator) { this.metadata = new CSVFileMetadata(separator, Optional.empty()); return this; }
java
public CSVParserBuilder<T, K> usingSeparatorWithNoQuotes(char separator) { this.metadata = new CSVFileMetadata(separator, Optional.empty()); return this; }
[ "public", "CSVParserBuilder", "<", "T", ",", "K", ">", "usingSeparatorWithNoQuotes", "(", "char", "separator", ")", "{", "this", ".", "metadata", "=", "new", "CSVFileMetadata", "(", "separator", ",", "Optional", ".", "empty", "(", ")", ")", ";", "return", ...
Use specified character as field separator. @param separator - field separator character @return this parser builder
[ "Use", "specified", "character", "as", "field", "separator", "." ]
train
https://github.com/titorenko/quick-csv-streamer/blob/cc11f6e9db6df4f3aac57ca72c4176501667f41d/src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java#L108-L111
redkale/redkale
src/org/redkale/net/http/HttpRequest.java
HttpRequest.getShortParameter
public short getShortParameter(int radix, String name, short defaultValue) { parseBody(); return params.getShortValue(radix, name, defaultValue); }
java
public short getShortParameter(int radix, String name, short defaultValue) { parseBody(); return params.getShortValue(radix, name, defaultValue); }
[ "public", "short", "getShortParameter", "(", "int", "radix", ",", "String", "name", ",", "short", "defaultValue", ")", "{", "parseBody", "(", ")", ";", "return", "params", ".", "getShortValue", "(", "radix", ",", "name", ",", "defaultValue", ")", ";", "}" ...
获取指定的参数short值, 没有返回默认short值 @param radix 进制数 @param name 参数名 @param defaultValue 默认short值 @return 参数值
[ "获取指定的参数short值", "没有返回默认short值" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpRequest.java#L1341-L1344
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/taglets/TagletManager.java
TagletManager.addNewSimpleCustomTag
public void addNewSimpleCustomTag(String tagName, String header, String locations) { if (tagName == null || locations == null) { return; } Taglet tag = customTags.get(tagName); locations = StringUtils.toLowerCase(locations); if (tag == null || header != null) { customTags.remove(tagName); customTags.put(tagName, new SimpleTaglet(tagName, header, locations)); if (locations != null && locations.indexOf('x') == -1) { checkTagName(tagName); } } else { //Move to back customTags.remove(tagName); customTags.put(tagName, tag); } }
java
public void addNewSimpleCustomTag(String tagName, String header, String locations) { if (tagName == null || locations == null) { return; } Taglet tag = customTags.get(tagName); locations = StringUtils.toLowerCase(locations); if (tag == null || header != null) { customTags.remove(tagName); customTags.put(tagName, new SimpleTaglet(tagName, header, locations)); if (locations != null && locations.indexOf('x') == -1) { checkTagName(tagName); } } else { //Move to back customTags.remove(tagName); customTags.put(tagName, tag); } }
[ "public", "void", "addNewSimpleCustomTag", "(", "String", "tagName", ",", "String", "header", ",", "String", "locations", ")", "{", "if", "(", "tagName", "==", "null", "||", "locations", "==", "null", ")", "{", "return", ";", "}", "Taglet", "tag", "=", "...
Add a new <code>SimpleTaglet</code>. If this tag already exists and the header passed as an argument is null, move tag to the back of the list. If this tag already exists and the header passed as an argument is not null, overwrite previous tag with new one. Otherwise, add new SimpleTaglet to list. @param tagName the name of this tag @param header the header to output. @param locations the possible locations that this tag can appear in.
[ "Add", "a", "new", "<code", ">", "SimpleTaglet<", "/", "code", ">", ".", "If", "this", "tag", "already", "exists", "and", "the", "header", "passed", "as", "an", "argument", "is", "null", "move", "tag", "to", "the", "back", "of", "the", "list", ".", "...
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/taglets/TagletManager.java#L352-L369
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getUntaggedImageCountAsync
public Observable<Integer> getUntaggedImageCountAsync(UUID projectId, GetUntaggedImageCountOptionalParameter getUntaggedImageCountOptionalParameter) { return getUntaggedImageCountWithServiceResponseAsync(projectId, getUntaggedImageCountOptionalParameter).map(new Func1<ServiceResponse<Integer>, Integer>() { @Override public Integer call(ServiceResponse<Integer> response) { return response.body(); } }); }
java
public Observable<Integer> getUntaggedImageCountAsync(UUID projectId, GetUntaggedImageCountOptionalParameter getUntaggedImageCountOptionalParameter) { return getUntaggedImageCountWithServiceResponseAsync(projectId, getUntaggedImageCountOptionalParameter).map(new Func1<ServiceResponse<Integer>, Integer>() { @Override public Integer call(ServiceResponse<Integer> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Integer", ">", "getUntaggedImageCountAsync", "(", "UUID", "projectId", ",", "GetUntaggedImageCountOptionalParameter", "getUntaggedImageCountOptionalParameter", ")", "{", "return", "getUntaggedImageCountWithServiceResponseAsync", "(", "projectId", ","...
Gets the number of untagged images. This API returns the images which have no tags for a given project and optionally an iteration. If no iteration is specified the current workspace is used. @param projectId The project id @param getUntaggedImageCountOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Integer object
[ "Gets", "the", "number", "of", "untagged", "images", ".", "This", "API", "returns", "the", "images", "which", "have", "no", "tags", "for", "a", "given", "project", "and", "optionally", "an", "iteration", ".", "If", "no", "iteration", "is", "specified", "th...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L4483-L4490
google/closure-templates
java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java
GenJsCodeVisitor.handleForeachLoop
private Statement handleForeachLoop( ForNonemptyNode node, Expression limit, Function<Expression, Expression> getDataItemFunction) { // Build some local variable names. String varName = node.getVarName(); String varPrefix = varName + node.getForNodeId(); // TODO(b/32224284): A more consistent pattern for local variable management. String loopIndexName = varPrefix + "Index"; String dataName = varPrefix + "Data"; Expression loopIndex = id(loopIndexName); VariableDeclaration data = VariableDeclaration.builder(dataName).setRhs(getDataItemFunction.apply(loopIndex)).build(); // Populate the local var translations with the translations from this node. templateTranslationContext .soyToJsVariableMappings() .put(varName, id(dataName)) .put(varName + "__isFirst", loopIndex.doubleEquals(number(0))) .put(varName + "__isLast", loopIndex.doubleEquals(limit.minus(number(1)))) .put(varName + "__index", loopIndex); // Generate the loop body. Statement foreachBody = Statement.of(data, visitChildrenReturningCodeChunk(node)); // Create the entire for block. return forLoop(loopIndexName, limit, foreachBody); }
java
private Statement handleForeachLoop( ForNonemptyNode node, Expression limit, Function<Expression, Expression> getDataItemFunction) { // Build some local variable names. String varName = node.getVarName(); String varPrefix = varName + node.getForNodeId(); // TODO(b/32224284): A more consistent pattern for local variable management. String loopIndexName = varPrefix + "Index"; String dataName = varPrefix + "Data"; Expression loopIndex = id(loopIndexName); VariableDeclaration data = VariableDeclaration.builder(dataName).setRhs(getDataItemFunction.apply(loopIndex)).build(); // Populate the local var translations with the translations from this node. templateTranslationContext .soyToJsVariableMappings() .put(varName, id(dataName)) .put(varName + "__isFirst", loopIndex.doubleEquals(number(0))) .put(varName + "__isLast", loopIndex.doubleEquals(limit.minus(number(1)))) .put(varName + "__index", loopIndex); // Generate the loop body. Statement foreachBody = Statement.of(data, visitChildrenReturningCodeChunk(node)); // Create the entire for block. return forLoop(loopIndexName, limit, foreachBody); }
[ "private", "Statement", "handleForeachLoop", "(", "ForNonemptyNode", "node", ",", "Expression", "limit", ",", "Function", "<", "Expression", ",", "Expression", ">", "getDataItemFunction", ")", "{", "// Build some local variable names.", "String", "varName", "=", "node",...
Example: <pre> {for $foo in $boo.foos} ... {/for} </pre> might generate <pre> for (var foo2Index = 0; foo2Index &lt; foo2ListLen; foo2Index++) { var foo2Data = foo2List[foo2Index]; ... } </pre>
[ "Example", ":" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L1249-L1278
ag-gipp/MathMLTools
mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java
MathMLConverter.verifyMathML
String verifyMathML(String canMathML) throws MathConverterException { try { Document tempDoc = XMLHelper.string2Doc(canMathML, true); Content content = scanFormulaNode((Element) tempDoc.getFirstChild()); //verify the formula if (content == Content.mathml) { return canMathML; } else { throw new MathConverterException("could not verify produced mathml, content was: " + content.name()); } } catch (Exception e) { logger.error("could not verify mathml", e); throw new MathConverterException("could not verify mathml"); } }
java
String verifyMathML(String canMathML) throws MathConverterException { try { Document tempDoc = XMLHelper.string2Doc(canMathML, true); Content content = scanFormulaNode((Element) tempDoc.getFirstChild()); //verify the formula if (content == Content.mathml) { return canMathML; } else { throw new MathConverterException("could not verify produced mathml, content was: " + content.name()); } } catch (Exception e) { logger.error("could not verify mathml", e); throw new MathConverterException("could not verify mathml"); } }
[ "String", "verifyMathML", "(", "String", "canMathML", ")", "throws", "MathConverterException", "{", "try", "{", "Document", "tempDoc", "=", "XMLHelper", ".", "string2Doc", "(", "canMathML", ",", "true", ")", ";", "Content", "content", "=", "scanFormulaNode", "("...
Just a quick scan over. @param canMathML final mathml to be inspected @return returns input string @throws MathConverterException if it is not a well-structured mathml
[ "Just", "a", "quick", "scan", "over", "." ]
train
https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/MathMLConverter.java#L125-L139
gondor/kbop
src/main/java/org/pacesys/kbop/internal/AbstractKeyedObjectPool.java
AbstractKeyedObjectPool.getBlockingUntilAvailableOrTimeout
E getBlockingUntilAvailableOrTimeout(final PoolKey<K> key, final long timeout, final TimeUnit unit, final PoolWaitFuture<E> future) throws InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date(System.currentTimeMillis() + unit.toMillis(timeout)); } lock.lock(); try { E entry = null; for(;;) { validateShutdown(); entry = createOrAttemptToBorrow(key); if (entry != null) return entry.flagOwner(); if (!await(future, key, deadline) && deadline != null && deadline.getTime() <= System.currentTimeMillis()) break; } throw new TimeoutException("Timeout waiting for Pool for Key: " + key); } finally { lock.unlock(); } }
java
E getBlockingUntilAvailableOrTimeout(final PoolKey<K> key, final long timeout, final TimeUnit unit, final PoolWaitFuture<E> future) throws InterruptedException, TimeoutException { Date deadline = null; if (timeout > 0) { deadline = new Date(System.currentTimeMillis() + unit.toMillis(timeout)); } lock.lock(); try { E entry = null; for(;;) { validateShutdown(); entry = createOrAttemptToBorrow(key); if (entry != null) return entry.flagOwner(); if (!await(future, key, deadline) && deadline != null && deadline.getTime() <= System.currentTimeMillis()) break; } throw new TimeoutException("Timeout waiting for Pool for Key: " + key); } finally { lock.unlock(); } }
[ "E", "getBlockingUntilAvailableOrTimeout", "(", "final", "PoolKey", "<", "K", ">", "key", ",", "final", "long", "timeout", ",", "final", "TimeUnit", "unit", ",", "final", "PoolWaitFuture", "<", "E", ">", "future", ")", "throws", "InterruptedException", ",", "T...
Internal: Blocks until the object to be borrowed based on the key is available or until the max timeout specified has lapsed. @param key the Pool Key used to lookup the Object to borrow @param timeout the maximum time to wait @param unit the time unit of the timeout argument @param future the current future waiting on the object to become available @return the Object which was successfully borrowed. @throws InterruptedException if the thread was interrupted @throws IllegalStateException if the pool has been shutdown @throws TimeoutException if the wait timed out
[ "Internal", ":", "Blocks", "until", "the", "object", "to", "be", "borrowed", "based", "on", "the", "key", "is", "available", "or", "until", "the", "max", "timeout", "specified", "has", "lapsed", "." ]
train
https://github.com/gondor/kbop/blob/a176fd845f1e146610f03a1cb3cb0d661ebf4faa/src/main/java/org/pacesys/kbop/internal/AbstractKeyedObjectPool.java#L146-L172
geomajas/geomajas-project-client-gwt
common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/service/ClientConfigurationService.java
ClientConfigurationService.addCallback
private static boolean addCallback(String applicationId, DelayedCallback callback) { boolean isFirst = false; List<DelayedCallback> list = BACKLOG.get(applicationId); if (null == list) { list = new ArrayList<DelayedCallback>(); BACKLOG.put(applicationId, list); isFirst = true; } list.add(callback); return isFirst; }
java
private static boolean addCallback(String applicationId, DelayedCallback callback) { boolean isFirst = false; List<DelayedCallback> list = BACKLOG.get(applicationId); if (null == list) { list = new ArrayList<DelayedCallback>(); BACKLOG.put(applicationId, list); isFirst = true; } list.add(callback); return isFirst; }
[ "private", "static", "boolean", "addCallback", "(", "String", "applicationId", ",", "DelayedCallback", "callback", ")", "{", "boolean", "isFirst", "=", "false", ";", "List", "<", "DelayedCallback", ">", "list", "=", "BACKLOG", ".", "get", "(", "applicationId", ...
Add a delayed callback for the given application id. Returns whether this is the first request for the application id. @param applicationId application id @param callback callback @return true when first request for that application id
[ "Add", "a", "delayed", "callback", "for", "the", "given", "application", "id", ".", "Returns", "whether", "this", "is", "the", "first", "request", "for", "the", "application", "id", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/service/ClientConfigurationService.java#L107-L117
OpenLiberty/open-liberty
dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java
ThreadPoolController.getThroughputDistribution
ThroughputDistribution getThroughputDistribution(int activeThreads, boolean create) { if (activeThreads < coreThreads) activeThreads = coreThreads; Integer threads = Integer.valueOf(activeThreads); ThroughputDistribution throughput = threadStats.get(threads); if ((throughput == null) && create) { throughput = new ThroughputDistribution(); throughput.setLastUpdate(controllerCycle); threadStats.put(threads, throughput); } return throughput; }
java
ThroughputDistribution getThroughputDistribution(int activeThreads, boolean create) { if (activeThreads < coreThreads) activeThreads = coreThreads; Integer threads = Integer.valueOf(activeThreads); ThroughputDistribution throughput = threadStats.get(threads); if ((throughput == null) && create) { throughput = new ThroughputDistribution(); throughput.setLastUpdate(controllerCycle); threadStats.put(threads, throughput); } return throughput; }
[ "ThroughputDistribution", "getThroughputDistribution", "(", "int", "activeThreads", ",", "boolean", "create", ")", "{", "if", "(", "activeThreads", "<", "coreThreads", ")", "activeThreads", "=", "coreThreads", ";", "Integer", "threads", "=", "Integer", ".", "valueOf...
Get the throughput distribution data associated with the specified number of active threads. @param activeThreads the number of active threads when the data was collected @param create whether to create and return a new throughput distribution if none currently exists @return the data representing the throughput distribution for the specified number of active threads
[ "Get", "the", "throughput", "distribution", "data", "associated", "with", "the", "specified", "number", "of", "active", "threads", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java#L752-L763
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ReferrerURLCookieHandler.java
ReferrerURLCookieHandler.invalidateCookie
public void invalidateCookie(HttpServletRequest req, HttpServletResponse res, String cookieName, boolean enableHttpOnly) { Cookie c = new Cookie(cookieName, ""); if (cookieName.equals("WASReqURL")) { c.setPath(getPathName(req)); } else { c.setPath("/"); } c.setMaxAge(0); if (enableHttpOnly && webAppSecConfig.getHttpOnlyCookies()) { c.setHttpOnly(true); } if (webAppSecConfig.getSSORequiresSSL()) { c.setSecure(true); } res.addCookie(c); }
java
public void invalidateCookie(HttpServletRequest req, HttpServletResponse res, String cookieName, boolean enableHttpOnly) { Cookie c = new Cookie(cookieName, ""); if (cookieName.equals("WASReqURL")) { c.setPath(getPathName(req)); } else { c.setPath("/"); } c.setMaxAge(0); if (enableHttpOnly && webAppSecConfig.getHttpOnlyCookies()) { c.setHttpOnly(true); } if (webAppSecConfig.getSSORequiresSSL()) { c.setSecure(true); } res.addCookie(c); }
[ "public", "void", "invalidateCookie", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ",", "String", "cookieName", ",", "boolean", "enableHttpOnly", ")", "{", "Cookie", "c", "=", "new", "Cookie", "(", "cookieName", ",", "\"\"", ")", ";", "...
Invalidate (clear) the referrer URL cookie in the HttpServletResponse. Setting age to 0 invalidates it. @param res
[ "Invalidate", "(", "clear", ")", "the", "referrer", "URL", "cookie", "in", "the", "HttpServletResponse", ".", "Setting", "age", "to", "0", "invalidates", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ReferrerURLCookieHandler.java#L130-L145
lessthanoptimal/ejml
main/ejml-ddense/generate/org/ejml/dense/row/misc/GenerateInverseFromMinor.java
GenerateInverseFromMinor.printMinors
public void printMinors(int matrix[], int N, PrintStream stream) { this.N = N; this.stream = stream; // compute all the minors int index = 0; for( int i = 1; i <= N; i++ ) { for( int j = 1; j <= N; j++ , index++) { stream.print(" double m"+i+""+j+" = "); if( (i+j) % 2 == 1 ) stream.print("-( "); printTopMinor(matrix,i-1,j-1,N); if( (i+j) % 2 == 1 ) stream.print(")"); stream.print(";\n"); } } stream.println(); // compute the determinant stream.print(" double det = (a11*m11"); for( int i = 2; i <= N; i++ ) { stream.print(" + "+a(i-1)+"*m"+1+""+i); } stream.println(")/scale;"); }
java
public void printMinors(int matrix[], int N, PrintStream stream) { this.N = N; this.stream = stream; // compute all the minors int index = 0; for( int i = 1; i <= N; i++ ) { for( int j = 1; j <= N; j++ , index++) { stream.print(" double m"+i+""+j+" = "); if( (i+j) % 2 == 1 ) stream.print("-( "); printTopMinor(matrix,i-1,j-1,N); if( (i+j) % 2 == 1 ) stream.print(")"); stream.print(";\n"); } } stream.println(); // compute the determinant stream.print(" double det = (a11*m11"); for( int i = 2; i <= N; i++ ) { stream.print(" + "+a(i-1)+"*m"+1+""+i); } stream.println(")/scale;"); }
[ "public", "void", "printMinors", "(", "int", "matrix", "[", "]", ",", "int", "N", ",", "PrintStream", "stream", ")", "{", "this", ".", "N", "=", "N", ";", "this", ".", "stream", "=", "stream", ";", "// compute all the minors", "int", "index", "=", "0",...
Put the core auto-code algorithm here so an external class can call it
[ "Put", "the", "core", "auto", "-", "code", "algorithm", "here", "so", "an", "external", "class", "can", "call", "it" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/generate/org/ejml/dense/row/misc/GenerateInverseFromMinor.java#L147-L173
FasterXML/woodstox
src/main/java/com/ctc/wstx/sr/StreamScanner.java
StreamScanner.throwParseError
@Override public void throwParseError(String format, Object arg, Object arg2) throws XMLStreamException { String msg = (arg != null || arg2 != null) ? MessageFormat.format(format, new Object[] { arg, arg2 }) : format; throw constructWfcException(msg); }
java
@Override public void throwParseError(String format, Object arg, Object arg2) throws XMLStreamException { String msg = (arg != null || arg2 != null) ? MessageFormat.format(format, new Object[] { arg, arg2 }) : format; throw constructWfcException(msg); }
[ "@", "Override", "public", "void", "throwParseError", "(", "String", "format", ",", "Object", "arg", ",", "Object", "arg2", ")", "throws", "XMLStreamException", "{", "String", "msg", "=", "(", "arg", "!=", "null", "||", "arg2", "!=", "null", ")", "?", "M...
Throws generic parse error with specified message and current parsing location. <p> Note: public access only because core code in other packages needs to access it.
[ "Throws", "generic", "parse", "error", "with", "specified", "message", "and", "current", "parsing", "location", ".", "<p", ">", "Note", ":", "public", "access", "only", "because", "core", "code", "in", "other", "packages", "needs", "to", "access", "it", "." ...
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/StreamScanner.java#L498-L505
pravega/pravega
bindings/src/main/java/io/pravega/storage/hdfs/HDFSExceptionHelpers.java
HDFSExceptionHelpers.convertException
static <T> StreamSegmentException convertException(String segmentName, Throwable e) { if (e instanceof RemoteException) { e = ((RemoteException) e).unwrapRemoteException(); } if (e instanceof PathNotFoundException || e instanceof FileNotFoundException) { return new StreamSegmentNotExistsException(segmentName, e); } else if (e instanceof FileAlreadyExistsException || e instanceof AlreadyBeingCreatedException) { return new StreamSegmentExistsException(segmentName, e); } else if (e instanceof AclException) { return new StreamSegmentSealedException(segmentName, e); } else { throw Exceptions.sneakyThrow(e); } }
java
static <T> StreamSegmentException convertException(String segmentName, Throwable e) { if (e instanceof RemoteException) { e = ((RemoteException) e).unwrapRemoteException(); } if (e instanceof PathNotFoundException || e instanceof FileNotFoundException) { return new StreamSegmentNotExistsException(segmentName, e); } else if (e instanceof FileAlreadyExistsException || e instanceof AlreadyBeingCreatedException) { return new StreamSegmentExistsException(segmentName, e); } else if (e instanceof AclException) { return new StreamSegmentSealedException(segmentName, e); } else { throw Exceptions.sneakyThrow(e); } }
[ "static", "<", "T", ">", "StreamSegmentException", "convertException", "(", "String", "segmentName", ",", "Throwable", "e", ")", "{", "if", "(", "e", "instanceof", "RemoteException", ")", "{", "e", "=", "(", "(", "RemoteException", ")", "e", ")", ".", "unw...
Translates HDFS specific Exceptions to Pravega-equivalent Exceptions. @param segmentName Name of the stream segment on which the exception occurs. @param e The exception to be translated. @return The exception to be thrown.
[ "Translates", "HDFS", "specific", "Exceptions", "to", "Pravega", "-", "equivalent", "Exceptions", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/bindings/src/main/java/io/pravega/storage/hdfs/HDFSExceptionHelpers.java#L36-L50
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java
JsonRpcClient.internalWriteRequest
private void internalWriteRequest(String methodName, Object arguments, OutputStream output, String id) throws IOException { final ObjectNode request = internalCreateRequest(methodName, arguments, id); logger.debug("Request {}", request); writeAndFlushValue(output, request); }
java
private void internalWriteRequest(String methodName, Object arguments, OutputStream output, String id) throws IOException { final ObjectNode request = internalCreateRequest(methodName, arguments, id); logger.debug("Request {}", request); writeAndFlushValue(output, request); }
[ "private", "void", "internalWriteRequest", "(", "String", "methodName", ",", "Object", "arguments", ",", "OutputStream", "output", ",", "String", "id", ")", "throws", "IOException", "{", "final", "ObjectNode", "request", "=", "internalCreateRequest", "(", "methodNam...
Writes a request. @param methodName the method name @param arguments the arguments @param output the stream @param id the optional id @throws IOException on error
[ "Writes", "a", "request", "." ]
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L304-L308
apache/flink
flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java
InstantiationUtil.resolveClassByName
public static <T> Class<T> resolveClassByName( DataInputView in, ClassLoader cl) throws IOException { return resolveClassByName(in, cl, Object.class); }
java
public static <T> Class<T> resolveClassByName( DataInputView in, ClassLoader cl) throws IOException { return resolveClassByName(in, cl, Object.class); }
[ "public", "static", "<", "T", ">", "Class", "<", "T", ">", "resolveClassByName", "(", "DataInputView", "in", ",", "ClassLoader", "cl", ")", "throws", "IOException", "{", "return", "resolveClassByName", "(", "in", ",", "cl", ",", "Object", ".", "class", ")"...
Loads a class by name from the given input stream and reflectively instantiates it. <p>This method will use {@link DataInputView#readUTF()} to read the class name, and then attempt to load the class from the given ClassLoader. @param in The stream to read the class name from. @param cl The class loader to resolve the class. @throws IOException Thrown, if the class name could not be read, the class could not be found.
[ "Loads", "a", "class", "by", "name", "from", "the", "given", "input", "stream", "and", "reflectively", "instantiates", "it", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java#L678-L682
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemgroup_binding.java
systemgroup_binding.get
public static systemgroup_binding get(nitro_service service, String groupname) throws Exception{ systemgroup_binding obj = new systemgroup_binding(); obj.set_groupname(groupname); systemgroup_binding response = (systemgroup_binding) obj.get_resource(service); return response; }
java
public static systemgroup_binding get(nitro_service service, String groupname) throws Exception{ systemgroup_binding obj = new systemgroup_binding(); obj.set_groupname(groupname); systemgroup_binding response = (systemgroup_binding) obj.get_resource(service); return response; }
[ "public", "static", "systemgroup_binding", "get", "(", "nitro_service", "service", ",", "String", "groupname", ")", "throws", "Exception", "{", "systemgroup_binding", "obj", "=", "new", "systemgroup_binding", "(", ")", ";", "obj", ".", "set_groupname", "(", "group...
Use this API to fetch systemgroup_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "systemgroup_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/system/systemgroup_binding.java#L114-L119
JOML-CI/JOML
src/org/joml/Matrix3x2f.java
Matrix3x2f.shearY
public Matrix3x2f shearY(float xFactor, Matrix3x2f dest) { float nm00 = m00 + m10 * xFactor; float nm01 = m01 + m11 * xFactor; dest.m00 = nm00; dest.m01 = nm01; dest.m10 = m10; dest.m11 = m11; dest.m20 = m20; dest.m21 = m21; return dest; }
java
public Matrix3x2f shearY(float xFactor, Matrix3x2f dest) { float nm00 = m00 + m10 * xFactor; float nm01 = m01 + m11 * xFactor; dest.m00 = nm00; dest.m01 = nm01; dest.m10 = m10; dest.m11 = m11; dest.m20 = m20; dest.m21 = m21; return dest; }
[ "public", "Matrix3x2f", "shearY", "(", "float", "xFactor", ",", "Matrix3x2f", "dest", ")", "{", "float", "nm00", "=", "m00", "+", "m10", "*", "xFactor", ";", "float", "nm01", "=", "m01", "+", "m11", "*", "xFactor", ";", "dest", ".", "m00", "=", "nm00...
Apply shearing to this matrix by shearing along the Y axis using the X axis factor <code>xFactor</code>, and store the result in <code>dest</code>. @param xFactor the factor for the X component to shear along the Y axis @param dest will hold the result @return dest
[ "Apply", "shearing", "to", "this", "matrix", "by", "shearing", "along", "the", "Y", "axis", "using", "the", "X", "axis", "factor", "<code", ">", "xFactor<", "/", "code", ">", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L2365-L2375
lucee/Lucee
core/src/main/java/lucee/runtime/schedule/SchedulerImpl.java
SchedulerImpl.readInTask
private ScheduleTaskImpl readInTask(Element el) throws PageException { long timeout = su.toLong(el, "timeout"); if (timeout > 0 && timeout < 1000) timeout *= 1000; if (timeout < 0) timeout = 600000; try { ScheduleTaskImpl st = new ScheduleTaskImpl(this, su.toString(el, "name").trim(), su.toResource(config, el, "file"), su.toDate(config, el, "startDate"), su.toTime(config, el, "startTime"), su.toDate(config, el, "endDate"), su.toTime(config, el, "endTime"), su.toString(el, "url"), su.toInt(el, "port", -1), su.toString(el, "interval"), timeout, su.toCredentials(el, "username", "password"), ProxyDataImpl.getInstance(su.toString(el, "proxyHost"), su.toInt(el, "proxyPort", 80), su.toString(el, "proxyUser"), su.toString(el, "proxyPassword")), su.toBoolean(el, "resolveUrl"), su.toBoolean(el, "publish"), su.toBoolean(el, "hidden", false), su.toBoolean(el, "readonly", false), su.toBoolean(el, "paused", false), su.toBoolean(el, "autoDelete", false)); return st; } catch (Exception e) { SystemOut.printDate(e); throw Caster.toPageException(e); } }
java
private ScheduleTaskImpl readInTask(Element el) throws PageException { long timeout = su.toLong(el, "timeout"); if (timeout > 0 && timeout < 1000) timeout *= 1000; if (timeout < 0) timeout = 600000; try { ScheduleTaskImpl st = new ScheduleTaskImpl(this, su.toString(el, "name").trim(), su.toResource(config, el, "file"), su.toDate(config, el, "startDate"), su.toTime(config, el, "startTime"), su.toDate(config, el, "endDate"), su.toTime(config, el, "endTime"), su.toString(el, "url"), su.toInt(el, "port", -1), su.toString(el, "interval"), timeout, su.toCredentials(el, "username", "password"), ProxyDataImpl.getInstance(su.toString(el, "proxyHost"), su.toInt(el, "proxyPort", 80), su.toString(el, "proxyUser"), su.toString(el, "proxyPassword")), su.toBoolean(el, "resolveUrl"), su.toBoolean(el, "publish"), su.toBoolean(el, "hidden", false), su.toBoolean(el, "readonly", false), su.toBoolean(el, "paused", false), su.toBoolean(el, "autoDelete", false)); return st; } catch (Exception e) { SystemOut.printDate(e); throw Caster.toPageException(e); } }
[ "private", "ScheduleTaskImpl", "readInTask", "(", "Element", "el", ")", "throws", "PageException", "{", "long", "timeout", "=", "su", ".", "toLong", "(", "el", ",", "\"timeout\"", ")", ";", "if", "(", "timeout", ">", "0", "&&", "timeout", "<", "1000", ")...
read in a single task element @param el @return matching task to Element @throws PageException
[ "read", "in", "a", "single", "task", "element" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/SchedulerImpl.java#L184-L201
mikepenz/FastAdapter
library-extensions-expandable/src/main/java/com/mikepenz/fastadapter/expandable/ExpandableExtension.java
ExpandableExtension.notifyAdapterSubItemsChanged
public int notifyAdapterSubItemsChanged(int position, int previousCount) { Item item = mFastAdapter.getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; IAdapter adapter = mFastAdapter.getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, previousCount); ((IItemAdapter) adapter).add(position + 1, expandable.getSubItems()); } return expandable.getSubItems().size(); } return 0; }
java
public int notifyAdapterSubItemsChanged(int position, int previousCount) { Item item = mFastAdapter.getItem(position); if (item != null && item instanceof IExpandable) { IExpandable expandable = (IExpandable) item; IAdapter adapter = mFastAdapter.getAdapter(position); if (adapter != null && adapter instanceof IItemAdapter) { ((IItemAdapter) adapter).removeRange(position + 1, previousCount); ((IItemAdapter) adapter).add(position + 1, expandable.getSubItems()); } return expandable.getSubItems().size(); } return 0; }
[ "public", "int", "notifyAdapterSubItemsChanged", "(", "int", "position", ",", "int", "previousCount", ")", "{", "Item", "item", "=", "mFastAdapter", ".", "getItem", "(", "position", ")", ";", "if", "(", "item", "!=", "null", "&&", "item", "instanceof", "IExp...
notifies the fastAdapter about new / removed items within a sub hierarchy NOTE this currently only works for sub items with only 1 level @param position the global position of the parent item @param previousCount the previous count of sub items @return the new count of subItems
[ "notifies", "the", "fastAdapter", "about", "new", "/", "removed", "items", "within", "a", "sub", "hierarchy", "NOTE", "this", "currently", "only", "works", "for", "sub", "items", "with", "only", "1", "level" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions-expandable/src/main/java/com/mikepenz/fastadapter/expandable/ExpandableExtension.java#L182-L194
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistry.java
ConfigurationPropertyRegistry.addInstance
void addInstance(final Class<?> discoveredType, final Object newlyConstructed) { WeakHashMap<Object, Void> map; synchronized (instances) { map = instances.get(discoveredType); if (map == null) { map = new WeakHashMap<>(); instances.put(discoveredType, map); } } synchronized (map) { map.put(newlyConstructed, null); } }
java
void addInstance(final Class<?> discoveredType, final Object newlyConstructed) { WeakHashMap<Object, Void> map; synchronized (instances) { map = instances.get(discoveredType); if (map == null) { map = new WeakHashMap<>(); instances.put(discoveredType, map); } } synchronized (map) { map.put(newlyConstructed, null); } }
[ "void", "addInstance", "(", "final", "Class", "<", "?", ">", "discoveredType", ",", "final", "Object", "newlyConstructed", ")", "{", "WeakHashMap", "<", "Object", ",", "Void", ">", "map", ";", "synchronized", "(", "instances", ")", "{", "map", "=", "instan...
Register an instance of a property-consuming type; the registry will use a weak reference to hold on to this instance, so that it can be discarded if it has a short lifespan @param discoveredType @param newlyConstructed
[ "Register", "an", "instance", "of", "a", "property", "-", "consuming", "type", ";", "the", "registry", "will", "use", "a", "weak", "reference", "to", "hold", "on", "to", "this", "instance", "so", "that", "it", "can", "be", "discarded", "if", "it", "has",...
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistry.java#L112-L131
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_database_databaseName_extension_extensionName_GET
public OvhDatabaseExtension serviceName_database_databaseName_extension_extensionName_GET(String serviceName, String databaseName, String extensionName) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/database/{databaseName}/extension/{extensionName}"; StringBuilder sb = path(qPath, serviceName, databaseName, extensionName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDatabaseExtension.class); }
java
public OvhDatabaseExtension serviceName_database_databaseName_extension_extensionName_GET(String serviceName, String databaseName, String extensionName) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/database/{databaseName}/extension/{extensionName}"; StringBuilder sb = path(qPath, serviceName, databaseName, extensionName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDatabaseExtension.class); }
[ "public", "OvhDatabaseExtension", "serviceName_database_databaseName_extension_extensionName_GET", "(", "String", "serviceName", ",", "String", "databaseName", ",", "String", "extensionName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/privateDatabase...
Get this object properties REST: GET /hosting/privateDatabase/{serviceName}/database/{databaseName}/extension/{extensionName} @param serviceName [required] The internal name of your private database @param databaseName [required] Database name @param extensionName [required] Extension name
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L430-L435
tvesalainen/util
vfs/src/main/java/org/vesalainen/vfs/VirtualFileChannel.java
VirtualFileChannel.tryLock
@Override public FileLock tryLock(long position, long size, boolean shared) throws IOException { return new FileLockImpl(this, position, size, shared); }
java
@Override public FileLock tryLock(long position, long size, boolean shared) throws IOException { return new FileLockImpl(this, position, size, shared); }
[ "@", "Override", "public", "FileLock", "tryLock", "(", "long", "position", ",", "long", "size", ",", "boolean", "shared", ")", "throws", "IOException", "{", "return", "new", "FileLockImpl", "(", "this", ",", "position", ",", "size", ",", "shared", ")", ";"...
Returns always a lock. Locking virtual file makes no sense. Dummy implementation is provided so that existing applications don't throw exception. @param position @param size @param shared @return @throws IOException
[ "Returns", "always", "a", "lock", ".", "Locking", "virtual", "file", "makes", "no", "sense", ".", "Dummy", "implementation", "is", "provided", "so", "that", "existing", "applications", "don", "t", "throw", "exception", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/vfs/src/main/java/org/vesalainen/vfs/VirtualFileChannel.java#L399-L403
apache/groovy
src/main/java/org/codehaus/groovy/transform/trait/Traits.java
Traits.collectSelfTypes
public static LinkedHashSet<ClassNode> collectSelfTypes( ClassNode receiver, LinkedHashSet<ClassNode> selfTypes) { return collectSelfTypes(receiver, selfTypes, true, true); }
java
public static LinkedHashSet<ClassNode> collectSelfTypes( ClassNode receiver, LinkedHashSet<ClassNode> selfTypes) { return collectSelfTypes(receiver, selfTypes, true, true); }
[ "public", "static", "LinkedHashSet", "<", "ClassNode", ">", "collectSelfTypes", "(", "ClassNode", "receiver", ",", "LinkedHashSet", "<", "ClassNode", ">", "selfTypes", ")", "{", "return", "collectSelfTypes", "(", "receiver", ",", "selfTypes", ",", "true", ",", "...
Collects all the self types that a type should extend or implement, given the traits is implements. Collects from interfaces and superclasses too. @param receiver a class node that may implement a trait @param selfTypes a collection where the list of self types will be written @return the selfTypes collection itself @since 2.4.0
[ "Collects", "all", "the", "self", "types", "that", "a", "type", "should", "extend", "or", "implement", "given", "the", "traits", "is", "implements", ".", "Collects", "from", "interfaces", "and", "superclasses", "too", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/trait/Traits.java#L308-L312
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/APIClient.java
APIClient.generateSecuredApiKey
@Deprecated public String generateSecuredApiKey(String privateApiKey, String tagFilters) throws NoSuchAlgorithmException, InvalidKeyException { if (!tagFilters.contains("=")) return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), null); else { return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8"))); } }
java
@Deprecated public String generateSecuredApiKey(String privateApiKey, String tagFilters) throws NoSuchAlgorithmException, InvalidKeyException { if (!tagFilters.contains("=")) return generateSecuredApiKey(privateApiKey, new Query().setTagFilters(tagFilters), null); else { return Base64.encodeBase64String(String.format("%s%s", hmac(privateApiKey, tagFilters), tagFilters).getBytes(Charset.forName("UTF8"))); } }
[ "@", "Deprecated", "public", "String", "generateSecuredApiKey", "(", "String", "privateApiKey", ",", "String", "tagFilters", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeyException", "{", "if", "(", "!", "tagFilters", ".", "contains", "(", "\"=\"", ")",...
Generate a secured and public API Key from a list of tagFilters and an optional user token identifying the current user @param privateApiKey your private API Key @param tagFilters the list of tags applied to the query (used as security) @deprecated Use `generateSecuredApiKey(String privateApiKey, Query query)` version
[ "Generate", "a", "secured", "and", "public", "API", "Key", "from", "a", "list", "of", "tagFilters", "and", "an", "optional", "user", "token", "identifying", "the", "current", "user" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/APIClient.java#L977-L984
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java
ChatRoomClient.getChatRoomMembers
public ChatRoomMemberList getChatRoomMembers(long roomId, int start, int count) throws APIConnectionException, APIRequestException { Preconditions.checkArgument(roomId > 0, "room id is invalid"); Preconditions.checkArgument(start >= 0 && count > 0, "Illegal argument"); ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + mChatRoomPath + "/" + roomId + "/members" + "?start=" + start + "&count=" + count); return ChatRoomMemberList.fromResponse(responseWrapper, ChatRoomMemberList.class); }
java
public ChatRoomMemberList getChatRoomMembers(long roomId, int start, int count) throws APIConnectionException, APIRequestException { Preconditions.checkArgument(roomId > 0, "room id is invalid"); Preconditions.checkArgument(start >= 0 && count > 0, "Illegal argument"); ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + mChatRoomPath + "/" + roomId + "/members" + "?start=" + start + "&count=" + count); return ChatRoomMemberList.fromResponse(responseWrapper, ChatRoomMemberList.class); }
[ "public", "ChatRoomMemberList", "getChatRoomMembers", "(", "long", "roomId", ",", "int", "start", ",", "int", "count", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "Preconditions", ".", "checkArgument", "(", "roomId", ">", "0", ",", "\...
Get all member info of chat room @param roomId chat room id @param start start index @param count member count @return {@link ChatRoomMemberList} @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "all", "member", "info", "of", "chat", "room" ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/chatroom/ChatRoomClient.java#L172-L179
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java
Evaluation.fBeta
public double fBeta(double beta, int classLabel, double defaultValue) { double precision = precision(classLabel, -1); double recall = recall(classLabel, -1); if (precision == -1 || recall == -1) { return defaultValue; } return EvaluationUtils.fBeta(beta, precision, recall); }
java
public double fBeta(double beta, int classLabel, double defaultValue) { double precision = precision(classLabel, -1); double recall = recall(classLabel, -1); if (precision == -1 || recall == -1) { return defaultValue; } return EvaluationUtils.fBeta(beta, precision, recall); }
[ "public", "double", "fBeta", "(", "double", "beta", ",", "int", "classLabel", ",", "double", "defaultValue", ")", "{", "double", "precision", "=", "precision", "(", "classLabel", ",", "-", "1", ")", ";", "double", "recall", "=", "recall", "(", "classLabel"...
Calculate the f_beta for a given class, where f_beta is defined as:<br> (1+beta^2) * (precision * recall) / (beta^2 * precision + recall).<br> F1 is a special case of f_beta, with beta=1.0 @param beta Beta value to use @param classLabel Class label @param defaultValue Default value to use when precision or recall is undefined (0/0 for prec. or recall) @return F_beta
[ "Calculate", "the", "f_beta", "for", "a", "given", "class", "where", "f_beta", "is", "defined", "as", ":", "<br", ">", "(", "1", "+", "beta^2", ")", "*", "(", "precision", "*", "recall", ")", "/", "(", "beta^2", "*", "precision", "+", "recall", ")", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/classification/Evaluation.java#L1225-L1232
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDisplayLayoutPersistenceImpl.java
CPDisplayLayoutPersistenceImpl.findByUUID_G
@Override public CPDisplayLayout findByUUID_G(String uuid, long groupId) throws NoSuchCPDisplayLayoutException { CPDisplayLayout cpDisplayLayout = fetchByUUID_G(uuid, groupId); if (cpDisplayLayout == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDisplayLayoutException(msg.toString()); } return cpDisplayLayout; }
java
@Override public CPDisplayLayout findByUUID_G(String uuid, long groupId) throws NoSuchCPDisplayLayoutException { CPDisplayLayout cpDisplayLayout = fetchByUUID_G(uuid, groupId); if (cpDisplayLayout == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDisplayLayoutException(msg.toString()); } return cpDisplayLayout; }
[ "@", "Override", "public", "CPDisplayLayout", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPDisplayLayoutException", "{", "CPDisplayLayout", "cpDisplayLayout", "=", "fetchByUUID_G", "(", "uuid", ",", "groupId", ")", ";", "if"...
Returns the cp display layout where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchCPDisplayLayoutException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching cp display layout @throws NoSuchCPDisplayLayoutException if a matching cp display layout could not be found
[ "Returns", "the", "cp", "display", "layout", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPDisplayLayoutException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDisplayLayoutPersistenceImpl.java#L665-L691
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.getDate
@Override public Date getDate(int parameterIndex, Calendar cal) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
@Override public Date getDate(int parameterIndex, Calendar cal) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "Date", "getDate", "(", "int", "parameterIndex", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Retrieves the value of the designated JDBC DATE parameter as a java.sql.Date object, using the given Calendar object to construct the date.
[ "Retrieves", "the", "value", "of", "the", "designated", "JDBC", "DATE", "parameter", "as", "a", "java", ".", "sql", ".", "Date", "object", "using", "the", "given", "Calendar", "object", "to", "construct", "the", "date", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L191-L196
atomix/atomix
cluster/src/main/java/io/atomix/cluster/MulticastConfig.java
MulticastConfig.setGroup
public MulticastConfig setGroup(String group) { try { InetAddress address = InetAddress.getByName(group); if (!address.isMulticastAddress()) { throw new ConfigurationException("Invalid multicast group " + group); } return setGroup(address); } catch (UnknownHostException e) { throw new ConfigurationException("Failed to locate multicast group", e); } }
java
public MulticastConfig setGroup(String group) { try { InetAddress address = InetAddress.getByName(group); if (!address.isMulticastAddress()) { throw new ConfigurationException("Invalid multicast group " + group); } return setGroup(address); } catch (UnknownHostException e) { throw new ConfigurationException("Failed to locate multicast group", e); } }
[ "public", "MulticastConfig", "setGroup", "(", "String", "group", ")", "{", "try", "{", "InetAddress", "address", "=", "InetAddress", ".", "getByName", "(", "group", ")", ";", "if", "(", "!", "address", ".", "isMulticastAddress", "(", ")", ")", "{", "throw"...
Sets the multicast group. @param group the multicast group @return the multicast configuration @throws ConfigurationException if the group is invalid
[ "Sets", "the", "multicast", "group", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/MulticastConfig.java#L81-L91
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.errorsHomographySymm
public static void errorsHomographySymm(List<AssociatedPair> observations , DMatrixRMaj H , @Nullable DMatrixRMaj H_inv , GrowQueue_F64 storage ) { storage.reset(); if( H_inv == null ) H_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(H,H_inv); Point3D_F64 tmp = new Point3D_F64(); for (int i = 0; i < observations.size(); i++) { AssociatedPair p = observations.get(i); double dx,dy; double error = 0; GeometryMath_F64.mult(H,p.p1,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p2.x - tmp.x/tmp.z; dy = p.p2.y - tmp.y/tmp.z; error += dx*dx + dy*dy; GeometryMath_F64.mult(H_inv,p.p2,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p1.x - tmp.x/tmp.z; dy = p.p1.y - tmp.y/tmp.z; error += dx*dx + dy*dy; storage.add(error); } }
java
public static void errorsHomographySymm(List<AssociatedPair> observations , DMatrixRMaj H , @Nullable DMatrixRMaj H_inv , GrowQueue_F64 storage ) { storage.reset(); if( H_inv == null ) H_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(H,H_inv); Point3D_F64 tmp = new Point3D_F64(); for (int i = 0; i < observations.size(); i++) { AssociatedPair p = observations.get(i); double dx,dy; double error = 0; GeometryMath_F64.mult(H,p.p1,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p2.x - tmp.x/tmp.z; dy = p.p2.y - tmp.y/tmp.z; error += dx*dx + dy*dy; GeometryMath_F64.mult(H_inv,p.p2,tmp); if( Math.abs(tmp.z) <= UtilEjml.EPS ) continue; dx = p.p1.x - tmp.x/tmp.z; dy = p.p1.y - tmp.y/tmp.z; error += dx*dx + dy*dy; storage.add(error); } }
[ "public", "static", "void", "errorsHomographySymm", "(", "List", "<", "AssociatedPair", ">", "observations", ",", "DMatrixRMaj", "H", ",", "@", "Nullable", "DMatrixRMaj", "H_inv", ",", "GrowQueue_F64", "storage", ")", "{", "storage", ".", "reset", "(", ")", ";...
<p>Computes symmetric Euclidean error for each observation and puts it into the storage. If the homography projects the point into the plane at infinity (z=0) then it is skipped</p> error[i] = (H*x1 - x2')**2 + (inv(H)*x2 - x1')**2<br> @param observations (Input) observations @param H (Input) Homography @param H_inv (Input) Inverse of homography. if null it will be computed internally @param storage (Output) storage for found errors
[ "<p", ">", "Computes", "symmetric", "Euclidean", "error", "for", "each", "observation", "and", "puts", "it", "into", "the", "storage", ".", "If", "the", "homography", "projects", "the", "point", "into", "the", "plane", "at", "infinity", "(", "z", "=", "0",...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L1182-L1216
gallandarakhneorg/afc
core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java
MathUtil.clampCyclic
@Pure public static double clampCyclic(double value, double min, double max) { assert min <= max : AssertMessages.lowerEqualParameters(1, min, 2, max); if (Double.isNaN(max) || Double.isNaN(min) || Double.isNaN(max)) { return Double.NaN; } if (value < min) { final double perimeter = max - min; final double nvalue = min - value; double rest = perimeter - (nvalue % perimeter); if (rest >= perimeter) { rest -= perimeter; } return min + rest; } else if (value >= max) { final double perimeter = max - min; final double nvalue = value - max; final double rest = nvalue % perimeter; return min + rest; } return value; }
java
@Pure public static double clampCyclic(double value, double min, double max) { assert min <= max : AssertMessages.lowerEqualParameters(1, min, 2, max); if (Double.isNaN(max) || Double.isNaN(min) || Double.isNaN(max)) { return Double.NaN; } if (value < min) { final double perimeter = max - min; final double nvalue = min - value; double rest = perimeter - (nvalue % perimeter); if (rest >= perimeter) { rest -= perimeter; } return min + rest; } else if (value >= max) { final double perimeter = max - min; final double nvalue = value - max; final double rest = nvalue % perimeter; return min + rest; } return value; }
[ "@", "Pure", "public", "static", "double", "clampCyclic", "(", "double", "value", ",", "double", "min", ",", "double", "max", ")", "{", "assert", "min", "<=", "max", ":", "AssertMessages", ".", "lowerEqualParameters", "(", "1", ",", "min", ",", "2", ",",...
Clamp the given value to fit between the min and max values according to a cyclic heuristic. If the given value is not between the minimum and maximum values, the replied value is modulo the min-max range. @param value the value to clamp. @param min the minimum value inclusive. @param max the maximum value exclusive. @return the clamped value
[ "Clamp", "the", "given", "value", "to", "fit", "between", "the", "min", "and", "max", "values", "according", "to", "a", "cyclic", "heuristic", ".", "If", "the", "given", "value", "is", "not", "between", "the", "minimum", "and", "maximum", "values", "the", ...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgen/src/main/java/org/arakhne/afc/math/MathUtil.java#L428-L449
deephacks/confit
api-runtime/src/main/java/org/deephacks/confit/query/ConfigQueryBuilder.java
ConfigQueryBuilder.lessThan
public static <A extends Comparable<A>> Restriction lessThan(String property, A value) { return new LessThan(property, value); }
java
public static <A extends Comparable<A>> Restriction lessThan(String property, A value) { return new LessThan(property, value); }
[ "public", "static", "<", "A", "extends", "Comparable", "<", "A", ">", ">", "Restriction", "lessThan", "(", "String", "property", ",", "A", "value", ")", "{", "return", "new", "LessThan", "(", "property", ",", "value", ")", ";", "}" ]
Query which asserts that a property is less than (but not equal to) a value. @param property field to query @param value value to query for @return restriction to be added to {@link ConfigQuery}.
[ "Query", "which", "asserts", "that", "a", "property", "is", "less", "than", "(", "but", "not", "equal", "to", ")", "a", "value", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/api-runtime/src/main/java/org/deephacks/confit/query/ConfigQueryBuilder.java#L69-L72
astrapi69/mystic-crypt
crypt-core/src/main/java/de/alpharogroup/crypto/pw/PasswordEncryptor.java
PasswordEncryptor.hashAndHexPassword
public String hashAndHexPassword(final String password, final String salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { return hashAndHexPassword(password, salt, DEFAULT_ALGORITHM, DEFAULT_CHARSET); }
java
public String hashAndHexPassword(final String password, final String salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { return hashAndHexPassword(password, salt, DEFAULT_ALGORITHM, DEFAULT_CHARSET); }
[ "public", "String", "hashAndHexPassword", "(", "final", "String", "password", ",", "final", "String", "salt", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeyException", ",", "UnsupportedEncodingException", ",", "NoSuchPaddingException", ",", "IllegalBlockSizeExc...
Hash and hex password with the given salt. @param password the password @param salt the salt @return the generated {@link String} object @throws NoSuchAlgorithmException is thrown if instantiation of the MessageDigest object fails. @throws UnsupportedEncodingException is thrown by get the byte array of the private key String object fails. @throws NoSuchPaddingException is thrown if instantiation of the cypher object fails. @throws InvalidKeyException the invalid key exception is thrown if initialization of the cypher object fails. @throws BadPaddingException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws IllegalBlockSizeException is thrown if {@link Cipher#doFinal(byte[])} fails. @throws InvalidAlgorithmParameterException is thrown if initialization of the cypher object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails.
[ "Hash", "and", "hex", "password", "with", "the", "given", "salt", "." ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-core/src/main/java/de/alpharogroup/crypto/pw/PasswordEncryptor.java#L148-L154
xetorthio/jedis
src/main/java/redis/clients/jedis/BinaryJedis.java
BinaryJedis.incrByFloat
@Override public Double incrByFloat(final byte[] key, final double increment) { checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); }
java
@Override public Double incrByFloat(final byte[] key, final double increment) { checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); }
[ "@", "Override", "public", "Double", "incrByFloat", "(", "final", "byte", "[", "]", "key", ",", "final", "double", "increment", ")", "{", "checkIsInMultiOrPipeline", "(", ")", ";", "client", ".", "incrByFloat", "(", "key", ",", "increment", ")", ";", "Stri...
INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats instead of integers. <p> INCRBYFLOAT commands are limited to double precision floating point values. <p> Note: this is actually a string operation, that is, in Redis there are not "double" types. Simply the string stored at the key is parsed as a base double precision floating point value, incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a negative value will work as expected. <p> Time complexity: O(1) @see #incr(byte[]) @see #decr(byte[]) @see #decrBy(byte[], long) @param key the key to increment @param increment the value to increment by @return Integer reply, this commands will reply with the new value of key after the increment.
[ "INCRBYFLOAT", "work", "just", "like", "{" ]
train
https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L807-L813
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionSpecificationOptionValueWrapper.java
CPDefinitionSpecificationOptionValueWrapper.setValue
@Override public void setValue(String value, java.util.Locale locale) { _cpDefinitionSpecificationOptionValue.setValue(value, locale); }
java
@Override public void setValue(String value, java.util.Locale locale) { _cpDefinitionSpecificationOptionValue.setValue(value, locale); }
[ "@", "Override", "public", "void", "setValue", "(", "String", "value", ",", "java", ".", "util", ".", "Locale", "locale", ")", "{", "_cpDefinitionSpecificationOptionValue", ".", "setValue", "(", "value", ",", "locale", ")", ";", "}" ]
Sets the localized value of this cp definition specification option value in the language. @param value the localized value of this cp definition specification option value @param locale the locale of the language
[ "Sets", "the", "localized", "value", "of", "this", "cp", "definition", "specification", "option", "value", "in", "the", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPDefinitionSpecificationOptionValueWrapper.java#L685-L688
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/http2/decode/HttpParser.java
HttpParser.complianceViolation
protected boolean complianceViolation(HttpComplianceSection violation, String reason) { if (_compliances.contains(violation)) return true; if (reason == null) reason = violation.description; if (_complianceHandler != null) _complianceHandler.onComplianceViolation(_compliance, violation, reason); return false; }
java
protected boolean complianceViolation(HttpComplianceSection violation, String reason) { if (_compliances.contains(violation)) return true; if (reason == null) reason = violation.description; if (_complianceHandler != null) _complianceHandler.onComplianceViolation(_compliance, violation, reason); return false; }
[ "protected", "boolean", "complianceViolation", "(", "HttpComplianceSection", "violation", ",", "String", "reason", ")", "{", "if", "(", "_compliances", ".", "contains", "(", "violation", ")", ")", "return", "true", ";", "if", "(", "reason", "==", "null", ")", ...
Check RFC compliance violation @param violation The compliance section violation @param reason The reason for the violation @return True if the current compliance level is set so as to Not allow this violation
[ "Check", "RFC", "compliance", "violation" ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/decode/HttpParser.java#L304-L313
TNG/ArchUnit
archunit/src/main/java/com/tngtech/archunit/core/importer/Location.java
Location.encodeIllegalCharacters
private String encodeIllegalCharacters(String relativeURI) { try { return new URI(null, null, relativeURI, null).toString(); } catch (URISyntaxException e) { throw new LocationException(e); } }
java
private String encodeIllegalCharacters(String relativeURI) { try { return new URI(null, null, relativeURI, null).toString(); } catch (URISyntaxException e) { throw new LocationException(e); } }
[ "private", "String", "encodeIllegalCharacters", "(", "String", "relativeURI", ")", "{", "try", "{", "return", "new", "URI", "(", "null", ",", "null", ",", "relativeURI", ",", "null", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "URISyntaxExcepti...
hand form-encodes all characters, even '/' which we do not want.
[ "hand", "form", "-", "encodes", "all", "characters", "even", "/", "which", "we", "do", "not", "want", "." ]
train
https://github.com/TNG/ArchUnit/blob/024c5d2502e91de6cb586b86c7084dbd12f3ef37/archunit/src/main/java/com/tngtech/archunit/core/importer/Location.java#L122-L128
Hygieia/Hygieia
collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java
DefaultArtifactoryClient.joinUrl
private String joinUrl(String url, String... paths) { StringBuilder result = new StringBuilder(url); for (String path : paths) { if (path != null) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } } return result.toString(); }
java
private String joinUrl(String url, String... paths) { StringBuilder result = new StringBuilder(url); for (String path : paths) { if (path != null) { String p = path.replaceFirst("^(\\/)+", ""); if (result.lastIndexOf("/") != result.length() - 1) { result.append('/'); } result.append(p); } } return result.toString(); }
[ "private", "String", "joinUrl", "(", "String", "url", ",", "String", "...", "paths", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "url", ")", ";", "for", "(", "String", "path", ":", "paths", ")", "{", "if", "(", "path", "!=", ...
join a base url to another path or paths - this will handle trailing or non-trailing /'s
[ "join", "a", "base", "url", "to", "another", "path", "or", "paths", "-", "this", "will", "handle", "trailing", "or", "non", "-", "trailing", "/", "s" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/artifact/artifactory/src/main/java/com/capitalone/dashboard/collector/DefaultArtifactoryClient.java#L413-L425
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.averagingDouble
@NotNull public static <T> Collector<T, ?, Double> averagingDouble(@NotNull final ToDoubleFunction<? super T> mapper) { return new CollectorsImpl<T, double[], Double>( DOUBLE_2ELEMENTS_ARRAY_SUPPLIER, new BiConsumer<double[], T>() { @Override public void accept(double[] t, T u) { t[0]++; // count t[1] += mapper.applyAsDouble(u); // sum } }, new Function<double[], Double>() { @NotNull @Override public Double apply(double[] t) { if (t[0] == 0) return 0d; return t[1] / t[0]; } } ); }
java
@NotNull public static <T> Collector<T, ?, Double> averagingDouble(@NotNull final ToDoubleFunction<? super T> mapper) { return new CollectorsImpl<T, double[], Double>( DOUBLE_2ELEMENTS_ARRAY_SUPPLIER, new BiConsumer<double[], T>() { @Override public void accept(double[] t, T u) { t[0]++; // count t[1] += mapper.applyAsDouble(u); // sum } }, new Function<double[], Double>() { @NotNull @Override public Double apply(double[] t) { if (t[0] == 0) return 0d; return t[1] / t[0]; } } ); }
[ "@", "NotNull", "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "Double", ">", "averagingDouble", "(", "@", "NotNull", "final", "ToDoubleFunction", "<", "?", "super", "T", ">", "mapper", ")", "{", "return", "new", "CollectorsImpl...
Returns a {@code Collector} that calculates average of double-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "calculates", "average", "of", "double", "-", "valued", "input", "elements", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L544-L567
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/components/TimePicker.java
TimePicker.zDrawTextFieldIndicators
public void zDrawTextFieldIndicators() { if (!isEnabled()) { // (Possibility: DisabledComponent) // Note: The time should always be validated (as if the component lost focus), before // the component is disabled. timeTextField.setBackground(new Color(240, 240, 240)); timeTextField.setForeground(new Color(109, 109, 109)); timeTextField.setFont(settings.fontValidTime); return; } // Reset all atributes to normal before going further. // (Possibility: ValidFullOrEmptyValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundValidTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextValidTime)); timeTextField.setFont(settings.fontValidTime); // Get the text, and check to see if it is empty. String timeText = timeTextField.getText(); boolean textIsEmpty = timeText.trim().isEmpty(); // Handle the various possibilities. if (textIsEmpty) { if (settings.getAllowEmptyTimes()) { // (Possibility: ValidFullOrEmptyValue) } else { // (Possibility: DisallowedEmptyValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundDisallowedEmptyTime)); } return; } // The text is not empty. LocalTime parsedTime = InternalUtilities.getParsedTimeOrNull(timeText, settings.getFormatForDisplayTime(), settings.getFormatForMenuTimes(), settings.formatsForParsing, settings.getLocale()); if (parsedTime == null) { // (Possibility: UnparsableValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundInvalidTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextInvalidTime)); timeTextField.setFont(settings.fontInvalidTime); return; } // The text was parsed to a value. TimeVetoPolicy vetoPolicy = settings.getVetoPolicy(); boolean isTimeVetoed = InternalUtilities.isTimeVetoed(vetoPolicy, parsedTime); if (isTimeVetoed) { // (Possibility: VetoedValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundVetoedTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextVetoedTime)); timeTextField.setFont(settings.fontVetoedTime); } }
java
public void zDrawTextFieldIndicators() { if (!isEnabled()) { // (Possibility: DisabledComponent) // Note: The time should always be validated (as if the component lost focus), before // the component is disabled. timeTextField.setBackground(new Color(240, 240, 240)); timeTextField.setForeground(new Color(109, 109, 109)); timeTextField.setFont(settings.fontValidTime); return; } // Reset all atributes to normal before going further. // (Possibility: ValidFullOrEmptyValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundValidTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextValidTime)); timeTextField.setFont(settings.fontValidTime); // Get the text, and check to see if it is empty. String timeText = timeTextField.getText(); boolean textIsEmpty = timeText.trim().isEmpty(); // Handle the various possibilities. if (textIsEmpty) { if (settings.getAllowEmptyTimes()) { // (Possibility: ValidFullOrEmptyValue) } else { // (Possibility: DisallowedEmptyValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundDisallowedEmptyTime)); } return; } // The text is not empty. LocalTime parsedTime = InternalUtilities.getParsedTimeOrNull(timeText, settings.getFormatForDisplayTime(), settings.getFormatForMenuTimes(), settings.formatsForParsing, settings.getLocale()); if (parsedTime == null) { // (Possibility: UnparsableValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundInvalidTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextInvalidTime)); timeTextField.setFont(settings.fontInvalidTime); return; } // The text was parsed to a value. TimeVetoPolicy vetoPolicy = settings.getVetoPolicy(); boolean isTimeVetoed = InternalUtilities.isTimeVetoed(vetoPolicy, parsedTime); if (isTimeVetoed) { // (Possibility: VetoedValue) timeTextField.setBackground(settings.getColor(TimeArea.TextFieldBackgroundVetoedTime)); timeTextField.setForeground(settings.getColor(TimeArea.TimePickerTextVetoedTime)); timeTextField.setFont(settings.fontVetoedTime); } }
[ "public", "void", "zDrawTextFieldIndicators", "(", ")", "{", "if", "(", "!", "isEnabled", "(", ")", ")", "{", "// (Possibility: DisabledComponent)", "// Note: The time should always be validated (as if the component lost focus), before", "// the component is disabled.", "timeTextFi...
zDrawTextFieldIndicators, This will draw the text field indicators, to indicate to the user the state of any text in the text field, including the validity of any time that has been typed. The text field indicators include the text field background color, foreground color, font color, and font. Note: This function is called automatically by the time picker. Under most circumstances, the programmer will not need to call this function. List of possible text field states: DisabledComponent, ValidFullOrEmptyValue, UnparsableValue, VetoedValue, DisallowedEmptyValue.
[ "zDrawTextFieldIndicators", "This", "will", "draw", "the", "text", "field", "indicators", "to", "indicate", "to", "the", "user", "the", "state", "of", "any", "text", "in", "the", "text", "field", "including", "the", "validity", "of", "any", "time", "that", "...
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/components/TimePicker.java#L844-L891
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPHandler.java
RTMPHandler.invokeCall
protected void invokeCall(RTMPConnection conn, IServiceCall call) { final IScope scope = conn.getScope(); if (scope != null) { if (scope.hasHandler()) { final IScopeHandler handler = scope.getHandler(); log.debug("Scope: {} handler: {}", scope, handler); if (!handler.serviceCall(conn, call)) { // XXX: What to do here? Return an error? log.warn("Scope: {} handler failed on service call", scope.getName(), new Exception("Service call failed")); return; } } final IContext context = scope.getContext(); log.debug("Context: {}", context); context.getServiceInvoker().invoke(call, scope); } else { log.warn("Scope was null for invoke: {} connection state: {}", call.getServiceMethodName(), conn.getStateCode()); } }
java
protected void invokeCall(RTMPConnection conn, IServiceCall call) { final IScope scope = conn.getScope(); if (scope != null) { if (scope.hasHandler()) { final IScopeHandler handler = scope.getHandler(); log.debug("Scope: {} handler: {}", scope, handler); if (!handler.serviceCall(conn, call)) { // XXX: What to do here? Return an error? log.warn("Scope: {} handler failed on service call", scope.getName(), new Exception("Service call failed")); return; } } final IContext context = scope.getContext(); log.debug("Context: {}", context); context.getServiceInvoker().invoke(call, scope); } else { log.warn("Scope was null for invoke: {} connection state: {}", call.getServiceMethodName(), conn.getStateCode()); } }
[ "protected", "void", "invokeCall", "(", "RTMPConnection", "conn", ",", "IServiceCall", "call", ")", "{", "final", "IScope", "scope", "=", "conn", ".", "getScope", "(", ")", ";", "if", "(", "scope", "!=", "null", ")", "{", "if", "(", "scope", ".", "hasH...
Remoting call invocation handler. @param conn RTMP connection @param call Service call
[ "Remoting", "call", "invocation", "handler", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPHandler.java#L177-L195
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_historyConsumption_date_file_GET
public OvhPcsFile billingAccount_historyConsumption_date_file_GET(String billingAccount, java.util.Date date, OvhBillDocument extension) throws IOException { String qPath = "/telephony/{billingAccount}/historyConsumption/{date}/file"; StringBuilder sb = path(qPath, billingAccount, date); query(sb, "extension", extension); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPcsFile.class); }
java
public OvhPcsFile billingAccount_historyConsumption_date_file_GET(String billingAccount, java.util.Date date, OvhBillDocument extension) throws IOException { String qPath = "/telephony/{billingAccount}/historyConsumption/{date}/file"; StringBuilder sb = path(qPath, billingAccount, date); query(sb, "extension", extension); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPcsFile.class); }
[ "public", "OvhPcsFile", "billingAccount_historyConsumption_date_file_GET", "(", "String", "billingAccount", ",", "java", ".", "util", ".", "Date", "date", ",", "OvhBillDocument", "extension", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{bill...
Previous billed consumption files REST: GET /telephony/{billingAccount}/historyConsumption/{date}/file @param extension [required] Document suffix @param billingAccount [required] The name of your billingAccount @param date [required]
[ "Previous", "billed", "consumption", "files" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L685-L691
alibaba/canal
dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/LogBuffer.java
LogBuffer.getDecimal
public final BigDecimal getDecimal(final int pos, final int precision, final int scale) { final int intg = precision - scale; final int frac = scale; final int intg0 = intg / DIG_PER_INT32; final int frac0 = frac / DIG_PER_INT32; final int intg0x = intg - intg0 * DIG_PER_INT32; final int frac0x = frac - frac0 * DIG_PER_INT32; final int binSize = intg0 * SIZE_OF_INT32 + dig2bytes[intg0x] + frac0 * SIZE_OF_INT32 + dig2bytes[frac0x]; if (pos + binSize > limit || pos < 0) { throw new IllegalArgumentException("limit excceed: " + (pos < 0 ? pos : (pos + binSize))); } return getDecimal0(origin + pos, intg, frac, // NL intg0, frac0, intg0x, frac0x); }
java
public final BigDecimal getDecimal(final int pos, final int precision, final int scale) { final int intg = precision - scale; final int frac = scale; final int intg0 = intg / DIG_PER_INT32; final int frac0 = frac / DIG_PER_INT32; final int intg0x = intg - intg0 * DIG_PER_INT32; final int frac0x = frac - frac0 * DIG_PER_INT32; final int binSize = intg0 * SIZE_OF_INT32 + dig2bytes[intg0x] + frac0 * SIZE_OF_INT32 + dig2bytes[frac0x]; if (pos + binSize > limit || pos < 0) { throw new IllegalArgumentException("limit excceed: " + (pos < 0 ? pos : (pos + binSize))); } return getDecimal0(origin + pos, intg, frac, // NL intg0, frac0, intg0x, frac0x); }
[ "public", "final", "BigDecimal", "getDecimal", "(", "final", "int", "pos", ",", "final", "int", "precision", ",", "final", "int", "scale", ")", "{", "final", "int", "intg", "=", "precision", "-", "scale", ";", "final", "int", "frac", "=", "scale", ";", ...
Return big decimal from buffer. @see mysql-5.1.60/strings/decimal.c - bin2decimal()
[ "Return", "big", "decimal", "from", "buffer", "." ]
train
https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/LogBuffer.java#L1229-L1246
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java
SASLAuthentication.challengeReceived
public void challengeReceived(String challenge, boolean finalChallenge) throws SmackSaslException, NotConnectedException, InterruptedException { try { currentMechanism.challengeReceived(challenge, finalChallenge); } catch (InterruptedException | SmackSaslException | NotConnectedException e) { authenticationFailed(e); throw e; } }
java
public void challengeReceived(String challenge, boolean finalChallenge) throws SmackSaslException, NotConnectedException, InterruptedException { try { currentMechanism.challengeReceived(challenge, finalChallenge); } catch (InterruptedException | SmackSaslException | NotConnectedException e) { authenticationFailed(e); throw e; } }
[ "public", "void", "challengeReceived", "(", "String", "challenge", ",", "boolean", "finalChallenge", ")", "throws", "SmackSaslException", ",", "NotConnectedException", ",", "InterruptedException", "{", "try", "{", "currentMechanism", ".", "challengeReceived", "(", "chal...
The server is challenging the SASL authentication we just sent. Forward the challenge to the current SASLMechanism we are using. The SASLMechanism will eventually send a response to the server. The length of the challenge-response sequence varies according to the SASLMechanism in use. @param challenge a base64 encoded string representing the challenge. @param finalChallenge true if this is the last challenge send by the server within the success stanza @throws SmackSaslException @throws NotConnectedException @throws InterruptedException
[ "The", "server", "is", "challenging", "the", "SASL", "authentication", "we", "just", "sent", ".", "Forward", "the", "challenge", "to", "the", "current", "SASLMechanism", "we", "are", "using", ".", "The", "SASLMechanism", "will", "eventually", "send", "a", "res...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/SASLAuthentication.java#L261-L268
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/trees/SemanticHeadFinder.java
SemanticHeadFinder.ruleChanges
private void ruleChanges() { // NP: don't want a POS to be the head nonTerminalInfo.put("NP", new String[][]{{"rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "NML", "JJR"}, {"left", "NP", "PRP"}, {"rightdis", "$", "ADJP", "FW"}, {"right", "CD"}, {"rightdis", "JJ", "JJS", "QP", "DT", "WDT", "NML", "PRN", "RB", "RBR", "ADVP"}, {"left", "POS"}, rightExceptPunct}); // WHNP clauses should have the same sort of head as an NP // but it a WHNP has a NP and a WHNP under it, the WHNP should be the head. E.g., (WHNP (WHNP (WP$ whose) (JJ chief) (JJ executive) (NN officer))(, ,) (NP (NNP James) (NNP Gatward))(, ,)) nonTerminalInfo.put("WHNP", new String[][]{{"rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "NML", "JJR", "WP"}, {"left", "WHNP", "NP"}, {"rightdis", "$", "ADJP", "PRN", "FW"}, {"right", "CD"}, {"rightdis", "JJ", "JJS", "RB", "QP"}, {"left", "WHPP", "WHADJP", "WP$", "WDT"}}); //WHADJP nonTerminalInfo.put("WHADJP", new String[][]{{"left", "ADJP", "JJ", "JJR"}, {"right", "RB"}, rightExceptPunct}); //WHADJP nonTerminalInfo.put("WHADVP", new String[][]{{"rightdis", "WRB", "WHADVP", "RB", "JJ"}, rightExceptPunct}); // if not WRB or WHADVP, probably has flat NP structure, allow JJ for "how long" constructions // QP: we don't want the first CD to be the semantic head (e.g., "three billion": head should be "billion"), so we go from right to left nonTerminalInfo.put("QP", new String[][]{{"right", "$", "NNS", "NN", "CD", "JJ", "PDT", "DT", "IN", "RB", "NCD", "QP", "JJR", "JJS"}}); // S, SBAR and SQ clauses should prefer the main verb as the head // S: "He considered him a friend" -> we want a friend to be the head nonTerminalInfo.put("S", new String[][]{{"left", "VP", "S", "FRAG", "SBAR", "ADJP", "UCP", "TO"}, {"right", "NP"}}); nonTerminalInfo.put("SBAR", new String[][]{{"left", "S", "SQ", "SINV", "SBAR", "FRAG", "VP", "WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT"}}); // VP shouldn't be needed in SBAR, but occurs in one buggy tree in PTB3 wsj_1457 and otherwise does no harm nonTerminalInfo.put("SQ", new String[][]{{"left", "VP", "SQ", "ADJP", "VB", "VBZ", "VBD", "VBP", "MD", "AUX", "AUXG"}}); // UCP take the first element as head nonTerminalInfo.put("UCP", new String[][]{leftExceptPunct}); // CONJP: we want different heads for "but also" and "but not" and we don't want "not" to be the head in "not to mention"; now make "mention" head of "not to mention" nonTerminalInfo.put("CONJP", new String[][]{{"right", "VB", "JJ", "RB", "IN", "CC"}, rightExceptPunct}); // FRAG: crap rule needs to be change if you want to parse glosses nonTerminalInfo.put("FRAG", new String[][]{{"left", "IN"}, {"right", "RB"}, {"left", "NP"}, {"left", "ADJP", "ADVP", "FRAG", "S", "SBAR", "VP"}, leftExceptPunct}); // PP first word (especially in coordination of PPs) nonTerminalInfo.put("PP", new String[][]{{"right", "IN", "TO", "VBG", "VBN", "RP", "FW", "JJ"}, {"left", "PP"}}); // PRN: sentence first nonTerminalInfo.put("PRN", new String[][]{{"left", "VP", "SQ", "S", "SINV", "SBAR", "NP", "ADJP", "PP", "ADVP", "INTJ", "WHNP", "NAC", "VBP", "JJ", "NN", "NNP"}, leftExceptPunct}); // add the constituent XS (special node to add a layer in a QP tree introduced in our QPTreeTransformer) nonTerminalInfo.put("XS", new String[][]{{"right", "IN"}}); }
java
private void ruleChanges() { // NP: don't want a POS to be the head nonTerminalInfo.put("NP", new String[][]{{"rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "NML", "JJR"}, {"left", "NP", "PRP"}, {"rightdis", "$", "ADJP", "FW"}, {"right", "CD"}, {"rightdis", "JJ", "JJS", "QP", "DT", "WDT", "NML", "PRN", "RB", "RBR", "ADVP"}, {"left", "POS"}, rightExceptPunct}); // WHNP clauses should have the same sort of head as an NP // but it a WHNP has a NP and a WHNP under it, the WHNP should be the head. E.g., (WHNP (WHNP (WP$ whose) (JJ chief) (JJ executive) (NN officer))(, ,) (NP (NNP James) (NNP Gatward))(, ,)) nonTerminalInfo.put("WHNP", new String[][]{{"rightdis", "NN", "NNP", "NNPS", "NNS", "NX", "NML", "JJR", "WP"}, {"left", "WHNP", "NP"}, {"rightdis", "$", "ADJP", "PRN", "FW"}, {"right", "CD"}, {"rightdis", "JJ", "JJS", "RB", "QP"}, {"left", "WHPP", "WHADJP", "WP$", "WDT"}}); //WHADJP nonTerminalInfo.put("WHADJP", new String[][]{{"left", "ADJP", "JJ", "JJR"}, {"right", "RB"}, rightExceptPunct}); //WHADJP nonTerminalInfo.put("WHADVP", new String[][]{{"rightdis", "WRB", "WHADVP", "RB", "JJ"}, rightExceptPunct}); // if not WRB or WHADVP, probably has flat NP structure, allow JJ for "how long" constructions // QP: we don't want the first CD to be the semantic head (e.g., "three billion": head should be "billion"), so we go from right to left nonTerminalInfo.put("QP", new String[][]{{"right", "$", "NNS", "NN", "CD", "JJ", "PDT", "DT", "IN", "RB", "NCD", "QP", "JJR", "JJS"}}); // S, SBAR and SQ clauses should prefer the main verb as the head // S: "He considered him a friend" -> we want a friend to be the head nonTerminalInfo.put("S", new String[][]{{"left", "VP", "S", "FRAG", "SBAR", "ADJP", "UCP", "TO"}, {"right", "NP"}}); nonTerminalInfo.put("SBAR", new String[][]{{"left", "S", "SQ", "SINV", "SBAR", "FRAG", "VP", "WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT"}}); // VP shouldn't be needed in SBAR, but occurs in one buggy tree in PTB3 wsj_1457 and otherwise does no harm nonTerminalInfo.put("SQ", new String[][]{{"left", "VP", "SQ", "ADJP", "VB", "VBZ", "VBD", "VBP", "MD", "AUX", "AUXG"}}); // UCP take the first element as head nonTerminalInfo.put("UCP", new String[][]{leftExceptPunct}); // CONJP: we want different heads for "but also" and "but not" and we don't want "not" to be the head in "not to mention"; now make "mention" head of "not to mention" nonTerminalInfo.put("CONJP", new String[][]{{"right", "VB", "JJ", "RB", "IN", "CC"}, rightExceptPunct}); // FRAG: crap rule needs to be change if you want to parse glosses nonTerminalInfo.put("FRAG", new String[][]{{"left", "IN"}, {"right", "RB"}, {"left", "NP"}, {"left", "ADJP", "ADVP", "FRAG", "S", "SBAR", "VP"}, leftExceptPunct}); // PP first word (especially in coordination of PPs) nonTerminalInfo.put("PP", new String[][]{{"right", "IN", "TO", "VBG", "VBN", "RP", "FW", "JJ"}, {"left", "PP"}}); // PRN: sentence first nonTerminalInfo.put("PRN", new String[][]{{"left", "VP", "SQ", "S", "SINV", "SBAR", "NP", "ADJP", "PP", "ADVP", "INTJ", "WHNP", "NAC", "VBP", "JJ", "NN", "NNP"}, leftExceptPunct}); // add the constituent XS (special node to add a layer in a QP tree introduced in our QPTreeTransformer) nonTerminalInfo.put("XS", new String[][]{{"right", "IN"}}); }
[ "private", "void", "ruleChanges", "(", ")", "{", "// NP: don't want a POS to be the head\r", "nonTerminalInfo", ".", "put", "(", "\"NP\"", ",", "new", "String", "[", "]", "[", "]", "{", "{", "\"rightdis\"", ",", "\"NN\"", ",", "\"NNP\"", ",", "\"NNPS\"", ",",...
makes modifications of Collins' rules to better fit with semantic notions of heads
[ "makes", "modifications", "of", "Collins", "rules", "to", "better", "fit", "with", "semantic", "notions", "of", "heads" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/trees/SemanticHeadFinder.java#L110-L151
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceIndividualGroupService.java
ReferenceIndividualGroupService.findLocalMemberGroups
protected Iterator findLocalMemberGroups(IEntityGroup eg) throws GroupsException { Collection groups = new ArrayList(10); IEntityGroup group = null; for (Iterator it = getGroupStore().findMemberGroups(eg); it.hasNext(); ) { group = (IEntityGroup) it.next(); if (group == null) { log.warn( "A null IEntityGroup object was part of a list groupStore.findMemberGroups"); continue; } group.setLocalGroupService(this); groups.add(group); if (cacheInUse()) { try { if (getGroupFromCache(group.getEntityIdentifier().getKey()) == null) { cacheAdd(group); } } catch (CachingException ce) { throw new GroupsException("Problem finding member groups", ce); } } } return groups.iterator(); }
java
protected Iterator findLocalMemberGroups(IEntityGroup eg) throws GroupsException { Collection groups = new ArrayList(10); IEntityGroup group = null; for (Iterator it = getGroupStore().findMemberGroups(eg); it.hasNext(); ) { group = (IEntityGroup) it.next(); if (group == null) { log.warn( "A null IEntityGroup object was part of a list groupStore.findMemberGroups"); continue; } group.setLocalGroupService(this); groups.add(group); if (cacheInUse()) { try { if (getGroupFromCache(group.getEntityIdentifier().getKey()) == null) { cacheAdd(group); } } catch (CachingException ce) { throw new GroupsException("Problem finding member groups", ce); } } } return groups.iterator(); }
[ "protected", "Iterator", "findLocalMemberGroups", "(", "IEntityGroup", "eg", ")", "throws", "GroupsException", "{", "Collection", "groups", "=", "new", "ArrayList", "(", "10", ")", ";", "IEntityGroup", "group", "=", "null", ";", "for", "(", "Iterator", "it", "...
Returns and caches the member groups for the <code>IEntityGroup</code> @param eg IEntityGroup
[ "Returns", "and", "caches", "the", "member", "groups", "for", "the", "<code", ">", "IEntityGroup<", "/", "code", ">" ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/groups/ReferenceIndividualGroupService.java#L268-L291
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java
ContentSpecParser.createEmptyLevelFromType
protected Level createEmptyLevelFromType(final int lineNumber, final LevelType levelType, final String input) { // Create the level based on the type switch (levelType) { case APPENDIX: return new Appendix(null, lineNumber, input); case CHAPTER: return new Chapter(null, lineNumber, input); case SECTION: return new Section(null, lineNumber, input); case PART: return new Part(null, lineNumber, input); case PROCESS: return new Process(null, lineNumber, input); case INITIAL_CONTENT: return new InitialContent(lineNumber, input); default: return new Level(null, lineNumber, input, levelType); } }
java
protected Level createEmptyLevelFromType(final int lineNumber, final LevelType levelType, final String input) { // Create the level based on the type switch (levelType) { case APPENDIX: return new Appendix(null, lineNumber, input); case CHAPTER: return new Chapter(null, lineNumber, input); case SECTION: return new Section(null, lineNumber, input); case PART: return new Part(null, lineNumber, input); case PROCESS: return new Process(null, lineNumber, input); case INITIAL_CONTENT: return new InitialContent(lineNumber, input); default: return new Level(null, lineNumber, input, levelType); } }
[ "protected", "Level", "createEmptyLevelFromType", "(", "final", "int", "lineNumber", ",", "final", "LevelType", "levelType", ",", "final", "String", "input", ")", "{", "// Create the level based on the type", "switch", "(", "levelType", ")", "{", "case", "APPENDIX", ...
Creates an empty Level using the LevelType to determine which Level subclass to instantiate. @param lineNumber The line number of the level. @param levelType The Level Type. @param input The string that represents the level, if one exists, @return The empty Level subclass object, or a plain Level object if no type matches a subclass.
[ "Creates", "an", "empty", "Level", "using", "the", "LevelType", "to", "determine", "which", "Level", "subclass", "to", "instantiate", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java#L1243-L1261
joniles/mpxj
src/main/java/net/sf/mpxj/asta/TextFileRow.java
TextFileRow.getColumnValue
private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException { try { Object value = null; switch (type) { case Types.BIT: { value = DatatypeConverter.parseBoolean(data); break; } case Types.VARCHAR: case Types.LONGVARCHAR: { value = DatatypeConverter.parseString(data); break; } case Types.TIME: { value = DatatypeConverter.parseBasicTime(data); break; } case Types.TIMESTAMP: { if (epochDateFormat) { value = DatatypeConverter.parseEpochTimestamp(data); } else { value = DatatypeConverter.parseBasicTimestamp(data); } break; } case Types.DOUBLE: { value = DatatypeConverter.parseDouble(data); break; } case Types.INTEGER: { value = DatatypeConverter.parseInteger(data); break; } default: { throw new IllegalArgumentException("Unsupported SQL type: " + type); } } return value; } catch (Exception ex) { throw new MPXJException("Failed to parse " + table + "." + column + " (data=" + data + ", type=" + type + ")", ex); } }
java
private Object getColumnValue(String table, String column, String data, int type, boolean epochDateFormat) throws MPXJException { try { Object value = null; switch (type) { case Types.BIT: { value = DatatypeConverter.parseBoolean(data); break; } case Types.VARCHAR: case Types.LONGVARCHAR: { value = DatatypeConverter.parseString(data); break; } case Types.TIME: { value = DatatypeConverter.parseBasicTime(data); break; } case Types.TIMESTAMP: { if (epochDateFormat) { value = DatatypeConverter.parseEpochTimestamp(data); } else { value = DatatypeConverter.parseBasicTimestamp(data); } break; } case Types.DOUBLE: { value = DatatypeConverter.parseDouble(data); break; } case Types.INTEGER: { value = DatatypeConverter.parseInteger(data); break; } default: { throw new IllegalArgumentException("Unsupported SQL type: " + type); } } return value; } catch (Exception ex) { throw new MPXJException("Failed to parse " + table + "." + column + " (data=" + data + ", type=" + type + ")", ex); } }
[ "private", "Object", "getColumnValue", "(", "String", "table", ",", "String", "column", ",", "String", "data", ",", "int", "type", ",", "boolean", "epochDateFormat", ")", "throws", "MPXJException", "{", "try", "{", "Object", "value", "=", "null", ";", "switc...
Maps the text representation of column data to Java types. @param table table name @param column column name @param data text representation of column data @param type column data type @param epochDateFormat true if date is represented as an offset from an epoch @return Java representation of column data @throws MPXJException
[ "Maps", "the", "text", "representation", "of", "column", "data", "to", "Java", "types", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/asta/TextFileRow.java#L75-L140
dita-ot/dita-ot
src/main/java/org/dita/dost/invoker/Main.java
Main.findBuildFile
private File findBuildFile(final String start, final String suffix) { if (args.msgOutputLevel >= Project.MSG_INFO) { System.out.println("Searching for " + suffix + " ..."); } File parent = new File(new File(start).getAbsolutePath()); File file = new File(parent, suffix); // check if the target file exists in the current directory while (!file.exists()) { // change to parent directory parent = getParentFile(parent); // if parent is null, then we are at the root of the fs, // complain that we can't find the build file. if (parent == null) { return null; } // refresh our file handle file = new File(parent, suffix); } return file; }
java
private File findBuildFile(final String start, final String suffix) { if (args.msgOutputLevel >= Project.MSG_INFO) { System.out.println("Searching for " + suffix + " ..."); } File parent = new File(new File(start).getAbsolutePath()); File file = new File(parent, suffix); // check if the target file exists in the current directory while (!file.exists()) { // change to parent directory parent = getParentFile(parent); // if parent is null, then we are at the root of the fs, // complain that we can't find the build file. if (parent == null) { return null; } // refresh our file handle file = new File(parent, suffix); } return file; }
[ "private", "File", "findBuildFile", "(", "final", "String", "start", ",", "final", "String", "suffix", ")", "{", "if", "(", "args", ".", "msgOutputLevel", ">=", "Project", ".", "MSG_INFO", ")", "{", "System", ".", "out", ".", "println", "(", "\"Searching f...
Search parent directories for the build file. <p> Takes the given target as a suffix to append to each parent directory in search of a build file. Once the root of the file-system has been reached <code>null</code> is returned. @param start Leaf directory of search. Must not be <code>null</code>. @param suffix Suffix filename to look for in parents. Must not be <code>null</code>. @return A handle to the build file if one is found, <code>null</code> if not
[ "Search", "parent", "directories", "for", "the", "build", "file", ".", "<p", ">", "Takes", "the", "given", "target", "as", "a", "suffix", "to", "append", "to", "each", "parent", "directory", "in", "search", "of", "a", "build", "file", ".", "Once", "the",...
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/invoker/Main.java#L515-L539
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.createFormatter
private TypeSpec createFormatter(DateTimeData dateTimeData, TimeZoneData timeZoneData, String className) { LocaleID id = dateTimeData.id; MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC); constructor.addStatement("this.bundleId = $T.$L", CLDR_LOCALE_IF, id.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
java
private TypeSpec createFormatter(DateTimeData dateTimeData, TimeZoneData timeZoneData, String className) { LocaleID id = dateTimeData.id; MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC); constructor.addStatement("this.bundleId = $T.$L", CLDR_LOCALE_IF, id.safe); constructor.addStatement("this.firstDay = $L", dateTimeData.firstDay); constructor.addStatement("this.minDays = $L", dateTimeData.minDays); variantsFieldInit(constructor, "this.eras", dateTimeData.eras); variantsFieldInit(constructor, "this.quartersFormat", dateTimeData.quartersFormat); variantsFieldInit(constructor, "this.quartersStandalone", dateTimeData.quartersStandalone); variantsFieldInit(constructor, "this.monthsFormat", dateTimeData.monthsFormat); variantsFieldInit(constructor, "this.monthsStandalone", dateTimeData.monthsStandalone); variantsFieldInit(constructor, "this.weekdaysFormat", dateTimeData.weekdaysFormat); variantsFieldInit(constructor, "this.weekdaysStandalone", dateTimeData.weekdaysStandalone); variantsFieldInit(constructor, "this.dayPeriodsFormat", dateTimeData.dayPeriodsFormat); variantsFieldInit(constructor, "this.dayPeriodsStandalone", dateTimeData.dayPeriodsStandalone); buildTimeZoneExemplarCities(constructor, timeZoneData); buildTimeZoneNames(constructor, timeZoneData); buildMetaZoneNames(constructor, timeZoneData); TypeSpec.Builder type = TypeSpec.classBuilder(className) .superclass(CALENDAR_FORMATTER) .addModifiers(PUBLIC) .addJavadoc( "Locale \"" + dateTimeData.id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n") .addMethod(constructor.build()); MethodSpec dateMethod = buildTypedPatternMethod("formatDate", CALENDAR_FORMAT, dateTimeData.dateFormats); MethodSpec timeMethod = buildTypedPatternMethod("formatTime", CALENDAR_FORMAT, dateTimeData.timeFormats); MethodSpec wrapperMethod = buildWrapperMethod(dateTimeData.dateTimeFormats); MethodSpec skeletonMethod = buildSkeletonFormatter(dateTimeData.dateTimeSkeletons); MethodSpec intervalMethod = buildIntervalMethod(dateTimeData.intervalFormats, dateTimeData.intervalFallbackFormat); MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod(timeZoneData); MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod(timeZoneData); return type .addMethod(dateMethod) .addMethod(timeMethod) .addMethod(wrapperMethod) .addMethod(skeletonMethod) .addMethod(intervalMethod) .addMethod(gmtMethod) .addMethod(regionFormatMethod) .build(); }
[ "private", "TypeSpec", "createFormatter", "(", "DateTimeData", "dateTimeData", ",", "TimeZoneData", "timeZoneData", ",", "String", "className", ")", "{", "LocaleID", "id", "=", "dateTimeData", ".", "id", ";", "MethodSpec", ".", "Builder", "constructor", "=", "Meth...
Create a Java class that captures all data formats for a given locale.
[ "Create", "a", "Java", "class", "that", "captures", "all", "data", "formats", "for", "a", "given", "locale", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L204-L253
amzn/ion-java
src/com/amazon/ion/impl/IonReaderTextRawTokensX.java
IonReaderTextRawTokensX.load_digits
private final int load_digits(StringBuilder sb, int c) throws IOException { if (!IonTokenConstsX.isDigit(c)) { return c; } sb.append((char) c); return readNumeric(sb, Radix.DECIMAL, NumericState.DIGIT); }
java
private final int load_digits(StringBuilder sb, int c) throws IOException { if (!IonTokenConstsX.isDigit(c)) { return c; } sb.append((char) c); return readNumeric(sb, Radix.DECIMAL, NumericState.DIGIT); }
[ "private", "final", "int", "load_digits", "(", "StringBuilder", "sb", ",", "int", "c", ")", "throws", "IOException", "{", "if", "(", "!", "IonTokenConstsX", ".", "isDigit", "(", "c", ")", ")", "{", "return", "c", ";", "}", "sb", ".", "append", "(", "...
Accumulates digits into the buffer, starting with the given character. @return the first non-digit character on the input. Could be the given character if its not a digit. @see IonTokenConstsX#isDigit(int)
[ "Accumulates", "digits", "into", "the", "buffer", "starting", "with", "the", "given", "character", "." ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/IonReaderTextRawTokensX.java#L1682-L1691
heinrichreimer/material-drawer
library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerItem.java
DrawerItem.setTextSecondary
public DrawerItem setTextSecondary(String textSecondary, int textMode) { mTextSecondary = textSecondary; setTextMode(textMode); notifyDataChanged(); return this; }
java
public DrawerItem setTextSecondary(String textSecondary, int textMode) { mTextSecondary = textSecondary; setTextMode(textMode); notifyDataChanged(); return this; }
[ "public", "DrawerItem", "setTextSecondary", "(", "String", "textSecondary", ",", "int", "textMode", ")", "{", "mTextSecondary", "=", "textSecondary", ";", "setTextMode", "(", "textMode", ")", ";", "notifyDataChanged", "(", ")", ";", "return", "this", ";", "}" ]
Sets a secondary text with a given text mode to the drawer item @param textSecondary Secondary text to set @param textMode Text mode to set
[ "Sets", "a", "secondary", "text", "with", "a", "given", "text", "mode", "to", "the", "drawer", "item" ]
train
https://github.com/heinrichreimer/material-drawer/blob/7c2406812d73f710ef8bb73d4a0f4bbef3b275ce/library/src/main/java/com/heinrichreimersoftware/materialdrawer/structure/DrawerItem.java#L363-L368
apache/incubator-heron
heron/api/src/java/org/apache/heron/streamlet/impl/streamlets/CustomStreamlet.java
CustomStreamlet.doBuild
@Override public boolean doBuild(TopologyBuilder bldr, Set<String> stageNames) { // Create and set bolt BoltDeclarer declarer; if (operator instanceof IStreamletBasicOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM, stageNames); IStreamletBasicOperator<R, T> op = (IStreamletBasicOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletRichOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_BASIC, stageNames); IStreamletRichOperator<R, T> op = (IStreamletRichOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletWindowOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_WINDOW, stageNames); IStreamletWindowOperator<R, T> op = (IStreamletWindowOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else { throw new RuntimeException("Unhandled operator class is found!"); } return true; }
java
@Override public boolean doBuild(TopologyBuilder bldr, Set<String> stageNames) { // Create and set bolt BoltDeclarer declarer; if (operator instanceof IStreamletBasicOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM, stageNames); IStreamletBasicOperator<R, T> op = (IStreamletBasicOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletRichOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_BASIC, stageNames); IStreamletRichOperator<R, T> op = (IStreamletRichOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else if (operator instanceof IStreamletWindowOperator) { setDefaultNameIfNone(StreamletNamePrefix.CUSTOM_WINDOW, stageNames); IStreamletWindowOperator<R, T> op = (IStreamletWindowOperator<R, T>) operator; bldr.setBolt(getName(), op, getNumPartitions()) .grouping(parent.getName(), parent.getStreamId(), grouper); } else { throw new RuntimeException("Unhandled operator class is found!"); } return true; }
[ "@", "Override", "public", "boolean", "doBuild", "(", "TopologyBuilder", "bldr", ",", "Set", "<", "String", ">", "stageNames", ")", "{", "// Create and set bolt", "BoltDeclarer", "declarer", ";", "if", "(", "operator", "instanceof", "IStreamletBasicOperator", ")", ...
Connect this streamlet to TopologyBuilder. @param bldr The TopologyBuilder for the topology @param stageNames The existing stage names @return True if successful
[ "Connect", "this", "streamlet", "to", "TopologyBuilder", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/streamlets/CustomStreamlet.java#L63-L87
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/sftp/SftpFsHelper.java
SftpFsHelper.getFileStream
@Override public InputStream getFileStream(String file) throws FileBasedHelperException { SftpGetMonitor monitor = new SftpGetMonitor(); try { ChannelSftp channel = getSftpChannel(); return new SftpFsFileInputStream(channel.get(file, monitor), channel); } catch (SftpException e) { throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e); } }
java
@Override public InputStream getFileStream(String file) throws FileBasedHelperException { SftpGetMonitor monitor = new SftpGetMonitor(); try { ChannelSftp channel = getSftpChannel(); return new SftpFsFileInputStream(channel.get(file, monitor), channel); } catch (SftpException e) { throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e); } }
[ "@", "Override", "public", "InputStream", "getFileStream", "(", "String", "file", ")", "throws", "FileBasedHelperException", "{", "SftpGetMonitor", "monitor", "=", "new", "SftpGetMonitor", "(", ")", ";", "try", "{", "ChannelSftp", "channel", "=", "getSftpChannel", ...
Executes a get SftpCommand and returns an input stream to the file @param cmd is the command to execute @param sftp is the channel to execute the command on @throws SftpException
[ "Executes", "a", "get", "SftpCommand", "and", "returns", "an", "input", "stream", "to", "the", "file" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/sftp/SftpFsHelper.java#L209-L218
lessthanoptimal/BoofCV
main/boofcv-types/src/main/java/boofcv/struct/image/ImageType.java
ImageType.createImage
public T createImage( int width , int height ) { switch( family ) { case GRAY: return (T)GeneralizedImageOps.createSingleBand(getImageClass(),width,height); case INTERLEAVED: return (T)GeneralizedImageOps.createInterleaved(getImageClass(), width, height, numBands); case PLANAR: return (T)new Planar(getImageClass(),width,height,numBands); default: throw new IllegalArgumentException("Type not yet supported"); } }
java
public T createImage( int width , int height ) { switch( family ) { case GRAY: return (T)GeneralizedImageOps.createSingleBand(getImageClass(),width,height); case INTERLEAVED: return (T)GeneralizedImageOps.createInterleaved(getImageClass(), width, height, numBands); case PLANAR: return (T)new Planar(getImageClass(),width,height,numBands); default: throw new IllegalArgumentException("Type not yet supported"); } }
[ "public", "T", "createImage", "(", "int", "width", ",", "int", "height", ")", "{", "switch", "(", "family", ")", "{", "case", "GRAY", ":", "return", "(", "T", ")", "GeneralizedImageOps", ".", "createSingleBand", "(", "getImageClass", "(", ")", ",", "widt...
Creates a new image. @param width Number of columns in the image. @param height Number of rows in the image. @return New instance of the image.
[ "Creates", "a", "new", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/image/ImageType.java#L87-L101
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.saveElementValue
protected void saveElementValue(String field, String targetKey, Page page) throws TechnicalException, FailureException { logger.debug("saveValueInStep: {} to {} in {}.", field, targetKey, page.getApplication()); String txt = ""; try { final WebElement elem = Utilities.findElement(page, field); txt = elem.getAttribute(VALUE) != null ? elem.getAttribute(VALUE) : elem.getText(); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, page.getCallBack()); } try { Context.saveValue(targetKey, txt); Context.getCurrentScenario().write("SAVE " + targetKey + "=" + txt); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE), page.getPageElementByKey(field), page.getApplication()), true, page.getCallBack()); } }
java
protected void saveElementValue(String field, String targetKey, Page page) throws TechnicalException, FailureException { logger.debug("saveValueInStep: {} to {} in {}.", field, targetKey, page.getApplication()); String txt = ""; try { final WebElement elem = Utilities.findElement(page, field); txt = elem.getAttribute(VALUE) != null ? elem.getAttribute(VALUE) : elem.getText(); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, page.getCallBack()); } try { Context.saveValue(targetKey, txt); Context.getCurrentScenario().write("SAVE " + targetKey + "=" + txt); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE), page.getPageElementByKey(field), page.getApplication()), true, page.getCallBack()); } }
[ "protected", "void", "saveElementValue", "(", "String", "field", ",", "String", "targetKey", ",", "Page", "page", ")", "throws", "TechnicalException", ",", "FailureException", "{", "logger", ".", "debug", "(", "\"saveValueInStep: {} to {} in {}.\"", ",", "field", ",...
Save value in memory. @param field is name of the field to retrieve. @param targetKey is the key to save value to @param page is target page. @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message (with screenshot, with exception) or with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error
[ "Save", "value", "in", "memory", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L568-L584
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java
br_restoreconfig.restoreconfig
public static br_restoreconfig restoreconfig(nitro_service client, br_restoreconfig resource) throws Exception { return ((br_restoreconfig[]) resource.perform_operation(client, "restoreconfig"))[0]; }
java
public static br_restoreconfig restoreconfig(nitro_service client, br_restoreconfig resource) throws Exception { return ((br_restoreconfig[]) resource.perform_operation(client, "restoreconfig"))[0]; }
[ "public", "static", "br_restoreconfig", "restoreconfig", "(", "nitro_service", "client", ",", "br_restoreconfig", "resource", ")", "throws", "Exception", "{", "return", "(", "(", "br_restoreconfig", "[", "]", ")", "resource", ".", "perform_operation", "(", "client",...
<pre> Use this operation to restore config from file on Repeater Instances. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "restore", "config", "from", "file", "on", "Repeater", "Instances", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_restoreconfig.java#L105-L108
datastax/java-driver
core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java
GenericType.where
@NonNull public final <X> GenericType<T> where( @NonNull GenericTypeParameter<X> freeVariable, @NonNull Class<X> actualType) { return where(freeVariable, GenericType.of(actualType)); }
java
@NonNull public final <X> GenericType<T> where( @NonNull GenericTypeParameter<X> freeVariable, @NonNull Class<X> actualType) { return where(freeVariable, GenericType.of(actualType)); }
[ "@", "NonNull", "public", "final", "<", "X", ">", "GenericType", "<", "T", ">", "where", "(", "@", "NonNull", "GenericTypeParameter", "<", "X", ">", "freeVariable", ",", "@", "NonNull", "Class", "<", "X", ">", "actualType", ")", "{", "return", "where", ...
Substitutes a free type variable with an actual type. See {@link GenericType this class's javadoc} for an example.
[ "Substitutes", "a", "free", "type", "variable", "with", "an", "actual", "type", ".", "See", "{" ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java#L249-L253
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/registry/VisitRegistry.java
VisitRegistry.isVisited
public boolean isVisited(int from, int upTo) { if (checkBounds(from) && checkBounds(upTo - 1)) { // perform the visit check // for (int i = from; i < upTo; i++) { if (ONE == this.registry[i]) { return true; } } return false; } else { throw new RuntimeException("The location " + from + "," + upTo + " out of bounds [0," + (this.registry.length - 1) + "]"); } }
java
public boolean isVisited(int from, int upTo) { if (checkBounds(from) && checkBounds(upTo - 1)) { // perform the visit check // for (int i = from; i < upTo; i++) { if (ONE == this.registry[i]) { return true; } } return false; } else { throw new RuntimeException("The location " + from + "," + upTo + " out of bounds [0," + (this.registry.length - 1) + "]"); } }
[ "public", "boolean", "isVisited", "(", "int", "from", ",", "int", "upTo", ")", "{", "if", "(", "checkBounds", "(", "from", ")", "&&", "checkBounds", "(", "upTo", "-", "1", ")", ")", "{", "// perform the visit check", "//", "for", "(", "int", "i", "=", ...
Check if the interval and its boundaries were visited. @param from The interval start (inclusive). @param upTo The interval end (exclusive). @return True if visited.
[ "Check", "if", "the", "interval", "and", "its", "boundaries", "were", "visited", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/registry/VisitRegistry.java#L124-L139
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.copyImage
public static BufferedImage copyImage(Image img, int imageType) { final BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), imageType); final Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); return bimage; }
java
public static BufferedImage copyImage(Image img, int imageType) { final BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), imageType); final Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(img, 0, 0, null); bGr.dispose(); return bimage; }
[ "public", "static", "BufferedImage", "copyImage", "(", "Image", "img", ",", "int", "imageType", ")", "{", "final", "BufferedImage", "bimage", "=", "new", "BufferedImage", "(", "img", ".", "getWidth", "(", "null", ")", ",", "img", ".", "getHeight", "(", "nu...
将已有Image复制新的一份出来 @param img {@link Image} @param imageType {@link BufferedImage}中的常量,图像类型,例如黑白等 @return {@link BufferedImage} @see BufferedImage#TYPE_INT_RGB @see BufferedImage#TYPE_INT_ARGB @see BufferedImage#TYPE_INT_ARGB_PRE @see BufferedImage#TYPE_INT_BGR @see BufferedImage#TYPE_3BYTE_BGR @see BufferedImage#TYPE_4BYTE_ABGR @see BufferedImage#TYPE_4BYTE_ABGR_PRE @see BufferedImage#TYPE_BYTE_GRAY @see BufferedImage#TYPE_USHORT_GRAY @see BufferedImage#TYPE_BYTE_BINARY @see BufferedImage#TYPE_BYTE_INDEXED @see BufferedImage#TYPE_USHORT_565_RGB @see BufferedImage#TYPE_USHORT_555_RGB
[ "将已有Image复制新的一份出来" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1213-L1220
atomix/atomix
cluster/src/main/java/io/atomix/cluster/AtomixClusterBuilder.java
AtomixClusterBuilder.withAddress
@Deprecated public AtomixClusterBuilder withAddress(String host, int port) { return withAddress(Address.from(host, port)); }
java
@Deprecated public AtomixClusterBuilder withAddress(String host, int port) { return withAddress(Address.from(host, port)); }
[ "@", "Deprecated", "public", "AtomixClusterBuilder", "withAddress", "(", "String", "host", ",", "int", "port", ")", "{", "return", "withAddress", "(", "Address", ".", "from", "(", "host", ",", "port", ")", ")", ";", "}" ]
Sets the member host/port. <p> The constructed {@link AtomixCluster} will bind to the given host/port for intra-cluster communication. The provided host should be visible to other nodes in the cluster. @param host the host name @param port the port number @return the cluster builder @throws io.atomix.utils.net.MalformedAddressException if a valid {@link Address} cannot be constructed from the arguments @deprecated since 3.1. Use {@link #withHost(String)} and {@link #withPort(int)} instead
[ "Sets", "the", "member", "host", "/", "port", ".", "<p", ">", "The", "constructed", "{", "@link", "AtomixCluster", "}", "will", "bind", "to", "the", "given", "host", "/", "port", "for", "intra", "-", "cluster", "communication", ".", "The", "provided", "h...
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/cluster/src/main/java/io/atomix/cluster/AtomixClusterBuilder.java#L160-L163
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java
AFPChainer.getRmsd
private static double getRmsd(int focusResn, int[] focusRes1, int[] focusRes2, AFPChain afpChain, Atom[] ca1, Atom[] ca2){ Atom[] tmp1 = new Atom[focusResn]; Atom[] tmp2 = new Atom[focusResn]; for ( int i =0 ; i< focusResn;i++){ tmp1[i] = ca1[focusRes1[i]]; tmp2[i] = (Atom)ca2[focusRes2[i]].clone(); if (tmp1[i].getCoords() == null){ System.err.println("tmp1 got null: " +i + " pos: " + focusRes1[i]); } if (tmp2[i].getCoords() == null){ System.err.println("tmp1 got null: " +i + " pos: " + focusRes2[i]); } //XX //tmp2[i].setParent((Group) ca2[focusRes2[i]].getParent().clone()); } double rmsd = 99; try { rmsd = getRmsd(tmp1,tmp2); } catch (Exception e){ e.printStackTrace(); } return rmsd; }
java
private static double getRmsd(int focusResn, int[] focusRes1, int[] focusRes2, AFPChain afpChain, Atom[] ca1, Atom[] ca2){ Atom[] tmp1 = new Atom[focusResn]; Atom[] tmp2 = new Atom[focusResn]; for ( int i =0 ; i< focusResn;i++){ tmp1[i] = ca1[focusRes1[i]]; tmp2[i] = (Atom)ca2[focusRes2[i]].clone(); if (tmp1[i].getCoords() == null){ System.err.println("tmp1 got null: " +i + " pos: " + focusRes1[i]); } if (tmp2[i].getCoords() == null){ System.err.println("tmp1 got null: " +i + " pos: " + focusRes2[i]); } //XX //tmp2[i].setParent((Group) ca2[focusRes2[i]].getParent().clone()); } double rmsd = 99; try { rmsd = getRmsd(tmp1,tmp2); } catch (Exception e){ e.printStackTrace(); } return rmsd; }
[ "private", "static", "double", "getRmsd", "(", "int", "focusResn", ",", "int", "[", "]", "focusRes1", ",", "int", "[", "]", "focusRes2", ",", "AFPChain", "afpChain", ",", "Atom", "[", "]", "ca1", ",", "Atom", "[", "]", "ca2", ")", "{", "Atom", "[", ...
the the RMSD for the residues defined in the two arrays @param focusResn @param focusRes1 @param focusRes2 @return
[ "the", "the", "RMSD", "for", "the", "residues", "defined", "in", "the", "two", "arrays" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java#L666-L694
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addFilter
public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc .createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }
java
public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc .createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }
[ "public", "static", "void", "addFilter", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "filter", "=", "doc", ".", "createElement", "(", "\"filter\"", ")", ";", "Element", "filterName", "=", "doc", ".", "createElement", "(", "\"filter-n...
Adds the shiro filter to a web.xml file. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the filter to.
[ "Adds", "the", "shiro", "filter", "to", "a", "web", ".", "xml", "file", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L313-L324
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.attemptRedirect
protected void attemptRedirect(final Request request, final Response response, final Form form) { this.log.debug("redirectQueryName: {}", this.getRedirectQueryName()); this.log.debug("query: {}", request.getResourceRef().getQueryAsForm()); //this.log.info("form: {}", form); String targetUri = request.getResourceRef().getQueryAsForm().getFirstValue(this.getRedirectQueryName(), true); this.log.debug("attemptRedirect: targetUri={}", targetUri); if(targetUri == null && form != null) { targetUri = form.getFirstValue(this.getRedirectQueryName(), true); } this.log.debug("attemptRedirect: targetUri={}", targetUri); if(targetUri != null) { response.redirectSeeOther(Reference.decode(targetUri)); return; } if(this.getFixedRedirectUri() != null) { this.log.debug("attemptRedirect: fixedRedirectUri={}", this.getFixedRedirectUri()); response.redirectSeeOther(this.getFixedRedirectUri()); return; } else { this.log.debug("attemptRedirect: fixedRedirectUri={}", FixedRedirectCookieAuthenticator.DEFAULT_FIXED_REDIRECT_URI); response.redirectSeeOther(FixedRedirectCookieAuthenticator.DEFAULT_FIXED_REDIRECT_URI); return; } }
java
protected void attemptRedirect(final Request request, final Response response, final Form form) { this.log.debug("redirectQueryName: {}", this.getRedirectQueryName()); this.log.debug("query: {}", request.getResourceRef().getQueryAsForm()); //this.log.info("form: {}", form); String targetUri = request.getResourceRef().getQueryAsForm().getFirstValue(this.getRedirectQueryName(), true); this.log.debug("attemptRedirect: targetUri={}", targetUri); if(targetUri == null && form != null) { targetUri = form.getFirstValue(this.getRedirectQueryName(), true); } this.log.debug("attemptRedirect: targetUri={}", targetUri); if(targetUri != null) { response.redirectSeeOther(Reference.decode(targetUri)); return; } if(this.getFixedRedirectUri() != null) { this.log.debug("attemptRedirect: fixedRedirectUri={}", this.getFixedRedirectUri()); response.redirectSeeOther(this.getFixedRedirectUri()); return; } else { this.log.debug("attemptRedirect: fixedRedirectUri={}", FixedRedirectCookieAuthenticator.DEFAULT_FIXED_REDIRECT_URI); response.redirectSeeOther(FixedRedirectCookieAuthenticator.DEFAULT_FIXED_REDIRECT_URI); return; } }
[ "protected", "void", "attemptRedirect", "(", "final", "Request", "request", ",", "final", "Response", "response", ",", "final", "Form", "form", ")", "{", "this", ".", "log", ".", "debug", "(", "\"redirectQueryName: {}\"", ",", "this", ".", "getRedirectQueryName"...
Attempts to redirect the user's browser can be redirected to the URI provided in a query parameter named by {@link #getRedirectQueryName()}. Uses a configured fixed redirect URI or a default redirect URI if they are not setup. @param request The current request. @param response The current response. @param form The query parameters.
[ "Attempts", "to", "redirect", "the", "user", "s", "browser", "can", "be", "redirected", "to", "the", "URI", "provided", "in", "a", "query", "parameter", "named", "by", "{", "@link", "#getRedirectQueryName", "()", "}", "." ]
train
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L188-L224
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/menu/MenuFlyoutExample.java
MenuFlyoutExample.createImageMenuItem
private WMenuItem createImageMenuItem(final String resource, final String desc, final String cacheKey, final WText selectedMenuText) { WImage image = new WImage(resource, desc); image.setCacheKey(cacheKey); WDecoratedLabel label = new WDecoratedLabel(image, new WText(desc), null); WMenuItem menuItem = new WMenuItem(label, new ExampleMenuAction(selectedMenuText)); menuItem.setActionObject(desc); return menuItem; }
java
private WMenuItem createImageMenuItem(final String resource, final String desc, final String cacheKey, final WText selectedMenuText) { WImage image = new WImage(resource, desc); image.setCacheKey(cacheKey); WDecoratedLabel label = new WDecoratedLabel(image, new WText(desc), null); WMenuItem menuItem = new WMenuItem(label, new ExampleMenuAction(selectedMenuText)); menuItem.setActionObject(desc); return menuItem; }
[ "private", "WMenuItem", "createImageMenuItem", "(", "final", "String", "resource", ",", "final", "String", "desc", ",", "final", "String", "cacheKey", ",", "final", "WText", "selectedMenuText", ")", "{", "WImage", "image", "=", "new", "WImage", "(", "resource", ...
Creates an example menu item using an image. @param resource the name of the image resource @param desc the description for the image @param cacheKey the cache key for this image @param selectedMenuText the WText to display the selected menu item. @return a menu item using an image
[ "Creates", "an", "example", "menu", "item", "using", "an", "image", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/menu/MenuFlyoutExample.java#L158-L167
lets-blade/blade
src/main/java/com/blade/mvc/route/RouteMatcher.java
RouteMatcher.matchesPath
private boolean matchesPath(String routePath, String pathToMatch) { routePath = PathKit.VAR_REGEXP_PATTERN.matcher(routePath).replaceAll(PathKit.VAR_REPLACE); return pathToMatch.matches("(?i)" + routePath); }
java
private boolean matchesPath(String routePath, String pathToMatch) { routePath = PathKit.VAR_REGEXP_PATTERN.matcher(routePath).replaceAll(PathKit.VAR_REPLACE); return pathToMatch.matches("(?i)" + routePath); }
[ "private", "boolean", "matchesPath", "(", "String", "routePath", ",", "String", "pathToMatch", ")", "{", "routePath", "=", "PathKit", ".", "VAR_REGEXP_PATTERN", ".", "matcher", "(", "routePath", ")", ".", "replaceAll", "(", "PathKit", ".", "VAR_REPLACE", ")", ...
Matching path @param routePath route path @param pathToMatch match path @return return match is success
[ "Matching", "path" ]
train
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/mvc/route/RouteMatcher.java#L320-L323
cqframework/clinical_quality_language
Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java
ElmBaseVisitor.visitTupleElement
public T visitTupleElement(TupleElement elm, C context) { visitElement(elm.getValue(), context); return null; }
java
public T visitTupleElement(TupleElement elm, C context) { visitElement(elm.getValue(), context); return null; }
[ "public", "T", "visitTupleElement", "(", "TupleElement", "elm", ",", "C", "context", ")", "{", "visitElement", "(", "elm", ".", "getValue", "(", ")", ",", "context", ")", ";", "return", "null", ";", "}" ]
Visit a TupleElement. This method will be called for every node in the tree that is a TupleElement. @param elm the ELM tree @param context the context passed to the visitor @return the visitor result
[ "Visit", "a", "TupleElement", ".", "This", "method", "will", "be", "called", "for", "every", "node", "in", "the", "tree", "that", "is", "a", "TupleElement", "." ]
train
https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java#L455-L458
cdapio/netty-http
src/main/java/io/cdap/http/internal/RequestRouter.java
RequestRouter.channelRead
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (exceptionRaised.get()) { return; } if (!(msg instanceof HttpRequest)) { // If there is no methodInfo, it means the request was already rejected. // What we received here is just residue of the request, which can be ignored. if (methodInfo != null) { ReferenceCountUtil.retain(msg); ctx.fireChannelRead(msg); } return; } HttpRequest request = (HttpRequest) msg; BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled); // Reset the methodInfo for the incoming request error handling methodInfo = null; methodInfo = prepareHandleMethod(request, responder, ctx); if (methodInfo != null) { ReferenceCountUtil.retain(msg); ctx.fireChannelRead(msg); } else { if (!responder.isResponded()) { // If not yet responded, just respond with a not found and close the connection HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); HttpUtil.setContentLength(response, 0); HttpUtil.setKeepAlive(response, false); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { // If already responded, just close the connection ctx.channel().close(); } } } finally { ReferenceCountUtil.release(msg); } }
java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (exceptionRaised.get()) { return; } if (!(msg instanceof HttpRequest)) { // If there is no methodInfo, it means the request was already rejected. // What we received here is just residue of the request, which can be ignored. if (methodInfo != null) { ReferenceCountUtil.retain(msg); ctx.fireChannelRead(msg); } return; } HttpRequest request = (HttpRequest) msg; BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled); // Reset the methodInfo for the incoming request error handling methodInfo = null; methodInfo = prepareHandleMethod(request, responder, ctx); if (methodInfo != null) { ReferenceCountUtil.retain(msg); ctx.fireChannelRead(msg); } else { if (!responder.isResponded()) { // If not yet responded, just respond with a not found and close the connection HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); HttpUtil.setContentLength(response, 0); HttpUtil.setKeepAlive(response, false); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { // If already responded, just close the connection ctx.channel().close(); } } } finally { ReferenceCountUtil.release(msg); } }
[ "@", "Override", "public", "void", "channelRead", "(", "ChannelHandlerContext", "ctx", ",", "Object", "msg", ")", "throws", "Exception", "{", "try", "{", "if", "(", "exceptionRaised", ".", "get", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", ...
If the HttpRequest is valid and handled it will be sent upstream, if it cannot be invoked the response will be written back immediately.
[ "If", "the", "HttpRequest", "is", "valid", "and", "handled", "it", "will", "be", "sent", "upstream", "if", "it", "cannot", "be", "invoked", "the", "response", "will", "be", "written", "back", "immediately", "." ]
train
https://github.com/cdapio/netty-http/blob/02fdbb45bdd51d3dd58c0efbb2f27195d265cd0f/src/main/java/io/cdap/http/internal/RequestRouter.java#L67-L108
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTree.java
WTree.processCheckExpandedCustomNodes
private void processCheckExpandedCustomNodes(final TreeItemIdNode node, final Set<String> expandedRows) { // Node has no children if (!node.hasChildren()) { return; } // Check node is expanded boolean expanded = getExpandMode() == WTree.ExpandMode.CLIENT || expandedRows.contains(node.getItemId()); if (!expanded) { return; } if (node.getChildren().isEmpty()) { // Add children from the model loadCustomNodeChildren(node); } else { // Check the expanded child nodes for (TreeItemIdNode child : node.getChildren()) { processCheckExpandedCustomNodes(child, expandedRows); } } }
java
private void processCheckExpandedCustomNodes(final TreeItemIdNode node, final Set<String> expandedRows) { // Node has no children if (!node.hasChildren()) { return; } // Check node is expanded boolean expanded = getExpandMode() == WTree.ExpandMode.CLIENT || expandedRows.contains(node.getItemId()); if (!expanded) { return; } if (node.getChildren().isEmpty()) { // Add children from the model loadCustomNodeChildren(node); } else { // Check the expanded child nodes for (TreeItemIdNode child : node.getChildren()) { processCheckExpandedCustomNodes(child, expandedRows); } } }
[ "private", "void", "processCheckExpandedCustomNodes", "(", "final", "TreeItemIdNode", "node", ",", "final", "Set", "<", "String", ">", "expandedRows", ")", "{", "// Node has no children", "if", "(", "!", "node", ".", "hasChildren", "(", ")", ")", "{", "return", ...
Iterate through nodes to check expanded nodes have their child nodes. <p> If a node is flagged as having children and has none, then load them from the tree model. </p> @param node the node to check @param expandedRows the expanded rows
[ "Iterate", "through", "nodes", "to", "check", "expanded", "nodes", "have", "their", "child", "nodes", ".", "<p", ">", "If", "a", "node", "is", "flagged", "as", "having", "children", "and", "has", "none", "then", "load", "them", "from", "the", "tree", "mo...
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTree.java#L1254-L1275