repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/base/StringValueConverterImpl.java
StringValueConverterImpl.parseNumber
private Number parseNumber(String numberValue, Object valueSource) throws WrongValueTypeException { try { Double d = Double.valueOf(numberValue); return this.mathUtil.toSimplestNumber(d); } catch (NumberFormatException e) { throw new WrongValueTypeException(e, numberValue, valueSource, Number.class); } }
java
private Number parseNumber(String numberValue, Object valueSource) throws WrongValueTypeException { try { Double d = Double.valueOf(numberValue); return this.mathUtil.toSimplestNumber(d); } catch (NumberFormatException e) { throw new WrongValueTypeException(e, numberValue, valueSource, Number.class); } }
[ "private", "Number", "parseNumber", "(", "String", "numberValue", ",", "Object", "valueSource", ")", "throws", "WrongValueTypeException", "{", "try", "{", "Double", "d", "=", "Double", ".", "valueOf", "(", "numberValue", ")", ";", "return", "this", ".", "mathU...
This method parses a numeric value. @param numberValue is the number value as string. @param valueSource describes the source of the value. This may be the filename where the value was read from, an XPath where the value was located in an XML document, etc. It is used in exceptions thrown if something goes wrong. This will help to find the problem easier. @return the value as number. @throws WrongValueTypeException if the given string is no number.
[ "This", "method", "parses", "a", "numeric", "value", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/base/StringValueConverterImpl.java#L111-L119
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java
PersistenceBrokerImpl.createProxy
public Object createProxy(Class baseClassForProxy, Identity realSubjectsIdentity) { try { // the invocation handler manages all delegation stuff IndirectionHandler handler = getProxyFactory().createIndirectionHandler(pbKey, realSubjectsIdentity); // the proxy simply provides the interface of the real subject if (VirtualProxy.class.isAssignableFrom(baseClassForProxy)) { Constructor constructor = baseClassForProxy.getDeclaredConstructor(new Class[]{ IndirectionHandler.class }); return constructor.newInstance(new Object[]{ handler }); } else { return getProxyFactory().createProxy(baseClassForProxy,handler); } } catch (Exception ex) { throw new PersistenceBrokerException("Unable to create proxy using class:"+baseClassForProxy.getName(), ex); } }
java
public Object createProxy(Class baseClassForProxy, Identity realSubjectsIdentity) { try { // the invocation handler manages all delegation stuff IndirectionHandler handler = getProxyFactory().createIndirectionHandler(pbKey, realSubjectsIdentity); // the proxy simply provides the interface of the real subject if (VirtualProxy.class.isAssignableFrom(baseClassForProxy)) { Constructor constructor = baseClassForProxy.getDeclaredConstructor(new Class[]{ IndirectionHandler.class }); return constructor.newInstance(new Object[]{ handler }); } else { return getProxyFactory().createProxy(baseClassForProxy,handler); } } catch (Exception ex) { throw new PersistenceBrokerException("Unable to create proxy using class:"+baseClassForProxy.getName(), ex); } }
[ "public", "Object", "createProxy", "(", "Class", "baseClassForProxy", ",", "Identity", "realSubjectsIdentity", ")", "{", "try", "{", "// the invocation handler manages all delegation stuff", "IndirectionHandler", "handler", "=", "getProxyFactory", "(", ")", ".", "createIndi...
Creates a proxy instance. @param baseClassForProxy The base class that the Proxy should extend. For dynamic Proxies, the method of generation is dependent on the ProxyFactory implementation. @param realSubjectsIdentity The identity of the subject @return An instance of the proxy subclass @throws PersistenceBrokerException If there is an error creating the proxy object
[ "Creates", "a", "proxy", "instance", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/PersistenceBrokerImpl.java#L2241-L2265
icode/ameba
src/main/java/ameba/mvc/template/internal/TemplateHelper.java
TemplateHelper.getAbsolutePath
public static String getAbsolutePath(Class<?> resourceClass, String path, char delim) { return '/' + resourceClass.getName().replace('.', '/').replace('$', delim) + delim + path; }
java
public static String getAbsolutePath(Class<?> resourceClass, String path, char delim) { return '/' + resourceClass.getName().replace('.', '/').replace('$', delim) + delim + path; }
[ "public", "static", "String", "getAbsolutePath", "(", "Class", "<", "?", ">", "resourceClass", ",", "String", "path", ",", "char", "delim", ")", "{", "return", "'", "'", "+", "resourceClass", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ","...
Return an absolute path to the given class where segments are separated using {@code delim} character and {@code path} is appended to this path. @param resourceClass class for which an absolute path should be obtained. @param path segment to be appended to the resulting path. @param delim character used for separating path segments. @return an absolute path to the resource class.
[ "Return", "an", "absolute", "path", "to", "the", "given", "class", "where", "segments", "are", "separated", "using", "{", "@code", "delim", "}", "character", "and", "{", "@code", "path", "}", "is", "appended", "to", "this", "path", "." ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/mvc/template/internal/TemplateHelper.java#L58-L60
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Frame.java
Frame.getNumArgumentsIncludingObjectInstance
public int getNumArgumentsIncludingObjectInstance(InvokeInstruction ins, ConstantPoolGen cpg) throws DataflowAnalysisException { int numConsumed = ins.consumeStack(cpg); if (numConsumed == Const.UNPREDICTABLE) { throw new DataflowAnalysisException("Unpredictable stack consumption in " + ins); } return numConsumed; }
java
public int getNumArgumentsIncludingObjectInstance(InvokeInstruction ins, ConstantPoolGen cpg) throws DataflowAnalysisException { int numConsumed = ins.consumeStack(cpg); if (numConsumed == Const.UNPREDICTABLE) { throw new DataflowAnalysisException("Unpredictable stack consumption in " + ins); } return numConsumed; }
[ "public", "int", "getNumArgumentsIncludingObjectInstance", "(", "InvokeInstruction", "ins", ",", "ConstantPoolGen", "cpg", ")", "throws", "DataflowAnalysisException", "{", "int", "numConsumed", "=", "ins", ".", "consumeStack", "(", "cpg", ")", ";", "if", "(", "numCo...
Get the number of arguments passed to given method invocation, including the object instance if the call is to an instance method. @param ins the method invocation instruction @param cpg the ConstantPoolGen for the class containing the method @return number of arguments, including object instance if appropriate @throws DataflowAnalysisException
[ "Get", "the", "number", "of", "arguments", "passed", "to", "given", "method", "invocation", "including", "the", "object", "instance", "if", "the", "call", "is", "to", "an", "instance", "method", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Frame.java#L364-L371
eurekaclinical/javautil
src/main/java/org/arp/javautil/sql/DatabaseMetaDataWrapper.java
DatabaseMetaDataWrapper.isDriverCompatible
public boolean isDriverCompatible(String driverName, DriverVersion minVersion, DriverVersion maxVersion) throws SQLException { readMetaDataIfNeeded(); if (!this.driverName.equals(driverName)) { return false; } return new VersionRange(minVersion, maxVersion).isWithinRange(this.driverVersion); }
java
public boolean isDriverCompatible(String driverName, DriverVersion minVersion, DriverVersion maxVersion) throws SQLException { readMetaDataIfNeeded(); if (!this.driverName.equals(driverName)) { return false; } return new VersionRange(minVersion, maxVersion).isWithinRange(this.driverVersion); }
[ "public", "boolean", "isDriverCompatible", "(", "String", "driverName", ",", "DriverVersion", "minVersion", ",", "DriverVersion", "maxVersion", ")", "throws", "SQLException", "{", "readMetaDataIfNeeded", "(", ")", ";", "if", "(", "!", "this", ".", "driverName", "....
Compares JDBC driver name and version information to that reported by the driver. @param driverName the expected driver name. @param minVersion the expected minimum version, if any. @param maxVersion the expected maximum version, if any. @return whether the actual JDBC driver name and version match the provided arguments. The min and max version comparisons are inclusive. @throws SQLException if an error occurs fetching metadata containing the JDBC driver name and version from the database.
[ "Compares", "JDBC", "driver", "name", "and", "version", "information", "to", "that", "reported", "by", "the", "driver", "." ]
train
https://github.com/eurekaclinical/javautil/blob/779bbc5bf096c75f8eed4f99ca45b99c1d44df43/src/main/java/org/arp/javautil/sql/DatabaseMetaDataWrapper.java#L95-L102
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.isSameInstant
public static boolean isSameInstant(final Date date1, final Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } return date1.getTime() == date2.getTime(); }
java
public static boolean isSameInstant(final Date date1, final Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } return date1.getTime() == date2.getTime(); }
[ "public", "static", "boolean", "isSameInstant", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ")", "{", "if", "(", "date1", "==", "null", "||", "date2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The date must...
<p>Checks if two date objects represent the same instant in time.</p> <p>This method compares the long millisecond time of the two objects.</p> @param date1 the first date, not altered, not null @param date2 the second date, not altered, not null @return true if they represent the same millisecond instant @throws IllegalArgumentException if either date is <code>null</code> @since 2.1
[ "<p", ">", "Checks", "if", "two", "date", "objects", "represent", "the", "same", "instant", "in", "time", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L213-L218
mkotsur/restito
src/main/java/com/xebialabs/restito/resources/SmartDiscoverer.java
SmartDiscoverer.discoverResource
public URL discoverResource(Method m, String uri) { for (String s : possibleLocations(m, uri)) { try { URL resource = this.getClass().getClassLoader().getResource(resourcePrefix + "/" + URLDecoder.decode(s, UTF_8)); if (resource == null) { throw new IllegalArgumentException(String.format("Resource %s not found.", uri)); } if (!new File(URLDecoder.decode(resource.getFile(), UTF_8)).isFile()) { continue; // Probably directory } return resource; } catch (IllegalArgumentException ignored) { } // just go on } throw new IllegalArgumentException(String.format("Can not discover resource for method [%s] and URI [%s]", m, uri)); }
java
public URL discoverResource(Method m, String uri) { for (String s : possibleLocations(m, uri)) { try { URL resource = this.getClass().getClassLoader().getResource(resourcePrefix + "/" + URLDecoder.decode(s, UTF_8)); if (resource == null) { throw new IllegalArgumentException(String.format("Resource %s not found.", uri)); } if (!new File(URLDecoder.decode(resource.getFile(), UTF_8)).isFile()) { continue; // Probably directory } return resource; } catch (IllegalArgumentException ignored) { } // just go on } throw new IllegalArgumentException(String.format("Can not discover resource for method [%s] and URI [%s]", m, uri)); }
[ "public", "URL", "discoverResource", "(", "Method", "m", ",", "String", "uri", ")", "{", "for", "(", "String", "s", ":", "possibleLocations", "(", "m", ",", "uri", ")", ")", "{", "try", "{", "URL", "resource", "=", "this", ".", "getClass", "(", ")", ...
Discovers resource based on request Tries different options: <ul> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get.asd.bsd.asd</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get/asd/bsd/asd</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd.bsd.asd</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd/bsd/asd</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get.asd.bsd.asd.xml</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get/asd/bsd/asd.xml</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd.bsd.asd.xml</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd/bsd/asd.xml</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get.asd.bsd.asd.json</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/get/asd/bsd/asd.json</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd.bsd.asd.json</li> <li>GET asd/bsd/asd - resource: {resourcePrefix}/asd/bsd/asd.json</li> </ul>
[ "Discovers", "resource", "based", "on", "request", "Tries", "different", "options", ":", "<ul", ">", "<li", ">", "GET", "asd", "/", "bsd", "/", "asd", "-", "resource", ":", "{", "resourcePrefix", "}", "/", "get", ".", "asd", ".", "bsd", ".", "asd<", ...
train
https://github.com/mkotsur/restito/blob/b999293616ca84fdea1ffe929e92a5db29c7e415/src/main/java/com/xebialabs/restito/resources/SmartDiscoverer.java#L49-L65
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java
Indices.linearOffset
public static long linearOffset(int index, INDArray arr) { if (arr.ordering() == NDArrayFactory.C) { double otherTest = ((double) index) % arr.size(-1); int test = (int) Math.floor(otherTest); INDArray vec = arr.vectorAlongDimension(test, -1); long otherDim = arr.vectorAlongDimension(test, -1).offset() + index; return otherDim; } else { int majorStride = arr.stride(-2); long vectorsAlongDimension = arr.vectorsAlongDimension(-1); double rowCalc = (double) (index * majorStride) / (double) arr.length(); int floor = (int) Math.floor(rowCalc); INDArray arrVector = arr.vectorAlongDimension(floor, -1); long columnIndex = index % arr.size(-1); long retOffset = arrVector.linearIndex(columnIndex); return retOffset; } }
java
public static long linearOffset(int index, INDArray arr) { if (arr.ordering() == NDArrayFactory.C) { double otherTest = ((double) index) % arr.size(-1); int test = (int) Math.floor(otherTest); INDArray vec = arr.vectorAlongDimension(test, -1); long otherDim = arr.vectorAlongDimension(test, -1).offset() + index; return otherDim; } else { int majorStride = arr.stride(-2); long vectorsAlongDimension = arr.vectorsAlongDimension(-1); double rowCalc = (double) (index * majorStride) / (double) arr.length(); int floor = (int) Math.floor(rowCalc); INDArray arrVector = arr.vectorAlongDimension(floor, -1); long columnIndex = index % arr.size(-1); long retOffset = arrVector.linearIndex(columnIndex); return retOffset; } }
[ "public", "static", "long", "linearOffset", "(", "int", "index", ",", "INDArray", "arr", ")", "{", "if", "(", "arr", ".", "ordering", "(", ")", "==", "NDArrayFactory", ".", "C", ")", "{", "double", "otherTest", "=", "(", "(", "double", ")", "index", ...
Compute the linear offset for an index in an ndarray. For c ordering this is just the index itself. For fortran ordering, the following algorithm is used. Assuming an ndarray is a list of vectors. The index of the vector relative to the given index is calculated. vectorAlongDimension is then used along the last dimension using the computed index. The offset + the computed column wrt the index: (index % the size of the last dimension) will render the given index in fortran ordering @param index the index @param arr the array @return the linear offset
[ "Compute", "the", "linear", "offset", "for", "an", "index", "in", "an", "ndarray", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java#L89-L111
code4everything/util
src/main/java/com/zhazhapan/util/dialog/Alerts.java
Alerts.showError
public static Optional<ButtonType> showError(String title, String content) { return showError(title, null, content); }
java
public static Optional<ButtonType> showError(String title, String content) { return showError(title, null, content); }
[ "public", "static", "Optional", "<", "ButtonType", ">", "showError", "(", "String", "title", ",", "String", "content", ")", "{", "return", "showError", "(", "title", ",", "null", ",", "content", ")", ";", "}" ]
弹出错误框 @param title 标题 @param content 内容 @return {@link ButtonType}
[ "弹出错误框" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/dialog/Alerts.java#L82-L84
w3c/epubcheck
src/main/java/com/adobe/epubcheck/messages/LocalizedMessages.java
LocalizedMessages.getMessage
public Message getMessage(MessageId id) { // Performance note: this method uses a lazy initialization pattern. When // a MessageId is first requested, we fetch the data from the ResourceBundle // and create a new Message object, which is then cached. On the next // request, we'll use the cached version instead. Message message; if (cachedMessages.containsKey(id)) { message = cachedMessages.get(id); } else { message = new Message(id, defaultSeverities.get(id), getMessageAsString(id), getSuggestion(id)); cachedMessages.put(id, message); } return message; }
java
public Message getMessage(MessageId id) { // Performance note: this method uses a lazy initialization pattern. When // a MessageId is first requested, we fetch the data from the ResourceBundle // and create a new Message object, which is then cached. On the next // request, we'll use the cached version instead. Message message; if (cachedMessages.containsKey(id)) { message = cachedMessages.get(id); } else { message = new Message(id, defaultSeverities.get(id), getMessageAsString(id), getSuggestion(id)); cachedMessages.put(id, message); } return message; }
[ "public", "Message", "getMessage", "(", "MessageId", "id", ")", "{", "// Performance note: this method uses a lazy initialization pattern. When", "// a MessageId is first requested, we fetch the data from the ResourceBundle", "// and create a new Message object, which is then cached. On the next...
Gets the message for the given id. @param id @return A Message object, using the localized string if necessary.
[ "Gets", "the", "message", "for", "the", "given", "id", "." ]
train
https://github.com/w3c/epubcheck/blob/4d5a24d9f2878a2a5497eb11c036cc18fe2c0a78/src/main/java/com/adobe/epubcheck/messages/LocalizedMessages.java#L84-L102
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java
PolylineSplitMerge.removeCornerAndSavePolyline
boolean removeCornerAndSavePolyline( Element<Corner> corner, double sideErrorAfterRemoved ) { // System.out.println("removing a corner idx="+target.object.index); // Note: the corner is "lost" until the next contour is fit. Not worth the effort to recycle Element<Corner> p = previous(corner); // go through the hassle of passing in this value instead of recomputing it // since recomputing it isn't trivial p.object.sideError = sideErrorAfterRemoved; list.remove(corner); // the line below is commented out because right now the current algorithm will // never grow after removing a corner. If this changes in the future uncomment it // computePotentialSplitScore(contour,p); return savePolyline(); }
java
boolean removeCornerAndSavePolyline( Element<Corner> corner, double sideErrorAfterRemoved ) { // System.out.println("removing a corner idx="+target.object.index); // Note: the corner is "lost" until the next contour is fit. Not worth the effort to recycle Element<Corner> p = previous(corner); // go through the hassle of passing in this value instead of recomputing it // since recomputing it isn't trivial p.object.sideError = sideErrorAfterRemoved; list.remove(corner); // the line below is commented out because right now the current algorithm will // never grow after removing a corner. If this changes in the future uncomment it // computePotentialSplitScore(contour,p); return savePolyline(); }
[ "boolean", "removeCornerAndSavePolyline", "(", "Element", "<", "Corner", ">", "corner", ",", "double", "sideErrorAfterRemoved", ")", "{", "//\t\t\tSystem.out.println(\"removing a corner idx=\"+target.object.index);", "// Note: the corner is \"lost\" until the next contour is fit. Not wor...
Remove the corner from the current polyline. If the new polyline has a better score than the currently saved one with the same number of corners save it @param corner The corner to removed
[ "Remove", "the", "corner", "from", "the", "current", "polyline", ".", "If", "the", "new", "polyline", "has", "a", "better", "score", "than", "the", "currently", "saved", "one", "with", "the", "same", "number", "of", "corners", "save", "it" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/PolylineSplitMerge.java#L550-L563
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java
MultiMEProxyHandler.linkStarted
public void linkStarted(String busId, SIBUuid8 meUuid) throws SIIncorrectCallException, SIErrorException, SIDiscriminatorSyntaxException, SISelectorSyntaxException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "linkStarted", new Object[] {busId, meUuid}); // Look for existing neighbour for the link Neighbour neighbour = getNeighbour(meUuid); if (neighbour == null) { // If the neighbour doesn't exist then create it now. LocalTransaction tran = _transactionManager.createLocalTransaction(true); neighbour = createNeighbour(meUuid, busId, (Transaction) tran); tran.commit(); } // Reset the list of subscriptions _neighbours.resetBusSubscriptionList(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "linkStarted"); }
java
public void linkStarted(String busId, SIBUuid8 meUuid) throws SIIncorrectCallException, SIErrorException, SIDiscriminatorSyntaxException, SISelectorSyntaxException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "linkStarted", new Object[] {busId, meUuid}); // Look for existing neighbour for the link Neighbour neighbour = getNeighbour(meUuid); if (neighbour == null) { // If the neighbour doesn't exist then create it now. LocalTransaction tran = _transactionManager.createLocalTransaction(true); neighbour = createNeighbour(meUuid, busId, (Transaction) tran); tran.commit(); } // Reset the list of subscriptions _neighbours.resetBusSubscriptionList(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "linkStarted"); }
[ "public", "void", "linkStarted", "(", "String", "busId", ",", "SIBUuid8", "meUuid", ")", "throws", "SIIncorrectCallException", ",", "SIErrorException", ",", "SIDiscriminatorSyntaxException", ",", "SISelectorSyntaxException", ",", "SIResourceException", "{", "if", "(", "...
When a Link is started we want to send a reset message to the neighbouring bus. If the neighbour was not found, then create it here as we don't want to start sending messages to it until the link has started. @param String The name of the foreign bus @param SIBUuid8 The uuid of the link localising ME on the foreign bus
[ "When", "a", "Link", "is", "started", "we", "want", "to", "send", "a", "reset", "message", "to", "the", "neighbouring", "bus", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/proxyhandler/MultiMEProxyHandler.java#L858-L885
landawn/AbacusUtil
src/com/landawn/abacus/util/Primitives.java
Primitives.unbox
public static double[] unbox(final Double[] a, final double valueForNull) { if (a == null) { return null; } return unbox(a, 0, a.length, valueForNull); }
java
public static double[] unbox(final Double[] a, final double valueForNull) { if (a == null) { return null; } return unbox(a, 0, a.length, valueForNull); }
[ "public", "static", "double", "[", "]", "unbox", "(", "final", "Double", "[", "]", "a", ",", "final", "double", "valueForNull", ")", "{", "if", "(", "a", "==", "null", ")", "{", "return", "null", ";", "}", "return", "unbox", "(", "a", ",", "0", "...
<p> Converts an array of object Doubles to primitives handling {@code null}. </p> <p> This method returns {@code null} for a {@code null} input array. </p> @param a a {@code Double} array, may be {@code null} @param valueForNull the value to insert if {@code null} found @return a {@code double} array, {@code null} if null array input
[ "<p", ">", "Converts", "an", "array", "of", "object", "Doubles", "to", "primitives", "handling", "{", "@code", "null", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Primitives.java#L1196-L1202
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.rotateYXZ
public Matrix4d rotateYXZ(Vector3d angles) { return rotateYXZ(angles.y, angles.x, angles.z); }
java
public Matrix4d rotateYXZ(Vector3d angles) { return rotateYXZ(angles.y, angles.x, angles.z); }
[ "public", "Matrix4d", "rotateYXZ", "(", "Vector3d", "angles", ")", "{", "return", "rotateYXZ", "(", "angles", ".", "y", ",", "angles", ".", "x", ",", "angles", ".", "z", ")", ";", "}" ]
Apply rotation of <code>angles.y</code> radians about the Y axis, followed by a rotation of <code>angles.x</code> radians about the X axis and followed by a rotation of <code>angles.z</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> This method is equivalent to calling: <code>rotateY(angles.y).rotateX(angles.x).rotateZ(angles.z)</code> @param angles the Euler angles @return this
[ "Apply", "rotation", "of", "<code", ">", "angles", ".", "y<", "/", "code", ">", "radians", "about", "the", "Y", "axis", "followed", "by", "a", "rotation", "of", "<code", ">", "angles", ".", "x<", "/", "code", ">", "radians", "about", "the", "X", "axi...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L6617-L6619
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.neq
public SDVariable neq(String name, SDVariable x, double y) { validateNumerical("not equals (neq)", x); SDVariable result = f().neq(x, y); return updateVariableNameAndReference(result, name); }
java
public SDVariable neq(String name, SDVariable x, double y) { validateNumerical("not equals (neq)", x); SDVariable result = f().neq(x, y); return updateVariableNameAndReference(result, name); }
[ "public", "SDVariable", "neq", "(", "String", "name", ",", "SDVariable", "x", ",", "double", "y", ")", "{", "validateNumerical", "(", "\"not equals (neq)\"", ",", "x", ")", ";", "SDVariable", "result", "=", "f", "(", ")", ".", "neq", "(", "x", ",", "y"...
Not equals operation: elementwise x != y<br> Returns an array with the same shape/size as the input, with values 1 where condition is satisfied, or value 0 otherwise @param name Name of the output variable @param x Input array @param y Double value argument to use in operation @return Output SDVariable with values 0 and 1 based on where the condition is satisfied
[ "Not", "equals", "operation", ":", "elementwise", "x", "!", "=", "y<br", ">", "Returns", "an", "array", "with", "the", "same", "shape", "/", "size", "as", "the", "input", "with", "values", "1", "where", "condition", "is", "satisfied", "or", "value", "0",...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L1307-L1311
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.squaredNorm
public SDVariable squaredNorm(SDVariable x, boolean keepDims, int... dimensions) { return squaredNorm(null, x, keepDims, dimensions); }
java
public SDVariable squaredNorm(SDVariable x, boolean keepDims, int... dimensions) { return squaredNorm(null, x, keepDims, dimensions); }
[ "public", "SDVariable", "squaredNorm", "(", "SDVariable", "x", ",", "boolean", "keepDims", ",", "int", "...", "dimensions", ")", "{", "return", "squaredNorm", "(", "null", ",", "x", ",", "keepDims", ",", "dimensions", ")", ";", "}" ]
Squared L2 norm: see {@link #norm2(String, SDVariable, boolean, int...)}
[ "Squared", "L2", "norm", ":", "see", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L2513-L2515
googleapis/cloud-bigtable-client
bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/config/BigtableVeneerSettingsFactory.java
BigtableVeneerSettingsFactory.buildCredentialProvider
private static CredentialsProvider buildCredentialProvider( CredentialOptions credentialOptions) throws IOException { try { final Credentials credentials = CredentialFactory.getCredentials(credentialOptions); if (credentials == null) { LOG.info("Enabling the use of null credentials. This should not be used in production."); return NoCredentialsProvider.create(); } return FixedCredentialsProvider.create(credentials); } catch (GeneralSecurityException exception) { throw new IOException("Could not initialize credentials.", exception); } }
java
private static CredentialsProvider buildCredentialProvider( CredentialOptions credentialOptions) throws IOException { try { final Credentials credentials = CredentialFactory.getCredentials(credentialOptions); if (credentials == null) { LOG.info("Enabling the use of null credentials. This should not be used in production."); return NoCredentialsProvider.create(); } return FixedCredentialsProvider.create(credentials); } catch (GeneralSecurityException exception) { throw new IOException("Could not initialize credentials.", exception); } }
[ "private", "static", "CredentialsProvider", "buildCredentialProvider", "(", "CredentialOptions", "credentialOptions", ")", "throws", "IOException", "{", "try", "{", "final", "Credentials", "credentials", "=", "CredentialFactory", ".", "getCredentials", "(", "credentialOptio...
Creates {@link CredentialsProvider} based on {@link CredentialOptions}.
[ "Creates", "{" ]
train
https://github.com/googleapis/cloud-bigtable-client/blob/53543f36e4d6f9ed1963640d91a35be2a2047656/bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/config/BigtableVeneerSettingsFactory.java#L146-L159
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.writeStringToTempFileNoExceptions
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; File tmp = null; try{ tmp = File.createTempFile(path,".tmp"); if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(tmp)); } else { writer = new BufferedOutputStream(new FileOutputStream(tmp)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { e.printStackTrace(); } finally { if(writer != null){ closeIgnoringExceptions(writer); } } return tmp; }
java
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; File tmp = null; try{ tmp = File.createTempFile(path,".tmp"); if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(tmp)); } else { writer = new BufferedOutputStream(new FileOutputStream(tmp)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { e.printStackTrace(); } finally { if(writer != null){ closeIgnoringExceptions(writer); } } return tmp; }
[ "public", "static", "File", "writeStringToTempFileNoExceptions", "(", "String", "contents", ",", "String", "path", ",", "String", "encoding", ")", "{", "OutputStream", "writer", "=", "null", ";", "File", "tmp", "=", "null", ";", "try", "{", "tmp", "=", "File...
Writes a string to a temporary file, squashing exceptions @param contents The string to write @param path The file path @param encoding The encoding to encode in
[ "Writes", "a", "string", "to", "a", "temporary", "file", "squashing", "exceptions" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L255-L272
Stratio/stratio-cassandra
src/java/org/apache/cassandra/streaming/StreamPlan.java
StreamPlan.requestRanges
public StreamPlan requestRanges(InetAddress from, InetAddress connecting, String keyspace, Collection<Range<Token>> ranges, String... columnFamilies) { StreamSession session = coordinator.getOrCreateNextSession(from, connecting); session.addStreamRequest(keyspace, ranges, Arrays.asList(columnFamilies), repairedAt); return this; }
java
public StreamPlan requestRanges(InetAddress from, InetAddress connecting, String keyspace, Collection<Range<Token>> ranges, String... columnFamilies) { StreamSession session = coordinator.getOrCreateNextSession(from, connecting); session.addStreamRequest(keyspace, ranges, Arrays.asList(columnFamilies), repairedAt); return this; }
[ "public", "StreamPlan", "requestRanges", "(", "InetAddress", "from", ",", "InetAddress", "connecting", ",", "String", "keyspace", ",", "Collection", "<", "Range", "<", "Token", ">", ">", "ranges", ",", "String", "...", "columnFamilies", ")", "{", "StreamSession"...
Request data in {@code columnFamilies} under {@code keyspace} and {@code ranges} from specific node. @param from endpoint address to fetch data from. @param connecting Actual connecting address for the endpoint @param keyspace name of keyspace @param ranges ranges to fetch @param columnFamilies specific column families @return this object for chaining
[ "Request", "data", "in", "{", "@code", "columnFamilies", "}", "under", "{", "@code", "keyspace", "}", "and", "{", "@code", "ranges", "}", "from", "specific", "node", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/streaming/StreamPlan.java#L86-L91
ops4j/org.ops4j.pax.web
pax-web-runtime/src/main/java/org/ops4j/pax/web/service/internal/Activator.java
Activator.createManagedServiceFactory
private void createManagedServiceFactory(BundleContext context) { // sanity check if (managedServiceFactoryReg != null) { managedServiceFactoryReg.unregister(); managedServiceFactoryReg = null; } final Dictionary<String, String> props = new Hashtable<>(); props.put(Constants.SERVICE_PID, HttpContextProcessing.PID); httpContextProcessing = new HttpContextProcessing(bundleContext, serverController); managedServiceFactoryReg = context.registerService(ManagedServiceFactory.class, httpContextProcessing, props); }
java
private void createManagedServiceFactory(BundleContext context) { // sanity check if (managedServiceFactoryReg != null) { managedServiceFactoryReg.unregister(); managedServiceFactoryReg = null; } final Dictionary<String, String> props = new Hashtable<>(); props.put(Constants.SERVICE_PID, HttpContextProcessing.PID); httpContextProcessing = new HttpContextProcessing(bundleContext, serverController); managedServiceFactoryReg = context.registerService(ManagedServiceFactory.class, httpContextProcessing, props); }
[ "private", "void", "createManagedServiceFactory", "(", "BundleContext", "context", ")", "{", "// sanity check", "if", "(", "managedServiceFactoryReg", "!=", "null", ")", "{", "managedServiceFactoryReg", ".", "unregister", "(", ")", ";", "managedServiceFactoryReg", "=", ...
Registers a managed service factory to create {@link org.osgi.service.http.HttpContext} <em>processors</em> - these will possibly register additional web items (like login configurations or filters) for shared or per-bundle http services. @param context
[ "Registers", "a", "managed", "service", "factory", "to", "create", "{", "@link", "org", ".", "osgi", ".", "service", ".", "http", ".", "HttpContext", "}", "<em", ">", "processors<", "/", "em", ">", "-", "these", "will", "possibly", "register", "additional"...
train
https://github.com/ops4j/org.ops4j.pax.web/blob/9ecf3676c1d316be0d43ea7fcfdc8f0defffc2a2/pax-web-runtime/src/main/java/org/ops4j/pax/web/service/internal/Activator.java#L286-L296
gallandarakhneorg/afc
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/Segment3ifx.java
Segment3ifx.z2Property
@Pure public IntegerProperty z2Property() { if (this.p2.z == null) { this.p2.z = new SimpleIntegerProperty(this, MathFXAttributeNames.Z2); } return this.p2.z; }
java
@Pure public IntegerProperty z2Property() { if (this.p2.z == null) { this.p2.z = new SimpleIntegerProperty(this, MathFXAttributeNames.Z2); } return this.p2.z; }
[ "@", "Pure", "public", "IntegerProperty", "z2Property", "(", ")", "{", "if", "(", "this", ".", "p2", ".", "z", "==", "null", ")", "{", "this", ".", "p2", ".", "z", "=", "new", "SimpleIntegerProperty", "(", "this", ",", "MathFXAttributeNames", ".", "Z2"...
Replies the property that is the z coordinate of the second segment point. @return the z2 property.
[ "Replies", "the", "property", "that", "is", "the", "z", "coordinate", "of", "the", "second", "segment", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/Segment3ifx.java#L294-L300
j256/ormlite-core
src/main/java/com/j256/ormlite/stmt/StatementExecutor.java
StatementExecutor.queryForAll
public List<T> queryForAll(ConnectionSource connectionSource, ObjectCache objectCache) throws SQLException { prepareQueryForAll(); return query(connectionSource, preparedQueryForAll, objectCache); }
java
public List<T> queryForAll(ConnectionSource connectionSource, ObjectCache objectCache) throws SQLException { prepareQueryForAll(); return query(connectionSource, preparedQueryForAll, objectCache); }
[ "public", "List", "<", "T", ">", "queryForAll", "(", "ConnectionSource", "connectionSource", ",", "ObjectCache", "objectCache", ")", "throws", "SQLException", "{", "prepareQueryForAll", "(", ")", ";", "return", "query", "(", "connectionSource", ",", "preparedQueryFo...
Return a list of all of the data in the table. Should be used carefully if the table is large. Consider using the {@link Dao#iterator} if this is the case.
[ "Return", "a", "list", "of", "all", "of", "the", "data", "in", "the", "table", ".", "Should", "be", "used", "carefully", "if", "the", "table", "is", "large", ".", "Consider", "using", "the", "{" ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/StatementExecutor.java#L124-L127
op4j/op4j
src/main/java/org/op4j/functions/FnString.java
FnString.toLong
public static final Function<String,Long> toLong(final RoundingMode roundingMode, final Locale locale) { return new ToLong(roundingMode, locale); }
java
public static final Function<String,Long> toLong(final RoundingMode roundingMode, final Locale locale) { return new ToLong(roundingMode, locale); }
[ "public", "static", "final", "Function", "<", "String", ",", "Long", ">", "toLong", "(", "final", "RoundingMode", "roundingMode", ",", "final", "Locale", "locale", ")", "{", "return", "new", "ToLong", "(", "roundingMode", ",", "locale", ")", ";", "}" ]
<p> Converts a String into a Long, using the specified locale for determining decimal point. Rounding mode is used for removing the decimal part of the number. The integer part of the input string must be between {@link Long#MIN_VALUE} and {@link Long#MAX_VALUE} </p> @param roundingMode the rounding mode to be used when setting the scale @param locale the locale defining the way in which the number was written @return the resulting Long object
[ "<p", ">", "Converts", "a", "String", "into", "a", "Long", "using", "the", "specified", "locale", "for", "determining", "decimal", "point", ".", "Rounding", "mode", "is", "used", "for", "removing", "the", "decimal", "part", "of", "the", "number", ".", "The...
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/FnString.java#L806-L808
sahan/RoboZombie
robozombie/src/main/java/org/apache/http42/client/utils/URIBuilder.java
URIBuilder.setParameter
public URIBuilder setParameter(final String param, final String value) { if (this.queryParams == null) { this.queryParams = new ArrayList<NameValuePair>(); } if (!this.queryParams.isEmpty()) { for (Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) { NameValuePair nvp = it.next(); if (nvp.getName().equals(param)) { it.remove(); } } } this.queryParams.add(new BasicNameValuePair(param, value)); this.encodedQuery = null; this.encodedSchemeSpecificPart = null; return this; }
java
public URIBuilder setParameter(final String param, final String value) { if (this.queryParams == null) { this.queryParams = new ArrayList<NameValuePair>(); } if (!this.queryParams.isEmpty()) { for (Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) { NameValuePair nvp = it.next(); if (nvp.getName().equals(param)) { it.remove(); } } } this.queryParams.add(new BasicNameValuePair(param, value)); this.encodedQuery = null; this.encodedSchemeSpecificPart = null; return this; }
[ "public", "URIBuilder", "setParameter", "(", "final", "String", "param", ",", "final", "String", "value", ")", "{", "if", "(", "this", ".", "queryParams", "==", "null", ")", "{", "this", ".", "queryParams", "=", "new", "ArrayList", "<", "NameValuePair", ">...
Sets parameter of URI query overriding existing value if set. The parameter name and value are expected to be unescaped and may contain non ASCII characters.
[ "Sets", "parameter", "of", "URI", "query", "overriding", "existing", "value", "if", "set", ".", "The", "parameter", "name", "and", "value", "are", "expected", "to", "be", "unescaped", "and", "may", "contain", "non", "ASCII", "characters", "." ]
train
https://github.com/sahan/RoboZombie/blob/2e02f0d41647612e9d89360c5c48811ea86b33c8/robozombie/src/main/java/org/apache/http42/client/utils/URIBuilder.java#L283-L299
alipay/sofa-hessian
src/main/java/com/caucho/hessian/io/HessianOutput.java
HessianOutput.printString
public void printString(String v, int offset, int length) throws IOException { for (int i = 0; i < length; i++) { char ch = v.charAt(i + offset); if (ch < 0x80) os.write(ch); else if (ch < 0x800) { os.write(0xc0 + ((ch >> 6) & 0x1f)); os.write(0x80 + (ch & 0x3f)); } else { os.write(0xe0 + ((ch >> 12) & 0xf)); os.write(0x80 + ((ch >> 6) & 0x3f)); os.write(0x80 + (ch & 0x3f)); } } }
java
public void printString(String v, int offset, int length) throws IOException { for (int i = 0; i < length; i++) { char ch = v.charAt(i + offset); if (ch < 0x80) os.write(ch); else if (ch < 0x800) { os.write(0xc0 + ((ch >> 6) & 0x1f)); os.write(0x80 + (ch & 0x3f)); } else { os.write(0xe0 + ((ch >> 12) & 0xf)); os.write(0x80 + ((ch >> 6) & 0x3f)); os.write(0x80 + (ch & 0x3f)); } } }
[ "public", "void", "printString", "(", "String", "v", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "char", "ch", "=", "v", ".", ...
Prints a string to the stream, encoded as UTF-8 @param v the string to print.
[ "Prints", "a", "string", "to", "the", "stream", "encoded", "as", "UTF", "-", "8" ]
train
https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/caucho/hessian/io/HessianOutput.java#L915-L933
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2InboundLink.java
H2InboundLink.handleHTTP2AlpnConnect
public boolean handleHTTP2AlpnConnect(HttpInboundLink link) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "handleHTTP2AlpnConnect entry"); } initialHttpInboundLink = link; Integer streamID = new Integer(0); H2VirtualConnectionImpl h2VC = new H2VirtualConnectionImpl(initialVC); // remove the HttpDispatcherLink from the map, so a new one will be created and used by this new H2 stream h2VC.getStateMap().remove(HttpDispatcherLink.LINK_ID); H2HttpInboundLinkWrap wrap = new H2HttpInboundLinkWrap(httpInboundChannel, h2VC, streamID, this); // create the initial stream processor, add it to the link stream table, and add it to the write queue H2StreamProcessor streamProcessor = new H2StreamProcessor(streamID, wrap, this, StreamState.OPEN); streamTable.put(streamID, streamProcessor); writeQ.addNewNodeToQ(streamID, Node.ROOT_STREAM_ID, Node.DEFAULT_NODE_PRIORITY, false); this.setDeviceLink((ConnectionLink) myTSC); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "handleHTTP2AlpnConnect, exit"); } return true; }
java
public boolean handleHTTP2AlpnConnect(HttpInboundLink link) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "handleHTTP2AlpnConnect entry"); } initialHttpInboundLink = link; Integer streamID = new Integer(0); H2VirtualConnectionImpl h2VC = new H2VirtualConnectionImpl(initialVC); // remove the HttpDispatcherLink from the map, so a new one will be created and used by this new H2 stream h2VC.getStateMap().remove(HttpDispatcherLink.LINK_ID); H2HttpInboundLinkWrap wrap = new H2HttpInboundLinkWrap(httpInboundChannel, h2VC, streamID, this); // create the initial stream processor, add it to the link stream table, and add it to the write queue H2StreamProcessor streamProcessor = new H2StreamProcessor(streamID, wrap, this, StreamState.OPEN); streamTable.put(streamID, streamProcessor); writeQ.addNewNodeToQ(streamID, Node.ROOT_STREAM_ID, Node.DEFAULT_NODE_PRIORITY, false); this.setDeviceLink((ConnectionLink) myTSC); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "handleHTTP2AlpnConnect, exit"); } return true; }
[ "public", "boolean", "handleHTTP2AlpnConnect", "(", "HttpInboundLink", "link", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"handleHT...
Handle a connection initiated via ALPN "h2" @param link the initial inbound link @return true if the upgrade was sucessful
[ "Handle", "a", "connection", "initiated", "via", "ALPN", "h2" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2InboundLink.java#L291-L315
watchrabbit/rabbit-commons
src/main/java/com/watchrabbit/commons/sleep/Sleep.java
Sleep.sleep
public static void sleep(long timeout, TimeUnit unit) throws SystemException { suppress((Long sleepTimeout) -> Thread.sleep(sleepTimeout)) .accept(TimeUnit.MILLISECONDS.convert(timeout, unit)); }
java
public static void sleep(long timeout, TimeUnit unit) throws SystemException { suppress((Long sleepTimeout) -> Thread.sleep(sleepTimeout)) .accept(TimeUnit.MILLISECONDS.convert(timeout, unit)); }
[ "public", "static", "void", "sleep", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "SystemException", "{", "suppress", "(", "(", "Long", "sleepTimeout", ")", "->", "Thread", ".", "sleep", "(", "sleepTimeout", ")", ")", ".", "accept", "(",...
Causes the current thread to wait until the specified waiting time elapses. <p> Any {@code InterruptedException}'s are suppress and logged. Any {@code Exception}'s thrown by callable are propagate as SystemException @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @throws SystemException if callable throws exception
[ "Causes", "the", "current", "thread", "to", "wait", "until", "the", "specified", "waiting", "time", "elapses", "." ]
train
https://github.com/watchrabbit/rabbit-commons/blob/b11c9f804b5ab70b9264635c34a02f5029bd2a5d/src/main/java/com/watchrabbit/commons/sleep/Sleep.java#L42-L45
facebookarchive/hadoop-20
src/core/org/apache/hadoop/raid/ReedSolomonCode.java
ReedSolomonCode.computeSyndrome
private boolean computeSyndrome(int[] data, int [] syndrome) { boolean corruptionFound = false; for (int i = 0; i < paritySize; i++) { syndrome[i] = GF.substitute(data, primitivePower[i]); if (syndrome[i] != 0) { corruptionFound = true; } } return !corruptionFound; }
java
private boolean computeSyndrome(int[] data, int [] syndrome) { boolean corruptionFound = false; for (int i = 0; i < paritySize; i++) { syndrome[i] = GF.substitute(data, primitivePower[i]); if (syndrome[i] != 0) { corruptionFound = true; } } return !corruptionFound; }
[ "private", "boolean", "computeSyndrome", "(", "int", "[", "]", "data", ",", "int", "[", "]", "syndrome", ")", "{", "boolean", "corruptionFound", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paritySize", ";", "i", "++", ")", ...
Compute the syndrome of the input [parity, message] @param data [parity, message] @param syndrome The syndromes (checksums) of the data @return true If syndromes are all zeros
[ "Compute", "the", "syndrome", "of", "the", "input", "[", "parity", "message", "]" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/raid/ReedSolomonCode.java#L299-L308
aws/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/UpdateIdentityProviderRequest.java
UpdateIdentityProviderRequest.withProviderDetails
public UpdateIdentityProviderRequest withProviderDetails(java.util.Map<String, String> providerDetails) { setProviderDetails(providerDetails); return this; }
java
public UpdateIdentityProviderRequest withProviderDetails(java.util.Map<String, String> providerDetails) { setProviderDetails(providerDetails); return this; }
[ "public", "UpdateIdentityProviderRequest", "withProviderDetails", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "providerDetails", ")", "{", "setProviderDetails", "(", "providerDetails", ")", ";", "return", "this", ";", "}" ]
<p> The identity provider details to be updated, such as <code>MetadataURL</code> and <code>MetadataFile</code>. </p> @param providerDetails The identity provider details to be updated, such as <code>MetadataURL</code> and <code>MetadataFile</code>. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "identity", "provider", "details", "to", "be", "updated", "such", "as", "<code", ">", "MetadataURL<", "/", "code", ">", "and", "<code", ">", "MetadataFile<", "/", "code", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/UpdateIdentityProviderRequest.java#L177-L180
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java
Text.isDescendantOrEqual
public static boolean isDescendantOrEqual(String path, String descendant) { if (path.equals(descendant)) { return true; } else { String pattern = path.endsWith("/") ? path : path + "/"; return descendant.startsWith(pattern); } }
java
public static boolean isDescendantOrEqual(String path, String descendant) { if (path.equals(descendant)) { return true; } else { String pattern = path.endsWith("/") ? path : path + "/"; return descendant.startsWith(pattern); } }
[ "public", "static", "boolean", "isDescendantOrEqual", "(", "String", "path", ",", "String", "descendant", ")", "{", "if", "(", "path", ".", "equals", "(", "descendant", ")", ")", "{", "return", "true", ";", "}", "else", "{", "String", "pattern", "=", "pa...
Determines if the <code>descendant</code> path is hierarchical a descendant of <code>path</code> or equal to it. @param path the path to check @param descendant the potential descendant @return <code>true</code> if the <code>descendant</code> is a descendant or equal; <code>false</code> otherwise.
[ "Determines", "if", "the", "<code", ">", "descendant<", "/", "code", ">", "path", "is", "hierarchical", "a", "descendant", "of", "<code", ">", "path<", "/", "code", ">", "or", "equal", "to", "it", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java#L733-L744
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/utils/MiscUtil.java
MiscUtil.appendTo
public static void appendTo(Formatter formatter, int width, int precision, boolean leftJustified, String out) { try { Appendable appendable = formatter.out(); if (precision > -1 && out.length() > precision) { appendable.append(Helpers.truncate(out, precision)); return; } if (leftJustified) appendable.append(Helpers.rightPad(out, width)); else appendable.append(Helpers.leftPad(out, width)); } catch (IOException e) { throw new AssertionError(e); } }
java
public static void appendTo(Formatter formatter, int width, int precision, boolean leftJustified, String out) { try { Appendable appendable = formatter.out(); if (precision > -1 && out.length() > precision) { appendable.append(Helpers.truncate(out, precision)); return; } if (leftJustified) appendable.append(Helpers.rightPad(out, width)); else appendable.append(Helpers.leftPad(out, width)); } catch (IOException e) { throw new AssertionError(e); } }
[ "public", "static", "void", "appendTo", "(", "Formatter", "formatter", ",", "int", "width", ",", "int", "precision", ",", "boolean", "leftJustified", ",", "String", "out", ")", "{", "try", "{", "Appendable", "appendable", "=", "formatter", ".", "out", "(", ...
Can be used to append a String to a formatter. @param formatter The {@link java.util.Formatter Formatter} @param width Minimum width to meet, filled with space if needed @param precision Maximum amount of characters to append @param leftJustified Whether or not to left-justify the value @param out The String to append
[ "Can", "be", "used", "to", "append", "a", "String", "to", "a", "formatter", "." ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/utils/MiscUtil.java#L267-L287
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/wan/impl/DistributedServiceWanEventCounters.java
DistributedServiceWanEventCounters.incrementSync
public void incrementSync(String distributedObjectName, int count) { getOrPutIfAbsent(eventCounterMap, distributedObjectName, EVENT_COUNTER_CONSTRUCTOR_FN) .incrementSyncCount(count); }
java
public void incrementSync(String distributedObjectName, int count) { getOrPutIfAbsent(eventCounterMap, distributedObjectName, EVENT_COUNTER_CONSTRUCTOR_FN) .incrementSyncCount(count); }
[ "public", "void", "incrementSync", "(", "String", "distributedObjectName", ",", "int", "count", ")", "{", "getOrPutIfAbsent", "(", "eventCounterMap", ",", "distributedObjectName", ",", "EVENT_COUNTER_CONSTRUCTOR_FN", ")", ".", "incrementSyncCount", "(", "count", ")", ...
Increment the number of sync events for the {@code distributedObjectName} by {@code count}.
[ "Increment", "the", "number", "of", "sync", "events", "for", "the", "{" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/wan/impl/DistributedServiceWanEventCounters.java#L54-L57
aol/cyclops
cyclops/src/main/java/com/oath/cyclops/util/box/MutableShort.java
MutableShort.fromExternal
public static MutableShort fromExternal(final Supplier<Short> s, final Consumer<Short> c) { return new MutableShort() { @Override public short getAsShort() { return s.get(); } @Override public Short get() { return getAsShort(); } @Override public MutableShort set(final short value) { c.accept(value); return this; } }; }
java
public static MutableShort fromExternal(final Supplier<Short> s, final Consumer<Short> c) { return new MutableShort() { @Override public short getAsShort() { return s.get(); } @Override public Short get() { return getAsShort(); } @Override public MutableShort set(final short value) { c.accept(value); return this; } }; }
[ "public", "static", "MutableShort", "fromExternal", "(", "final", "Supplier", "<", "Short", ">", "s", ",", "final", "Consumer", "<", "Short", ">", "c", ")", "{", "return", "new", "MutableShort", "(", ")", "{", "@", "Override", "public", "short", "getAsShor...
Construct a MutableShort that gets and sets an external value using the provided Supplier and Consumer e.g. <pre> {@code MutableShort mutable = MutableShort.fromExternal(()->!this.value,val->!this.value); } </pre> @param s Supplier of an external value @param c Consumer that sets an external value @return MutableShort that gets / sets an external (mutable) value
[ "Construct", "a", "MutableShort", "that", "gets", "and", "sets", "an", "external", "value", "using", "the", "provided", "Supplier", "and", "Consumer" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/com/oath/cyclops/util/box/MutableShort.java#L81-L99
ocpsoft/common
api/src/main/java/org/ocpsoft/common/util/Strings.java
Strings.areEqual
public static boolean areEqual(final String left, final String right) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } return left.equals(right); }
java
public static boolean areEqual(final String left, final String right) { if ((left == null) && (right == null)) { return true; } else if ((left == null) || (right == null)) { return false; } return left.equals(right); }
[ "public", "static", "boolean", "areEqual", "(", "final", "String", "left", ",", "final", "String", "right", ")", "{", "if", "(", "(", "left", "==", "null", ")", "&&", "(", "right", "==", "null", ")", ")", "{", "return", "true", ";", "}", "else", "i...
Return true if the given {@link String} instances are equal, or if both {@link String} instances are null.
[ "Return", "true", "if", "the", "given", "{" ]
train
https://github.com/ocpsoft/common/blob/ae926dfd6f9af278786520faee7ee3c2f1f52ca1/api/src/main/java/org/ocpsoft/common/util/Strings.java#L34-L45
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.getChildAccounts
public Accounts getChildAccounts(final String accountCode) { return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + "/child_accounts", Accounts.class, new QueryParams()); }
java
public Accounts getChildAccounts(final String accountCode) { return doGET(Account.ACCOUNT_RESOURCE + "/" + accountCode + "/child_accounts", Accounts.class, new QueryParams()); }
[ "public", "Accounts", "getChildAccounts", "(", "final", "String", "accountCode", ")", "{", "return", "doGET", "(", "Account", ".", "ACCOUNT_RESOURCE", "+", "\"/\"", "+", "accountCode", "+", "\"/child_accounts\"", ",", "Accounts", ".", "class", ",", "new", "Query...
Get Child Accounts <p> Returns information about a the child accounts of an account. @param accountCode recurly account id @return Accounts on success, null otherwise
[ "Get", "Child", "Accounts", "<p", ">", "Returns", "information", "about", "a", "the", "child", "accounts", "of", "an", "account", "." ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L361-L363
ical4j/ical4j
src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java
CalendarParserImpl.assertToken
private int assertToken(final StreamTokenizer tokeniser, Reader in, final int token) throws IOException, ParserException { int ntok = nextToken(tokeniser, in); if (ntok != token) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, tokeniser.ttype), getLineNumber(tokeniser, in)); } if (log.isDebugEnabled()) { log.debug("[" + token + "]"); } return ntok; }
java
private int assertToken(final StreamTokenizer tokeniser, Reader in, final int token) throws IOException, ParserException { int ntok = nextToken(tokeniser, in); if (ntok != token) { throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, tokeniser.ttype), getLineNumber(tokeniser, in)); } if (log.isDebugEnabled()) { log.debug("[" + token + "]"); } return ntok; }
[ "private", "int", "assertToken", "(", "final", "StreamTokenizer", "tokeniser", ",", "Reader", "in", ",", "final", "int", "token", ")", "throws", "IOException", ",", "ParserException", "{", "int", "ntok", "=", "nextToken", "(", "tokeniser", ",", "in", ")", ";...
Asserts that the next token in the stream matches the specified token. @param tokeniser stream tokeniser to perform assertion on @param token expected token @return int value of the ttype field of the tokeniser @throws IOException when unable to read from stream @throws ParserException when next token in the stream does not match the expected token
[ "Asserts", "that", "the", "next", "token", "in", "the", "stream", "matches", "the", "specified", "token", "." ]
train
https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java#L462-L474
m9aertner/PBKDF2
src/main/java/de/rtner/security/auth/spi/SimplePBKDF2.java
SimplePBKDF2.verifyKeyFormatted
public boolean verifyKeyFormatted(String formatted, String candidatePassword) { // Parameter as member of Engine was not the smartest design decision back then... PBKDF2Parameters p = getParameters(); PBKDF2Parameters q = new PBKDF2Parameters(); q.hashAlgorithm = p.hashAlgorithm; q.hashCharset = p.hashCharset; boolean verifyOK = false; if (!getFormatter().fromString(q, formatted)) { try { setParameters(q); verifyOK = verifyKey(candidatePassword); } finally { setParameters(p); } } return verifyOK; }
java
public boolean verifyKeyFormatted(String formatted, String candidatePassword) { // Parameter as member of Engine was not the smartest design decision back then... PBKDF2Parameters p = getParameters(); PBKDF2Parameters q = new PBKDF2Parameters(); q.hashAlgorithm = p.hashAlgorithm; q.hashCharset = p.hashCharset; boolean verifyOK = false; if (!getFormatter().fromString(q, formatted)) { try { setParameters(q); verifyOK = verifyKey(candidatePassword); } finally { setParameters(p); } } return verifyOK; }
[ "public", "boolean", "verifyKeyFormatted", "(", "String", "formatted", ",", "String", "candidatePassword", ")", "{", "// Parameter as member of Engine was not the smartest design decision back then...", "PBKDF2Parameters", "p", "=", "getParameters", "(", ")", ";", "PBKDF2Parame...
Verification function. @param formatted &quot;salt:iteration-count:derived-key&quot; (depends on effective formatter). This value should come from server-side storage. @param candidatePassword The password that is checked against the formatted reference data. This value will usually be supplied by the &quot;user&quot; or &quot;client&quot;. @return <code>true</code> verification OK. <code>false</code> verification failed or formatter unable to decode input value as PBKDF2 parameters.
[ "Verification", "function", "." ]
train
https://github.com/m9aertner/PBKDF2/blob/b84511bb78848106c0f778136d9f01870c957722/src/main/java/de/rtner/security/auth/spi/SimplePBKDF2.java#L154-L170
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java
DiagnosticsInner.listSiteDetectorResponsesSlotWithServiceResponseAsync
public Observable<ServiceResponse<Page<DetectorResponseInner>>> listSiteDetectorResponsesSlotWithServiceResponseAsync(final String resourceGroupName, final String siteName, final String slot) { return listSiteDetectorResponsesSlotSinglePageAsync(resourceGroupName, siteName, slot) .concatMap(new Func1<ServiceResponse<Page<DetectorResponseInner>>, Observable<ServiceResponse<Page<DetectorResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<DetectorResponseInner>>> call(ServiceResponse<Page<DetectorResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listSiteDetectorResponsesSlotNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<DetectorResponseInner>>> listSiteDetectorResponsesSlotWithServiceResponseAsync(final String resourceGroupName, final String siteName, final String slot) { return listSiteDetectorResponsesSlotSinglePageAsync(resourceGroupName, siteName, slot) .concatMap(new Func1<ServiceResponse<Page<DetectorResponseInner>>, Observable<ServiceResponse<Page<DetectorResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<DetectorResponseInner>>> call(ServiceResponse<Page<DetectorResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listSiteDetectorResponsesSlotNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "DetectorResponseInner", ">", ">", ">", "listSiteDetectorResponsesSlotWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "siteName", ",", "final", "String", "s...
List Site Detector Responses. List Site Detector Responses. @param resourceGroupName Name of the resource group to which the resource belongs. @param siteName Site Name @param slot Slot Name @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;DetectorResponseInner&gt; object
[ "List", "Site", "Detector", "Responses", ".", "List", "Site", "Detector", "Responses", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/DiagnosticsInner.java#L2108-L2120
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/CommonSteps.java
CommonSteps.waitStalenessOf
@Conditioned @Lorsque("Je patiente la disparition de '(.*)-(.*)' avec un timeout de '(.*)' secondes[\\.|\\?]") @Then("I wait staleness of '(.*)-(.*)' with timeout of '(.*)' seconds[\\.|\\?]") public void waitStalenessOf(String page, String element, int time, List<GherkinStepCondition> conditions) throws TechnicalException { final WebElement we = Utilities.findElement(Page.getInstance(page).getPageElementByKey('-' + element)); Context.waitUntil(ExpectedConditions.stalenessOf(we), time); }
java
@Conditioned @Lorsque("Je patiente la disparition de '(.*)-(.*)' avec un timeout de '(.*)' secondes[\\.|\\?]") @Then("I wait staleness of '(.*)-(.*)' with timeout of '(.*)' seconds[\\.|\\?]") public void waitStalenessOf(String page, String element, int time, List<GherkinStepCondition> conditions) throws TechnicalException { final WebElement we = Utilities.findElement(Page.getInstance(page).getPageElementByKey('-' + element)); Context.waitUntil(ExpectedConditions.stalenessOf(we), time); }
[ "@", "Conditioned", "@", "Lorsque", "(", "\"Je patiente la disparition de '(.*)-(.*)' avec un timeout de '(.*)' secondes[\\\\.|\\\\?]\"", ")", "@", "Then", "(", "\"I wait staleness of '(.*)-(.*)' with timeout of '(.*)' seconds[\\\\.|\\\\?]\"", ")", "public", "void", "waitStalenessOf", ...
Waits staleness of element with timeout of x seconds. @param page The concerned page of field @param element is key of PageElement concerned @param time is custom timeout @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws TechnicalException is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
[ "Waits", "staleness", "of", "element", "with", "timeout", "of", "x", "seconds", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L110-L116
netty/netty
codec/src/main/java/io/netty/handler/codec/LengthFieldBasedFrameDecoder.java
LengthFieldBasedFrameDecoder.extractFrame
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { return buffer.retainedSlice(index, length); }
java
protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { return buffer.retainedSlice(index, length); }
[ "protected", "ByteBuf", "extractFrame", "(", "ChannelHandlerContext", "ctx", ",", "ByteBuf", "buffer", ",", "int", "index", ",", "int", "length", ")", "{", "return", "buffer", ".", "retainedSlice", "(", "index", ",", "length", ")", ";", "}" ]
Extract the sub-region of the specified buffer. <p> If you are sure that the frame and its content are not accessed after the current {@link #decode(ChannelHandlerContext, ByteBuf)} call returns, you can even avoid memory copy by returning the sliced sub-region (i.e. <tt>return buffer.slice(index, length)</tt>). It's often useful when you convert the extracted frame into an object. Refer to the source code of {@link ObjectDecoder} to see how this method is overridden to avoid memory copy.
[ "Extract", "the", "sub", "-", "region", "of", "the", "specified", "buffer", ".", "<p", ">", "If", "you", "are", "sure", "that", "the", "frame", "and", "its", "content", "are", "not", "accessed", "after", "the", "current", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/LengthFieldBasedFrameDecoder.java#L507-L509
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.epoch
public static BigDecimal epoch(EvaluationContext ctx, Object datetime) { Instant instant = Conversions.toDateTime(datetime, ctx).toInstant(); BigDecimal nanos = new BigDecimal(instant.getEpochSecond() * 1000000000 + instant.getNano()); return nanos.divide(new BigDecimal(1000000000)); }
java
public static BigDecimal epoch(EvaluationContext ctx, Object datetime) { Instant instant = Conversions.toDateTime(datetime, ctx).toInstant(); BigDecimal nanos = new BigDecimal(instant.getEpochSecond() * 1000000000 + instant.getNano()); return nanos.divide(new BigDecimal(1000000000)); }
[ "public", "static", "BigDecimal", "epoch", "(", "EvaluationContext", "ctx", ",", "Object", "datetime", ")", "{", "Instant", "instant", "=", "Conversions", ".", "toDateTime", "(", "datetime", ",", "ctx", ")", ".", "toInstant", "(", ")", ";", "BigDecimal", "na...
Converts the given date to the number of nanoseconds since January 1st, 1970 UTC
[ "Converts", "the", "given", "date", "to", "the", "number", "of", "nanoseconds", "since", "January", "1st", "1970", "UTC" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L63-L67
pravega/pravega
controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java
StreamMetrics.sealStreamFailed
public void sealStreamFailed(String scope, String streamName) { DYNAMIC_LOGGER.incCounterValue(globalMetricName(SEAL_STREAM_FAILED), 1); DYNAMIC_LOGGER.incCounterValue(SEAL_STREAM_FAILED, 1, streamTags(scope, streamName)); }
java
public void sealStreamFailed(String scope, String streamName) { DYNAMIC_LOGGER.incCounterValue(globalMetricName(SEAL_STREAM_FAILED), 1); DYNAMIC_LOGGER.incCounterValue(SEAL_STREAM_FAILED, 1, streamTags(scope, streamName)); }
[ "public", "void", "sealStreamFailed", "(", "String", "scope", ",", "String", "streamName", ")", "{", "DYNAMIC_LOGGER", ".", "incCounterValue", "(", "globalMetricName", "(", "SEAL_STREAM_FAILED", ")", ",", "1", ")", ";", "DYNAMIC_LOGGER", ".", "incCounterValue", "(...
This method increments the counter of failed Stream seal operations in the system as well as the failed seal attempts for this specific Stream. @param scope Scope. @param streamName Name of the Stream.
[ "This", "method", "increments", "the", "counter", "of", "failed", "Stream", "seal", "operations", "in", "the", "system", "as", "well", "as", "the", "failed", "seal", "attempts", "for", "this", "specific", "Stream", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/StreamMetrics.java#L126-L129
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
TypeUtils.isAnnotationMirrorOfType
public static boolean isAnnotationMirrorOfType(AnnotationMirror annotationMirror, String fqcn) { assert annotationMirror != null; assert fqcn != null; String annotationClassName = annotationMirror.getAnnotationType().toString(); return annotationClassName.equals( fqcn ); }
java
public static boolean isAnnotationMirrorOfType(AnnotationMirror annotationMirror, String fqcn) { assert annotationMirror != null; assert fqcn != null; String annotationClassName = annotationMirror.getAnnotationType().toString(); return annotationClassName.equals( fqcn ); }
[ "public", "static", "boolean", "isAnnotationMirrorOfType", "(", "AnnotationMirror", "annotationMirror", ",", "String", "fqcn", ")", "{", "assert", "annotationMirror", "!=", "null", ";", "assert", "fqcn", "!=", "null", ";", "String", "annotationClassName", "=", "anno...
Returns {@code true} if the provided annotation type is of the same type as the provided class, {@code false} otherwise. This method uses the string class names for comparison. See also <a href="http://www.retep.org/2009/02/getting-class-values-from-annotations.html">getting-class-values-from-annotations</a>. @param annotationMirror The annotation mirror @param fqcn the fully qualified class name to check against @return {@code true} if the provided annotation type is of the same type as the provided class, {@code false} otherwise.
[ "Returns", "{", "@code", "true", "}", "if", "the", "provided", "annotation", "type", "is", "of", "the", "same", "type", "as", "the", "provided", "class", "{", "@code", "false", "}", "otherwise", ".", "This", "method", "uses", "the", "string", "class", "n...
train
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java#L128-L134
ThreeTen/threetenbp
src/main/java/org/threeten/bp/zone/ZoneRulesProvider.java
ZoneRulesProvider.getRules
public static ZoneRules getRules(String zoneId, boolean forCaching) { Jdk8Methods.requireNonNull(zoneId, "zoneId"); return getProvider(zoneId).provideRules(zoneId, forCaching); }
java
public static ZoneRules getRules(String zoneId, boolean forCaching) { Jdk8Methods.requireNonNull(zoneId, "zoneId"); return getProvider(zoneId).provideRules(zoneId, forCaching); }
[ "public", "static", "ZoneRules", "getRules", "(", "String", "zoneId", ",", "boolean", "forCaching", ")", "{", "Jdk8Methods", ".", "requireNonNull", "(", "zoneId", ",", "\"zoneId\"", ")", ";", "return", "getProvider", "(", "zoneId", ")", ".", "provideRules", "(...
Gets the rules for the zone ID. <p> This returns the latest available rules for the zone ID. <p> This method relies on time-zone data provider files that are configured. These are loaded using a {@code ServiceLoader}. <p> The caching flag is designed to allow provider implementations to prevent the rules being cached in {@code ZoneId}. Under normal circumstances, the caching of zone rules is highly desirable as it will provide greater performance. However, there is a use case where the caching would not be desirable, see {@link #provideRules}. @param zoneId the zone ID as defined by {@code ZoneId}, not null @param forCaching whether the rules are being queried for caching, true if the returned rules will be cached by {@code ZoneId}, false if they will be returned to the user without being cached in {@code ZoneId} @return the rules, null if {@code forCaching} is true and this is a dynamic provider that wants to prevent caching in {@code ZoneId}, otherwise not null @throws ZoneRulesException if rules cannot be obtained for the zone ID
[ "Gets", "the", "rules", "for", "the", "zone", "ID", ".", "<p", ">", "This", "returns", "the", "latest", "available", "rules", "for", "the", "zone", "ID", ".", "<p", ">", "This", "method", "relies", "on", "time", "-", "zone", "data", "provider", "files"...
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/zone/ZoneRulesProvider.java#L120-L123
groovy/groovy-core
src/main/org/codehaus/groovy/reflection/ClassInfo.java
ClassInfo.isValidWeakMetaClass
private boolean isValidWeakMetaClass(MetaClass metaClass, MetaClassRegistry.MetaClassCreationHandle mccHandle) { if(metaClass==null) return false; boolean enableGloballyOn = (mccHandle instanceof ExpandoMetaClassCreationHandle); boolean cachedAnswerIsEMC = (metaClass instanceof ExpandoMetaClass); return (!enableGloballyOn || cachedAnswerIsEMC); }
java
private boolean isValidWeakMetaClass(MetaClass metaClass, MetaClassRegistry.MetaClassCreationHandle mccHandle) { if(metaClass==null) return false; boolean enableGloballyOn = (mccHandle instanceof ExpandoMetaClassCreationHandle); boolean cachedAnswerIsEMC = (metaClass instanceof ExpandoMetaClass); return (!enableGloballyOn || cachedAnswerIsEMC); }
[ "private", "boolean", "isValidWeakMetaClass", "(", "MetaClass", "metaClass", ",", "MetaClassRegistry", ".", "MetaClassCreationHandle", "mccHandle", ")", "{", "if", "(", "metaClass", "==", "null", ")", "return", "false", ";", "boolean", "enableGloballyOn", "=", "(", ...
if EMC.enableGlobally() is OFF, return whatever the cached answer is. but if EMC.enableGlobally() is ON and the cached answer is not an EMC, come up with a fresh answer
[ "if", "EMC", ".", "enableGlobally", "()", "is", "OFF", "return", "whatever", "the", "cached", "answer", "is", ".", "but", "if", "EMC", ".", "enableGlobally", "()", "is", "ON", "and", "the", "cached", "answer", "is", "not", "an", "EMC", "come", "up", "w...
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/reflection/ClassInfo.java#L271-L276
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java
TasksInner.beginUpdateAsync
public Observable<TaskInner> beginUpdateAsync(String resourceGroupName, String registryName, String taskName, TaskUpdateParameters taskUpdateParameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, taskName, taskUpdateParameters).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() { @Override public TaskInner call(ServiceResponse<TaskInner> response) { return response.body(); } }); }
java
public Observable<TaskInner> beginUpdateAsync(String resourceGroupName, String registryName, String taskName, TaskUpdateParameters taskUpdateParameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, taskName, taskUpdateParameters).map(new Func1<ServiceResponse<TaskInner>, TaskInner>() { @Override public TaskInner call(ServiceResponse<TaskInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TaskInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "String", "taskName", ",", "TaskUpdateParameters", "taskUpdateParameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", ...
Updates a task with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param taskName The name of the container registry task. @param taskUpdateParameters The parameters for updating a task. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the TaskInner object
[ "Updates", "a", "task", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java#L791-L798
RestComm/Restcomm-Connect
restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisUsageDao.java
MybatisUsageDao.getUsageCalls
private List<Usage> getUsageCalls(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, final String queryName) { return getUsageCalls(accountSid, category, startDate, endDate, "", queryName); }
java
private List<Usage> getUsageCalls(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, final String queryName) { return getUsageCalls(accountSid, category, startDate, endDate, "", queryName); }
[ "private", "List", "<", "Usage", ">", "getUsageCalls", "(", "final", "Sid", "accountSid", ",", "Usage", ".", "Category", "category", ",", "DateTime", "startDate", ",", "DateTime", "endDate", ",", "final", "String", "queryName", ")", "{", "return", "getUsageCal...
/* @Override public List<Usage> getUsageToday(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) { return getUsageCalls(accountSid, category, startDate, endDate, "getTodayCalls"); } @Override public List<Usage> getUsageYesterday(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) { return getUsageCalls(accountSid, category, startDate, endDate, "getYesterdayCalls"); } @Override public List<Usage> getUsageThisMonth(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) { return getUsageCalls(accountSid, category, startDate, endDate, "getThisMonthCalls"); } @Override public List<Usage> getUsageLastMonth(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) { return getUsageCalls(accountSid, category, startDate, endDate, "getLastMonthCalls"); }
[ "/", "*", "@Override", "public", "List<Usage", ">", "getUsageToday", "(", "final", "Sid", "accountSid", "Usage", ".", "Category", "category", "DateTime", "startDate", "DateTime", "endDate", ")", "{", "return", "getUsageCalls", "(", "accountSid", "category", "start...
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisUsageDao.java#L126-L128
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java
XmlUtil.getElementByXPath
public static Element getElementByXPath(String expression, Object source) { return (Element) getNodeByXPath(expression, source); }
java
public static Element getElementByXPath(String expression, Object source) { return (Element) getNodeByXPath(expression, source); }
[ "public", "static", "Element", "getElementByXPath", "(", "String", "expression", ",", "Object", "source", ")", "{", "return", "(", "Element", ")", "getNodeByXPath", "(", "expression", ",", "source", ")", ";", "}" ]
通过XPath方式读取XML节点等信息<br> Xpath相关文章:https://www.ibm.com/developerworks/cn/xml/x-javaxpathapi.html @param expression XPath表达式 @param source 资源,可以是Docunent、Node节点等 @return 匹配返回类型的值 @since 4.0.9
[ "通过XPath方式读取XML节点等信息<br", ">", "Xpath相关文章:https", ":", "//", "www", ".", "ibm", ".", "com", "/", "developerworks", "/", "cn", "/", "xml", "/", "x", "-", "javaxpathapi", ".", "html" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L572-L574
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_credit_POST
public void project_serviceName_credit_POST(String serviceName, String code) throws IOException { String qPath = "/cloud/project/{serviceName}/credit"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "code", code); exec(qPath, "POST", sb.toString(), o); }
java
public void project_serviceName_credit_POST(String serviceName, String code) throws IOException { String qPath = "/cloud/project/{serviceName}/credit"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "code", code); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "project_serviceName_credit_POST", "(", "String", "serviceName", ",", "String", "code", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/credit\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", ...
Add credit to your project REST: POST /cloud/project/{serviceName}/credit @param code [required] Voucher code @param serviceName [required] The project id
[ "Add", "credit", "to", "your", "project" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L975-L981
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java
PipelineBuilder.addCastableExpr
public void addCastableExpr(final INodeReadTrx mTransaction, final SingleType mSingleType) { assert getPipeStack().size() >= 1; final AbsAxis candidate = getPipeStack().pop().getExpr(); final AbsAxis axis = new CastableExpr(mTransaction, candidate, mSingleType); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(axis); }
java
public void addCastableExpr(final INodeReadTrx mTransaction, final SingleType mSingleType) { assert getPipeStack().size() >= 1; final AbsAxis candidate = getPipeStack().pop().getExpr(); final AbsAxis axis = new CastableExpr(mTransaction, candidate, mSingleType); if (getPipeStack().empty() || getExpression().getSize() != 0) { addExpressionSingle(); } getExpression().add(axis); }
[ "public", "void", "addCastableExpr", "(", "final", "INodeReadTrx", "mTransaction", ",", "final", "SingleType", "mSingleType", ")", "{", "assert", "getPipeStack", "(", ")", ".", "size", "(", ")", ">=", "1", ";", "final", "AbsAxis", "candidate", "=", "getPipeSta...
Adds a castable expression to the pipeline. @param mTransaction Transaction to operate with. @param mSingleType single type the context item will be casted to.
[ "Adds", "a", "castable", "expression", "to", "the", "pipeline", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/xpath/PipelineBuilder.java#L625-L637
biojava/biojava
biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java
NCBIQBlastService.sendAlignmentRequest
public String sendAlignmentRequest(int gid, RemotePairwiseAlignmentProperties rpa) throws Exception { return sendAlignmentRequest(Integer.toString(gid), rpa); }
java
public String sendAlignmentRequest(int gid, RemotePairwiseAlignmentProperties rpa) throws Exception { return sendAlignmentRequest(Integer.toString(gid), rpa); }
[ "public", "String", "sendAlignmentRequest", "(", "int", "gid", ",", "RemotePairwiseAlignmentProperties", "rpa", ")", "throws", "Exception", "{", "return", "sendAlignmentRequest", "(", "Integer", ".", "toString", "(", "gid", ")", ",", "rpa", ")", ";", "}" ]
Converts given GenBank GID to String and calls {@link #sendAlignmentRequest(String, RemotePairwiseAlignmentProperties)}
[ "Converts", "given", "GenBank", "GID", "to", "String", "and", "calls", "{" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java#L151-L153
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/io/GeoPackageIOUtils.java
GeoPackageIOUtils.copyFile
public static void copyFile(File copyFrom, File copyTo) throws IOException { InputStream from = new FileInputStream(copyFrom); OutputStream to = new FileOutputStream(copyTo); copyStream(from, to); }
java
public static void copyFile(File copyFrom, File copyTo) throws IOException { InputStream from = new FileInputStream(copyFrom); OutputStream to = new FileOutputStream(copyTo); copyStream(from, to); }
[ "public", "static", "void", "copyFile", "(", "File", "copyFrom", ",", "File", "copyTo", ")", "throws", "IOException", "{", "InputStream", "from", "=", "new", "FileInputStream", "(", "copyFrom", ")", ";", "OutputStream", "to", "=", "new", "FileOutputStream", "(...
Copy a file to a file location @param copyFrom from file @param copyTo to file @throws IOException upon failure
[ "Copy", "a", "file", "to", "a", "file", "location" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/io/GeoPackageIOUtils.java#L103-L109
Jasig/uPortal
uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java
UserLocaleHelper.updateUserLocale
public void updateUserLocale(HttpServletRequest request, String localeString) { IUserInstance ui = userInstanceManager.getUserInstance(request); IUserPreferencesManager upm = ui.getPreferencesManager(); final IUserProfile userProfile = upm.getUserProfile(); LocaleManager localeManager = userProfile.getLocaleManager(); if (localeString != null) { // build a new List<Locale> from the specified locale Locale userLocale = localeManagerFactory.parseLocale(localeString); List<Locale> locales = Collections.singletonList(userLocale); // set this locale in the session localeManager.setSessionLocales(locales); // if the current user is logged in, also update the persisted // user locale final IPerson person = ui.getPerson(); if (!person.isGuest()) { try { localeManager.setUserLocales(Collections.singletonList(userLocale)); localeStore.updateUserLocales(person, new Locale[] {userLocale}); // remove person layout framgent from session since it contains some of the data // in previous // translation and won't be cleared until next logout-login (applies when using // RDBMDistributedLayoutStore as user layout store). person.setAttribute(Constants.PLF, null); upm.getUserLayoutManager().loadUserLayout(true); } catch (Exception e) { throw new PortalException(e); } } } }
java
public void updateUserLocale(HttpServletRequest request, String localeString) { IUserInstance ui = userInstanceManager.getUserInstance(request); IUserPreferencesManager upm = ui.getPreferencesManager(); final IUserProfile userProfile = upm.getUserProfile(); LocaleManager localeManager = userProfile.getLocaleManager(); if (localeString != null) { // build a new List<Locale> from the specified locale Locale userLocale = localeManagerFactory.parseLocale(localeString); List<Locale> locales = Collections.singletonList(userLocale); // set this locale in the session localeManager.setSessionLocales(locales); // if the current user is logged in, also update the persisted // user locale final IPerson person = ui.getPerson(); if (!person.isGuest()) { try { localeManager.setUserLocales(Collections.singletonList(userLocale)); localeStore.updateUserLocales(person, new Locale[] {userLocale}); // remove person layout framgent from session since it contains some of the data // in previous // translation and won't be cleared until next logout-login (applies when using // RDBMDistributedLayoutStore as user layout store). person.setAttribute(Constants.PLF, null); upm.getUserLayoutManager().loadUserLayout(true); } catch (Exception e) { throw new PortalException(e); } } } }
[ "public", "void", "updateUserLocale", "(", "HttpServletRequest", "request", ",", "String", "localeString", ")", "{", "IUserInstance", "ui", "=", "userInstanceManager", ".", "getUserInstance", "(", "request", ")", ";", "IUserPreferencesManager", "upm", "=", "ui", "."...
Update the current user's locale to match the selected locale. This implementation will update the session locale, and if the user is not a guest, will also update the locale in the user's persisted preferences. @param request @param localeString
[ "Update", "the", "current", "user", "s", "locale", "to", "match", "the", "selected", "locale", ".", "This", "implementation", "will", "update", "the", "session", "locale", "and", "if", "the", "user", "is", "not", "a", "guest", "will", "also", "update", "th...
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-api/uPortal-api-internal/src/main/java/org/apereo/portal/portlets/localization/UserLocaleHelper.java#L133-L168
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.createFolder
public JenkinsServer createFolder(FolderJob folder, String jobName, Boolean crumbFlag) throws IOException { // https://gist.github.com/stuart-warren/7786892 was slightly helpful // here //TODO: JDK9+: Map.of(...) Map<String, String> params = new HashMap<>(); params.put("mode", "com.cloudbees.hudson.plugins.folder.Folder"); params.put("name", jobName); params.put("from", ""); params.put("Submit", "OK"); client.post_form(UrlUtils.toBaseUrl(folder) + "createItem?", params, crumbFlag); return this; }
java
public JenkinsServer createFolder(FolderJob folder, String jobName, Boolean crumbFlag) throws IOException { // https://gist.github.com/stuart-warren/7786892 was slightly helpful // here //TODO: JDK9+: Map.of(...) Map<String, String> params = new HashMap<>(); params.put("mode", "com.cloudbees.hudson.plugins.folder.Folder"); params.put("name", jobName); params.put("from", ""); params.put("Submit", "OK"); client.post_form(UrlUtils.toBaseUrl(folder) + "createItem?", params, crumbFlag); return this; }
[ "public", "JenkinsServer", "createFolder", "(", "FolderJob", "folder", ",", "String", "jobName", ",", "Boolean", "crumbFlag", ")", "throws", "IOException", "{", "// https://gist.github.com/stuart-warren/7786892 was slightly helpful", "// here", "//TODO: JDK9+: Map.of(...)", "Ma...
Create a job on the server (in the given folder) @param folder {@link FolderJob} @param jobName name of the job. @param crumbFlag <code>true</code> to add <b>crumbIssuer</b> <code>false</code> otherwise. @throws IOException in case of an error.
[ "Create", "a", "job", "on", "the", "server", "(", "in", "the", "given", "folder", ")" ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L491-L502
lucee/Lucee
core/src/main/java/lucee/runtime/tag/TagUtil.java
TagUtil.addTagMetaData
public static void addTagMetaData(ConfigWebImpl cw, lucee.commons.io.log.Log log) { if (true) return; PageContextImpl pc = null; try { pc = ThreadUtil.createPageContext(cw, DevNullOutputStream.DEV_NULL_OUTPUT_STREAM, "localhost", "/", "", new Cookie[0], new Pair[0], null, new Pair[0], new StructImpl(), false, -1); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return; } PageContext orgPC = ThreadLocalPageContext.get(); try { ThreadLocalPageContext.register(pc); // MUST MOST of them are the same, so this is a huge overhead _addTagMetaData(pc, cw, CFMLEngine.DIALECT_CFML); _addTagMetaData(pc, cw, CFMLEngine.DIALECT_LUCEE); } catch (Exception e) { XMLConfigWebFactory.log(cw, log, e); } finally { pc.getConfig().getFactory().releaseLuceePageContext(pc, true); ThreadLocalPageContext.register(orgPC); } }
java
public static void addTagMetaData(ConfigWebImpl cw, lucee.commons.io.log.Log log) { if (true) return; PageContextImpl pc = null; try { pc = ThreadUtil.createPageContext(cw, DevNullOutputStream.DEV_NULL_OUTPUT_STREAM, "localhost", "/", "", new Cookie[0], new Pair[0], null, new Pair[0], new StructImpl(), false, -1); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); return; } PageContext orgPC = ThreadLocalPageContext.get(); try { ThreadLocalPageContext.register(pc); // MUST MOST of them are the same, so this is a huge overhead _addTagMetaData(pc, cw, CFMLEngine.DIALECT_CFML); _addTagMetaData(pc, cw, CFMLEngine.DIALECT_LUCEE); } catch (Exception e) { XMLConfigWebFactory.log(cw, log, e); } finally { pc.getConfig().getFactory().releaseLuceePageContext(pc, true); ThreadLocalPageContext.register(orgPC); } }
[ "public", "static", "void", "addTagMetaData", "(", "ConfigWebImpl", "cw", ",", "lucee", ".", "commons", ".", "io", ".", "log", ".", "Log", "log", ")", "{", "if", "(", "true", ")", "return", ";", "PageContextImpl", "pc", "=", "null", ";", "try", "{", ...
load metadata from cfc based custom tags and add the info to the tag @param cs @param config
[ "load", "metadata", "from", "cfc", "based", "custom", "tags", "and", "add", "the", "info", "to", "the", "tag" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/TagUtil.java#L257-L286
RestComm/Restcomm-Connect
restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/Bootstrapper.java
Bootstrapper.generateDefaultProfile
private void generateDefaultProfile(final DaoManager storage, final String profileSourcePath) throws SQLException, IOException{ Profile profile = storage.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); if (profile == null) { if(logger.isDebugEnabled()) { logger.debug("default profile does not exist, will create one from default Plan"); } JsonNode jsonNode = JsonLoader.fromPath(profileSourcePath); profile = new Profile(DEFAULT_PROFILE_SID, jsonNode.toString(), new Date(), new Date()); storage.getProfilesDao().addProfile(profile); } else { if(logger.isDebugEnabled()){ logger.debug("default profile already exists, will not override it."); } } }
java
private void generateDefaultProfile(final DaoManager storage, final String profileSourcePath) throws SQLException, IOException{ Profile profile = storage.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); if (profile == null) { if(logger.isDebugEnabled()) { logger.debug("default profile does not exist, will create one from default Plan"); } JsonNode jsonNode = JsonLoader.fromPath(profileSourcePath); profile = new Profile(DEFAULT_PROFILE_SID, jsonNode.toString(), new Date(), new Date()); storage.getProfilesDao().addProfile(profile); } else { if(logger.isDebugEnabled()){ logger.debug("default profile already exists, will not override it."); } } }
[ "private", "void", "generateDefaultProfile", "(", "final", "DaoManager", "storage", ",", "final", "String", "profileSourcePath", ")", "throws", "SQLException", ",", "IOException", "{", "Profile", "profile", "=", "storage", ".", "getProfilesDao", "(", ")", ".", "ge...
generateDefaultProfile if does not already exists @throws SQLException @throws IOException
[ "generateDefaultProfile", "if", "does", "not", "already", "exists" ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/Bootstrapper.java#L323-L338
GoogleCloudPlatform/appengine-mapreduce
java/src/main/java/com/google/appengine/tools/mapreduce/impl/GoogleCloudStorageMergeInput.java
GoogleCloudStorageMergeInput.createReaderForShard
private MergingReader<ByteBuffer, ByteBuffer> createReaderForShard( Marshaller<KeyValue<ByteBuffer, ? extends Iterable<ByteBuffer>>> marshaller, GoogleCloudStorageFileSet inputFileSet) { ArrayList<PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<ByteBuffer>>>> inputFiles = new ArrayList<>(); GoogleCloudStorageLevelDbInput reducerInput = new GoogleCloudStorageLevelDbInput(inputFileSet, DEFAULT_IO_BUFFER_SIZE); for (InputReader<ByteBuffer> in : reducerInput.createReaders()) { inputFiles.add(new PeekingInputReader<>(in, marshaller)); } return new MergingReader<>(inputFiles, Marshallers.getByteBufferMarshaller(), false); }
java
private MergingReader<ByteBuffer, ByteBuffer> createReaderForShard( Marshaller<KeyValue<ByteBuffer, ? extends Iterable<ByteBuffer>>> marshaller, GoogleCloudStorageFileSet inputFileSet) { ArrayList<PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<ByteBuffer>>>> inputFiles = new ArrayList<>(); GoogleCloudStorageLevelDbInput reducerInput = new GoogleCloudStorageLevelDbInput(inputFileSet, DEFAULT_IO_BUFFER_SIZE); for (InputReader<ByteBuffer> in : reducerInput.createReaders()) { inputFiles.add(new PeekingInputReader<>(in, marshaller)); } return new MergingReader<>(inputFiles, Marshallers.getByteBufferMarshaller(), false); }
[ "private", "MergingReader", "<", "ByteBuffer", ",", "ByteBuffer", ">", "createReaderForShard", "(", "Marshaller", "<", "KeyValue", "<", "ByteBuffer", ",", "?", "extends", "Iterable", "<", "ByteBuffer", ">", ">", ">", "marshaller", ",", "GoogleCloudStorageFileSet", ...
Create a {@link MergingReader} that combines all the input files and maintain sort order. (There are multiple input files in the event that the data didn't fit into the sorter's memory) A {@link MergingReader} is used to combine contents while maintaining key-order. This requires a {@link PeekingInputReader}s to preview the next item of input. @returns a reader producing key-sorted input for a shard.
[ "Create", "a", "{", "@link", "MergingReader", "}", "that", "combines", "all", "the", "input", "files", "and", "maintain", "sort", "order", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/GoogleCloudStorageMergeInput.java#L81-L92
JOML-CI/JOML
src/org/joml/Matrix3x2d.java
Matrix3x2d.scaleAround
public Matrix3x2d scaleAround(double factor, double ox, double oy, Matrix3x2d dest) { return scaleAround(factor, factor, ox, oy, this); }
java
public Matrix3x2d scaleAround(double factor, double ox, double oy, Matrix3x2d dest) { return scaleAround(factor, factor, ox, oy, this); }
[ "public", "Matrix3x2d", "scaleAround", "(", "double", "factor", ",", "double", "ox", ",", "double", "oy", ",", "Matrix3x2d", "dest", ")", "{", "return", "scaleAround", "(", "factor", ",", "factor", ",", "ox", ",", "oy", ",", "this", ")", ";", "}" ]
Apply scaling to this matrix by scaling the base axes by the given <code>factor</code> while using <code>(ox, oy)</code> as the scaling origin, and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, then the new matrix will be <code>M * S</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first! <p> This method is equivalent to calling: <code>translate(ox, oy, dest).scale(factor).translate(-ox, -oy)</code> @param factor the scaling factor for all three axes @param ox the x coordinate of the scaling origin @param oy the y coordinate of the scaling origin @param dest will hold the result @return this
[ "Apply", "scaling", "to", "this", "matrix", "by", "scaling", "the", "base", "axes", "by", "the", "given", "<code", ">", "factor<", "/", "code", ">", "while", "using", "<code", ">", "(", "ox", "oy", ")", "<", "/", "code", ">", "as", "the", "scaling", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2d.java#L1490-L1492
EXIficient/exificient
src/main/java/com/siemens/ct/exi/main/api/stream/StAXEncoder.java
StAXEncoder.writeNamespace
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { try { this.exiAttributes.addNamespaceDeclaration(namespaceURI, prefix); // encoder.encodeNamespaceDeclaration(namespaceURI, prefix); } catch (Exception e) { throw new XMLStreamException(e.getLocalizedMessage(), e); } }
java
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { try { this.exiAttributes.addNamespaceDeclaration(namespaceURI, prefix); // encoder.encodeNamespaceDeclaration(namespaceURI, prefix); } catch (Exception e) { throw new XMLStreamException(e.getLocalizedMessage(), e); } }
[ "public", "void", "writeNamespace", "(", "String", "prefix", ",", "String", "namespaceURI", ")", "throws", "XMLStreamException", "{", "try", "{", "this", ".", "exiAttributes", ".", "addNamespaceDeclaration", "(", "namespaceURI", ",", "prefix", ")", ";", "// encode...
/* Writes a namespace to the output stream If the prefix argument to this method is the empty string, "xmlns", or null this method will delegate to writeDefaultNamespace (non-Javadoc) @see javax.xml.stream.XMLStreamWriter#writeNamespace(java.lang.String, java.lang.String)
[ "/", "*", "Writes", "a", "namespace", "to", "the", "output", "stream", "If", "the", "prefix", "argument", "to", "this", "method", "is", "the", "empty", "string", "xmlns", "or", "null", "this", "method", "will", "delegate", "to", "writeDefaultNamespace" ]
train
https://github.com/EXIficient/exificient/blob/93c7c0d63d74cfccf6ab1d5041b203745ef9ddb8/src/main/java/com/siemens/ct/exi/main/api/stream/StAXEncoder.java#L459-L467
diffplug/JMatIO
src/main/java/ca/mjdsystems/jmatio/types/MLStructure.java
MLStructure.setField
public void setField(String name, MLArray value, int index) { keys.add(name); currentIndex = index; if ( mlStructArray.isEmpty() || mlStructArray.size() <= index ) { mlStructArray.add(index, new LinkedHashMap<String, MLArray>() ); } mlStructArray.get(index).put(name, value); }
java
public void setField(String name, MLArray value, int index) { keys.add(name); currentIndex = index; if ( mlStructArray.isEmpty() || mlStructArray.size() <= index ) { mlStructArray.add(index, new LinkedHashMap<String, MLArray>() ); } mlStructArray.get(index).put(name, value); }
[ "public", "void", "setField", "(", "String", "name", ",", "MLArray", "value", ",", "int", "index", ")", "{", "keys", ".", "add", "(", "name", ")", ";", "currentIndex", "=", "index", ";", "if", "(", "mlStructArray", ".", "isEmpty", "(", ")", "||", "ml...
Sets filed for structure described by index in struct array @param name - name of the field @param value - <code>MLArray</code> field value @param index
[ "Sets", "filed", "for", "structure", "described", "by", "index", "in", "struct", "array" ]
train
https://github.com/diffplug/JMatIO/blob/dab8a54fa21a8faeaa81537cdc45323c5c4e6ca6/src/main/java/ca/mjdsystems/jmatio/types/MLStructure.java#L80-L90
codegist/crest
core/src/main/java/org/codegist/crest/param/ParamProcessors.java
ParamProcessors.newInstance
public static ParamProcessor newInstance(ParamType type, String listSeparator){ switch(type){ case COOKIE: return listSeparator != null ? new CollectionMergingCookieParamProcessor(listSeparator) : DefaultCookieParamProcessor.INSTANCE; default: return listSeparator != null ? new CollectionMergingParamProcessor(listSeparator) : DefaultParamProcessor.INSTANCE; } }
java
public static ParamProcessor newInstance(ParamType type, String listSeparator){ switch(type){ case COOKIE: return listSeparator != null ? new CollectionMergingCookieParamProcessor(listSeparator) : DefaultCookieParamProcessor.INSTANCE; default: return listSeparator != null ? new CollectionMergingParamProcessor(listSeparator) : DefaultParamProcessor.INSTANCE; } }
[ "public", "static", "ParamProcessor", "newInstance", "(", "ParamType", "type", ",", "String", "listSeparator", ")", "{", "switch", "(", "type", ")", "{", "case", "COOKIE", ":", "return", "listSeparator", "!=", "null", "?", "new", "CollectionMergingCookieParamProce...
Returns an instance of a param processor. @param type parameter type @param listSeparator list separator if applicable, otherwise null @return instance of param processor
[ "Returns", "an", "instance", "of", "a", "param", "processor", "." ]
train
https://github.com/codegist/crest/blob/e99ba7728b27d2ddb2c247261350f1b6fa7a6698/core/src/main/java/org/codegist/crest/param/ParamProcessors.java#L48-L55
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/randomizers/range/BigIntegerRangeRandomizer.java
BigIntegerRangeRandomizer.aNewBigIntegerRangeRandomizer
public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed) { return new BigIntegerRangeRandomizer(min, max, seed); }
java
public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed) { return new BigIntegerRangeRandomizer(min, max, seed); }
[ "public", "static", "BigIntegerRangeRandomizer", "aNewBigIntegerRangeRandomizer", "(", "final", "Integer", "min", ",", "final", "Integer", "max", ",", "final", "long", "seed", ")", "{", "return", "new", "BigIntegerRangeRandomizer", "(", "min", ",", "max", ",", "se...
Create a new {@link BigIntegerRangeRandomizer}. @param min min value @param max max value @param seed initial seed @return a new {@link BigIntegerRangeRandomizer}.
[ "Create", "a", "new", "{", "@link", "BigIntegerRangeRandomizer", "}", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/range/BigIntegerRangeRandomizer.java#L79-L81
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/mapred/TrackerClientCache.java
TrackerClientCache.createClient
private CoronaTaskTrackerProtocol createClient(String host, int port) throws IOException { String staticHost = NetUtils.getStaticResolution(host); InetSocketAddress s = null; InetAddress inetAddress = null; byte[] byteArr = null; if (staticHost != null) { inetAddress = InetAddress.getByName(staticHost); } else { byteArr = Utilities.asBytes(host); if ( byteArr == null) { inetAddress = InetAddress.getByName(host); } else { inetAddress = InetAddress.getByAddress(byteArr); } } s = new InetSocketAddress(inetAddress, port); LOG.info("Creating client to " + (staticHost != null ? staticHost : host) + ":" + s.getPort()); long connectTimeout = conf.getLong(CoronaJobTracker.TT_CONNECT_TIMEOUT_MSEC_KEY, 10000L); int rpcTimeout = conf.getInt(CoronaJobTracker.TT_RPC_TIMEOUT_MSEC_KEY, 60000); return RPC.waitForProxy( CoronaTaskTrackerProtocol.class, CoronaTaskTrackerProtocol.versionID, s, conf, connectTimeout, rpcTimeout); }
java
private CoronaTaskTrackerProtocol createClient(String host, int port) throws IOException { String staticHost = NetUtils.getStaticResolution(host); InetSocketAddress s = null; InetAddress inetAddress = null; byte[] byteArr = null; if (staticHost != null) { inetAddress = InetAddress.getByName(staticHost); } else { byteArr = Utilities.asBytes(host); if ( byteArr == null) { inetAddress = InetAddress.getByName(host); } else { inetAddress = InetAddress.getByAddress(byteArr); } } s = new InetSocketAddress(inetAddress, port); LOG.info("Creating client to " + (staticHost != null ? staticHost : host) + ":" + s.getPort()); long connectTimeout = conf.getLong(CoronaJobTracker.TT_CONNECT_TIMEOUT_MSEC_KEY, 10000L); int rpcTimeout = conf.getInt(CoronaJobTracker.TT_RPC_TIMEOUT_MSEC_KEY, 60000); return RPC.waitForProxy( CoronaTaskTrackerProtocol.class, CoronaTaskTrackerProtocol.versionID, s, conf, connectTimeout, rpcTimeout); }
[ "private", "CoronaTaskTrackerProtocol", "createClient", "(", "String", "host", ",", "int", "port", ")", "throws", "IOException", "{", "String", "staticHost", "=", "NetUtils", ".", "getStaticResolution", "(", "host", ")", ";", "InetSocketAddress", "s", "=", "null",...
Connect to the task tracker and get the RPC client. @param host The host. @param port the port. @return The RPC client. @throws IOException
[ "Connect", "to", "the", "task", "tracker", "and", "get", "the", "RPC", "client", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/mapred/TrackerClientCache.java#L100-L131
Azure/autorest-clientruntime-for-java
client-runtime/src/main/java/com/microsoft/rest/retry/ExponentialBackoffRetryStrategy.java
ExponentialBackoffRetryStrategy.shouldRetry
@Override public boolean shouldRetry(int retryCount, Response response) { int code = response.code(); //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES return retryCount < this.retryCount && (code == 408 || (code >= 500 && code != 501 && code != 505)); }
java
@Override public boolean shouldRetry(int retryCount, Response response) { int code = response.code(); //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES return retryCount < this.retryCount && (code == 408 || (code >= 500 && code != 501 && code != 505)); }
[ "@", "Override", "public", "boolean", "shouldRetry", "(", "int", "retryCount", ",", "Response", "response", ")", "{", "int", "code", "=", "response", ".", "code", "(", ")", ";", "//CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES", "return", "retryCount", "<", "this...
Returns if a request should be retried based on the retry count, current response, and the current strategy. @param retryCount The current retry attempt count. @param response The exception that caused the retry conditions to occur. @return true if the request should be retried; false otherwise.
[ "Returns", "if", "a", "request", "should", "be", "retried", "based", "on", "the", "retry", "count", "current", "response", "and", "the", "current", "strategy", "." ]
train
https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/client-runtime/src/main/java/com/microsoft/rest/retry/ExponentialBackoffRetryStrategy.java#L98-L104
logic-ng/LogicNG
src/main/java/org/logicng/cardinalityconstraints/CCAMKCardinalityNetwork.java
CCAMKCardinalityNetwork.buildForIncremental
void buildForIncremental(final EncodingResult result, final Variable[] vars, int rhs) { cardinalityNetwork.buildAMKForIncremental(result, vars, rhs); }
java
void buildForIncremental(final EncodingResult result, final Variable[] vars, int rhs) { cardinalityNetwork.buildAMKForIncremental(result, vars, rhs); }
[ "void", "buildForIncremental", "(", "final", "EncodingResult", "result", ",", "final", "Variable", "[", "]", "vars", ",", "int", "rhs", ")", "{", "cardinalityNetwork", ".", "buildAMKForIncremental", "(", "result", ",", "vars", ",", "rhs", ")", ";", "}" ]
Builds the constraint for incremental usage. @param result the result @param vars the variables @param rhs the right-hand side
[ "Builds", "the", "constraint", "for", "incremental", "usage", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/cardinalityconstraints/CCAMKCardinalityNetwork.java#L67-L69
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/DatabaseHelper.java
DatabaseHelper.getSQLJContext
public Object getSQLJContext(WSRdbManagedConnectionImpl mc, Class<?> DefaultContext, WSConnectionManager connMgr) throws SQLException { return null; }
java
public Object getSQLJContext(WSRdbManagedConnectionImpl mc, Class<?> DefaultContext, WSConnectionManager connMgr) throws SQLException { return null; }
[ "public", "Object", "getSQLJContext", "(", "WSRdbManagedConnectionImpl", "mc", ",", "Class", "<", "?", ">", "DefaultContext", ",", "WSConnectionManager", "connMgr", ")", "throws", "SQLException", "{", "return", "null", ";", "}" ]
This method returns a sqljConnectContext. It will go to DB2 to get the connection Context. We need to create a new WSJccConnection to get the phsyical sqlj context.So the sqlj runtime will use our WSJccConnection to do the work. @param a managedConnection @param DefaultContext the sqlj.runtime.ref.DefaultContext class @return a physical sqlj connectionContext for DB2 only or return null for other database @exception a SQLException if can't get a DefaultContext
[ "This", "method", "returns", "a", "sqljConnectContext", ".", "It", "will", "go", "to", "DB2", "to", "get", "the", "connection", "Context", ".", "We", "need", "to", "create", "a", "new", "WSJccConnection", "to", "get", "the", "phsyical", "sqlj", "context", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/impl/DatabaseHelper.java#L740-L742
Whiley/WhileyCompiler
src/main/java/wyil/check/DefiniteUnassignmentCheck.java
DefiniteUnassignmentCheck.visitFunctionOrMethod
@Override public ControlFlow visitFunctionOrMethod(Decl.FunctionOrMethod declaration, MaybeAssignedSet dummy) { MaybeAssignedSet environment = new MaybeAssignedSet(); // Definitely assigned variables includes all parameters. environment = environment.addAll(declaration.getParameters()); // Iterate through each statement in the body of the function or method, // updating the set of definitely assigned variables as appropriate. visitStatement(declaration.getBody(), environment); // return null; }
java
@Override public ControlFlow visitFunctionOrMethod(Decl.FunctionOrMethod declaration, MaybeAssignedSet dummy) { MaybeAssignedSet environment = new MaybeAssignedSet(); // Definitely assigned variables includes all parameters. environment = environment.addAll(declaration.getParameters()); // Iterate through each statement in the body of the function or method, // updating the set of definitely assigned variables as appropriate. visitStatement(declaration.getBody(), environment); // return null; }
[ "@", "Override", "public", "ControlFlow", "visitFunctionOrMethod", "(", "Decl", ".", "FunctionOrMethod", "declaration", ",", "MaybeAssignedSet", "dummy", ")", "{", "MaybeAssignedSet", "environment", "=", "new", "MaybeAssignedSet", "(", ")", ";", "// Definitely assigned ...
Check a function or method declaration for definite assignment. @param declaration @return
[ "Check", "a", "function", "or", "method", "declaration", "for", "definite", "assignment", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/DefiniteUnassignmentCheck.java#L93-L103
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java
MsgSettingController.downloadApiJson
@GetMapping("/setting/download/api/json") public void downloadApiJson(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { this.validationSessionComponent.sessionCheck(req); url = new String(Base64.getDecoder().decode(url)); List<ValidationData> list = this.msgSettingService.getValidationData(method, url); ValidationFileUtil.sendFileToHttpServiceResponse(method + url.replaceAll("/", "-") + ".json", list, res); }
java
@GetMapping("/setting/download/api/json") public void downloadApiJson(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { this.validationSessionComponent.sessionCheck(req); url = new String(Base64.getDecoder().decode(url)); List<ValidationData> list = this.msgSettingService.getValidationData(method, url); ValidationFileUtil.sendFileToHttpServiceResponse(method + url.replaceAll("/", "-") + ".json", list, res); }
[ "@", "GetMapping", "(", "\"/setting/download/api/json\"", ")", "public", "void", "downloadApiJson", "(", "HttpServletRequest", "req", ",", "@", "RequestParam", "(", "\"method\"", ")", "String", "method", ",", "@", "RequestParam", "(", "\"url\"", ")", "String", "ur...
Download api json. @param req the req @param method the method @param url the url @param res the res
[ "Download", "api", "json", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java#L89-L95
google/error-prone-javac
src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java
Util.forwardExecutionControl
public static void forwardExecutionControl(ExecutionControl ec, ObjectInput in, ObjectOutput out) { new ExecutionControlForwarder(ec, in, out).commandLoop(); }
java
public static void forwardExecutionControl(ExecutionControl ec, ObjectInput in, ObjectOutput out) { new ExecutionControlForwarder(ec, in, out).commandLoop(); }
[ "public", "static", "void", "forwardExecutionControl", "(", "ExecutionControl", "ec", ",", "ObjectInput", "in", ",", "ObjectOutput", "out", ")", "{", "new", "ExecutionControlForwarder", "(", "ec", ",", "in", ",", "out", ")", ".", "commandLoop", "(", ")", ";", ...
Forward commands from the input to the specified {@link ExecutionControl} instance, then responses back on the output. @param ec the direct instance of {@link ExecutionControl} to process commands @param in the command input @param out the command response output
[ "Forward", "commands", "from", "the", "input", "to", "the", "specified", "{" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java#L74-L77
ebourgeois/common-java
src/main/java/ca/jeb/common/infra/JStringUtils.java
JStringUtils.convertInputStreamToString
public static String convertInputStreamToString(InputStream is, String charset) throws IOException { if (is == null) { return EMPTY; } final StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { if (charset != null) { reader = new BufferedReader(new InputStreamReader(is, charset)); } else { reader = new BufferedReader(new InputStreamReader(is)); } String line; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) { reader.close(); } } return sb.toString(); }
java
public static String convertInputStreamToString(InputStream is, String charset) throws IOException { if (is == null) { return EMPTY; } final StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { if (charset != null) { reader = new BufferedReader(new InputStreamReader(is, charset)); } else { reader = new BufferedReader(new InputStreamReader(is)); } String line; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) { reader.close(); } } return sb.toString(); }
[ "public", "static", "String", "convertInputStreamToString", "(", "InputStream", "is", ",", "String", "charset", ")", "throws", "IOException", "{", "if", "(", "is", "==", "null", ")", "{", "return", "EMPTY", ";", "}", "final", "StringBuilder", "sb", "=", "new...
To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the BufferedReader return null which means there's no more data to read. Each line will appended to a StringBuilder and returned as String. @param is - InputStream @param charset - String, the character set @return String @throws IOException
[ "To", "convert", "the", "InputStream", "to", "String", "we", "use", "the", "BufferedReader", ".", "readLine", "()", "method", ".", "We", "iterate", "until", "the", "BufferedReader", "return", "null", "which", "means", "there", "s", "no", "more", "data", "to"...
train
https://github.com/ebourgeois/common-java/blob/8ba7e05b1228aad1ec2949b5707ac4b5e8889f92/src/main/java/ca/jeb/common/infra/JStringUtils.java#L183-L219
camunda/camunda-commons
utils/src/main/java/org/camunda/commons/utils/EnsureUtil.java
EnsureUtil.ensureParamInstanceOf
@SuppressWarnings("unchecked") public static <T> T ensureParamInstanceOf(String objectName, Object object, Class<T> type) { if(type.isAssignableFrom(object.getClass())) { return (T) object; } else { throw LOG.unsupportedParameterType(objectName, object, type); } }
java
@SuppressWarnings("unchecked") public static <T> T ensureParamInstanceOf(String objectName, Object object, Class<T> type) { if(type.isAssignableFrom(object.getClass())) { return (T) object; } else { throw LOG.unsupportedParameterType(objectName, object, type); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "ensureParamInstanceOf", "(", "String", "objectName", ",", "Object", "object", ",", "Class", "<", "T", ">", "type", ")", "{", "if", "(", "type", ".", "isAssignableF...
Ensure the object is of a given type and return the casted object @param objectName the name of the parameter @param object the parameter value @param type the expected type @return the parameter casted to the requested type @throws IllegalArgumentException in case object cannot be casted to type
[ "Ensure", "the", "object", "is", "of", "a", "given", "type", "and", "return", "the", "casted", "object" ]
train
https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/utils/src/main/java/org/camunda/commons/utils/EnsureUtil.java#L48-L55
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java
Client.performTeardownExchange
private void performTeardownExchange() throws IOException { Message teardownRequest = new Message(0xfffffffeL, Message.KnownType.TEARDOWN_REQ); sendMessage(teardownRequest); // At this point, the server closes the connection from its end, so we can’t read any more. }
java
private void performTeardownExchange() throws IOException { Message teardownRequest = new Message(0xfffffffeL, Message.KnownType.TEARDOWN_REQ); sendMessage(teardownRequest); // At this point, the server closes the connection from its end, so we can’t read any more. }
[ "private", "void", "performTeardownExchange", "(", ")", "throws", "IOException", "{", "Message", "teardownRequest", "=", "new", "Message", "(", "0xfffffffe", "L", ",", "Message", ".", "KnownType", ".", "TEARDOWN_REQ", ")", ";", "sendMessage", "(", "teardownRequest...
Exchanges the final messages which politely report our intention to disconnect from the dbserver.
[ "Exchanges", "the", "final", "messages", "which", "politely", "report", "our", "intention", "to", "disconnect", "from", "the", "dbserver", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java#L140-L144
jayantk/jklol
src/com/jayantkrish/jklol/models/TableFactorBuilder.java
TableFactorBuilder.setWeightList
public void setWeightList(List<? extends Object> varValues, double weight) { Preconditions.checkNotNull(varValues); Preconditions.checkArgument(getVars().size() == varValues.size()); setWeight(vars.outcomeToAssignment(varValues), weight); }
java
public void setWeightList(List<? extends Object> varValues, double weight) { Preconditions.checkNotNull(varValues); Preconditions.checkArgument(getVars().size() == varValues.size()); setWeight(vars.outcomeToAssignment(varValues), weight); }
[ "public", "void", "setWeightList", "(", "List", "<", "?", "extends", "Object", ">", "varValues", ",", "double", "weight", ")", "{", "Preconditions", ".", "checkNotNull", "(", "varValues", ")", ";", "Preconditions", ".", "checkArgument", "(", "getVars", "(", ...
Convenience wrapper for {@link #setWeight(Assignment, double)}. {@code varValues} is the list of values to construct an assignment out of, sorted in order of variable number. @param varValues @param weight
[ "Convenience", "wrapper", "for", "{", "@link", "#setWeight", "(", "Assignment", "double", ")", "}", ".", "{", "@code", "varValues", "}", "is", "the", "list", "of", "values", "to", "construct", "an", "assignment", "out", "of", "sorted", "in", "order", "of",...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/TableFactorBuilder.java#L146-L150
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/collection/ring/RingBuffer.java
RingBuffer.addConsumer
public boolean addConsumer( final C consumer, final int timesToRetryUponTimeout ) { if (!addEntries.get()) { throw new IllegalStateException(); } ConsumerRunner runner = new ConsumerRunner(consumer, timesToRetryUponTimeout); if (gcConsumer != null) gcConsumer.stayBehind(runner.getPointer()); // Try to add the runner instance, with equality based upon consumer instance equality ... if (!consumers.add(runner)) return false; // It was added, so start it ... executor.execute(runner); return true; }
java
public boolean addConsumer( final C consumer, final int timesToRetryUponTimeout ) { if (!addEntries.get()) { throw new IllegalStateException(); } ConsumerRunner runner = new ConsumerRunner(consumer, timesToRetryUponTimeout); if (gcConsumer != null) gcConsumer.stayBehind(runner.getPointer()); // Try to add the runner instance, with equality based upon consumer instance equality ... if (!consumers.add(runner)) return false; // It was added, so start it ... executor.execute(runner); return true; }
[ "public", "boolean", "addConsumer", "(", "final", "C", "consumer", ",", "final", "int", "timesToRetryUponTimeout", ")", "{", "if", "(", "!", "addEntries", ".", "get", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "Consume...
Add the supplied consumer, and have it start processing entries in a separate thread. <p> The consumer is automatically removed from the ring buffer when it returns {@code false} from its {@link Consumer#consume(Object, long, long)} method. </p> @param consumer the component that will process the entries; may not be null @param timesToRetryUponTimeout the number of times that the thread should retry after timing out while waiting for the next entry; retries will not be attempted if the value is less than 1 @return true if the consumer was added, or false if the consumer was already registered with this buffer @throws IllegalStateException if the ring buffer has already been {@link #shutdown()}
[ "Add", "the", "supplied", "consumer", "and", "have", "it", "start", "processing", "entries", "in", "a", "separate", "thread", ".", "<p", ">", "The", "consumer", "is", "automatically", "removed", "from", "the", "ring", "buffer", "when", "it", "returns", "{", ...
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/collection/ring/RingBuffer.java#L236-L250
lessthanoptimal/BoofCV
main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/EstimateSceneCalibrated.java
EstimateSceneCalibrated.defineCoordinateSystem
void defineCoordinateSystem(View viewA, Motion motion) { View viewB = motion.destination(viewA); viewA.viewToWorld.reset(); // identity since it's the origin viewB.viewToWorld.set(motion.motionSrcToDst(viewB)); // translation is only known up to a scale factor so pick a reasonable scale factor double scale = viewB.viewToWorld.T.norm(); viewB.viewToWorld.T.scale(1.0/scale); viewsAdded.add(viewA); viewsAdded.add(viewB); viewA.state = ViewState.PROCESSED; viewB.state = ViewState.PROCESSED; // Take the already triangulated points and turn them into official 3D features boolean originIsDst = viewA == motion.viewDst; for (int i = 0; i < motion.stereoTriangulations.size(); i++) { Feature3D f = motion.stereoTriangulations.get(i); if( f.obsIdx.size != 2 ) throw new RuntimeException("BUG"); int indexSrc = f.obsIdx.get(0); int indexDst = f.obsIdx.get(1); motion.viewSrc.features3D[indexSrc] = f; motion.viewDst.features3D[indexDst] = f; if( originIsDst ) { SePointOps_F64.transform(motion.a_to_b,f.worldPt,f.worldPt); } f.worldPt.scale(1.0/scale); graph.features3D.add(f); } // free memory and mark as already processed motion.stereoTriangulations = new ArrayList<>(); // All features which can be added using triangulation should now be added addTriangulatedFeaturesForAllEdges(viewA); addTriangulatedFeaturesForAllEdges(viewB); if( verbose != null ) { verbose.println("root = " + viewA.index); verbose.println("other = " + viewB.index); verbose.println("-------------"); } }
java
void defineCoordinateSystem(View viewA, Motion motion) { View viewB = motion.destination(viewA); viewA.viewToWorld.reset(); // identity since it's the origin viewB.viewToWorld.set(motion.motionSrcToDst(viewB)); // translation is only known up to a scale factor so pick a reasonable scale factor double scale = viewB.viewToWorld.T.norm(); viewB.viewToWorld.T.scale(1.0/scale); viewsAdded.add(viewA); viewsAdded.add(viewB); viewA.state = ViewState.PROCESSED; viewB.state = ViewState.PROCESSED; // Take the already triangulated points and turn them into official 3D features boolean originIsDst = viewA == motion.viewDst; for (int i = 0; i < motion.stereoTriangulations.size(); i++) { Feature3D f = motion.stereoTriangulations.get(i); if( f.obsIdx.size != 2 ) throw new RuntimeException("BUG"); int indexSrc = f.obsIdx.get(0); int indexDst = f.obsIdx.get(1); motion.viewSrc.features3D[indexSrc] = f; motion.viewDst.features3D[indexDst] = f; if( originIsDst ) { SePointOps_F64.transform(motion.a_to_b,f.worldPt,f.worldPt); } f.worldPt.scale(1.0/scale); graph.features3D.add(f); } // free memory and mark as already processed motion.stereoTriangulations = new ArrayList<>(); // All features which can be added using triangulation should now be added addTriangulatedFeaturesForAllEdges(viewA); addTriangulatedFeaturesForAllEdges(viewB); if( verbose != null ) { verbose.println("root = " + viewA.index); verbose.println("other = " + viewB.index); verbose.println("-------------"); } }
[ "void", "defineCoordinateSystem", "(", "View", "viewA", ",", "Motion", "motion", ")", "{", "View", "viewB", "=", "motion", ".", "destination", "(", "viewA", ")", ";", "viewA", ".", "viewToWorld", ".", "reset", "(", ")", ";", "// identity since it's the origin"...
Sets the origin and scale of the coordinate system @param viewA The origin of the coordinate system @param motion Motion which will define the coordinate system's scale
[ "Sets", "the", "origin", "and", "scale", "of", "the", "coordinate", "system" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-sfm/src/main/java/boofcv/alg/sfm/structure/EstimateSceneCalibrated.java#L671-L720
apache/groovy
subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java
Sql.newInstance
public static Sql newInstance(String url, String driverClassName) throws SQLException, ClassNotFoundException { loadDriver(driverClassName); return newInstance(url); }
java
public static Sql newInstance(String url, String driverClassName) throws SQLException, ClassNotFoundException { loadDriver(driverClassName); return newInstance(url); }
[ "public", "static", "Sql", "newInstance", "(", "String", "url", ",", "String", "driverClassName", ")", "throws", "SQLException", ",", "ClassNotFoundException", "{", "loadDriver", "(", "driverClassName", ")", ";", "return", "newInstance", "(", "url", ")", ";", "}...
Creates a new Sql instance given a JDBC connection URL and a driver class name. @param url a database url of the form <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> @param driverClassName the fully qualified class name of the driver class @return a new Sql instance with a connection @throws SQLException if a database access error occurs @throws ClassNotFoundException if the driver class cannot be found or loaded
[ "Creates", "a", "new", "Sql", "instance", "given", "a", "JDBC", "connection", "URL", "and", "a", "driver", "class", "name", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-sql/src/main/java/groovy/sql/Sql.java#L470-L473
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/FileInfo.java
FileInfo.addModificationTimeToAttributes
public static void addModificationTimeToAttributes(Map<String, byte[]> attributes, Clock clock) { attributes.put(FILE_MODIFICATION_TIMESTAMP_KEY, Longs.toByteArray(clock.currentTimeMillis())); }
java
public static void addModificationTimeToAttributes(Map<String, byte[]> attributes, Clock clock) { attributes.put(FILE_MODIFICATION_TIMESTAMP_KEY, Longs.toByteArray(clock.currentTimeMillis())); }
[ "public", "static", "void", "addModificationTimeToAttributes", "(", "Map", "<", "String", ",", "byte", "[", "]", ">", "attributes", ",", "Clock", "clock", ")", "{", "attributes", ".", "put", "(", "FILE_MODIFICATION_TIMESTAMP_KEY", ",", "Longs", ".", "toByteArray...
Add a key and value representing the current time, as determined by the passed clock, to the passed attributes dictionary. @param attributes The file attributes map to update @param clock The clock to retrieve the current time from
[ "Add", "a", "key", "and", "value", "representing", "the", "current", "time", "as", "determined", "by", "the", "passed", "clock", "to", "the", "passed", "attributes", "dictionary", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/FileInfo.java#L217-L219
OpenLiberty/open-liberty
dev/com.ibm.ws.artifact.bundle/src/com/ibm/ws/artifact/bundle/internal/BundleArchive.java
BundleArchive.getBundleEntry
@FFDCIgnore(IllegalStateException.class) public URL getBundleEntry(Bundle bundleToTest, String pathAndName) { try { URL bundleEntry = bundleToTest.getEntry(pathAndName); /* * Defect 54588 discovered that if a directory does not have a zip entry then calling getEntry will return null unless the path has a "/" on the end so if we have null * still then add a "/" on the end of the path and retest */ if (bundleEntry == null) { bundleEntry = bundleToTest.getEntry(pathAndName + "/"); } return bundleEntry; } catch (IllegalStateException ise) { //bundle context was no longer valid, so we cannot use getEntry any more. return null; } }
java
@FFDCIgnore(IllegalStateException.class) public URL getBundleEntry(Bundle bundleToTest, String pathAndName) { try { URL bundleEntry = bundleToTest.getEntry(pathAndName); /* * Defect 54588 discovered that if a directory does not have a zip entry then calling getEntry will return null unless the path has a "/" on the end so if we have null * still then add a "/" on the end of the path and retest */ if (bundleEntry == null) { bundleEntry = bundleToTest.getEntry(pathAndName + "/"); } return bundleEntry; } catch (IllegalStateException ise) { //bundle context was no longer valid, so we cannot use getEntry any more. return null; } }
[ "@", "FFDCIgnore", "(", "IllegalStateException", ".", "class", ")", "public", "URL", "getBundleEntry", "(", "Bundle", "bundleToTest", ",", "String", "pathAndName", ")", "{", "try", "{", "URL", "bundleEntry", "=", "bundleToTest", ".", "getEntry", "(", "pathAndNam...
This method will return a bundle entry URL for the supplied path, it will test for both a normal entry and a directory entry for it. @param pathAndName The path to the entry @return The URL for the bundle entry
[ "This", "method", "will", "return", "a", "bundle", "entry", "URL", "for", "the", "supplied", "path", "it", "will", "test", "for", "both", "a", "normal", "entry", "and", "a", "directory", "entry", "for", "it", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.artifact.bundle/src/com/ibm/ws/artifact/bundle/internal/BundleArchive.java#L106-L123
rapidpro/expressions
java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java
CustomFunctions.regex_group
public static String regex_group(EvaluationContext ctx, Object text, Object pattern, Object groupNum) { String _text = Conversions.toString(text, ctx); String _pattern = Conversions.toString(pattern, ctx); int _groupNum = Conversions.toInteger(groupNum, ctx); try { // check whether we match int flags = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; Pattern regex = Pattern.compile(_pattern, flags); Matcher matcher = regex.matcher(_text); if (matcher.find()) { if (_groupNum < 0 || _groupNum > matcher.groupCount()) { throw new RuntimeException("No such matching group " + _groupNum); } return matcher.group(_groupNum); } } catch (PatternSyntaxException ignored) {} return ""; }
java
public static String regex_group(EvaluationContext ctx, Object text, Object pattern, Object groupNum) { String _text = Conversions.toString(text, ctx); String _pattern = Conversions.toString(pattern, ctx); int _groupNum = Conversions.toInteger(groupNum, ctx); try { // check whether we match int flags = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE; Pattern regex = Pattern.compile(_pattern, flags); Matcher matcher = regex.matcher(_text); if (matcher.find()) { if (_groupNum < 0 || _groupNum > matcher.groupCount()) { throw new RuntimeException("No such matching group " + _groupNum); } return matcher.group(_groupNum); } } catch (PatternSyntaxException ignored) {} return ""; }
[ "public", "static", "String", "regex_group", "(", "EvaluationContext", "ctx", ",", "Object", "text", ",", "Object", "pattern", ",", "Object", "groupNum", ")", "{", "String", "_text", "=", "Conversions", ".", "toString", "(", "text", ",", "ctx", ")", ";", "...
Tries to match the text with the given pattern and returns the value of matching group
[ "Tries", "to", "match", "the", "text", "with", "the", "given", "pattern", "and", "returns", "the", "value", "of", "matching", "group" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/functions/CustomFunctions.java#L180-L201
notnoop/java-apns
src/main/java/com/notnoop/apns/PayloadBuilder.java
PayloadBuilder.customField
public PayloadBuilder customField(final String key, final Object value) { root.put(key, value); return this; }
java
public PayloadBuilder customField(final String key, final Object value) { root.put(key, value); return this; }
[ "public", "PayloadBuilder", "customField", "(", "final", "String", "key", ",", "final", "Object", "value", ")", "{", "root", ".", "put", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets any application-specific custom fields. The values are presented to the application and the iPhone doesn't display them automatically. This can be used to pass specific values (urls, ids, etc) to the application in addition to the notification message itself. @param key the custom field name @param value the custom field value @return this
[ "Sets", "any", "application", "-", "specific", "custom", "fields", ".", "The", "values", "are", "presented", "to", "the", "application", "and", "the", "iPhone", "doesn", "t", "display", "them", "automatically", "." ]
train
https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/PayloadBuilder.java#L327-L330
czyzby/gdx-lml
mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java
InterfaceService.addViewAction
public void addViewAction(final String actionId, final ActorConsumer<?, ?> action) { parser.getData().addActorConsumer(actionId, action); }
java
public void addViewAction(final String actionId, final ActorConsumer<?, ?> action) { parser.getData().addActorConsumer(actionId, action); }
[ "public", "void", "addViewAction", "(", "final", "String", "actionId", ",", "final", "ActorConsumer", "<", "?", ",", "?", ">", "action", ")", "{", "parser", ".", "getData", "(", ")", ".", "addActorConsumer", "(", "actionId", ",", "action", ")", ";", "}" ...
Registers an action globally for all views. @param actionId ID of the action. @param action will be available in views with the selected ID.
[ "Registers", "an", "action", "globally", "for", "all", "views", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java#L142-L144
Abnaxos/markdown-doclet
doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java
PredefinedArgumentValidators.argumentTypeValidator
public static ArgumentValidator argumentTypeValidator(String description, ArgumentPredicate argumentPredicate) { return argumentTypeValidator(description, IndexFilter.all(), argumentPredicate); }
java
public static ArgumentValidator argumentTypeValidator(String description, ArgumentPredicate argumentPredicate) { return argumentTypeValidator(description, IndexFilter.all(), argumentPredicate); }
[ "public", "static", "ArgumentValidator", "argumentTypeValidator", "(", "String", "description", ",", "ArgumentPredicate", "argumentPredicate", ")", "{", "return", "argumentTypeValidator", "(", "description", ",", "IndexFilter", ".", "all", "(", ")", ",", "argumentPredic...
# Creates a {@link ArgumentValidator} which apply the {@link ArgumentPredicate} on all arguments. This is convenient for ```java {@linkplain #argumentTypeValidator(String, IndexFilter, ArgumentPredicate) argumentTypeValidator}( description, PredefinedIndexFilters.all(), argumentPredicate ); ``` @param description the description in case that the predicate returns {@code false}. @param argumentPredicate the {@link ArgumentPredicate} to be applied on a single argument. @return the {@link ArgumentValidator} @see IndexFilter#all() @see PredefinedArgumentPredicates
[ "#", "Creates", "a", "{", "@link", "ArgumentValidator", "}", "which", "apply", "the", "{", "@link", "ArgumentPredicate", "}", "on", "all", "arguments", "." ]
train
https://github.com/Abnaxos/markdown-doclet/blob/e98a9630206fc9c8d813cf2349ff594be8630054/doclet/jdk8/src/main/java/ch/raffael/mddoclet/mdtaglet/argval/PredefinedArgumentValidators.java#L343-L345
jenkinsci/jenkins
core/src/main/java/hudson/Util.java
Util.changeExtension
@Nonnull public static File changeExtension(@Nonnull File dst, @Nonnull String ext) { String p = dst.getPath(); int pos = p.lastIndexOf('.'); if (pos<0) return new File(p+ext); else return new File(p.substring(0,pos)+ext); }
java
@Nonnull public static File changeExtension(@Nonnull File dst, @Nonnull String ext) { String p = dst.getPath(); int pos = p.lastIndexOf('.'); if (pos<0) return new File(p+ext); else return new File(p.substring(0,pos)+ext); }
[ "@", "Nonnull", "public", "static", "File", "changeExtension", "(", "@", "Nonnull", "File", "dst", ",", "@", "Nonnull", "String", "ext", ")", "{", "String", "p", "=", "dst", ".", "getPath", "(", ")", ";", "int", "pos", "=", "p", ".", "lastIndexOf", "...
Returns a file name by changing its extension. @param ext For example, ".zip"
[ "Returns", "a", "file", "name", "by", "changing", "its", "extension", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L1371-L1377
vlingo/vlingo-http
src/main/java/io/vlingo/http/resource/Client.java
Client.using
public static Client using(final Configuration configuration, final ClientConsumerType type, final int poolSize) throws Exception { return new Client(configuration, type, poolSize); }
java
public static Client using(final Configuration configuration, final ClientConsumerType type, final int poolSize) throws Exception { return new Client(configuration, type, poolSize); }
[ "public", "static", "Client", "using", "(", "final", "Configuration", "configuration", ",", "final", "ClientConsumerType", "type", ",", "final", "int", "poolSize", ")", "throws", "Exception", "{", "return", "new", "Client", "(", "configuration", ",", "type", ","...
Answer a new {@code Client} from the {@code configuration}. @param configuration the Configuration @param type the ClientConsumerType @param poolSize the int size of the pool of workers @return Client @throws Exception when the Client cannot be created
[ "Answer", "a", "new", "{" ]
train
https://github.com/vlingo/vlingo-http/blob/746065fb1eaf1609c550ae45e96e3dbb9bfa37a2/src/main/java/io/vlingo/http/resource/Client.java#L42-L44
facebookarchive/hadoop-20
src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/PersistentState.java
PersistentState.updateState
public static void updateState(String filename, String firstLine, long offset) { ParseState ps = getState(filename); if (firstLine != null) ps.firstLine = firstLine; ps.offset = offset; setState(ps); }
java
public static void updateState(String filename, String firstLine, long offset) { ParseState ps = getState(filename); if (firstLine != null) ps.firstLine = firstLine; ps.offset = offset; setState(ps); }
[ "public", "static", "void", "updateState", "(", "String", "filename", ",", "String", "firstLine", ",", "long", "offset", ")", "{", "ParseState", "ps", "=", "getState", "(", "filename", ")", ";", "if", "(", "firstLine", "!=", "null", ")", "ps", ".", "firs...
Upadate the state of parsing for a particular log file. @param filename the log file for which to update the state @param firstLine the first line of the log file currently @param offset the byte offset of the last character parsed
[ "Upadate", "the", "state", "of", "parsing", "for", "a", "particular", "log", "file", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/PersistentState.java#L116-L126
wcm-io/wcm-io-sling
commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java
RequestParam.getFloat
public static float getFloat(@NotNull ServletRequest request, @NotNull String param) { return getFloat(request, param, 0f); }
java
public static float getFloat(@NotNull ServletRequest request, @NotNull String param) { return getFloat(request, param, 0f); }
[ "public", "static", "float", "getFloat", "(", "@", "NotNull", "ServletRequest", "request", ",", "@", "NotNull", "String", "param", ")", "{", "return", "getFloat", "(", "request", ",", "param", ",", "0f", ")", ";", "}" ]
Returns a request parameter as float. @param request Request. @param param Parameter name. @return Parameter value or 0 if it does not exist or is not a number.
[ "Returns", "a", "request", "parameter", "as", "float", "." ]
train
https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java#L189-L191
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListJobsRequest.java
ListJobsRequest.withTags
public ListJobsRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public ListJobsRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "ListJobsRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> Specifies to return only these tagged resources. </p> @param tags Specifies to return only these tagged resources. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Specifies", "to", "return", "only", "these", "tagged", "resources", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListJobsRequest.java#L162-L165
brianwhu/xillium
base/src/main/java/org/xillium/base/text/Balanced.java
Balanced.indexOf
public static int indexOf( Functor<Integer, Integer> symbols, String text, int begin, int end, char target, Functor<Integer, Integer> extra ) { ArrayDeque<Integer> deque = new ArrayDeque<>(); while (begin < end) { int c = text.charAt(begin); if (deque.size() > 0 && c == balance(symbols, deque.peek(), extra)) { deque.pop(); } else if (balance(symbols, c, extra) > 0) { if (deque.size() == 0 || balance(symbols, deque.peek(), extra) != deque.peek()) deque.push(c); } else if (deque.size() == 0 && c == target) { return begin; } ++begin; } return -1; }
java
public static int indexOf( Functor<Integer, Integer> symbols, String text, int begin, int end, char target, Functor<Integer, Integer> extra ) { ArrayDeque<Integer> deque = new ArrayDeque<>(); while (begin < end) { int c = text.charAt(begin); if (deque.size() > 0 && c == balance(symbols, deque.peek(), extra)) { deque.pop(); } else if (balance(symbols, c, extra) > 0) { if (deque.size() == 0 || balance(symbols, deque.peek(), extra) != deque.peek()) deque.push(c); } else if (deque.size() == 0 && c == target) { return begin; } ++begin; } return -1; }
[ "public", "static", "int", "indexOf", "(", "Functor", "<", "Integer", ",", "Integer", ">", "symbols", ",", "String", "text", ",", "int", "begin", ",", "int", "end", ",", "char", "target", ",", "Functor", "<", "Integer", ",", "Integer", ">", "extra", ")...
Returns the index within a string of the first occurrence of the specified character, similar to {@code String.indexOf}. However, any occurrence of the specified character enclosed between balanced symbols is ignored. @param symbols an optional functor to provide the complete set of balancing symbols @param text a String @param begin a begin offset @param end an end offset @param target the character to search for @param extra an optional functor to provide balancing symbols in addition to the standard ones @return the index of the character in the string, or -1 if the specified character is not found
[ "Returns", "the", "index", "within", "a", "string", "of", "the", "first", "occurrence", "of", "the", "specified", "character", "similar", "to", "{", "@code", "String", ".", "indexOf", "}", ".", "However", "any", "occurrence", "of", "the", "specified", "chara...
train
https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/base/src/main/java/org/xillium/base/text/Balanced.java#L39-L55
lmdbjava/lmdbjava
src/main/java/org/lmdbjava/Cursor.java
Cursor.get
public boolean get(final T key, final GetOp op) { if (SHOULD_CHECK) { requireNonNull(key); requireNonNull(op); checkNotClosed(); txn.checkReady(); } kv.keyIn(key); final int rc = LIB.mdb_cursor_get(ptrCursor, kv.pointerKey(), kv .pointerVal(), op.getCode()); if (rc == MDB_NOTFOUND) { return false; } checkRc(rc); kv.keyOut(); kv.valOut(); return true; }
java
public boolean get(final T key, final GetOp op) { if (SHOULD_CHECK) { requireNonNull(key); requireNonNull(op); checkNotClosed(); txn.checkReady(); } kv.keyIn(key); final int rc = LIB.mdb_cursor_get(ptrCursor, kv.pointerKey(), kv .pointerVal(), op.getCode()); if (rc == MDB_NOTFOUND) { return false; } checkRc(rc); kv.keyOut(); kv.valOut(); return true; }
[ "public", "boolean", "get", "(", "final", "T", "key", ",", "final", "GetOp", "op", ")", "{", "if", "(", "SHOULD_CHECK", ")", "{", "requireNonNull", "(", "key", ")", ";", "requireNonNull", "(", "op", ")", ";", "checkNotClosed", "(", ")", ";", "txn", "...
Reposition the key/value buffers based on the passed key and operation. @param key to search for @param op options for this operation @return false if key not found
[ "Reposition", "the", "key", "/", "value", "buffers", "based", "on", "the", "passed", "key", "and", "operation", "." ]
train
https://github.com/lmdbjava/lmdbjava/blob/5912beb1037722c71f3ddc05e70fcbe739dfa272/src/main/java/org/lmdbjava/Cursor.java#L135-L155
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java
AbstractService.bindProgressProperty
private void bindProgressProperty(final ServiceTaskBase<?> task, final DoubleProperty progressProperty) { // Perform this binding into the JAT to respect widget and task API JRebirth.runIntoJAT("Bind Progress Property to " + task.getServiceHandlerName(), () -> { // Avoid the progress bar to display 100% at start up task.updateProgress(0, 0); // Bind the progress bar progressProperty.bind(task.workDoneProperty().divide(task.totalWorkProperty())); }); }
java
private void bindProgressProperty(final ServiceTaskBase<?> task, final DoubleProperty progressProperty) { // Perform this binding into the JAT to respect widget and task API JRebirth.runIntoJAT("Bind Progress Property to " + task.getServiceHandlerName(), () -> { // Avoid the progress bar to display 100% at start up task.updateProgress(0, 0); // Bind the progress bar progressProperty.bind(task.workDoneProperty().divide(task.totalWorkProperty())); }); }
[ "private", "void", "bindProgressProperty", "(", "final", "ServiceTaskBase", "<", "?", ">", "task", ",", "final", "DoubleProperty", "progressProperty", ")", "{", "// Perform this binding into the JAT to respect widget and task API", "JRebirth", ".", "runIntoJAT", "(", "\"Bin...
Bind a task to a progress property to follow its progression. @param task the service task that we need to follow the progression @param progressBar graphical progress bar
[ "Bind", "a", "task", "to", "a", "progress", "property", "to", "follow", "its", "progression", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java#L186-L197
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.ofScale
public static BigMoney ofScale(CurrencyUnit currency, BigDecimal amount, int scale) { return BigMoney.ofScale(currency, amount, scale, RoundingMode.UNNECESSARY); }
java
public static BigMoney ofScale(CurrencyUnit currency, BigDecimal amount, int scale) { return BigMoney.ofScale(currency, amount, scale, RoundingMode.UNNECESSARY); }
[ "public", "static", "BigMoney", "ofScale", "(", "CurrencyUnit", "currency", ",", "BigDecimal", "amount", ",", "int", "scale", ")", "{", "return", "BigMoney", ".", "ofScale", "(", "currency", ",", "amount", ",", "scale", ",", "RoundingMode", ".", "UNNECESSARY",...
Obtains an instance of {@code BigMoney} from a {@code BigDecimal} at a specific scale. <p> This allows you to create an instance with a specific currency and amount. No rounding is performed on the amount, so it must have a scale less than or equal to the new scale. The result will have a minimum scale of zero. @param currency the currency, not null @param amount the amount of money, not null @param scale the scale to use, zero or positive @return the new instance, never null @throws ArithmeticException if the scale exceeds the currency scale
[ "Obtains", "an", "instance", "of", "{", "@code", "BigMoney", "}", "from", "a", "{", "@code", "BigDecimal", "}", "at", "a", "specific", "scale", ".", "<p", ">", "This", "allows", "you", "to", "create", "an", "instance", "with", "a", "specific", "currency"...
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L131-L133
phax/ph-commons
ph-json/src/main/java/com/helger/json/serialize/JsonReader.java
JsonReader.isValidJson
public static boolean isValidJson (@Nonnull @WillClose final InputStream aIS, @Nonnull final Charset aFallbackCharset) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aFallbackCharset, "FallbackCharset"); try { final Reader aReader = CharsetHelper.getReaderByBOM (aIS, aFallbackCharset); return isValidJson (aReader); } finally { StreamHelper.close (aIS); } }
java
public static boolean isValidJson (@Nonnull @WillClose final InputStream aIS, @Nonnull final Charset aFallbackCharset) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aFallbackCharset, "FallbackCharset"); try { final Reader aReader = CharsetHelper.getReaderByBOM (aIS, aFallbackCharset); return isValidJson (aReader); } finally { StreamHelper.close (aIS); } }
[ "public", "static", "boolean", "isValidJson", "(", "@", "Nonnull", "@", "WillClose", "final", "InputStream", "aIS", ",", "@", "Nonnull", "final", "Charset", "aFallbackCharset", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aIS", ",", "\"InputStream\"", ")", ...
Check if the passed input stream can be resembled to valid Json content. This is accomplished by fully parsing the Json file each time the method is called. This consumes <b>less memory</b> than calling any of the <code>read...</code> methods and checking for a non-<code>null</code> result. @param aIS The input stream to use. Is automatically closed. May not be <code>null</code>. @param aFallbackCharset The charset to be used in case no BOM is present. May not be <code>null</code>. @return <code>true</code> if the Json is valid according to the version, <code>false</code> if not
[ "Check", "if", "the", "passed", "input", "stream", "can", "be", "resembled", "to", "valid", "Json", "content", ".", "This", "is", "accomplished", "by", "fully", "parsing", "the", "Json", "file", "each", "time", "the", "method", "is", "called", ".", "This",...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-json/src/main/java/com/helger/json/serialize/JsonReader.java#L344-L358
lunisolar/magma
magma-func/src/main/java/eu/lunisolar/magma/func/Function4U.java
Function4U.biFunc
public static <T1, T2, R> BiFunction biFunc(final BiFunction<T1, T2, R> lambda) { return lambda; }
java
public static <T1, T2, R> BiFunction biFunc(final BiFunction<T1, T2, R> lambda) { return lambda; }
[ "public", "static", "<", "T1", ",", "T2", ",", "R", ">", "BiFunction", "biFunc", "(", "final", "BiFunction", "<", "T1", ",", "T2", ",", "R", ">", "lambda", ")", "{", "return", "lambda", ";", "}" ]
Convenient method in case lambda expression is ambiguous for the compiler.
[ "Convenient", "method", "in", "case", "lambda", "expression", "is", "ambiguous", "for", "the", "compiler", "." ]
train
https://github.com/lunisolar/magma/blob/83809c6d1a33d913aec6c49920251e4f0be8b213/magma-func/src/main/java/eu/lunisolar/magma/func/Function4U.java#L237-L239
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/ComponentTagDeclarationLibrary.java
ComponentTagDeclarationLibrary.addComponent
public final void addComponent(String namespace, String name, String componentType, String rendererType, Class<? extends TagHandler> handlerType) { Map<String, TagHandlerFactory> map = _factories.get(namespace); if (map == null) { map = new HashMap<String, TagHandlerFactory>(); _factories.put(namespace, map); } map.put(name, new UserComponentHandlerFactory(componentType, rendererType, handlerType)); }
java
public final void addComponent(String namespace, String name, String componentType, String rendererType, Class<? extends TagHandler> handlerType) { Map<String, TagHandlerFactory> map = _factories.get(namespace); if (map == null) { map = new HashMap<String, TagHandlerFactory>(); _factories.put(namespace, map); } map.put(name, new UserComponentHandlerFactory(componentType, rendererType, handlerType)); }
[ "public", "final", "void", "addComponent", "(", "String", "namespace", ",", "String", "name", ",", "String", "componentType", ",", "String", "rendererType", ",", "Class", "<", "?", "extends", "TagHandler", ">", "handlerType", ")", "{", "Map", "<", "String", ...
Add a ComponentHandler with the specified componentType and rendererType, aliased by the tag name. The Facelet will be compiled with the specified HandlerType (which must extend AbstractComponentHandler). @see AbstractComponentHandler @param name name to use, "foo" would be &lt;my:foo /> @param componentType componentType to use @param rendererType rendererType to use @param handlerType a Class that extends AbstractComponentHandler
[ "Add", "a", "ComponentHandler", "with", "the", "specified", "componentType", "and", "rendererType", "aliased", "by", "the", "tag", "name", ".", "The", "Facelet", "will", "be", "compiled", "with", "the", "specified", "HandlerType", "(", "which", "must", "extend",...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/ComponentTagDeclarationLibrary.java#L169-L179
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/touchSpin/TouchSpinRenderer.java
TouchSpinRenderer.decode
@Override public void decode(FacesContext context, UIComponent component) { TouchSpin spinner = (TouchSpin) component; if (spinner.isDisabled() || spinner.isReadonly()) { return; } decodeBehaviors(context, spinner); String clientId = spinner.getClientId(context); String name = spinner.getName(); if (null == name) { name = "input_" + clientId; } String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(name); if (submittedValue != null) { spinner.setSubmittedValue(submittedValue); } new AJAXRenderer().decode(context, component, name); }
java
@Override public void decode(FacesContext context, UIComponent component) { TouchSpin spinner = (TouchSpin) component; if (spinner.isDisabled() || spinner.isReadonly()) { return; } decodeBehaviors(context, spinner); String clientId = spinner.getClientId(context); String name = spinner.getName(); if (null == name) { name = "input_" + clientId; } String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(name); if (submittedValue != null) { spinner.setSubmittedValue(submittedValue); } new AJAXRenderer().decode(context, component, name); }
[ "@", "Override", "public", "void", "decode", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "TouchSpin", "spinner", "=", "(", "TouchSpin", ")", "component", ";", "if", "(", "spinner", ".", "isDisabled", "(", ")", "||", "spinner", ...
This methods receives and processes input made by the user. More specifically, it ckecks whether the user has interacted with the current b:spinner. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:spinner.
[ "This", "methods", "receives", "and", "processes", "input", "made", "by", "the", "user", ".", "More", "specifically", "it", "ckecks", "whether", "the", "user", "has", "interacted", "with", "the", "current", "b", ":", "spinner", ".", "The", "default", "implem...
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/touchSpin/TouchSpinRenderer.java#L46-L67
pedrovgs/DraggablePanel
draggablepanel/src/main/java/com/github/pedrovgs/DraggableView.java
DraggableView.cloneMotionEventWithAction
private MotionEvent cloneMotionEventWithAction(MotionEvent event, int action) { return MotionEvent.obtain(event.getDownTime(), event.getEventTime(), action, event.getX(), event.getY(), event.getMetaState()); }
java
private MotionEvent cloneMotionEventWithAction(MotionEvent event, int action) { return MotionEvent.obtain(event.getDownTime(), event.getEventTime(), action, event.getX(), event.getY(), event.getMetaState()); }
[ "private", "MotionEvent", "cloneMotionEventWithAction", "(", "MotionEvent", "event", ",", "int", "action", ")", "{", "return", "MotionEvent", ".", "obtain", "(", "event", ".", "getDownTime", "(", ")", ",", "event", ".", "getEventTime", "(", ")", ",", "action",...
Clone given motion event and set specified action. This method is useful, when we want to cancel event propagation in child views by sending event with {@link android.view.MotionEvent#ACTION_CANCEL} action. @param event event to clone @param action new action @return cloned motion event
[ "Clone", "given", "motion", "event", "and", "set", "specified", "action", ".", "This", "method", "is", "useful", "when", "we", "want", "to", "cancel", "event", "propagation", "in", "child", "views", "by", "sending", "event", "with", "{", "@link", "android", ...
train
https://github.com/pedrovgs/DraggablePanel/blob/6b6d1806fa4140113f31307a2571bf02435aa53a/draggablepanel/src/main/java/com/github/pedrovgs/DraggableView.java#L420-L423
VoltDB/voltdb
third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java
HelpFormatter.appendOptionGroup
private void appendOptionGroup(StringBuffer buff, OptionGroup group) { if (!group.isRequired()) { buff.append("["); } List<Option> optList = new ArrayList<Option>(group.getOptions()); if (getOptionComparator() != null) { Collections.sort(optList, getOptionComparator()); } // for each option in the OptionGroup for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // whether the option is required or not is handled at group level appendOption(buff, it.next(), true); if (it.hasNext()) { buff.append(" | "); } } if (!group.isRequired()) { buff.append("]"); } }
java
private void appendOptionGroup(StringBuffer buff, OptionGroup group) { if (!group.isRequired()) { buff.append("["); } List<Option> optList = new ArrayList<Option>(group.getOptions()); if (getOptionComparator() != null) { Collections.sort(optList, getOptionComparator()); } // for each option in the OptionGroup for (Iterator<Option> it = optList.iterator(); it.hasNext();) { // whether the option is required or not is handled at group level appendOption(buff, it.next(), true); if (it.hasNext()) { buff.append(" | "); } } if (!group.isRequired()) { buff.append("]"); } }
[ "private", "void", "appendOptionGroup", "(", "StringBuffer", "buff", ",", "OptionGroup", "group", ")", "{", "if", "(", "!", "group", ".", "isRequired", "(", ")", ")", "{", "buff", ".", "append", "(", "\"[\"", ")", ";", "}", "List", "<", "Option", ">", ...
Appends the usage clause for an OptionGroup to a StringBuffer. The clause is wrapped in square brackets if the group is required. The display of the options is handled by appendOption @param buff the StringBuffer to append to @param group the group to append @see #appendOption(StringBuffer,Option,boolean)
[ "Appends", "the", "usage", "clause", "for", "an", "OptionGroup", "to", "a", "StringBuffer", ".", "The", "clause", "is", "wrapped", "in", "square", "brackets", "if", "the", "group", "is", "required", ".", "The", "display", "of", "the", "options", "is", "han...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java#L644-L672
ManfredTremmel/gwt-commons-lang3
src/main/resources/org/apache/commons/jre/java/util/GregorianCalendar.java
GregorianCalendar.getWeekOne
@SuppressWarnings("deprecation") private Date getWeekOne(int year) { GregorianCalendar weekOne = new GregorianCalendar(); weekOne.setFirstDayOfWeek(getFirstDayOfWeek()); weekOne.setMinimalDaysInFirstWeek(getMinimalDaysInFirstWeek()); weekOne.setTime(new Date(year, 0, 1)); // can we use the week of 1/1/year as week one? int dow = weekOne.get(DAY_OF_WEEK); if (dow < weekOne.getFirstDayOfWeek()) dow += 7; int eow = weekOne.getFirstDayOfWeek() + 7; if ((eow - dow) < weekOne.getMinimalDaysInFirstWeek()) { // nope, week one is the following week weekOne.add(DATE, 7); } weekOne.set(DAY_OF_WEEK, weekOne.getFirstDayOfWeek()); return weekOne.getTime(); }
java
@SuppressWarnings("deprecation") private Date getWeekOne(int year) { GregorianCalendar weekOne = new GregorianCalendar(); weekOne.setFirstDayOfWeek(getFirstDayOfWeek()); weekOne.setMinimalDaysInFirstWeek(getMinimalDaysInFirstWeek()); weekOne.setTime(new Date(year, 0, 1)); // can we use the week of 1/1/year as week one? int dow = weekOne.get(DAY_OF_WEEK); if (dow < weekOne.getFirstDayOfWeek()) dow += 7; int eow = weekOne.getFirstDayOfWeek() + 7; if ((eow - dow) < weekOne.getMinimalDaysInFirstWeek()) { // nope, week one is the following week weekOne.add(DATE, 7); } weekOne.set(DAY_OF_WEEK, weekOne.getFirstDayOfWeek()); return weekOne.getTime(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "private", "Date", "getWeekOne", "(", "int", "year", ")", "{", "GregorianCalendar", "weekOne", "=", "new", "GregorianCalendar", "(", ")", ";", "weekOne", ".", "setFirstDayOfWeek", "(", "getFirstDayOfWeek", "(",...
Gets the date of the first week for the specified year. @param year This is year - 1900 as returned by Date.getYear() @return
[ "Gets", "the", "date", "of", "the", "first", "week", "for", "the", "specified", "year", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/resources/org/apache/commons/jre/java/util/GregorianCalendar.java#L396-L412
devnied/Bit-lib4j
src/main/java/fr/devnied/bitlib/BitUtils.java
BitUtils.setNextValue
protected void setNextValue(final long pValue, final int pLength, final int pMaxSize) { long value = pValue; // Set to max value if pValue cannot be stored on pLength bits. long bitMax = (long) Math.pow(2, Math.min(pLength, pMaxSize)); if (pValue > bitMax) { value = bitMax - 1; } // size to wrote int writeSize = pLength; while (writeSize > 0) { // modulo int mod = currentBitIndex % BYTE_SIZE; byte ret = 0; if (mod == 0 && writeSize <= BYTE_SIZE || pLength < BYTE_SIZE - mod) { // shift left value ret = (byte) (value << BYTE_SIZE - (writeSize + mod)); } else { // shift right long length = Long.toBinaryString(value).length(); ret = (byte) (value >> writeSize - length - (BYTE_SIZE - length - mod)); } byteTab[currentBitIndex / BYTE_SIZE] |= ret; long val = Math.min(writeSize, BYTE_SIZE - mod); writeSize -= val; currentBitIndex += val; } }
java
protected void setNextValue(final long pValue, final int pLength, final int pMaxSize) { long value = pValue; // Set to max value if pValue cannot be stored on pLength bits. long bitMax = (long) Math.pow(2, Math.min(pLength, pMaxSize)); if (pValue > bitMax) { value = bitMax - 1; } // size to wrote int writeSize = pLength; while (writeSize > 0) { // modulo int mod = currentBitIndex % BYTE_SIZE; byte ret = 0; if (mod == 0 && writeSize <= BYTE_SIZE || pLength < BYTE_SIZE - mod) { // shift left value ret = (byte) (value << BYTE_SIZE - (writeSize + mod)); } else { // shift right long length = Long.toBinaryString(value).length(); ret = (byte) (value >> writeSize - length - (BYTE_SIZE - length - mod)); } byteTab[currentBitIndex / BYTE_SIZE] |= ret; long val = Math.min(writeSize, BYTE_SIZE - mod); writeSize -= val; currentBitIndex += val; } }
[ "protected", "void", "setNextValue", "(", "final", "long", "pValue", ",", "final", "int", "pLength", ",", "final", "int", "pMaxSize", ")", "{", "long", "value", "=", "pValue", ";", "// Set to max value if pValue cannot be stored on pLength bits.\r", "long", "bitMax", ...
Add Value to the current position with the specified size @param pValue value to add @param pLength length of the value @param pMaxSize max size in bits
[ "Add", "Value", "to", "the", "current", "position", "with", "the", "specified", "size" ]
train
https://github.com/devnied/Bit-lib4j/blob/bdfa79fd12e7e3d5cf1196291825ef1bb12a1ee0/src/main/java/fr/devnied/bitlib/BitUtils.java#L590-L616
alkacon/opencms-core
src/org/opencms/widgets/serialdate/CmsSerialDateValue.java
CmsSerialDateValue.readOptionalString
private String readOptionalString(JSONObject json, String key, String defaultValue) { try { String str = json.getString(key); if (str != null) { return str; } } catch (JSONException e) { LOG.debug("Reading optional JSON string failed. Default to provided default value.", e); } return defaultValue; }
java
private String readOptionalString(JSONObject json, String key, String defaultValue) { try { String str = json.getString(key); if (str != null) { return str; } } catch (JSONException e) { LOG.debug("Reading optional JSON string failed. Default to provided default value.", e); } return defaultValue; }
[ "private", "String", "readOptionalString", "(", "JSONObject", "json", ",", "String", "key", ",", "String", "defaultValue", ")", "{", "try", "{", "String", "str", "=", "json", ".", "getString", "(", "key", ")", ";", "if", "(", "str", "!=", "null", ")", ...
Read an optional string value form a JSON Object. @param json the JSON object to read from. @param key the key for the string value in the provided JSON object. @param defaultValue the default value, to be returned if the string can not be read from the JSON object. @return the string or the default value if reading the string fails.
[ "Read", "an", "optional", "string", "value", "form", "a", "JSON", "Object", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/serialdate/CmsSerialDateValue.java#L385-L397