repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
OpenLiberty/open-liberty
dev/com.ibm.json4j/src/com/ibm/json/java/JSONArray.java
JSONArray.parse
static public JSONArray parse(InputStream is) throws IOException { InputStreamReader isr = null; try { isr = new InputStreamReader(is, "UTF-8"); } catch (Exception ex) { isr = new InputStreamReader(is); } return parse(isr); }
java
static public JSONArray parse(InputStream is) throws IOException { InputStreamReader isr = null; try { isr = new InputStreamReader(is, "UTF-8"); } catch (Exception ex) { isr = new InputStreamReader(is); } return parse(isr); }
[ "static", "public", "JSONArray", "parse", "(", "InputStream", "is", ")", "throws", "IOException", "{", "InputStreamReader", "isr", "=", "null", ";", "try", "{", "isr", "=", "new", "InputStreamReader", "(", "is", ",", "\"UTF-8\"", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "isr", "=", "new", "InputStreamReader", "(", "is", ")", ";", "}", "return", "parse", "(", "isr", ")", ";", "}" ]
Convert a stream of JSONArray text into JSONArray form. @param is The inputStream from which to read the JSON. It will assume the input stream is in UTF-8 and read it as such. @return The contructed JSONArray Object. @throws IOEXception Thrown if an underlying IO error from the stream occurs, or if malformed JSON is read,
[ "Convert", "a", "stream", "of", "JSONArray", "text", "into", "JSONArray", "form", ".", "@param", "is", "The", "inputStream", "from", "which", "to", "read", "the", "JSON", ".", "It", "will", "assume", "the", "input", "stream", "is", "in", "UTF", "-", "8", "and", "read", "it", "as", "such", ".", "@return", "The", "contructed", "JSONArray", "Object", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.json4j/src/com/ibm/json/java/JSONArray.java#L121-L132
forge/core
parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/beans/FieldOperations.java
FieldOperations.addFieldTo
public FieldSource<JavaClassSource> addFieldTo(final JavaClassSource targetClass, final String fieldType, final String fieldName, Visibility visibility, boolean withGetter, boolean withSetter, String... annotations) { return addFieldTo(targetClass, fieldType, fieldName, visibility, withGetter, withSetter, true, annotations); }
java
public FieldSource<JavaClassSource> addFieldTo(final JavaClassSource targetClass, final String fieldType, final String fieldName, Visibility visibility, boolean withGetter, boolean withSetter, String... annotations) { return addFieldTo(targetClass, fieldType, fieldName, visibility, withGetter, withSetter, true, annotations); }
[ "public", "FieldSource", "<", "JavaClassSource", ">", "addFieldTo", "(", "final", "JavaClassSource", "targetClass", ",", "final", "String", "fieldType", ",", "final", "String", "fieldName", ",", "Visibility", "visibility", ",", "boolean", "withGetter", ",", "boolean", "withSetter", ",", "String", "...", "annotations", ")", "{", "return", "addFieldTo", "(", "targetClass", ",", "fieldType", ",", "fieldName", ",", "visibility", ",", "withGetter", ",", "withSetter", ",", "true", ",", "annotations", ")", ";", "}" ]
Adds the field, updating the toString(). If specified, adds a getter, a setter or both. @param targetClass The class which the field will be added to @param fieldType The type of the field @param fieldName The name of the field @param visibility The visibility of the newly created field @param withGetter Specifies whether accessor method should be created @param withSetter Specifies whether mutator method should be created @param annotations An optional list of annotations that will be added to the field @return The newly created field
[ "Adds", "the", "field", "updating", "the", "toString", "()", ".", "If", "specified", "adds", "a", "getter", "a", "setter", "or", "both", "." ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/beans/FieldOperations.java#L127-L132
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/factory/geo/FactoryMultiView.java
FactoryMultiView.fundamentalRefine
public static RefineEpipolar fundamentalRefine(double tol , int maxIterations , EpipolarError type ) { switch( type ) { case SAMPSON: return new LeastSquaresFundamental(tol,maxIterations,true); case SIMPLE: return new LeastSquaresFundamental(tol,maxIterations,false); } throw new IllegalArgumentException("Type not supported: "+type); }
java
public static RefineEpipolar fundamentalRefine(double tol , int maxIterations , EpipolarError type ) { switch( type ) { case SAMPSON: return new LeastSquaresFundamental(tol,maxIterations,true); case SIMPLE: return new LeastSquaresFundamental(tol,maxIterations,false); } throw new IllegalArgumentException("Type not supported: "+type); }
[ "public", "static", "RefineEpipolar", "fundamentalRefine", "(", "double", "tol", ",", "int", "maxIterations", ",", "EpipolarError", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "SAMPSON", ":", "return", "new", "LeastSquaresFundamental", "(", "tol", ",", "maxIterations", ",", "true", ")", ";", "case", "SIMPLE", ":", "return", "new", "LeastSquaresFundamental", "(", "tol", ",", "maxIterations", ",", "false", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Type not supported: \"", "+", "type", ")", ";", "}" ]
Creates a non-linear optimizer for refining estimates of fundamental or essential matrices. @see boofcv.alg.geo.f.FundamentalResidualSampson @see boofcv.alg.geo.f.FundamentalResidualSimple @param tol Tolerance for convergence. Try 1e-8 @param maxIterations Maximum number of iterations it will perform. Try 100 or more. @return RefineEpipolar
[ "Creates", "a", "non", "-", "linear", "optimizer", "for", "refining", "estimates", "of", "fundamental", "or", "essential", "matrices", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/factory/geo/FactoryMultiView.java#L370-L380
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.lowerCase
public static String lowerCase(final String str, final Locale locale) { if (str == null) { return null; } return str.toLowerCase(locale); }
java
public static String lowerCase(final String str, final Locale locale) { if (str == null) { return null; } return str.toLowerCase(locale); }
[ "public", "static", "String", "lowerCase", "(", "final", "String", "str", ",", "final", "Locale", "locale", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "null", ";", "}", "return", "str", ".", "toLowerCase", "(", "locale", ")", ";", "}" ]
<p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p> <p>A {@code null} input String returns {@code null}.</p> <pre> StringUtils.lowerCase(null, Locale.ENGLISH) = null StringUtils.lowerCase("", Locale.ENGLISH) = "" StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc" </pre> @param str the String to lower case, may be null @param locale the locale that defines the case transformation rules, must not be null @return the lower cased String, {@code null} if null String input @since 2.5
[ "<p", ">", "Converts", "a", "String", "to", "lower", "case", "as", "per", "{", "@link", "String#toLowerCase", "(", "Locale", ")", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L6690-L6695
headius/invokebinder
src/main/java/com/headius/invokebinder/Signature.java
Signature.prependArgs
public Signature prependArgs(String[] names, Class<?>... types) { String[] newArgNames = new String[argNames.length + names.length]; System.arraycopy(argNames, 0, newArgNames, names.length, argNames.length); System.arraycopy(names, 0, newArgNames, 0, names.length); MethodType newMethodType = methodType.insertParameterTypes(0, types); return new Signature(newMethodType, newArgNames); }
java
public Signature prependArgs(String[] names, Class<?>... types) { String[] newArgNames = new String[argNames.length + names.length]; System.arraycopy(argNames, 0, newArgNames, names.length, argNames.length); System.arraycopy(names, 0, newArgNames, 0, names.length); MethodType newMethodType = methodType.insertParameterTypes(0, types); return new Signature(newMethodType, newArgNames); }
[ "public", "Signature", "prependArgs", "(", "String", "[", "]", "names", ",", "Class", "<", "?", ">", "...", "types", ")", "{", "String", "[", "]", "newArgNames", "=", "new", "String", "[", "argNames", ".", "length", "+", "names", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "argNames", ",", "0", ",", "newArgNames", ",", "names", ".", "length", ",", "argNames", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "names", ",", "0", ",", "newArgNames", ",", "0", ",", "names", ".", "length", ")", ";", "MethodType", "newMethodType", "=", "methodType", ".", "insertParameterTypes", "(", "0", ",", "types", ")", ";", "return", "new", "Signature", "(", "newMethodType", ",", "newArgNames", ")", ";", "}" ]
Prepend arguments (names + types) to the signature. @param names the names of the arguments @param types the types of the arguments @return a new signature with the added arguments
[ "Prepend", "arguments", "(", "names", "+", "types", ")", "to", "the", "signature", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Signature.java#L234-L240
kiegroup/jbpm
jbpm-audit/src/main/java/org/jbpm/process/audit/AuditLoggerFactory.java
AuditLoggerFactory.newJMSInstance
public static AbstractAuditLogger newJMSInstance(boolean transacted, ConnectionFactory connFactory, Queue queue) { AsyncAuditLogProducer logger = new AsyncAuditLogProducer(); logger.setTransacted(transacted); logger.setConnectionFactory(connFactory); logger.setQueue(queue); return logger; }
java
public static AbstractAuditLogger newJMSInstance(boolean transacted, ConnectionFactory connFactory, Queue queue) { AsyncAuditLogProducer logger = new AsyncAuditLogProducer(); logger.setTransacted(transacted); logger.setConnectionFactory(connFactory); logger.setQueue(queue); return logger; }
[ "public", "static", "AbstractAuditLogger", "newJMSInstance", "(", "boolean", "transacted", ",", "ConnectionFactory", "connFactory", ",", "Queue", "queue", ")", "{", "AsyncAuditLogProducer", "logger", "=", "new", "AsyncAuditLogProducer", "(", ")", ";", "logger", ".", "setTransacted", "(", "transacted", ")", ";", "logger", ".", "setConnectionFactory", "(", "connFactory", ")", ";", "logger", ".", "setQueue", "(", "queue", ")", ";", "return", "logger", ";", "}" ]
Creates new instance of JMS audit logger based on given connection factory and queue. NOTE: this will build the logger but it is not registered directly on a session: once received, it will need to be registered as an event listener @param transacted determines if JMS session is transacted or not @param connFactory connection factory instance @param queue JMS queue instance @return new instance of JMS audit logger
[ "Creates", "new", "instance", "of", "JMS", "audit", "logger", "based", "on", "given", "connection", "factory", "and", "queue", ".", "NOTE", ":", "this", "will", "build", "the", "logger", "but", "it", "is", "not", "registered", "directly", "on", "a", "session", ":", "once", "received", "it", "will", "need", "to", "be", "registered", "as", "an", "event", "listener" ]
train
https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-audit/src/main/java/org/jbpm/process/audit/AuditLoggerFactory.java#L197-L204
twilliamson/mogwee-logging
src/main/java/com/mogwee/logging/Logger.java
Logger.warnDebug
public final void warnDebug(final Throwable cause, final String message) { logDebug(Level.WARN, cause, message); }
java
public final void warnDebug(final Throwable cause, final String message) { logDebug(Level.WARN, cause, message); }
[ "public", "final", "void", "warnDebug", "(", "final", "Throwable", "cause", ",", "final", "String", "message", ")", "{", "logDebug", "(", "Level", ".", "WARN", ",", "cause", ",", "message", ")", ";", "}" ]
Logs a message and stack trace if DEBUG logging is enabled or a formatted message and exception description if WARN logging is enabled. @param cause an exception to print stack trace of if DEBUG logging is enabled @param message a message
[ "Logs", "a", "message", "and", "stack", "trace", "if", "DEBUG", "logging", "is", "enabled", "or", "a", "formatted", "message", "and", "exception", "description", "if", "WARN", "logging", "is", "enabled", "." ]
train
https://github.com/twilliamson/mogwee-logging/blob/30b99c2649de455432d956a8f6a74316de4cd62c/src/main/java/com/mogwee/logging/Logger.java#L381-L384
OpenLiberty/open-liberty
dev/com.ibm.ws.transaction.cdi/src/com/ibm/tx/jta/cdi/interceptors/Never.java
Never.never
@AroundInvoke public Object never(final InvocationContext context) throws Exception { if (getUOWM().getUOWType() == UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION) { throw new TransactionalException("TxType.NEVER method called within a global tx", new InvalidTransactionException()); } return runUnderUOWNoEnablement(UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION, true, context, "NEVER"); }
java
@AroundInvoke public Object never(final InvocationContext context) throws Exception { if (getUOWM().getUOWType() == UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION) { throw new TransactionalException("TxType.NEVER method called within a global tx", new InvalidTransactionException()); } return runUnderUOWNoEnablement(UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION, true, context, "NEVER"); }
[ "@", "AroundInvoke", "public", "Object", "never", "(", "final", "InvocationContext", "context", ")", "throws", "Exception", "{", "if", "(", "getUOWM", "(", ")", ".", "getUOWType", "(", ")", "==", "UOWSynchronizationRegistry", ".", "UOW_TYPE_GLOBAL_TRANSACTION", ")", "{", "throw", "new", "TransactionalException", "(", "\"TxType.NEVER method called within a global tx\"", ",", "new", "InvalidTransactionException", "(", ")", ")", ";", "}", "return", "runUnderUOWNoEnablement", "(", "UOWSynchronizationRegistry", ".", "UOW_TYPE_LOCAL_TRANSACTION", ",", "true", ",", "context", ",", "\"NEVER\"", ")", ";", "}" ]
<p>If called outside a transaction context, managed bean method execution must then continue outside a transaction context.</p> <p>If called inside a transaction context, a TransactionalException with a nested InvalidTransactionException must be thrown.</p>
[ "<p", ">", "If", "called", "outside", "a", "transaction", "context", "managed", "bean", "method", "execution", "must", "then", "continue", "outside", "a", "transaction", "context", ".", "<", "/", "p", ">", "<p", ">", "If", "called", "inside", "a", "transaction", "context", "a", "TransactionalException", "with", "a", "nested", "InvalidTransactionException", "must", "be", "thrown", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transaction.cdi/src/com/ibm/tx/jta/cdi/interceptors/Never.java#L37-L46
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.getFragmentInMilliseconds
@GwtIncompatible("incompatible method") public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) { return getFragment(calendar, fragment, TimeUnit.MILLISECONDS); }
java
@GwtIncompatible("incompatible method") public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) { return getFragment(calendar, fragment, TimeUnit.MILLISECONDS); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "long", "getFragmentInMilliseconds", "(", "final", "Calendar", "calendar", ",", "final", "int", "fragment", ")", "{", "return", "getFragment", "(", "calendar", ",", "fragment", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}" ]
<p>Returns the number of milliseconds within the fragment. All datefields greater than the fragment will be ignored.</p> <p>Asking the milliseconds of any date will only return the number of milliseconds of the current second (resulting in a number between 0 and 999). This method will retrieve the number of milliseconds for any fragment. For example, if you want to calculate the number of seconds past today, your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will be all seconds of the past hour(s), minutes(s) and second(s).</p> <p>Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND A fragment less than or equal to a MILLISECOND field will return 0.</p> <ul> <li>January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 (equivalent to calendar.get(Calendar.MILLISECOND))</li> <li>January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 (equivalent to calendar.get(Calendar.MILLISECOND))</li> <li>January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538 (10*1000 + 538)</li> <li>January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 (a millisecond cannot be split in milliseconds)</li> </ul> @param calendar the calendar to work with, not null @param fragment the {@code Calendar} field part of calendar to calculate @return number of milliseconds within the fragment of date @throws IllegalArgumentException if the date is <code>null</code> or fragment is not supported @since 2.4
[ "<p", ">", "Returns", "the", "number", "of", "milliseconds", "within", "the", "fragment", ".", "All", "datefields", "greater", "than", "the", "fragment", "will", "be", "ignored", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1491-L1494
btrplace/scheduler
api/src/main/java/org/btrplace/model/view/ShareableResource.java
ShareableResource.setCapacity
public ShareableResource setCapacity(Node n, int val) { if (val < 0) { throw new IllegalArgumentException(String.format("The '%s' capacity of node '%s' must be >= 0", rcId, n)); } nodesCapacity.put(n, val); return this; }
java
public ShareableResource setCapacity(Node n, int val) { if (val < 0) { throw new IllegalArgumentException(String.format("The '%s' capacity of node '%s' must be >= 0", rcId, n)); } nodesCapacity.put(n, val); return this; }
[ "public", "ShareableResource", "setCapacity", "(", "Node", "n", ",", "int", "val", ")", "{", "if", "(", "val", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"The '%s' capacity of node '%s' must be >= 0\"", ",", "rcId", ",", "n", ")", ")", ";", "}", "nodesCapacity", ".", "put", "(", "n", ",", "val", ")", ";", "return", "this", ";", "}" ]
Set the resource consumption of a node. @param n the node @param val the value to set @return the current resource
[ "Set", "the", "resource", "consumption", "of", "a", "node", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/ShareableResource.java#L177-L183
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/list/primitive/IntInterval.java
IntInterval.oddsFromTo
public static IntInterval oddsFromTo(int from, int to) { if (from % 2 == 0) { if (from < to) { from++; } else { from--; } } if (to % 2 == 0) { if (to > from) { to--; } else { to++; } } return IntInterval.fromToBy(from, to, to > from ? 2 : -2); }
java
public static IntInterval oddsFromTo(int from, int to) { if (from % 2 == 0) { if (from < to) { from++; } else { from--; } } if (to % 2 == 0) { if (to > from) { to--; } else { to++; } } return IntInterval.fromToBy(from, to, to > from ? 2 : -2); }
[ "public", "static", "IntInterval", "oddsFromTo", "(", "int", "from", ",", "int", "to", ")", "{", "if", "(", "from", "%", "2", "==", "0", ")", "{", "if", "(", "from", "<", "to", ")", "{", "from", "++", ";", "}", "else", "{", "from", "--", ";", "}", "}", "if", "(", "to", "%", "2", "==", "0", ")", "{", "if", "(", "to", ">", "from", ")", "{", "to", "--", ";", "}", "else", "{", "to", "++", ";", "}", "}", "return", "IntInterval", ".", "fromToBy", "(", "from", ",", "to", ",", "to", ">", "from", "?", "2", ":", "-", "2", ")", ";", "}" ]
Returns an IntInterval representing the odd values from the value from to the value to.
[ "Returns", "an", "IntInterval", "representing", "the", "odd", "values", "from", "the", "value", "from", "to", "the", "value", "to", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/list/primitive/IntInterval.java#L207-L232
apache/reef
lang/java/reef-common/src/main/java/org/apache/reef/client/DriverLauncher.java
DriverLauncher.waitForStatus
public LauncherStatus waitForStatus(final long waitTime, final LauncherStatus... statuses) { final long endTime = System.currentTimeMillis() + waitTime; final HashSet<LauncherStatus> statSet = new HashSet<>(statuses.length * 2); Collections.addAll(statSet, statuses); Collections.addAll(statSet, LauncherStatus.FAILED, LauncherStatus.FORCE_CLOSED); LOG.log(Level.FINEST, "Wait for status: {0}", statSet); final LauncherStatus finalStatus; synchronized (this) { while (!statSet.contains(this.status)) { try { final long delay = endTime - System.currentTimeMillis(); if (delay <= 0) { break; } LOG.log(Level.FINE, "Wait for {0} milliSeconds", delay); this.wait(delay); } catch (final InterruptedException ex) { LOG.log(Level.FINE, "Interrupted: {0}", ex); } } finalStatus = this.status; } LOG.log(Level.FINEST, "Final status: {0}", finalStatus); return finalStatus; }
java
public LauncherStatus waitForStatus(final long waitTime, final LauncherStatus... statuses) { final long endTime = System.currentTimeMillis() + waitTime; final HashSet<LauncherStatus> statSet = new HashSet<>(statuses.length * 2); Collections.addAll(statSet, statuses); Collections.addAll(statSet, LauncherStatus.FAILED, LauncherStatus.FORCE_CLOSED); LOG.log(Level.FINEST, "Wait for status: {0}", statSet); final LauncherStatus finalStatus; synchronized (this) { while (!statSet.contains(this.status)) { try { final long delay = endTime - System.currentTimeMillis(); if (delay <= 0) { break; } LOG.log(Level.FINE, "Wait for {0} milliSeconds", delay); this.wait(delay); } catch (final InterruptedException ex) { LOG.log(Level.FINE, "Interrupted: {0}", ex); } } finalStatus = this.status; } LOG.log(Level.FINEST, "Final status: {0}", finalStatus); return finalStatus; }
[ "public", "LauncherStatus", "waitForStatus", "(", "final", "long", "waitTime", ",", "final", "LauncherStatus", "...", "statuses", ")", "{", "final", "long", "endTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "waitTime", ";", "final", "HashSet", "<", "LauncherStatus", ">", "statSet", "=", "new", "HashSet", "<>", "(", "statuses", ".", "length", "*", "2", ")", ";", "Collections", ".", "addAll", "(", "statSet", ",", "statuses", ")", ";", "Collections", ".", "addAll", "(", "statSet", ",", "LauncherStatus", ".", "FAILED", ",", "LauncherStatus", ".", "FORCE_CLOSED", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINEST", ",", "\"Wait for status: {0}\"", ",", "statSet", ")", ";", "final", "LauncherStatus", "finalStatus", ";", "synchronized", "(", "this", ")", "{", "while", "(", "!", "statSet", ".", "contains", "(", "this", ".", "status", ")", ")", "{", "try", "{", "final", "long", "delay", "=", "endTime", "-", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "delay", "<=", "0", ")", "{", "break", ";", "}", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Wait for {0} milliSeconds\"", ",", "delay", ")", ";", "this", ".", "wait", "(", "delay", ")", ";", "}", "catch", "(", "final", "InterruptedException", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Interrupted: {0}\"", ",", "ex", ")", ";", "}", "}", "finalStatus", "=", "this", ".", "status", ";", "}", "LOG", ".", "log", "(", "Level", ".", "FINEST", ",", "\"Final status: {0}\"", ",", "finalStatus", ")", ";", "return", "finalStatus", ";", "}" ]
Wait for one of the specified statuses of the REEF job. This method is called after the job is submitted to the RM via submit(). @param waitTime wait time in milliseconds. @param statuses array of statuses to wait for. @return the state of the job after the wait.
[ "Wait", "for", "one", "of", "the", "specified", "statuses", "of", "the", "REEF", "job", ".", "This", "method", "is", "called", "after", "the", "job", "is", "submitted", "to", "the", "RM", "via", "submit", "()", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/client/DriverLauncher.java#L154-L184
jimmoores/quandl4j
core/src/main/java/com/jimmoores/quandl/util/ArgumentChecker.java
ArgumentChecker.notNullOrEmpty
public static <E> void notNullOrEmpty(final Collection<E> argument, final String name) { if (argument == null) { s_logger.error("Argument {} was null", name); throw new QuandlRuntimeException("Value " + name + " was null"); } else if (argument.size() == 0) { s_logger.error("Argument {} was empty collection", name); throw new QuandlRuntimeException("Value " + name + " was empty collection"); } }
java
public static <E> void notNullOrEmpty(final Collection<E> argument, final String name) { if (argument == null) { s_logger.error("Argument {} was null", name); throw new QuandlRuntimeException("Value " + name + " was null"); } else if (argument.size() == 0) { s_logger.error("Argument {} was empty collection", name); throw new QuandlRuntimeException("Value " + name + " was empty collection"); } }
[ "public", "static", "<", "E", ">", "void", "notNullOrEmpty", "(", "final", "Collection", "<", "E", ">", "argument", ",", "final", "String", "name", ")", "{", "if", "(", "argument", "==", "null", ")", "{", "s_logger", ".", "error", "(", "\"Argument {} was null\"", ",", "name", ")", ";", "throw", "new", "QuandlRuntimeException", "(", "\"Value \"", "+", "name", "+", "\" was null\"", ")", ";", "}", "else", "if", "(", "argument", ".", "size", "(", ")", "==", "0", ")", "{", "s_logger", ".", "error", "(", "\"Argument {} was empty collection\"", ",", "name", ")", ";", "throw", "new", "QuandlRuntimeException", "(", "\"Value \"", "+", "name", "+", "\" was empty collection\"", ")", ";", "}", "}" ]
Throws an exception if the collection argument is not null or empty. @param <E> type of array @param argument the object to check @param name the name of the parameter
[ "Throws", "an", "exception", "if", "the", "collection", "argument", "is", "not", "null", "or", "empty", "." ]
train
https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/util/ArgumentChecker.java#L54-L62
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/Activator.java
Activator.activateBean
public BeanO activateBean(EJBThreadData threadData, ContainerTx tx, BeanId beanId) throws RemoteException { BeanO beanO = null; try { beanO = beanId.getActivationStrategy().atActivate(threadData, tx, beanId); // d630940 } finally { if (beanO != null) { threadData.popCallbackBeanO(); } } return beanO; }
java
public BeanO activateBean(EJBThreadData threadData, ContainerTx tx, BeanId beanId) throws RemoteException { BeanO beanO = null; try { beanO = beanId.getActivationStrategy().atActivate(threadData, tx, beanId); // d630940 } finally { if (beanO != null) { threadData.popCallbackBeanO(); } } return beanO; }
[ "public", "BeanO", "activateBean", "(", "EJBThreadData", "threadData", ",", "ContainerTx", "tx", ",", "BeanId", "beanId", ")", "throws", "RemoteException", "{", "BeanO", "beanO", "=", "null", ";", "try", "{", "beanO", "=", "beanId", ".", "getActivationStrategy", "(", ")", ".", "atActivate", "(", "threadData", ",", "tx", ",", "beanId", ")", ";", "// d630940", "}", "finally", "{", "if", "(", "beanO", "!=", "null", ")", "{", "threadData", ".", "popCallbackBeanO", "(", ")", ";", "}", "}", "return", "beanO", ";", "}" ]
Activate a bean in the context of a transaction. If an instance of the bean is already active in the transaction, that instance is returned. Otherwise, one of several strategies is used to activate an instance depending on what the bean supports. <p> If this method completes normally, it must be balanced with a call to one of the following methods: removeBean, commitBean, rollbackBean. If this method throws an exception, any partial work has already been undone, and there should be no balancing method call. <p> This method should never be used to obtain bean instances for method invocations. See {@link #preInvokeActivateBean}. <p> @param threadData the EJB thread data for the currently executing thread @param tx the transaction context in which the bean instance should be activated. @param beanId the <code>BeanId</code> identifying the bean to activate. @return a fully-activated bean instance.
[ "Activate", "a", "bean", "in", "the", "context", "of", "a", "transaction", ".", "If", "an", "instance", "of", "the", "bean", "is", "already", "active", "in", "the", "transaction", "that", "instance", "is", "returned", ".", "Otherwise", "one", "of", "several", "strategies", "is", "used", "to", "activate", "an", "instance", "depending", "on", "what", "the", "bean", "supports", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/activator/Activator.java#L288-L305
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/WebJarController.java
WebJarController.removedBundle
@Override public void removedBundle(Bundle bundle, BundleEvent bundleEvent, List<BundleWebJarLib> webJarLibs) { removeWebJarLibs(webJarLibs); }
java
@Override public void removedBundle(Bundle bundle, BundleEvent bundleEvent, List<BundleWebJarLib> webJarLibs) { removeWebJarLibs(webJarLibs); }
[ "@", "Override", "public", "void", "removedBundle", "(", "Bundle", "bundle", ",", "BundleEvent", "bundleEvent", ",", "List", "<", "BundleWebJarLib", ">", "webJarLibs", ")", "{", "removeWebJarLibs", "(", "webJarLibs", ")", ";", "}" ]
A bundle is removed. @param bundle the bundle @param bundleEvent the event @param webJarLibs the webjars that were embedded in the bundle.
[ "A", "bundle", "is", "removed", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/WebJarController.java#L356-L359
aspectran/aspectran
web/src/main/java/com/aspectran/web/service/AspectranWebService.java
AspectranWebService.create
public static AspectranWebService create(ServletContext servletContext, CoreService rootService) { AspectranWebService service = new AspectranWebService(rootService); service.setDefaultServletHttpRequestHandler(servletContext); AspectranConfig aspectranConfig = rootService.getAspectranConfig(); if (aspectranConfig != null) { WebConfig webConfig = aspectranConfig.getWebConfig(); if (webConfig != null) { applyWebConfig(service, webConfig); } } setServiceStateListener(service); if (service.isLateStart()) { try { service.getServiceController().start(); } catch (Exception e) { throw new AspectranServiceException("Failed to start AspectranWebService"); } } return service; }
java
public static AspectranWebService create(ServletContext servletContext, CoreService rootService) { AspectranWebService service = new AspectranWebService(rootService); service.setDefaultServletHttpRequestHandler(servletContext); AspectranConfig aspectranConfig = rootService.getAspectranConfig(); if (aspectranConfig != null) { WebConfig webConfig = aspectranConfig.getWebConfig(); if (webConfig != null) { applyWebConfig(service, webConfig); } } setServiceStateListener(service); if (service.isLateStart()) { try { service.getServiceController().start(); } catch (Exception e) { throw new AspectranServiceException("Failed to start AspectranWebService"); } } return service; }
[ "public", "static", "AspectranWebService", "create", "(", "ServletContext", "servletContext", ",", "CoreService", "rootService", ")", "{", "AspectranWebService", "service", "=", "new", "AspectranWebService", "(", "rootService", ")", ";", "service", ".", "setDefaultServletHttpRequestHandler", "(", "servletContext", ")", ";", "AspectranConfig", "aspectranConfig", "=", "rootService", ".", "getAspectranConfig", "(", ")", ";", "if", "(", "aspectranConfig", "!=", "null", ")", "{", "WebConfig", "webConfig", "=", "aspectranConfig", ".", "getWebConfig", "(", ")", ";", "if", "(", "webConfig", "!=", "null", ")", "{", "applyWebConfig", "(", "service", ",", "webConfig", ")", ";", "}", "}", "setServiceStateListener", "(", "service", ")", ";", "if", "(", "service", ".", "isLateStart", "(", ")", ")", "{", "try", "{", "service", ".", "getServiceController", "(", ")", ".", "start", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "AspectranServiceException", "(", "\"Failed to start AspectranWebService\"", ")", ";", "}", "}", "return", "service", ";", "}" ]
Returns a new instance of {@code AspectranWebService}. @param servletContext the servlet context @param rootService the root service @return the instance of {@code AspectranWebService}
[ "Returns", "a", "new", "instance", "of", "{", "@code", "AspectranWebService", "}", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/web/src/main/java/com/aspectran/web/service/AspectranWebService.java#L205-L224
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.deleteCustomPrebuiltDomainAsync
public Observable<OperationStatus> deleteCustomPrebuiltDomainAsync(UUID appId, String versionId, String domainName) { return deleteCustomPrebuiltDomainWithServiceResponseAsync(appId, versionId, domainName).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> deleteCustomPrebuiltDomainAsync(UUID appId, String versionId, String domainName) { return deleteCustomPrebuiltDomainWithServiceResponseAsync(appId, versionId, domainName).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "deleteCustomPrebuiltDomainAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "String", "domainName", ")", "{", "return", "deleteCustomPrebuiltDomainWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "domainName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatus", ">", ",", "OperationStatus", ">", "(", ")", "{", "@", "Override", "public", "OperationStatus", "call", "(", "ServiceResponse", "<", "OperationStatus", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deletes a prebuilt domain's models from the application. @param appId The application ID. @param versionId The version ID. @param domainName Domain name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Deletes", "a", "prebuilt", "domain", "s", "models", "from", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L6176-L6183
docusign/docusign-java-client
src/main/java/com/docusign/esign/client/ApiClient.java
ApiClient.configureJWTAuthorizationFlow
@Deprecated public void configureJWTAuthorizationFlow(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws IOException, ApiException { try { String assertion = JWTUtils.generateJWTAssertion(publicKeyFilename, privateKeyFilename, oAuthBasePath, clientId, userId, expiresIn); MultivaluedMap<String, String> form = new MultivaluedMapImpl(); form.add("assertion", assertion); form.add("grant_type", OAuth.GRANT_TYPE_JWT); Client client = buildHttpClient(debugging); WebResource webResource = client.resource("https://" + oAuthBasePath + "/oauth/token"); ClientResponse response = webResource .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, form); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode responseJson = mapper.readValue(response.getEntityInputStream(), JsonNode.class); if (!responseJson.has("access_token") || !responseJson.has("expires_in")) { throw new ApiException("Error while requesting an access token: " + responseJson); } String accessToken = responseJson.get("access_token").asText(); expiresIn = responseJson.get("expires_in").asLong(); setAccessToken(accessToken, expiresIn); } catch (JsonParseException e) { throw new ApiException("Error while parsing the response for the access token."); } catch (JsonMappingException e) { throw e; } catch (IOException e) { throw e; } }
java
@Deprecated public void configureJWTAuthorizationFlow(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws IOException, ApiException { try { String assertion = JWTUtils.generateJWTAssertion(publicKeyFilename, privateKeyFilename, oAuthBasePath, clientId, userId, expiresIn); MultivaluedMap<String, String> form = new MultivaluedMapImpl(); form.add("assertion", assertion); form.add("grant_type", OAuth.GRANT_TYPE_JWT); Client client = buildHttpClient(debugging); WebResource webResource = client.resource("https://" + oAuthBasePath + "/oauth/token"); ClientResponse response = webResource .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, form); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode responseJson = mapper.readValue(response.getEntityInputStream(), JsonNode.class); if (!responseJson.has("access_token") || !responseJson.has("expires_in")) { throw new ApiException("Error while requesting an access token: " + responseJson); } String accessToken = responseJson.get("access_token").asText(); expiresIn = responseJson.get("expires_in").asLong(); setAccessToken(accessToken, expiresIn); } catch (JsonParseException e) { throw new ApiException("Error while parsing the response for the access token."); } catch (JsonMappingException e) { throw e; } catch (IOException e) { throw e; } }
[ "@", "Deprecated", "public", "void", "configureJWTAuthorizationFlow", "(", "String", "publicKeyFilename", ",", "String", "privateKeyFilename", ",", "String", "oAuthBasePath", ",", "String", "clientId", ",", "String", "userId", ",", "long", "expiresIn", ")", "throws", "IOException", ",", "ApiException", "{", "try", "{", "String", "assertion", "=", "JWTUtils", ".", "generateJWTAssertion", "(", "publicKeyFilename", ",", "privateKeyFilename", ",", "oAuthBasePath", ",", "clientId", ",", "userId", ",", "expiresIn", ")", ";", "MultivaluedMap", "<", "String", ",", "String", ">", "form", "=", "new", "MultivaluedMapImpl", "(", ")", ";", "form", ".", "add", "(", "\"assertion\"", ",", "assertion", ")", ";", "form", ".", "add", "(", "\"grant_type\"", ",", "OAuth", ".", "GRANT_TYPE_JWT", ")", ";", "Client", "client", "=", "buildHttpClient", "(", "debugging", ")", ";", "WebResource", "webResource", "=", "client", ".", "resource", "(", "\"https://\"", "+", "oAuthBasePath", "+", "\"/oauth/token\"", ")", ";", "ClientResponse", "response", "=", "webResource", ".", "type", "(", "MediaType", ".", "APPLICATION_FORM_URLENCODED_TYPE", ")", ".", "post", "(", "ClientResponse", ".", "class", ",", "form", ")", ";", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "mapper", ".", "configure", "(", "DeserializationFeature", ".", "FAIL_ON_UNKNOWN_PROPERTIES", ",", "false", ")", ";", "JsonNode", "responseJson", "=", "mapper", ".", "readValue", "(", "response", ".", "getEntityInputStream", "(", ")", ",", "JsonNode", ".", "class", ")", ";", "if", "(", "!", "responseJson", ".", "has", "(", "\"access_token\"", ")", "||", "!", "responseJson", ".", "has", "(", "\"expires_in\"", ")", ")", "{", "throw", "new", "ApiException", "(", "\"Error while requesting an access token: \"", "+", "responseJson", ")", ";", "}", "String", "accessToken", "=", "responseJson", ".", "get", "(", "\"access_token\"", ")", ".", "asText", "(", ")", ";", "expiresIn", "=", "responseJson", ".", "get", "(", "\"expires_in\"", ")", ".", "asLong", "(", ")", ";", "setAccessToken", "(", "accessToken", ",", "expiresIn", ")", ";", "}", "catch", "(", "JsonParseException", "e", ")", "{", "throw", "new", "ApiException", "(", "\"Error while parsing the response for the access token.\"", ")", ";", "}", "catch", "(", "JsonMappingException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "e", ";", "}", "}" ]
Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign @param publicKeyFilename the filename of the RSA public key @param privateKeyFilename the filename of the RSA private key @param oAuthBasePath DocuSign OAuth base path (account-d.docusign.com for the developer sandbox and account.docusign.com for the production platform) @param clientId DocuSign OAuth Client Id (AKA Integrator Key) @param userId DocuSign user Id to be impersonated (This is a UUID) @param expiresIn number of seconds remaining before the JWT assertion is considered as invalid @throws IOException if there is an issue with either the public or private file @throws ApiException if there is an error while exchanging the JWT with an access token @deprecated As of release 2.7.0, replaced by {@link #requestJWTUserToken()} and {@link #requestJWTApplicationToken()}
[ "Configures", "the", "current", "instance", "of", "ApiClient", "with", "a", "fresh", "OAuth", "JWT", "access", "token", "from", "DocuSign" ]
train
https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/client/ApiClient.java#L674-L703
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java
LOF.computeLRDs
private void computeLRDs(KNNQuery<O> knnq, DBIDs ids, WritableDoubleDataStore lrds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Local Reachability Densities (LRD)", ids.size(), LOG) : null; double lrd; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { lrd = computeLRD(knnq, iter); lrds.putDouble(iter, lrd); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
java
private void computeLRDs(KNNQuery<O> knnq, DBIDs ids, WritableDoubleDataStore lrds) { FiniteProgress lrdsProgress = LOG.isVerbose() ? new FiniteProgress("Local Reachability Densities (LRD)", ids.size(), LOG) : null; double lrd; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { lrd = computeLRD(knnq, iter); lrds.putDouble(iter, lrd); LOG.incrementProcessed(lrdsProgress); } LOG.ensureCompleted(lrdsProgress); }
[ "private", "void", "computeLRDs", "(", "KNNQuery", "<", "O", ">", "knnq", ",", "DBIDs", "ids", ",", "WritableDoubleDataStore", "lrds", ")", "{", "FiniteProgress", "lrdsProgress", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "\"Local Reachability Densities (LRD)\"", ",", "ids", ".", "size", "(", ")", ",", "LOG", ")", ":", "null", ";", "double", "lrd", ";", "for", "(", "DBIDIter", "iter", "=", "ids", ".", "iter", "(", ")", ";", "iter", ".", "valid", "(", ")", ";", "iter", ".", "advance", "(", ")", ")", "{", "lrd", "=", "computeLRD", "(", "knnq", ",", "iter", ")", ";", "lrds", ".", "putDouble", "(", "iter", ",", "lrd", ")", ";", "LOG", ".", "incrementProcessed", "(", "lrdsProgress", ")", ";", "}", "LOG", ".", "ensureCompleted", "(", "lrdsProgress", ")", ";", "}" ]
Compute local reachability distances. @param knnq KNN query @param ids IDs to process @param lrds Reachability storage
[ "Compute", "local", "reachability", "distances", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/lof/LOF.java#L159-L168
codegist/crest
core/src/main/java/org/codegist/crest/CRestBuilder.java
CRestBuilder.deserializeXmlWith
public CRestBuilder deserializeXmlWith(Class<? extends Deserializer> deserializer) { return deserializeXmlWith(deserializer, Collections.<String, Object>emptyMap()); }
java
public CRestBuilder deserializeXmlWith(Class<? extends Deserializer> deserializer) { return deserializeXmlWith(deserializer, Collections.<String, Object>emptyMap()); }
[ "public", "CRestBuilder", "deserializeXmlWith", "(", "Class", "<", "?", "extends", "Deserializer", ">", "deserializer", ")", "{", "return", "deserializeXmlWith", "(", "deserializer", ",", "Collections", ".", "<", "String", ",", "Object", ">", "emptyMap", "(", ")", ")", ";", "}" ]
<p>Overrides the default {@link org.codegist.crest.serializer.jaxb.JaxbDeserializer} XML deserializer with the given one</p> <p>By default, <b>CRest</b> will use this deserializer for the following response Content-Type:</p> <ul> <li>application/xml</li> <li>text/xml</li> </ul> @param deserializer deserializer to use for XML response Content-Type requests @return current builder @see org.codegist.crest.serializer.jaxb.JaxbDeserializer @see org.codegist.crest.serializer.simplexml.SimpleXmlDeserializer
[ "<p", ">", "Overrides", "the", "default", "{" ]
train
https://github.com/codegist/crest/blob/e99ba7728b27d2ddb2c247261350f1b6fa7a6698/core/src/main/java/org/codegist/crest/CRestBuilder.java#L740-L742
morimekta/utils
io-util/src/main/java/net/morimekta/util/Strings.java
Strings.commonSuffix
public static int commonSuffix(String text1, String text2) { // Performance analysis: http://neil.fraser.name/news/2007/10/09/ int text1_length = text1.length(); int text2_length = text2.length(); int n = Math.min(text1_length, text2_length); for (int i = 1; i <= n; i++) { if (text1.charAt(text1_length - i) != text2.charAt(text2_length - i)) { return i - 1; } } return n; }
java
public static int commonSuffix(String text1, String text2) { // Performance analysis: http://neil.fraser.name/news/2007/10/09/ int text1_length = text1.length(); int text2_length = text2.length(); int n = Math.min(text1_length, text2_length); for (int i = 1; i <= n; i++) { if (text1.charAt(text1_length - i) != text2.charAt(text2_length - i)) { return i - 1; } } return n; }
[ "public", "static", "int", "commonSuffix", "(", "String", "text1", ",", "String", "text2", ")", "{", "// Performance analysis: http://neil.fraser.name/news/2007/10/09/", "int", "text1_length", "=", "text1", ".", "length", "(", ")", ";", "int", "text2_length", "=", "text2", ".", "length", "(", ")", ";", "int", "n", "=", "Math", ".", "min", "(", "text1_length", ",", "text2_length", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "n", ";", "i", "++", ")", "{", "if", "(", "text1", ".", "charAt", "(", "text1_length", "-", "i", ")", "!=", "text2", ".", "charAt", "(", "text2_length", "-", "i", ")", ")", "{", "return", "i", "-", "1", ";", "}", "}", "return", "n", ";", "}" ]
Determine the common suffix of two strings @param text1 First string. @param text2 Second string. @return The number of characters common to the end of each string.
[ "Determine", "the", "common", "suffix", "of", "two", "strings" ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Strings.java#L697-L708
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/gaxx/reframing/ReframingResponseObserver.java
ReframingResponseObserver.onResponseImpl
@Override protected void onResponseImpl(InnerT response) { IllegalStateException error = null; // Guard against unsolicited notifications if (!awaitingInner || !newItem.compareAndSet(null, response)) { // Notify downstream if it's still open error = new IllegalStateException("Received unsolicited response from upstream."); cancellation.compareAndSet(null, error); } deliver(); // Notify upstream by throwing an exception if (error != null) { throw error; } }
java
@Override protected void onResponseImpl(InnerT response) { IllegalStateException error = null; // Guard against unsolicited notifications if (!awaitingInner || !newItem.compareAndSet(null, response)) { // Notify downstream if it's still open error = new IllegalStateException("Received unsolicited response from upstream."); cancellation.compareAndSet(null, error); } deliver(); // Notify upstream by throwing an exception if (error != null) { throw error; } }
[ "@", "Override", "protected", "void", "onResponseImpl", "(", "InnerT", "response", ")", "{", "IllegalStateException", "error", "=", "null", ";", "// Guard against unsolicited notifications", "if", "(", "!", "awaitingInner", "||", "!", "newItem", ".", "compareAndSet", "(", "null", ",", "response", ")", ")", "{", "// Notify downstream if it's still open", "error", "=", "new", "IllegalStateException", "(", "\"Received unsolicited response from upstream.\"", ")", ";", "cancellation", ".", "compareAndSet", "(", "null", ",", "error", ")", ";", "}", "deliver", "(", ")", ";", "// Notify upstream by throwing an exception", "if", "(", "error", "!=", "null", ")", "{", "throw", "error", ";", "}", "}" ]
Accept a new response from inner/upstream callable. This message will be processed by the {@link Reframer} in the delivery loop and the output will be delivered to the downstream {@link ResponseObserver}. <p>If the delivery loop is stopped, this will restart it.
[ "Accept", "a", "new", "response", "from", "inner", "/", "upstream", "callable", ".", "This", "message", "will", "be", "processed", "by", "the", "{", "@link", "Reframer", "}", "in", "the", "delivery", "loop", "and", "the", "output", "will", "be", "delivered", "to", "the", "downstream", "{", "@link", "ResponseObserver", "}", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/gaxx/reframing/ReframingResponseObserver.java#L193-L209
grails/gorm-hibernate5
grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/AbstractHibernateCriteriaBuilder.java
AbstractHibernateCriteriaBuilder.countDistinct
public org.grails.datastore.mapping.query.api.ProjectionList countDistinct(String propertyName, String alias) { final CountProjection proj = Projections.countDistinct(calculatePropertyName(propertyName)); addProjectionToList(proj, alias); return this; }
java
public org.grails.datastore.mapping.query.api.ProjectionList countDistinct(String propertyName, String alias) { final CountProjection proj = Projections.countDistinct(calculatePropertyName(propertyName)); addProjectionToList(proj, alias); return this; }
[ "public", "org", ".", "grails", ".", "datastore", ".", "mapping", ".", "query", ".", "api", ".", "ProjectionList", "countDistinct", "(", "String", "propertyName", ",", "String", "alias", ")", "{", "final", "CountProjection", "proj", "=", "Projections", ".", "countDistinct", "(", "calculatePropertyName", "(", "propertyName", ")", ")", ";", "addProjectionToList", "(", "proj", ",", "alias", ")", ";", "return", "this", ";", "}" ]
Adds a projection that allows the criteria to return the distinct property count @param propertyName The name of the property @param alias The alias to use
[ "Adds", "a", "projection", "that", "allows", "the", "criteria", "to", "return", "the", "distinct", "property", "count" ]
train
https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/query/AbstractHibernateCriteriaBuilder.java#L438-L442
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfOutline.java
PdfOutline.initOutline
void initOutline(PdfOutline parent, String title, boolean open) { this.open = open; this.parent = parent; writer = parent.writer; put(PdfName.TITLE, new PdfString(title, PdfObject.TEXT_UNICODE)); parent.addKid(this); if (destination != null && !destination.hasPage()) // bugfix Finn Bock setDestinationPage(writer.getCurrentPage()); }
java
void initOutline(PdfOutline parent, String title, boolean open) { this.open = open; this.parent = parent; writer = parent.writer; put(PdfName.TITLE, new PdfString(title, PdfObject.TEXT_UNICODE)); parent.addKid(this); if (destination != null && !destination.hasPage()) // bugfix Finn Bock setDestinationPage(writer.getCurrentPage()); }
[ "void", "initOutline", "(", "PdfOutline", "parent", ",", "String", "title", ",", "boolean", "open", ")", "{", "this", ".", "open", "=", "open", ";", "this", ".", "parent", "=", "parent", ";", "writer", "=", "parent", ".", "writer", ";", "put", "(", "PdfName", ".", "TITLE", ",", "new", "PdfString", "(", "title", ",", "PdfObject", ".", "TEXT_UNICODE", ")", ")", ";", "parent", ".", "addKid", "(", "this", ")", ";", "if", "(", "destination", "!=", "null", "&&", "!", "destination", ".", "hasPage", "(", ")", ")", "// bugfix Finn Bock", "setDestinationPage", "(", "writer", ".", "getCurrentPage", "(", ")", ")", ";", "}" ]
Helper for the constructors. @param parent the parent outline @param title the title for this outline @param open <CODE>true</CODE> if the children are visible
[ "Helper", "for", "the", "constructors", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfOutline.java#L324-L332
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDelta.java
JUnit3FloatingPointComparisonWithoutDelta.isNumeric
private boolean isNumeric(VisitorState state, Type type) { Type trueType = unboxedTypeOrType(state, type); return trueType.isNumeric(); }
java
private boolean isNumeric(VisitorState state, Type type) { Type trueType = unboxedTypeOrType(state, type); return trueType.isNumeric(); }
[ "private", "boolean", "isNumeric", "(", "VisitorState", "state", ",", "Type", "type", ")", "{", "Type", "trueType", "=", "unboxedTypeOrType", "(", "state", ",", "type", ")", ";", "return", "trueType", ".", "isNumeric", "(", ")", ";", "}" ]
Determines if the type is a numeric type, including reference types. <p>Type.isNumeric() does not handle reference types properly.
[ "Determines", "if", "the", "type", "is", "a", "numeric", "type", "including", "reference", "types", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/JUnit3FloatingPointComparisonWithoutDelta.java#L135-L138
apereo/cas
support/cas-server-support-consent-couchdb/src/main/java/org/apereo/cas/couchdb/consent/ConsentDecisionCouchDbRepository.java
ConsentDecisionCouchDbRepository.findByPrincipalAndId
@View(name = "by_principal_and_id", map = "function(doc) {emit([doc.principal, doc.id], doc)}") public CouchDbConsentDecision findByPrincipalAndId(final String principal, final long id) { val view = createQuery("by_principal_and_id").key(ComplexKey.of(principal, id)).limit(1).includeDocs(true); return db.queryView(view, CouchDbConsentDecision.class).stream().findFirst().orElse(null); }
java
@View(name = "by_principal_and_id", map = "function(doc) {emit([doc.principal, doc.id], doc)}") public CouchDbConsentDecision findByPrincipalAndId(final String principal, final long id) { val view = createQuery("by_principal_and_id").key(ComplexKey.of(principal, id)).limit(1).includeDocs(true); return db.queryView(view, CouchDbConsentDecision.class).stream().findFirst().orElse(null); }
[ "@", "View", "(", "name", "=", "\"by_principal_and_id\"", ",", "map", "=", "\"function(doc) {emit([doc.principal, doc.id], doc)}\"", ")", "public", "CouchDbConsentDecision", "findByPrincipalAndId", "(", "final", "String", "principal", ",", "final", "long", "id", ")", "{", "val", "view", "=", "createQuery", "(", "\"by_principal_and_id\"", ")", ".", "key", "(", "ComplexKey", ".", "of", "(", "principal", ",", "id", ")", ")", ".", "limit", "(", "1", ")", ".", "includeDocs", "(", "true", ")", ";", "return", "db", ".", "queryView", "(", "view", ",", "CouchDbConsentDecision", ".", "class", ")", ".", "stream", "(", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "null", ")", ";", "}" ]
Find a consent decision by +long+ ID and principal name. For CouchDb, this ID is randomly generated and the pair should be unique, with a very high probability, but is not guaranteed. This method is mostly only used by tests. @param principal User to search for. @param id decision id to search for. @return First consent decision matching principal and id.
[ "Find", "a", "consent", "decision", "by", "+", "long", "+", "ID", "and", "principal", "name", ".", "For", "CouchDb", "this", "ID", "is", "randomly", "generated", "and", "the", "pair", "should", "be", "unique", "with", "a", "very", "high", "probability", "but", "is", "not", "guaranteed", ".", "This", "method", "is", "mostly", "only", "used", "by", "tests", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-consent-couchdb/src/main/java/org/apereo/cas/couchdb/consent/ConsentDecisionCouchDbRepository.java#L75-L79
TakahikoKawasaki/nv-websocket-client
src/main/java/com/neovisionaries/ws/client/WebSocket.java
WebSocket.addHeader
public WebSocket addHeader(String name, String value) { mHandshakeBuilder.addHeader(name, value); return this; }
java
public WebSocket addHeader(String name, String value) { mHandshakeBuilder.addHeader(name, value); return this; }
[ "public", "WebSocket", "addHeader", "(", "String", "name", ",", "String", "value", ")", "{", "mHandshakeBuilder", ".", "addHeader", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add a pair of extra HTTP header. @param name An HTTP header name. When {@code null} or an empty string is given, no header is added. @param value The value of the HTTP header. @return {@code this} object.
[ "Add", "a", "pair", "of", "extra", "HTTP", "header", "." ]
train
https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L1467-L1472
OpenVidu/openvidu
openvidu-server/src/main/java/io/openvidu/server/core/SessionManager.java
SessionManager.closeSession
public Set<Participant> closeSession(String sessionId, EndReason reason) { Session session = sessions.get(sessionId); if (session == null) { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "Session '" + sessionId + "' not found"); } if (session.isClosed()) { this.closeSessionAndEmptyCollections(session, reason); throw new OpenViduException(Code.ROOM_CLOSED_ERROR_CODE, "Session '" + sessionId + "' already closed"); } Set<Participant> participants = getParticipants(sessionId); for (Participant p : participants) { try { this.evictParticipant(p, null, null, reason); } catch (OpenViduException e) { log.warn("Error evicting participant '{}' from session '{}'", p.getParticipantPublicId(), sessionId, e); } } this.closeSessionAndEmptyCollections(session, reason); return participants; }
java
public Set<Participant> closeSession(String sessionId, EndReason reason) { Session session = sessions.get(sessionId); if (session == null) { throw new OpenViduException(Code.ROOM_NOT_FOUND_ERROR_CODE, "Session '" + sessionId + "' not found"); } if (session.isClosed()) { this.closeSessionAndEmptyCollections(session, reason); throw new OpenViduException(Code.ROOM_CLOSED_ERROR_CODE, "Session '" + sessionId + "' already closed"); } Set<Participant> participants = getParticipants(sessionId); for (Participant p : participants) { try { this.evictParticipant(p, null, null, reason); } catch (OpenViduException e) { log.warn("Error evicting participant '{}' from session '{}'", p.getParticipantPublicId(), sessionId, e); } } this.closeSessionAndEmptyCollections(session, reason); return participants; }
[ "public", "Set", "<", "Participant", ">", "closeSession", "(", "String", "sessionId", ",", "EndReason", "reason", ")", "{", "Session", "session", "=", "sessions", ".", "get", "(", "sessionId", ")", ";", "if", "(", "session", "==", "null", ")", "{", "throw", "new", "OpenViduException", "(", "Code", ".", "ROOM_NOT_FOUND_ERROR_CODE", ",", "\"Session '\"", "+", "sessionId", "+", "\"' not found\"", ")", ";", "}", "if", "(", "session", ".", "isClosed", "(", ")", ")", "{", "this", ".", "closeSessionAndEmptyCollections", "(", "session", ",", "reason", ")", ";", "throw", "new", "OpenViduException", "(", "Code", ".", "ROOM_CLOSED_ERROR_CODE", ",", "\"Session '\"", "+", "sessionId", "+", "\"' already closed\"", ")", ";", "}", "Set", "<", "Participant", ">", "participants", "=", "getParticipants", "(", "sessionId", ")", ";", "for", "(", "Participant", "p", ":", "participants", ")", "{", "try", "{", "this", ".", "evictParticipant", "(", "p", ",", "null", ",", "null", ",", "reason", ")", ";", "}", "catch", "(", "OpenViduException", "e", ")", "{", "log", ".", "warn", "(", "\"Error evicting participant '{}' from session '{}'\"", ",", "p", ".", "getParticipantPublicId", "(", ")", ",", "sessionId", ",", "e", ")", ";", "}", "}", "this", ".", "closeSessionAndEmptyCollections", "(", "session", ",", "reason", ")", ";", "return", "participants", ";", "}" ]
Closes an existing session by releasing all resources that were allocated for it. Once closed, the session can be reopened (will be empty and it will use another Media Pipeline). Existing participants will be evicted. <br/> <strong>Dev advice:</strong> The session event handler should send notifications to the existing participants in the session to inform that it was forcibly closed. @param sessionId identifier of the session @return @return set of {@link Participant} POJOS representing the session's participants @throws OpenViduException in case the session doesn't exist or has been already closed
[ "Closes", "an", "existing", "session", "by", "releasing", "all", "resources", "that", "were", "allocated", "for", "it", ".", "Once", "closed", "the", "session", "can", "be", "reopened", "(", "will", "be", "empty", "and", "it", "will", "use", "another", "Media", "Pipeline", ")", ".", "Existing", "participants", "will", "be", "evicted", ".", "<br", "/", ">", "<strong", ">", "Dev", "advice", ":", "<", "/", "strong", ">", "The", "session", "event", "handler", "should", "send", "notifications", "to", "the", "existing", "participants", "in", "the", "session", "to", "inform", "that", "it", "was", "forcibly", "closed", "." ]
train
https://github.com/OpenVidu/openvidu/blob/89db47dd37949ceab29e5228371a8fcab04d8d55/openvidu-server/src/main/java/io/openvidu/server/core/SessionManager.java#L436-L457
EdwardRaff/JSAT
JSAT/src/jsat/distributions/kernels/GeneralRBFKernel.java
GeneralRBFKernel.setSigma
public void setSigma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new IllegalArgumentException("Sigma must be a positive constant, not " + sigma); this.sigma = sigma; this.sigmaSqrd2Inv = 0.5/(sigma*sigma); }
java
public void setSigma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new IllegalArgumentException("Sigma must be a positive constant, not " + sigma); this.sigma = sigma; this.sigmaSqrd2Inv = 0.5/(sigma*sigma); }
[ "public", "void", "setSigma", "(", "double", "sigma", ")", "{", "if", "(", "sigma", "<=", "0", "||", "Double", ".", "isNaN", "(", "sigma", ")", "||", "Double", ".", "isInfinite", "(", "sigma", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Sigma must be a positive constant, not \"", "+", "sigma", ")", ";", "this", ".", "sigma", "=", "sigma", ";", "this", ".", "sigmaSqrd2Inv", "=", "0.5", "/", "(", "sigma", "*", "sigma", ")", ";", "}" ]
Sets the kernel width parameter, which must be a positive value. Larger values indicate a larger width @param sigma the sigma value
[ "Sets", "the", "kernel", "width", "parameter", "which", "must", "be", "a", "positive", "value", ".", "Larger", "values", "indicate", "a", "larger", "width" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/GeneralRBFKernel.java#L57-L63
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/AbstractEventSerializer.java
AbstractEventSerializer.parseUserIdentity
private void parseUserIdentity(CloudTrailEventData eventData) throws IOException { JsonToken nextToken = jsonParser.nextToken(); if (nextToken == JsonToken.VALUE_NULL) { eventData.add(CloudTrailEventField.userIdentity.name(), null); return; } if (nextToken != JsonToken.START_OBJECT) { throw new JsonParseException("Not a UserIdentity object", jsonParser.getCurrentLocation()); } UserIdentity userIdentity = new UserIdentity(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = jsonParser.getCurrentName(); switch (key) { case "type": userIdentity.add(CloudTrailEventField.type.name(), jsonParser.nextTextValue()); break; case "principalId": userIdentity.add(CloudTrailEventField.principalId.name(), jsonParser.nextTextValue()); break; case "arn": userIdentity.add(CloudTrailEventField.arn.name(), jsonParser.nextTextValue()); break; case "accountId": userIdentity.add(CloudTrailEventField.accountId.name(), jsonParser.nextTextValue()); break; case "accessKeyId": userIdentity.add(CloudTrailEventField.accessKeyId.name(), jsonParser.nextTextValue()); break; case "userName": userIdentity.add(CloudTrailEventField.userName.name(), jsonParser.nextTextValue()); break; case "sessionContext": this.parseSessionContext(userIdentity); break; case "invokedBy": userIdentity.add(CloudTrailEventField.invokedBy.name(), jsonParser.nextTextValue()); break; case "identityProvider": userIdentity.add(CloudTrailEventField.identityProvider.name(), jsonParser.nextTextValue()); break; default: userIdentity.add(key, parseDefaultValue(key)); break; } } eventData.add(CloudTrailEventField.userIdentity.name(), userIdentity); }
java
private void parseUserIdentity(CloudTrailEventData eventData) throws IOException { JsonToken nextToken = jsonParser.nextToken(); if (nextToken == JsonToken.VALUE_NULL) { eventData.add(CloudTrailEventField.userIdentity.name(), null); return; } if (nextToken != JsonToken.START_OBJECT) { throw new JsonParseException("Not a UserIdentity object", jsonParser.getCurrentLocation()); } UserIdentity userIdentity = new UserIdentity(); while (jsonParser.nextToken() != JsonToken.END_OBJECT) { String key = jsonParser.getCurrentName(); switch (key) { case "type": userIdentity.add(CloudTrailEventField.type.name(), jsonParser.nextTextValue()); break; case "principalId": userIdentity.add(CloudTrailEventField.principalId.name(), jsonParser.nextTextValue()); break; case "arn": userIdentity.add(CloudTrailEventField.arn.name(), jsonParser.nextTextValue()); break; case "accountId": userIdentity.add(CloudTrailEventField.accountId.name(), jsonParser.nextTextValue()); break; case "accessKeyId": userIdentity.add(CloudTrailEventField.accessKeyId.name(), jsonParser.nextTextValue()); break; case "userName": userIdentity.add(CloudTrailEventField.userName.name(), jsonParser.nextTextValue()); break; case "sessionContext": this.parseSessionContext(userIdentity); break; case "invokedBy": userIdentity.add(CloudTrailEventField.invokedBy.name(), jsonParser.nextTextValue()); break; case "identityProvider": userIdentity.add(CloudTrailEventField.identityProvider.name(), jsonParser.nextTextValue()); break; default: userIdentity.add(key, parseDefaultValue(key)); break; } } eventData.add(CloudTrailEventField.userIdentity.name(), userIdentity); }
[ "private", "void", "parseUserIdentity", "(", "CloudTrailEventData", "eventData", ")", "throws", "IOException", "{", "JsonToken", "nextToken", "=", "jsonParser", ".", "nextToken", "(", ")", ";", "if", "(", "nextToken", "==", "JsonToken", ".", "VALUE_NULL", ")", "{", "eventData", ".", "add", "(", "CloudTrailEventField", ".", "userIdentity", ".", "name", "(", ")", ",", "null", ")", ";", "return", ";", "}", "if", "(", "nextToken", "!=", "JsonToken", ".", "START_OBJECT", ")", "{", "throw", "new", "JsonParseException", "(", "\"Not a UserIdentity object\"", ",", "jsonParser", ".", "getCurrentLocation", "(", ")", ")", ";", "}", "UserIdentity", "userIdentity", "=", "new", "UserIdentity", "(", ")", ";", "while", "(", "jsonParser", ".", "nextToken", "(", ")", "!=", "JsonToken", ".", "END_OBJECT", ")", "{", "String", "key", "=", "jsonParser", ".", "getCurrentName", "(", ")", ";", "switch", "(", "key", ")", "{", "case", "\"type\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "type", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"principalId\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "principalId", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"arn\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "arn", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"accountId\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "accountId", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"accessKeyId\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "accessKeyId", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"userName\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "userName", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"sessionContext\"", ":", "this", ".", "parseSessionContext", "(", "userIdentity", ")", ";", "break", ";", "case", "\"invokedBy\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "invokedBy", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "case", "\"identityProvider\"", ":", "userIdentity", ".", "add", "(", "CloudTrailEventField", ".", "identityProvider", ".", "name", "(", ")", ",", "jsonParser", ".", "nextTextValue", "(", ")", ")", ";", "break", ";", "default", ":", "userIdentity", ".", "add", "(", "key", ",", "parseDefaultValue", "(", "key", ")", ")", ";", "break", ";", "}", "}", "eventData", ".", "add", "(", "CloudTrailEventField", ".", "userIdentity", ".", "name", "(", ")", ",", "userIdentity", ")", ";", "}" ]
Parses the {@link UserIdentity} in CloudTrailEventData @param eventData {@link CloudTrailEventData} needs to parse. @throws IOException
[ "Parses", "the", "{", "@link", "UserIdentity", "}", "in", "CloudTrailEventData" ]
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/AbstractEventSerializer.java#L215-L265
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsChacc.java
CmsChacc.getConnectedResource
protected String getConnectedResource(CmsAccessControlEntry entry, Map<CmsUUID, String> parents) { CmsUUID resId = entry.getResource(); String resName = parents.get(resId); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resName)) { return resName; } return resId.toString(); }
java
protected String getConnectedResource(CmsAccessControlEntry entry, Map<CmsUUID, String> parents) { CmsUUID resId = entry.getResource(); String resName = parents.get(resId); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(resName)) { return resName; } return resId.toString(); }
[ "protected", "String", "getConnectedResource", "(", "CmsAccessControlEntry", "entry", ",", "Map", "<", "CmsUUID", ",", "String", ">", "parents", ")", "{", "CmsUUID", "resId", "=", "entry", ".", "getResource", "(", ")", ";", "String", "resName", "=", "parents", ".", "get", "(", "resId", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "resName", ")", ")", "{", "return", "resName", ";", "}", "return", "resId", ".", "toString", "(", ")", ";", "}" ]
Returns the resource on which the specified access control entry was set.<p> @param entry the current access control entry @param parents the parent resources to determine the connected resource @return the resource name of the corresponding resource
[ "Returns", "the", "resource", "on", "which", "the", "specified", "access", "control", "entry", "was", "set", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsChacc.java#L1038-L1046
graknlabs/grakn
server/src/graql/gremlin/spanningtree/datastructure/FibonacciHeap.java
FibonacciHeap.add
public Entry add(V value, P priority) { Preconditions.checkNotNull(value); Preconditions.checkNotNull(priority); if (size >= MAX_CAPACITY) return null; final Entry result = new Entry(value, priority); // add as a root oMinEntry = mergeLists(result, oMinEntry); size++; return result; }
java
public Entry add(V value, P priority) { Preconditions.checkNotNull(value); Preconditions.checkNotNull(priority); if (size >= MAX_CAPACITY) return null; final Entry result = new Entry(value, priority); // add as a root oMinEntry = mergeLists(result, oMinEntry); size++; return result; }
[ "public", "Entry", "add", "(", "V", "value", ",", "P", "priority", ")", "{", "Preconditions", ".", "checkNotNull", "(", "value", ")", ";", "Preconditions", ".", "checkNotNull", "(", "priority", ")", ";", "if", "(", "size", ">=", "MAX_CAPACITY", ")", "return", "null", ";", "final", "Entry", "result", "=", "new", "Entry", "(", "value", ",", "priority", ")", ";", "// add as a root", "oMinEntry", "=", "mergeLists", "(", "result", ",", "oMinEntry", ")", ";", "size", "++", ";", "return", "result", ";", "}" ]
Inserts a new entry into the heap and returns the entry if heap is not full. Returns absent otherwise. No heap consolidation is performed. Runtime: O(1)
[ "Inserts", "a", "new", "entry", "into", "the", "heap", "and", "returns", "the", "entry", "if", "heap", "is", "not", "full", ".", "Returns", "absent", "otherwise", ".", "No", "heap", "consolidation", "is", "performed", ".", "Runtime", ":", "O", "(", "1", ")" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/spanningtree/datastructure/FibonacciHeap.java#L146-L158
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.checkRoleForResource
public void checkRoleForResource(CmsRequestContext context, CmsRole role, CmsResource resource) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRoleForResource(dbc, role, resource); } finally { dbc.clear(); } }
java
public void checkRoleForResource(CmsRequestContext context, CmsRole role, CmsResource resource) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRoleForResource(dbc, role, resource); } finally { dbc.clear(); } }
[ "public", "void", "checkRoleForResource", "(", "CmsRequestContext", "context", ",", "CmsRole", "role", ",", "CmsResource", "resource", ")", "throws", "CmsRoleViolationException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", "{", "checkRoleForResource", "(", "dbc", ",", "role", ",", "resource", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "}" ]
Checks if the user of the current context has permissions to impersonate the given role for the given resource.<p> @param context the current request context @param role the role to check @param resource the resource to check the role for @throws CmsRoleViolationException if the user does not have the required role permissions
[ "Checks", "if", "the", "user", "of", "the", "current", "context", "has", "permissions", "to", "impersonate", "the", "given", "role", "for", "the", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L624-L633
sniggle/simple-pgp
simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java
BasePGPCommon.findPrivateKey
protected PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecretKey, String password) throws PGPException { LOGGER.trace("findPrivateKey(PGPSecretKey, String)"); LOGGER.trace("Secret Key: {}, Password: {}", pgpSecretKey == null ? "not set" : "set", password == null ? "not set" : "********"); PGPPrivateKey result = null; PBESecretKeyDecryptor pbeSecretKeyDecryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); LOGGER.info("Extracting private key"); result = pgpSecretKey.extractPrivateKey(pbeSecretKeyDecryptor); if( result == null && LOGGER.isErrorEnabled() ) { LOGGER.error("No private key could be extracted"); } return result; }
java
protected PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecretKey, String password) throws PGPException { LOGGER.trace("findPrivateKey(PGPSecretKey, String)"); LOGGER.trace("Secret Key: {}, Password: {}", pgpSecretKey == null ? "not set" : "set", password == null ? "not set" : "********"); PGPPrivateKey result = null; PBESecretKeyDecryptor pbeSecretKeyDecryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); LOGGER.info("Extracting private key"); result = pgpSecretKey.extractPrivateKey(pbeSecretKeyDecryptor); if( result == null && LOGGER.isErrorEnabled() ) { LOGGER.error("No private key could be extracted"); } return result; }
[ "protected", "PGPPrivateKey", "findPrivateKey", "(", "PGPSecretKey", "pgpSecretKey", ",", "String", "password", ")", "throws", "PGPException", "{", "LOGGER", ".", "trace", "(", "\"findPrivateKey(PGPSecretKey, String)\"", ")", ";", "LOGGER", ".", "trace", "(", "\"Secret Key: {}, Password: {}\"", ",", "pgpSecretKey", "==", "null", "?", "\"not set\"", ":", "\"set\"", ",", "password", "==", "null", "?", "\"not set\"", ":", "\"********\"", ")", ";", "PGPPrivateKey", "result", "=", "null", ";", "PBESecretKeyDecryptor", "pbeSecretKeyDecryptor", "=", "new", "BcPBESecretKeyDecryptorBuilder", "(", "new", "BcPGPDigestCalculatorProvider", "(", ")", ")", ".", "build", "(", "password", ".", "toCharArray", "(", ")", ")", ";", "LOGGER", ".", "info", "(", "\"Extracting private key\"", ")", ";", "result", "=", "pgpSecretKey", ".", "extractPrivateKey", "(", "pbeSecretKeyDecryptor", ")", ";", "if", "(", "result", "==", "null", "&&", "LOGGER", ".", "isErrorEnabled", "(", ")", ")", "{", "LOGGER", ".", "error", "(", "\"No private key could be extracted\"", ")", ";", "}", "return", "result", ";", "}" ]
read the private key from the given secret key @param pgpSecretKey the secret key @param password the password to unlock the private key @return the unlocked private key @throws PGPException
[ "read", "the", "private", "key", "from", "the", "given", "secret", "key" ]
train
https://github.com/sniggle/simple-pgp/blob/2ab83e4d370b8189f767d8e4e4c7e6020e60fbe3/simple-pgp-java/src/main/java/me/sniggle/pgp/crypt/internal/BasePGPCommon.java#L261-L272
aws/aws-sdk-java
aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/EntityFilter.java
EntityFilter.withTags
public EntityFilter withTags(java.util.Collection<java.util.Map<String, String>> tags) { setTags(tags); return this; }
java
public EntityFilter withTags(java.util.Collection<java.util.Map<String, String>> tags) { setTags(tags); return this; }
[ "public", "EntityFilter", "withTags", "(", "java", ".", "util", ".", "Collection", "<", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> A map of entity tags attached to the affected entity. </p> @param tags A map of entity tags attached to the affected entity. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "entity", "tags", "attached", "to", "the", "affected", "entity", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/EntityFilter.java#L422-L425
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java
HadoopUtils.getOptionallyThrottledFileSystem
public static FileSystem getOptionallyThrottledFileSystem(FileSystem fs, State state) throws IOException { DeprecationUtils.renameDeprecatedKeys(state, MAX_FILESYSTEM_QPS, DEPRECATED_KEYS); if (state.contains(MAX_FILESYSTEM_QPS)) { return getOptionallyThrottledFileSystem(fs, state.getPropAsInt(MAX_FILESYSTEM_QPS)); } return fs; }
java
public static FileSystem getOptionallyThrottledFileSystem(FileSystem fs, State state) throws IOException { DeprecationUtils.renameDeprecatedKeys(state, MAX_FILESYSTEM_QPS, DEPRECATED_KEYS); if (state.contains(MAX_FILESYSTEM_QPS)) { return getOptionallyThrottledFileSystem(fs, state.getPropAsInt(MAX_FILESYSTEM_QPS)); } return fs; }
[ "public", "static", "FileSystem", "getOptionallyThrottledFileSystem", "(", "FileSystem", "fs", ",", "State", "state", ")", "throws", "IOException", "{", "DeprecationUtils", ".", "renameDeprecatedKeys", "(", "state", ",", "MAX_FILESYSTEM_QPS", ",", "DEPRECATED_KEYS", ")", ";", "if", "(", "state", ".", "contains", "(", "MAX_FILESYSTEM_QPS", ")", ")", "{", "return", "getOptionallyThrottledFileSystem", "(", "fs", ",", "state", ".", "getPropAsInt", "(", "MAX_FILESYSTEM_QPS", ")", ")", ";", "}", "return", "fs", ";", "}" ]
Calls {@link #getOptionallyThrottledFileSystem(FileSystem, int)} parsing the qps from the input {@link State} at key {@link #MAX_FILESYSTEM_QPS}. @throws IOException
[ "Calls", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L544-L551
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.order_orderId_debt_pay_POST
public OvhOrder order_orderId_debt_pay_POST(Long orderId) throws IOException { String qPath = "/me/order/{orderId}/debt/pay"; StringBuilder sb = path(qPath, orderId); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder order_orderId_debt_pay_POST(Long orderId) throws IOException { String qPath = "/me/order/{orderId}/debt/pay"; StringBuilder sb = path(qPath, orderId); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "order_orderId_debt_pay_POST", "(", "Long", "orderId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/order/{orderId}/debt/pay\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "orderId", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Create an order in order to pay this order's debt REST: POST /me/order/{orderId}/debt/pay @param orderId [required]
[ "Create", "an", "order", "in", "order", "to", "pay", "this", "order", "s", "debt" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2041-L2046
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-logging/xwiki-commons-logging-api/src/main/java/org/xwiki/logging/LogUtils.java
LogUtils.newLogEvent
public static LogEvent newLogEvent(Marker marker, LogLevel level, String message, Object[] argumentArray, Throwable throwable, long timeStamp) { if (marker != null) { if (marker.contains(LogEvent.MARKER_BEGIN)) { return new BeginLogEvent(marker, level, message, argumentArray, throwable, timeStamp); } else if (marker.contains(LogEvent.MARKER_END)) { return new EndLogEvent(marker, level, message, argumentArray, throwable, timeStamp); } } return new LogEvent(marker, level, message, argumentArray, throwable, timeStamp); }
java
public static LogEvent newLogEvent(Marker marker, LogLevel level, String message, Object[] argumentArray, Throwable throwable, long timeStamp) { if (marker != null) { if (marker.contains(LogEvent.MARKER_BEGIN)) { return new BeginLogEvent(marker, level, message, argumentArray, throwable, timeStamp); } else if (marker.contains(LogEvent.MARKER_END)) { return new EndLogEvent(marker, level, message, argumentArray, throwable, timeStamp); } } return new LogEvent(marker, level, message, argumentArray, throwable, timeStamp); }
[ "public", "static", "LogEvent", "newLogEvent", "(", "Marker", "marker", ",", "LogLevel", "level", ",", "String", "message", ",", "Object", "[", "]", "argumentArray", ",", "Throwable", "throwable", ",", "long", "timeStamp", ")", "{", "if", "(", "marker", "!=", "null", ")", "{", "if", "(", "marker", ".", "contains", "(", "LogEvent", ".", "MARKER_BEGIN", ")", ")", "{", "return", "new", "BeginLogEvent", "(", "marker", ",", "level", ",", "message", ",", "argumentArray", ",", "throwable", ",", "timeStamp", ")", ";", "}", "else", "if", "(", "marker", ".", "contains", "(", "LogEvent", ".", "MARKER_END", ")", ")", "{", "return", "new", "EndLogEvent", "(", "marker", ",", "level", ",", "message", ",", "argumentArray", ",", "throwable", ",", "timeStamp", ")", ";", "}", "}", "return", "new", "LogEvent", "(", "marker", ",", "level", ",", "message", ",", "argumentArray", ",", "throwable", ",", "timeStamp", ")", ";", "}" ]
Create and return a new {@link LogEvent} instance based on the passed parameters. @param marker the log marker @param level the log level @param message the log message @param argumentArray the event arguments to insert in the message @param throwable the throwable associated to the event @param timeStamp the number of milliseconds elapsed from 1/1/1970 until logging event was created. @return the {@link LogEvent} @since 6.4M1
[ "Create", "and", "return", "a", "new", "{", "@link", "LogEvent", "}", "instance", "based", "on", "the", "passed", "parameters", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-logging/xwiki-commons-logging-api/src/main/java/org/xwiki/logging/LogUtils.java#L69-L81
opengeospatial/teamengine
teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java
SoapParser.validateSoapMessage
private void validateSoapMessage(Document soapMessage, ErrorHandler eh) throws Exception { String namespace = soapMessage.getDocumentElement().getNamespaceURI(); if (namespace == null) { throw new Exception( "Error: SOAP message cannot be validated. The returned response may be an HTML response: " + DomUtils.serializeNode(soapMessage)); } // Create SOAP validator SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema soap_schema = null; if (namespace.equals(SOAP_12_NAMESPACE)) { soap_schema = sf.newSchema(Misc .getResourceAsFile("com/occamlab/te/schemas/soap12.xsd")); } else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{ soap_schema = sf.newSchema(Misc .getResourceAsFile("com/occamlab/te/schemas/soap11.xsd")); } Validator soap_validator = soap_schema.newValidator(); soap_validator.setErrorHandler(eh); soap_validator.validate(new DOMSource(soapMessage)); }
java
private void validateSoapMessage(Document soapMessage, ErrorHandler eh) throws Exception { String namespace = soapMessage.getDocumentElement().getNamespaceURI(); if (namespace == null) { throw new Exception( "Error: SOAP message cannot be validated. The returned response may be an HTML response: " + DomUtils.serializeNode(soapMessage)); } // Create SOAP validator SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema soap_schema = null; if (namespace.equals(SOAP_12_NAMESPACE)) { soap_schema = sf.newSchema(Misc .getResourceAsFile("com/occamlab/te/schemas/soap12.xsd")); } else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{ soap_schema = sf.newSchema(Misc .getResourceAsFile("com/occamlab/te/schemas/soap11.xsd")); } Validator soap_validator = soap_schema.newValidator(); soap_validator.setErrorHandler(eh); soap_validator.validate(new DOMSource(soapMessage)); }
[ "private", "void", "validateSoapMessage", "(", "Document", "soapMessage", ",", "ErrorHandler", "eh", ")", "throws", "Exception", "{", "String", "namespace", "=", "soapMessage", ".", "getDocumentElement", "(", ")", ".", "getNamespaceURI", "(", ")", ";", "if", "(", "namespace", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Error: SOAP message cannot be validated. The returned response may be an HTML response: \"", "+", "DomUtils", ".", "serializeNode", "(", "soapMessage", ")", ")", ";", "}", "// Create SOAP validator", "SchemaFactory", "sf", "=", "SchemaFactory", ".", "newInstance", "(", "XMLConstants", ".", "W3C_XML_SCHEMA_NS_URI", ")", ";", "Schema", "soap_schema", "=", "null", ";", "if", "(", "namespace", ".", "equals", "(", "SOAP_12_NAMESPACE", ")", ")", "{", "soap_schema", "=", "sf", ".", "newSchema", "(", "Misc", ".", "getResourceAsFile", "(", "\"com/occamlab/te/schemas/soap12.xsd\"", ")", ")", ";", "}", "else", "/* if (namespace.equals(SOAP_11_NAMESPACE)) */", "{", "soap_schema", "=", "sf", ".", "newSchema", "(", "Misc", ".", "getResourceAsFile", "(", "\"com/occamlab/te/schemas/soap11.xsd\"", ")", ")", ";", "}", "Validator", "soap_validator", "=", "soap_schema", ".", "newValidator", "(", ")", ";", "soap_validator", ".", "setErrorHandler", "(", "eh", ")", ";", "soap_validator", ".", "validate", "(", "new", "DOMSource", "(", "soapMessage", ")", ")", ";", "}" ]
A method to validate the SOAP message received. The message is validated against the propoer SOAP Schema (1.1 or 1.2 depending on the namespace of the incoming message) @param soapMessage the SOAP message to validate. @param eh the error handler. @author Simone Gianfranceschi
[ "A", "method", "to", "validate", "the", "SOAP", "message", "received", ".", "The", "message", "is", "validated", "against", "the", "propoer", "SOAP", "Schema", "(", "1", ".", "1", "or", "1", ".", "2", "depending", "on", "the", "namespace", "of", "the", "incoming", "message", ")" ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L192-L217
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierAnnotation.java
TypeQualifierAnnotation.combineReturnTypeAnnotations
public static @CheckForNull TypeQualifierAnnotation combineReturnTypeAnnotations(TypeQualifierAnnotation a, TypeQualifierAnnotation b) { return combineAnnotations(a, b, combineReturnValueMatrix); }
java
public static @CheckForNull TypeQualifierAnnotation combineReturnTypeAnnotations(TypeQualifierAnnotation a, TypeQualifierAnnotation b) { return combineAnnotations(a, b, combineReturnValueMatrix); }
[ "public", "static", "@", "CheckForNull", "TypeQualifierAnnotation", "combineReturnTypeAnnotations", "(", "TypeQualifierAnnotation", "a", ",", "TypeQualifierAnnotation", "b", ")", "{", "return", "combineAnnotations", "(", "a", ",", "b", ",", "combineReturnValueMatrix", ")", ";", "}" ]
Combine return type annotations. @param a a TypeQualifierAnnotation used on a return value @param b another TypeQualifierAnnotation used on a return value @return combined return type annotation that is at least as narrow as both <code>a</code> or <code>b</code>, or null if no such TypeQualifierAnnotation exists
[ "Combine", "return", "type", "annotations", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierAnnotation.java#L120-L123
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/ProcessEngines.java
ProcessEngines.getProcessEngine
public static ProcessEngine getProcessEngine(String processEngineName, boolean forceCreate) { if (!isInitialized) { init(forceCreate); } return processEngines.get(processEngineName); }
java
public static ProcessEngine getProcessEngine(String processEngineName, boolean forceCreate) { if (!isInitialized) { init(forceCreate); } return processEngines.get(processEngineName); }
[ "public", "static", "ProcessEngine", "getProcessEngine", "(", "String", "processEngineName", ",", "boolean", "forceCreate", ")", "{", "if", "(", "!", "isInitialized", ")", "{", "init", "(", "forceCreate", ")", ";", "}", "return", "processEngines", ".", "get", "(", "processEngineName", ")", ";", "}" ]
obtain a process engine by name. @param processEngineName is the name of the process engine or null for the default process engine.
[ "obtain", "a", "process", "engine", "by", "name", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/ProcessEngines.java#L246-L251
stevespringett/Alpine
alpine/src/main/java/alpine/auth/LdapConnectionWrapper.java
LdapConnectionWrapper.createLdapContext
public LdapContext createLdapContext(final String userDn, final String password) throws NamingException { LOGGER.debug("Creating LDAP context for: " +userDn); if (StringUtils.isEmpty(userDn) || StringUtils.isEmpty(password)) { throw new NamingException("Username or password cannot be empty or null"); } final Hashtable<String, String> env = new Hashtable<>(); if (StringUtils.isNotBlank(LDAP_SECURITY_AUTH)) { env.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTH); } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); } try { return new InitialLdapContext(env, null); } catch (CommunicationException e) { LOGGER.error("Failed to connect to directory server", e); throw(e); } catch (NamingException e) { throw new NamingException("Failed to authenticate user"); } }
java
public LdapContext createLdapContext(final String userDn, final String password) throws NamingException { LOGGER.debug("Creating LDAP context for: " +userDn); if (StringUtils.isEmpty(userDn) || StringUtils.isEmpty(password)) { throw new NamingException("Username or password cannot be empty or null"); } final Hashtable<String, String> env = new Hashtable<>(); if (StringUtils.isNotBlank(LDAP_SECURITY_AUTH)) { env.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTH); } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); } try { return new InitialLdapContext(env, null); } catch (CommunicationException e) { LOGGER.error("Failed to connect to directory server", e); throw(e); } catch (NamingException e) { throw new NamingException("Failed to authenticate user"); } }
[ "public", "LdapContext", "createLdapContext", "(", "final", "String", "userDn", ",", "final", "String", "password", ")", "throws", "NamingException", "{", "LOGGER", ".", "debug", "(", "\"Creating LDAP context for: \"", "+", "userDn", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "userDn", ")", "||", "StringUtils", ".", "isEmpty", "(", "password", ")", ")", "{", "throw", "new", "NamingException", "(", "\"Username or password cannot be empty or null\"", ")", ";", "}", "final", "Hashtable", "<", "String", ",", "String", ">", "env", "=", "new", "Hashtable", "<>", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "LDAP_SECURITY_AUTH", ")", ")", "{", "env", ".", "put", "(", "Context", ".", "SECURITY_AUTHENTICATION", ",", "LDAP_SECURITY_AUTH", ")", ";", "}", "env", ".", "put", "(", "Context", ".", "SECURITY_PRINCIPAL", ",", "userDn", ")", ";", "env", ".", "put", "(", "Context", ".", "SECURITY_CREDENTIALS", ",", "password", ")", ";", "env", ".", "put", "(", "Context", ".", "INITIAL_CONTEXT_FACTORY", ",", "\"com.sun.jndi.ldap.LdapCtxFactory\"", ")", ";", "env", ".", "put", "(", "Context", ".", "PROVIDER_URL", ",", "LDAP_URL", ")", ";", "if", "(", "IS_LDAP_SSLTLS", ")", "{", "env", ".", "put", "(", "\"java.naming.ldap.factory.socket\"", ",", "\"alpine.crypto.RelaxedSSLSocketFactory\"", ")", ";", "}", "try", "{", "return", "new", "InitialLdapContext", "(", "env", ",", "null", ")", ";", "}", "catch", "(", "CommunicationException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Failed to connect to directory server\"", ",", "e", ")", ";", "throw", "(", "e", ")", ";", "}", "catch", "(", "NamingException", "e", ")", "{", "throw", "new", "NamingException", "(", "\"Failed to authenticate user\"", ")", ";", "}", "}" ]
Asserts a users credentials. Returns an LdapContext if assertion is successful or an exception for any other reason. @param userDn the users DN to assert @param password the password to assert @return the LdapContext upon a successful connection @throws NamingException when unable to establish a connection @since 1.4.0
[ "Asserts", "a", "users", "credentials", ".", "Returns", "an", "LdapContext", "if", "assertion", "is", "successful", "or", "an", "exception", "for", "any", "other", "reason", "." ]
train
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/LdapConnectionWrapper.java#L82-L106
att/AAF
inno/xgen/src/main/java/com/att/xgen/XGenBuff.java
XGenBuff.run
@SuppressWarnings({ "unchecked", "rawtypes" }) public void run(State<Env> state, Trans trans, Cache cache, DynamicCode code) throws APIException, IOException { code.code(state, trans, cache, xgen); }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void run(State<Env> state, Trans trans, Cache cache, DynamicCode code) throws APIException, IOException { code.code(state, trans, cache, xgen); }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "void", "run", "(", "State", "<", "Env", ">", "state", ",", "Trans", "trans", ",", "Cache", "cache", ",", "DynamicCode", "code", ")", "throws", "APIException", ",", "IOException", "{", "code", ".", "code", "(", "state", ",", "trans", ",", "cache", ",", "xgen", ")", ";", "}" ]
Special Case where code is dynamic, so give access to State and Trans info @param state @param trans @param cache @param code @throws APIException @throws IOException
[ "Special", "Case", "where", "code", "is", "dynamic", "so", "give", "access", "to", "State", "and", "Trans", "info" ]
train
https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/inno/xgen/src/main/java/com/att/xgen/XGenBuff.java#L46-L49
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/DescribeRobotApplicationResult.java
DescribeRobotApplicationResult.withTags
public DescribeRobotApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public DescribeRobotApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DescribeRobotApplicationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> The list of all tags added to the specified robot application. </p> @param tags The list of all tags added to the specified robot application. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "list", "of", "all", "tags", "added", "to", "the", "specified", "robot", "application", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/DescribeRobotApplicationResult.java#L420-L423
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistryModule.java
ConfigurationPropertyRegistryModule.bindAllGuiceProperties
private static void bindAllGuiceProperties(ConfigurationPropertyRegistry registry, AtomicReference<Injector> injector) { for (Field field : GuiceProperties.class.getFields()) { if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) { try { // We are just assuming these properties have a string type final String propertyName = String.valueOf(field.get(null)); registry.register(GuiceProperties.class, injector, propertyName, String.class, field); } catch (Exception e) { throw new IllegalArgumentException("Error trying to process GuiceProperties." + field.getName(), e); } } } }
java
private static void bindAllGuiceProperties(ConfigurationPropertyRegistry registry, AtomicReference<Injector> injector) { for (Field field : GuiceProperties.class.getFields()) { if (Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers())) { try { // We are just assuming these properties have a string type final String propertyName = String.valueOf(field.get(null)); registry.register(GuiceProperties.class, injector, propertyName, String.class, field); } catch (Exception e) { throw new IllegalArgumentException("Error trying to process GuiceProperties." + field.getName(), e); } } } }
[ "private", "static", "void", "bindAllGuiceProperties", "(", "ConfigurationPropertyRegistry", "registry", ",", "AtomicReference", "<", "Injector", ">", "injector", ")", "{", "for", "(", "Field", "field", ":", "GuiceProperties", ".", "class", ".", "getFields", "(", ")", ")", "{", "if", "(", "Modifier", ".", "isStatic", "(", "field", ".", "getModifiers", "(", ")", ")", "&&", "Modifier", ".", "isPublic", "(", "field", ".", "getModifiers", "(", ")", ")", ")", "{", "try", "{", "// We are just assuming these properties have a string type", "final", "String", "propertyName", "=", "String", ".", "valueOf", "(", "field", ".", "get", "(", "null", ")", ")", ";", "registry", ".", "register", "(", "GuiceProperties", ".", "class", ",", "injector", ",", "propertyName", ",", "String", ".", "class", ",", "field", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Error trying to process GuiceProperties.\"", "+", "field", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}", "}", "}" ]
Create fake bindings for all the properties in {@link com.peterphi.std.guice.apploader.GuiceProperties} @param registry @param injector
[ "Create", "fake", "bindings", "for", "all", "the", "properties", "in", "{", "@link", "com", ".", "peterphi", ".", "std", ".", "guice", ".", "apploader", ".", "GuiceProperties", "}" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistryModule.java#L56-L75
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updateEntityWithServiceResponseAsync
public Observable<ServiceResponse<OperationStatus>> updateEntityWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, UpdateEntityOptionalParameter updateEntityOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (entityId == null) { throw new IllegalArgumentException("Parameter entityId is required and cannot be null."); } final String name = updateEntityOptionalParameter != null ? updateEntityOptionalParameter.name() : null; return updateEntityWithServiceResponseAsync(appId, versionId, entityId, name); }
java
public Observable<ServiceResponse<OperationStatus>> updateEntityWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, UpdateEntityOptionalParameter updateEntityOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (versionId == null) { throw new IllegalArgumentException("Parameter versionId is required and cannot be null."); } if (entityId == null) { throw new IllegalArgumentException("Parameter entityId is required and cannot be null."); } final String name = updateEntityOptionalParameter != null ? updateEntityOptionalParameter.name() : null; return updateEntityWithServiceResponseAsync(appId, versionId, entityId, name); }
[ "public", "Observable", "<", "ServiceResponse", "<", "OperationStatus", ">", ">", "updateEntityWithServiceResponseAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UpdateEntityOptionalParameter", "updateEntityOptionalParameter", ")", "{", "if", "(", "this", ".", "client", ".", "endpoint", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.endpoint() is required and cannot be null.\"", ")", ";", "}", "if", "(", "appId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter appId is required and cannot be null.\"", ")", ";", "}", "if", "(", "versionId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter versionId is required and cannot be null.\"", ")", ";", "}", "if", "(", "entityId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter entityId is required and cannot be null.\"", ")", ";", "}", "final", "String", "name", "=", "updateEntityOptionalParameter", "!=", "null", "?", "updateEntityOptionalParameter", ".", "name", "(", ")", ":", "null", ";", "return", "updateEntityWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "name", ")", ";", "}" ]
Updates the name of an entity extractor. @param appId The application ID. @param versionId The version ID. @param entityId The entity extractor ID. @param updateEntityOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Updates", "the", "name", "of", "an", "entity", "extractor", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3426-L3442
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bos/BosClient.java
BosClient.listParts
public ListPartsResponse listParts(String bucketName, String key, String uploadId) { return this.listParts(new ListPartsRequest(bucketName, key, uploadId)); }
java
public ListPartsResponse listParts(String bucketName, String key, String uploadId) { return this.listParts(new ListPartsRequest(bucketName, key, uploadId)); }
[ "public", "ListPartsResponse", "listParts", "(", "String", "bucketName", ",", "String", "key", ",", "String", "uploadId", ")", "{", "return", "this", ".", "listParts", "(", "new", "ListPartsRequest", "(", "bucketName", ",", "key", ",", "uploadId", ")", ")", ";", "}" ]
Lists the parts that have been uploaded for a specific multipart upload. @param bucketName The name of the bucket containing the multipart upload whose parts are being listed. @param key The key of the associated multipart upload whose parts are being listed. @param uploadId The ID of the multipart upload whose parts are being listed. @return Returns a ListPartsResponse from Bos.
[ "Lists", "the", "parts", "that", "have", "been", "uploaded", "for", "a", "specific", "multipart", "upload", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L1187-L1189
centic9/commons-dost
src/main/java/org/dstadler/commons/metrics/MetricsUtils.java
MetricsUtils.sendMetric
public static void sendMetric(String metric, int value, long ts, String url, String user, String password) throws IOException { try (HttpClientWrapper metrics = new HttpClientWrapper(user, password, 60_000)) { sendMetric(metric, value, ts, metrics.getHttpClient(), url); } }
java
public static void sendMetric(String metric, int value, long ts, String url, String user, String password) throws IOException { try (HttpClientWrapper metrics = new HttpClientWrapper(user, password, 60_000)) { sendMetric(metric, value, ts, metrics.getHttpClient(), url); } }
[ "public", "static", "void", "sendMetric", "(", "String", "metric", ",", "int", "value", ",", "long", "ts", ",", "String", "url", ",", "String", "user", ",", "String", "password", ")", "throws", "IOException", "{", "try", "(", "HttpClientWrapper", "metrics", "=", "new", "HttpClientWrapper", "(", "user", ",", "password", ",", "60_000", ")", ")", "{", "sendMetric", "(", "metric", ",", "value", ",", "ts", ",", "metrics", ".", "getHttpClient", "(", ")", ",", "url", ")", ";", "}", "}" ]
Send the given value for the given metric and timestamp. Authentication can be provided via the configured {@link HttpClient} instance. @param metric The key of the metric @param value The value of the measurement @param ts The timestamp of the measurement @param url The base URL where Elasticsearch is available. @param user The username for basic authentication of the HTTP connection, empty if unused @param password The password for basic authentication of the HTTP connection, null if unused @throws IOException If the HTTP call fails with an HTTP status code.
[ "Send", "the", "given", "value", "for", "the", "given", "metric", "and", "timestamp", "." ]
train
https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/metrics/MetricsUtils.java#L39-L43
spring-projects/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java
ReactiveMongoClientFactory.createMongoClient
public MongoClient createMongoClient(MongoClientSettings settings) { Integer embeddedPort = getEmbeddedPort(); if (embeddedPort != null) { return createEmbeddedMongoClient(settings, embeddedPort); } return createNetworkMongoClient(settings); }
java
public MongoClient createMongoClient(MongoClientSettings settings) { Integer embeddedPort = getEmbeddedPort(); if (embeddedPort != null) { return createEmbeddedMongoClient(settings, embeddedPort); } return createNetworkMongoClient(settings); }
[ "public", "MongoClient", "createMongoClient", "(", "MongoClientSettings", "settings", ")", "{", "Integer", "embeddedPort", "=", "getEmbeddedPort", "(", ")", ";", "if", "(", "embeddedPort", "!=", "null", ")", "{", "return", "createEmbeddedMongoClient", "(", "settings", ",", "embeddedPort", ")", ";", "}", "return", "createNetworkMongoClient", "(", "settings", ")", ";", "}" ]
Creates a {@link MongoClient} using the given {@code settings}. If the environment contains a {@code local.mongo.port} property, it is used to configure a client to an embedded MongoDB instance. @param settings the settings @return the Mongo client
[ "Creates", "a", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactory.java#L63-L69
jglobus/JGlobus
gridftp/src/main/java/org/globus/ftp/dc/SocketPool.java
SocketPool.checkOut
public synchronized SocketBox checkOut() { Enumeration e = freeSockets.keys(); if (e.hasMoreElements()) { SocketBox sb = (SocketBox)e.nextElement(); if (busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket is marked free, but already exists in the pool of busy sockets."); } ((ManagedSocketBox) sb).setStatus(ManagedSocketBox.BUSY); freeSockets.remove(sb); busySockets.put(sb, sb); return sb; } else { return null; } }
java
public synchronized SocketBox checkOut() { Enumeration e = freeSockets.keys(); if (e.hasMoreElements()) { SocketBox sb = (SocketBox)e.nextElement(); if (busySockets.containsKey(sb)) { throw new IllegalArgumentException("This socket is marked free, but already exists in the pool of busy sockets."); } ((ManagedSocketBox) sb).setStatus(ManagedSocketBox.BUSY); freeSockets.remove(sb); busySockets.put(sb, sb); return sb; } else { return null; } }
[ "public", "synchronized", "SocketBox", "checkOut", "(", ")", "{", "Enumeration", "e", "=", "freeSockets", ".", "keys", "(", ")", ";", "if", "(", "e", ".", "hasMoreElements", "(", ")", ")", "{", "SocketBox", "sb", "=", "(", "SocketBox", ")", "e", ".", "nextElement", "(", ")", ";", "if", "(", "busySockets", ".", "containsKey", "(", "sb", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"This socket is marked free, but already exists in the pool of busy sockets.\"", ")", ";", "}", "(", "(", "ManagedSocketBox", ")", "sb", ")", ".", "setStatus", "(", "ManagedSocketBox", ".", "BUSY", ")", ";", "freeSockets", ".", "remove", "(", "sb", ")", ";", "busySockets", ".", "put", "(", "sb", ",", "sb", ")", ";", "return", "sb", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
checks out the next free socket and returns it, or returns null if there aren't any. Before calling this method, the socket needs to be first add()ed to the pool.
[ "checks", "out", "the", "next", "free", "socket", "and", "returns", "it", "or", "returns", "null", "if", "there", "aren", "t", "any", ".", "Before", "calling", "this", "method", "the", "socket", "needs", "to", "be", "first", "add", "()", "ed", "to", "the", "pool", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/dc/SocketPool.java#L100-L118
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.orthoSymmetricLH
public Matrix4d orthoSymmetricLH(double width, double height, double zNear, double zFar, boolean zZeroToOne) { return orthoSymmetricLH(width, height, zNear, zFar, zZeroToOne, this); }
java
public Matrix4d orthoSymmetricLH(double width, double height, double zNear, double zFar, boolean zZeroToOne) { return orthoSymmetricLH(width, height, zNear, zFar, zZeroToOne, this); }
[ "public", "Matrix4d", "orthoSymmetricLH", "(", "double", "width", ",", "double", "height", ",", "double", "zNear", ",", "double", "zFar", ",", "boolean", "zZeroToOne", ")", "{", "return", "orthoSymmetricLH", "(", "width", ",", "height", ",", "zNear", ",", "zFar", ",", "zZeroToOne", ",", "this", ")", ";", "}" ]
Apply a symmetric orthographic projection transformation for a left-handed coordinate system using the given NDC z range to this matrix. <p> This method is equivalent to calling {@link #orthoLH(double, double, double, double, double, double, boolean) orthoLH()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the orthographic projection transformation will be applied first! <p> In order to set the matrix to a symmetric orthographic projection without post-multiplying it, use {@link #setOrthoSymmetricLH(double, double, double, double, boolean) setOrthoSymmetricLH()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrthoSymmetricLH(double, double, double, double, boolean) @param width the distance between the right and left frustum edges @param height the distance between the top and bottom frustum edges @param zNear near clipping plane distance @param zFar far clipping plane distance @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return this
[ "Apply", "a", "symmetric", "orthographic", "projection", "transformation", "for", "a", "left", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", "to", "this", "matrix", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", "{", "@link", "#orthoLH", "(", "double", "double", "double", "double", "double", "double", "boolean", ")", "orthoLH", "()", "}", "with", "<code", ">", "left", "=", "-", "width", "/", "2<", "/", "code", ">", "<code", ">", "right", "=", "+", "width", "/", "2<", "/", "code", ">", "<code", ">", "bottom", "=", "-", "height", "/", "2<", "/", "code", ">", "and", "<code", ">", "top", "=", "+", "height", "/", "2<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "O<", "/", "code", ">", "the", "orthographic", "projection", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "O<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "O", "*", "v<", "/", "code", ">", "the", "orthographic", "projection", "transformation", "will", "be", "applied", "first!", "<p", ">", "In", "order", "to", "set", "the", "matrix", "to", "a", "symmetric", "orthographic", "projection", "without", "post", "-", "multiplying", "it", "use", "{", "@link", "#setOrthoSymmetricLH", "(", "double", "double", "double", "double", "boolean", ")", "setOrthoSymmetricLH", "()", "}", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "songho", ".", "ca", "/", "opengl", "/", "gl_projectionmatrix", ".", "html#ortho", ">", "http", ":", "//", "www", ".", "songho", ".", "ca<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L10361-L10363
bluelinelabs/Conductor
conductor/src/main/java/com/bluelinelabs/conductor/Controller.java
Controller.getChildRouter
@NonNull public final Router getChildRouter(@NonNull ViewGroup container, @Nullable String tag) { //noinspection ConstantConditions return getChildRouter(container, tag, true); }
java
@NonNull public final Router getChildRouter(@NonNull ViewGroup container, @Nullable String tag) { //noinspection ConstantConditions return getChildRouter(container, tag, true); }
[ "@", "NonNull", "public", "final", "Router", "getChildRouter", "(", "@", "NonNull", "ViewGroup", "container", ",", "@", "Nullable", "String", "tag", ")", "{", "//noinspection ConstantConditions", "return", "getChildRouter", "(", "container", ",", "tag", ",", "true", ")", ";", "}" ]
Retrieves the child {@link Router} for the given container/tag combination. If no child router for this container exists yet, it will be created. Note that multiple routers should not exist in the same container unless a lot of care is taken to maintain order between them. Avoid using the same container unless you have a great reason to do so (ex: ViewPagers). @param container The ViewGroup that hosts the child Router @param tag The router's tag or {@code null} if none is needed
[ "Retrieves", "the", "child", "{", "@link", "Router", "}", "for", "the", "given", "container", "/", "tag", "combination", ".", "If", "no", "child", "router", "for", "this", "container", "exists", "yet", "it", "will", "be", "created", ".", "Note", "that", "multiple", "routers", "should", "not", "exist", "in", "the", "same", "container", "unless", "a", "lot", "of", "care", "is", "taken", "to", "maintain", "order", "between", "them", ".", "Avoid", "using", "the", "same", "container", "unless", "you", "have", "a", "great", "reason", "to", "do", "so", "(", "ex", ":", "ViewPagers", ")", "." ]
train
https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/Controller.java#L195-L199
googlegenomics/utils-java
src/main/java/com/google/cloud/genomics/utils/grpc/GenomicsChannel.java
GenomicsChannel.fromOfflineAuth
public static ManagedChannel fromOfflineAuth(OfflineAuth auth, String fields) throws IOException, GeneralSecurityException { return fromCreds(auth.getCredentials(), fields); }
java
public static ManagedChannel fromOfflineAuth(OfflineAuth auth, String fields) throws IOException, GeneralSecurityException { return fromCreds(auth.getCredentials(), fields); }
[ "public", "static", "ManagedChannel", "fromOfflineAuth", "(", "OfflineAuth", "auth", ",", "String", "fields", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "return", "fromCreds", "(", "auth", ".", "getCredentials", "(", ")", ",", "fields", ")", ";", "}" ]
Create a new gRPC channel to the Google Genomics API, using either OfflineAuth or the application default credentials. This library will work with both the newer and older versions of OAuth2 client-side support. https://developers.google.com/identity/protocols/application-default-credentials @param auth The OfflineAuth object. @param fields Which fields to return in the partial response, or null for none. @return The ManagedChannel. @throws IOException @throws GeneralSecurityException
[ "Create", "a", "new", "gRPC", "channel", "to", "the", "Google", "Genomics", "API", "using", "either", "OfflineAuth", "or", "the", "application", "default", "credentials", "." ]
train
https://github.com/googlegenomics/utils-java/blob/7205d5b4e4f61fc6b93acb4bdd76b93df5b5f612/src/main/java/com/google/cloud/genomics/utils/grpc/GenomicsChannel.java#L145-L148
apache/incubator-shardingsphere
sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java
ShardingRule.getDataNode
public DataNode getDataNode(final String dataSourceName, final String logicTableName) { TableRule tableRule = getTableRule(logicTableName); for (DataNode each : tableRule.getActualDataNodes()) { if (shardingDataSourceNames.getDataSourceNames().contains(each.getDataSourceName()) && each.getDataSourceName().equals(dataSourceName)) { return each; } } throw new ShardingConfigurationException("Cannot find actual data node for data source name: '%s' and logic table name: '%s'", dataSourceName, logicTableName); }
java
public DataNode getDataNode(final String dataSourceName, final String logicTableName) { TableRule tableRule = getTableRule(logicTableName); for (DataNode each : tableRule.getActualDataNodes()) { if (shardingDataSourceNames.getDataSourceNames().contains(each.getDataSourceName()) && each.getDataSourceName().equals(dataSourceName)) { return each; } } throw new ShardingConfigurationException("Cannot find actual data node for data source name: '%s' and logic table name: '%s'", dataSourceName, logicTableName); }
[ "public", "DataNode", "getDataNode", "(", "final", "String", "dataSourceName", ",", "final", "String", "logicTableName", ")", "{", "TableRule", "tableRule", "=", "getTableRule", "(", "logicTableName", ")", ";", "for", "(", "DataNode", "each", ":", "tableRule", ".", "getActualDataNodes", "(", ")", ")", "{", "if", "(", "shardingDataSourceNames", ".", "getDataSourceNames", "(", ")", ".", "contains", "(", "each", ".", "getDataSourceName", "(", ")", ")", "&&", "each", ".", "getDataSourceName", "(", ")", ".", "equals", "(", "dataSourceName", ")", ")", "{", "return", "each", ";", "}", "}", "throw", "new", "ShardingConfigurationException", "(", "\"Cannot find actual data node for data source name: '%s' and logic table name: '%s'\"", ",", "dataSourceName", ",", "logicTableName", ")", ";", "}" ]
Find data node by data source and logic table. @param dataSourceName data source name @param logicTableName logic table name @return data node
[ "Find", "data", "node", "by", "data", "source", "and", "logic", "table", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java#L415-L423
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/products/ProductVariationUrl.java
ProductVariationUrl.getProductVariationLocalizedDeltaPricesUrl
public static MozuUrl getProductVariationLocalizedDeltaPricesUrl(String productCode, String variationKey) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/variations/{variationKey}/localizedDeltaPrice"); formatter.formatUrl("productCode", productCode); formatter.formatUrl("variationKey", variationKey); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getProductVariationLocalizedDeltaPricesUrl(String productCode, String variationKey) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/variations/{variationKey}/localizedDeltaPrice"); formatter.formatUrl("productCode", productCode); formatter.formatUrl("variationKey", variationKey); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getProductVariationLocalizedDeltaPricesUrl", "(", "String", "productCode", ",", "String", "variationKey", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/products/{productCode}/variations/{variationKey}/localizedDeltaPrice\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"productCode\"", ",", "productCode", ")", ";", "formatter", ".", "formatUrl", "(", "\"variationKey\"", ",", "variationKey", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for GetProductVariationLocalizedDeltaPrices @param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product. @param variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetProductVariationLocalizedDeltaPrices" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/products/ProductVariationUrl.java#L22-L28
OpenLiberty/open-liberty
dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/web/utils/SocialWebUtils.java
SocialWebUtils.deleteCookie
public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, WebAppSecurityConfig webAppSecConfig) { ReferrerURLCookieHandler referrerURLCookieHandler = getCookieHandler(); referrerURLCookieHandler.clearReferrerURLCookie(request, response, cookieName); Cookie paramCookie = createExpiredCookie(request, cookieName, webAppSecConfig); response.addCookie(paramCookie); }
java
public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, WebAppSecurityConfig webAppSecConfig) { ReferrerURLCookieHandler referrerURLCookieHandler = getCookieHandler(); referrerURLCookieHandler.clearReferrerURLCookie(request, response, cookieName); Cookie paramCookie = createExpiredCookie(request, cookieName, webAppSecConfig); response.addCookie(paramCookie); }
[ "public", "void", "deleteCookie", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "String", "cookieName", ",", "WebAppSecurityConfig", "webAppSecConfig", ")", "{", "ReferrerURLCookieHandler", "referrerURLCookieHandler", "=", "getCookieHandler", "(", ")", ";", "referrerURLCookieHandler", ".", "clearReferrerURLCookie", "(", "request", ",", "response", ",", "cookieName", ")", ";", "Cookie", "paramCookie", "=", "createExpiredCookie", "(", "request", ",", "cookieName", ",", "webAppSecConfig", ")", ";", "response", ".", "addCookie", "(", "paramCookie", ")", ";", "}" ]
Clears the specified cookie and sets its path to the current request URI.
[ "Clears", "the", "specified", "cookie", "and", "sets", "its", "path", "to", "the", "current", "request", "URI", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/web/utils/SocialWebUtils.java#L257-L263
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java
DefaultGroovyStaticMethods.getBundle
public static ResourceBundle getBundle(ResourceBundle self, String bundleName) { return getBundle(self, bundleName, Locale.getDefault()); }
java
public static ResourceBundle getBundle(ResourceBundle self, String bundleName) { return getBundle(self, bundleName, Locale.getDefault()); }
[ "public", "static", "ResourceBundle", "getBundle", "(", "ResourceBundle", "self", ",", "String", "bundleName", ")", "{", "return", "getBundle", "(", "self", ",", "bundleName", ",", "Locale", ".", "getDefault", "(", ")", ")", ";", "}" ]
Works exactly like ResourceBundle.getBundle(String). This is needed because the java method depends on a particular stack configuration that is not guaranteed in Groovy when calling the Java method. @param self placeholder variable used by Groovy categories; ignored for default static methods @param bundleName the name of the bundle. @return the resource bundle @see java.util.ResourceBundle#getBundle(java.lang.String) @since 1.6.0
[ "Works", "exactly", "like", "ResourceBundle", ".", "getBundle", "(", "String", ")", ".", "This", "is", "needed", "because", "the", "java", "method", "depends", "on", "a", "particular", "stack", "configuration", "that", "is", "not", "guaranteed", "in", "Groovy", "when", "calling", "the", "Java", "method", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyStaticMethods.java#L192-L194
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
Check.positionIndex
@Throws(IllegalPositionIndexException.class) public static int positionIndex(final int index, final int size) { final boolean isIndexValid = (size >= 0) && (index >= 0) && (index < size); if (!isIndexValid) { throw new IllegalPositionIndexException(index, size); } return index; }
java
@Throws(IllegalPositionIndexException.class) public static int positionIndex(final int index, final int size) { final boolean isIndexValid = (size >= 0) && (index >= 0) && (index < size); if (!isIndexValid) { throw new IllegalPositionIndexException(index, size); } return index; }
[ "@", "Throws", "(", "IllegalPositionIndexException", ".", "class", ")", "public", "static", "int", "positionIndex", "(", "final", "int", "index", ",", "final", "int", "size", ")", "{", "final", "boolean", "isIndexValid", "=", "(", "size", ">=", "0", ")", "&&", "(", "index", ">=", "0", ")", "&&", "(", "index", "<", "size", ")", ";", "if", "(", "!", "isIndexValid", ")", "{", "throw", "new", "IllegalPositionIndexException", "(", "index", ",", "size", ")", ";", "}", "return", "index", ";", "}" ]
Ensures that a given position index is valid within the size of an array, list or string ... @param index index of an array, list or string @param size size of an array list or string @return the index @throws IllegalPositionIndexException if the index is not a valid position index within an array, list or string of size <em>size</em>
[ "Ensures", "that", "a", "given", "position", "index", "is", "valid", "within", "the", "size", "of", "an", "array", "list", "or", "string", "..." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L3200-L3209
craftercms/profile
security-provider/src/main/java/org/craftercms/security/utils/social/ConnectionUtils.java
ConnectionUtils.removeConnectionData
public static void removeConnectionData(String providerId, String providerUserId, Profile profile) { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); if (MapUtils.isNotEmpty(allConnections)) { List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId); if (CollectionUtils.isNotEmpty(connectionsForProvider)) { for (Iterator<Map<String, Object>> iter = connectionsForProvider.iterator(); iter.hasNext();) { Map<String, Object> connectionDataMap = iter.next(); if (providerUserId.equals(connectionDataMap.get("providerUserId"))) { iter.remove(); } } } } }
java
public static void removeConnectionData(String providerId, String providerUserId, Profile profile) { Map<String, List<Map<String, Object>>> allConnections = profile.getAttribute(CONNECTIONS_ATTRIBUTE_NAME); if (MapUtils.isNotEmpty(allConnections)) { List<Map<String, Object>> connectionsForProvider = allConnections.get(providerId); if (CollectionUtils.isNotEmpty(connectionsForProvider)) { for (Iterator<Map<String, Object>> iter = connectionsForProvider.iterator(); iter.hasNext();) { Map<String, Object> connectionDataMap = iter.next(); if (providerUserId.equals(connectionDataMap.get("providerUserId"))) { iter.remove(); } } } } }
[ "public", "static", "void", "removeConnectionData", "(", "String", "providerId", ",", "String", "providerUserId", ",", "Profile", "profile", ")", "{", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "allConnections", "=", "profile", ".", "getAttribute", "(", "CONNECTIONS_ATTRIBUTE_NAME", ")", ";", "if", "(", "MapUtils", ".", "isNotEmpty", "(", "allConnections", ")", ")", "{", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "connectionsForProvider", "=", "allConnections", ".", "get", "(", "providerId", ")", ";", "if", "(", "CollectionUtils", ".", "isNotEmpty", "(", "connectionsForProvider", ")", ")", "{", "for", "(", "Iterator", "<", "Map", "<", "String", ",", "Object", ">", ">", "iter", "=", "connectionsForProvider", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "Map", "<", "String", ",", "Object", ">", "connectionDataMap", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "providerUserId", ".", "equals", "(", "connectionDataMap", ".", "get", "(", "\"providerUserId\"", ")", ")", ")", "{", "iter", ".", "remove", "(", ")", ";", "}", "}", "}", "}", "}" ]
Remove the {@link ConnectionData} associated to the provider ID and user ID. @param providerId the provider ID of the connection @param providerUserId the provider user ID @param profile the profile where to remove the data from
[ "Remove", "the", "{", "@link", "ConnectionData", "}", "associated", "to", "the", "provider", "ID", "and", "user", "ID", "." ]
train
https://github.com/craftercms/profile/blob/d829c1136b0fd21d87dc925cb7046cbd38a300a4/security-provider/src/main/java/org/craftercms/security/utils/social/ConnectionUtils.java#L193-L209
skyscreamer/JSONassert
src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
JSONAssert.assertNotEquals
public static void assertNotEquals(String message, JSONArray expected, JSONArray actual, JSONCompareMode compareMode) throws JSONException { JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode); if (result.passed()) { throw new AssertionError(getCombinedMessage(message, result.getMessage())); } }
java
public static void assertNotEquals(String message, JSONArray expected, JSONArray actual, JSONCompareMode compareMode) throws JSONException { JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode); if (result.passed()) { throw new AssertionError(getCombinedMessage(message, result.getMessage())); } }
[ "public", "static", "void", "assertNotEquals", "(", "String", "message", ",", "JSONArray", "expected", ",", "JSONArray", "actual", ",", "JSONCompareMode", "compareMode", ")", "throws", "JSONException", "{", "JSONCompareResult", "result", "=", "JSONCompare", ".", "compareJSON", "(", "expected", ",", "actual", ",", "compareMode", ")", ";", "if", "(", "result", ".", "passed", "(", ")", ")", "{", "throw", "new", "AssertionError", "(", "getCombinedMessage", "(", "message", ",", "result", ".", "getMessage", "(", ")", ")", ")", ";", "}", "}" ]
Asserts that the JSONArray provided does not match the expected JSONArray. If it is it throws an {@link AssertionError}. @param message Error message to be displayed in case of assertion failure @param expected Expected JSONArray @param actual JSONArray to compare @param compareMode Specifies which comparison mode to use @throws JSONException JSON parsing error
[ "Asserts", "that", "the", "JSONArray", "provided", "does", "not", "match", "the", "expected", "JSONArray", ".", "If", "it", "is", "it", "throws", "an", "{", "@link", "AssertionError", "}", "." ]
train
https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L754-L760
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
StringParser.parseDoubleObj
@Nullable public static Double parseDoubleObj (@Nullable final Object aObject, @Nullable final Double aDefault) { final double dValue = parseDouble (aObject, Double.NaN); return Double.isNaN (dValue) ? aDefault : Double.valueOf (dValue); }
java
@Nullable public static Double parseDoubleObj (@Nullable final Object aObject, @Nullable final Double aDefault) { final double dValue = parseDouble (aObject, Double.NaN); return Double.isNaN (dValue) ? aDefault : Double.valueOf (dValue); }
[ "@", "Nullable", "public", "static", "Double", "parseDoubleObj", "(", "@", "Nullable", "final", "Object", "aObject", ",", "@", "Nullable", "final", "Double", "aDefault", ")", "{", "final", "double", "dValue", "=", "parseDouble", "(", "aObject", ",", "Double", ".", "NaN", ")", ";", "return", "Double", ".", "isNaN", "(", "dValue", ")", "?", "aDefault", ":", "Double", ".", "valueOf", "(", "dValue", ")", ";", "}" ]
Parse the given {@link Object} as {@link Double}. Note: both the locale independent form of a double can be parsed here (e.g. 4.523) as well as a localized form using the comma as the decimal separator (e.g. the German 4,523). @param aObject The object to parse. May be <code>null</code>. @param aDefault The default value to be returned if the parsed object cannot be converted to a double. May be <code>null</code>. @return <code>aDefault</code> if the object does not represent a valid value.
[ "Parse", "the", "given", "{", "@link", "Object", "}", "as", "{", "@link", "Double", "}", ".", "Note", ":", "both", "the", "locale", "independent", "form", "of", "a", "double", "can", "be", "parsed", "here", "(", "e", ".", "g", ".", "4", ".", "523", ")", "as", "well", "as", "a", "localized", "form", "using", "the", "comma", "as", "the", "decimal", "separator", "(", "e", ".", "g", ".", "the", "German", "4", "523", ")", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L530-L535
mapsforge/mapsforge
mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java
MapViewPosition.moveCenterAndZoom
@Override public void moveCenterAndZoom(double moveHorizontal, double moveVertical, byte zoomLevelDiff) { moveCenterAndZoom(moveHorizontal, moveVertical, zoomLevelDiff, true); }
java
@Override public void moveCenterAndZoom(double moveHorizontal, double moveVertical, byte zoomLevelDiff) { moveCenterAndZoom(moveHorizontal, moveVertical, zoomLevelDiff, true); }
[ "@", "Override", "public", "void", "moveCenterAndZoom", "(", "double", "moveHorizontal", ",", "double", "moveVertical", ",", "byte", "zoomLevelDiff", ")", "{", "moveCenterAndZoom", "(", "moveHorizontal", ",", "moveVertical", ",", "zoomLevelDiff", ",", "true", ")", ";", "}" ]
Animates the center position of the map by the given amount of pixels. @param moveHorizontal the amount of pixels to move this MapViewPosition horizontally. @param moveVertical the amount of pixels to move this MapViewPosition vertically. @param zoomLevelDiff the difference in desired zoom level.
[ "Animates", "the", "center", "position", "of", "the", "map", "by", "the", "given", "amount", "of", "pixels", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java#L304-L307
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/Tesseract.java
Tesseract.getOCRText
protected String getOCRText(String filename, int pageNum) { if (filename != null && !filename.isEmpty()) { api.TessBaseAPISetInputName(handle, filename); } Pointer utf8Text = renderedFormat == RenderedFormat.HOCR ? api.TessBaseAPIGetHOCRText(handle, pageNum - 1) : api.TessBaseAPIGetUTF8Text(handle); String str = utf8Text.getString(0); api.TessDeleteText(utf8Text); return str; }
java
protected String getOCRText(String filename, int pageNum) { if (filename != null && !filename.isEmpty()) { api.TessBaseAPISetInputName(handle, filename); } Pointer utf8Text = renderedFormat == RenderedFormat.HOCR ? api.TessBaseAPIGetHOCRText(handle, pageNum - 1) : api.TessBaseAPIGetUTF8Text(handle); String str = utf8Text.getString(0); api.TessDeleteText(utf8Text); return str; }
[ "protected", "String", "getOCRText", "(", "String", "filename", ",", "int", "pageNum", ")", "{", "if", "(", "filename", "!=", "null", "&&", "!", "filename", ".", "isEmpty", "(", ")", ")", "{", "api", ".", "TessBaseAPISetInputName", "(", "handle", ",", "filename", ")", ";", "}", "Pointer", "utf8Text", "=", "renderedFormat", "==", "RenderedFormat", ".", "HOCR", "?", "api", ".", "TessBaseAPIGetHOCRText", "(", "handle", ",", "pageNum", "-", "1", ")", ":", "api", ".", "TessBaseAPIGetUTF8Text", "(", "handle", ")", ";", "String", "str", "=", "utf8Text", ".", "getString", "(", "0", ")", ";", "api", ".", "TessDeleteText", "(", "utf8Text", ")", ";", "return", "str", ";", "}" ]
Gets recognized text. @param filename input file name. Needed only for reading a UNLV zone file. @param pageNum page number; needed for hocr paging. @return the recognized text
[ "Gets", "recognized", "text", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/Tesseract.java#L497-L506
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/topology/RefreshFutures.java
RefreshFutures.awaitAll
static long awaitAll(long timeout, TimeUnit timeUnit, Collection<? extends Future<?>> futures) throws InterruptedException { long waitTime = 0; for (Future<?> future : futures) { long timeoutLeft = timeUnit.toNanos(timeout) - waitTime; if (timeoutLeft <= 0) { break; } long startWait = System.nanoTime(); try { future.get(timeoutLeft, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } catch (Exception e) { continue; } finally { waitTime += System.nanoTime() - startWait; } } return waitTime; }
java
static long awaitAll(long timeout, TimeUnit timeUnit, Collection<? extends Future<?>> futures) throws InterruptedException { long waitTime = 0; for (Future<?> future : futures) { long timeoutLeft = timeUnit.toNanos(timeout) - waitTime; if (timeoutLeft <= 0) { break; } long startWait = System.nanoTime(); try { future.get(timeoutLeft, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } catch (Exception e) { continue; } finally { waitTime += System.nanoTime() - startWait; } } return waitTime; }
[ "static", "long", "awaitAll", "(", "long", "timeout", ",", "TimeUnit", "timeUnit", ",", "Collection", "<", "?", "extends", "Future", "<", "?", ">", ">", "futures", ")", "throws", "InterruptedException", "{", "long", "waitTime", "=", "0", ";", "for", "(", "Future", "<", "?", ">", "future", ":", "futures", ")", "{", "long", "timeoutLeft", "=", "timeUnit", ".", "toNanos", "(", "timeout", ")", "-", "waitTime", ";", "if", "(", "timeoutLeft", "<=", "0", ")", "{", "break", ";", "}", "long", "startWait", "=", "System", ".", "nanoTime", "(", ")", ";", "try", "{", "future", ".", "get", "(", "timeoutLeft", ",", "TimeUnit", ".", "NANOSECONDS", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "continue", ";", "}", "finally", "{", "waitTime", "+=", "System", ".", "nanoTime", "(", ")", "-", "startWait", ";", "}", "}", "return", "waitTime", ";", "}" ]
Await for either future completion or to reach the timeout. Successful/exceptional future completion is not substantial. @param timeout the timeout value. @param timeUnit timeout unit. @param futures {@link Collection} of {@literal Future}s. @return time awaited in {@link TimeUnit#NANOSECONDS}. @throws InterruptedException
[ "Await", "for", "either", "future", "completion", "or", "to", "reach", "the", "timeout", ".", "Successful", "/", "exceptional", "future", "completion", "is", "not", "substantial", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/topology/RefreshFutures.java#L36-L63
netty/netty
codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheEncoder.java
AbstractBinaryMemcacheEncoder.encodeExtras
private static void encodeExtras(ByteBuf buf, ByteBuf extras) { if (extras == null || !extras.isReadable()) { return; } buf.writeBytes(extras); }
java
private static void encodeExtras(ByteBuf buf, ByteBuf extras) { if (extras == null || !extras.isReadable()) { return; } buf.writeBytes(extras); }
[ "private", "static", "void", "encodeExtras", "(", "ByteBuf", "buf", ",", "ByteBuf", "extras", ")", "{", "if", "(", "extras", "==", "null", "||", "!", "extras", ".", "isReadable", "(", ")", ")", "{", "return", ";", "}", "buf", ".", "writeBytes", "(", "extras", ")", ";", "}" ]
Encode the extras. @param buf the {@link ByteBuf} to write into. @param extras the extras to encode.
[ "Encode", "the", "extras", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/AbstractBinaryMemcacheEncoder.java#L54-L60
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/appservice/v2016_03_01/implementation/ResourceHealthMetadatasInner.java
ResourceHealthMetadatasInner.listBySiteAsync
public Observable<Page<ResourceHealthMetadataInner>> listBySiteAsync(final String resourceGroupName, final String name) { return listBySiteWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Page<ResourceHealthMetadataInner>>() { @Override public Page<ResourceHealthMetadataInner> call(ServiceResponse<Page<ResourceHealthMetadataInner>> response) { return response.body(); } }); }
java
public Observable<Page<ResourceHealthMetadataInner>> listBySiteAsync(final String resourceGroupName, final String name) { return listBySiteWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Page<ResourceHealthMetadataInner>>() { @Override public Page<ResourceHealthMetadataInner> call(ServiceResponse<Page<ResourceHealthMetadataInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ResourceHealthMetadataInner", ">", ">", "listBySiteAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ")", "{", "return", "listBySiteWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ResourceHealthMetadataInner", ">", ">", ",", "Page", "<", "ResourceHealthMetadataInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "ResourceHealthMetadataInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ResourceHealthMetadataInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets the category of ResourceHealthMetadata to use for the given site as a collection. Gets the category of ResourceHealthMetadata to use for the given site as a collection. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of web app. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ResourceHealthMetadataInner&gt; object
[ "Gets", "the", "category", "of", "ResourceHealthMetadata", "to", "use", "for", "the", "given", "site", "as", "a", "collection", ".", "Gets", "the", "category", "of", "ResourceHealthMetadata", "to", "use", "for", "the", "given", "site", "as", "a", "collection", "." ]
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/ResourceHealthMetadatasInner.java#L387-L395
Azure/azure-sdk-for-java
authorization/resource-manager/v2018_09_01_preview/src/main/java/com/microsoft/azure/management/authorization/v2018_09_01_preview/implementation/RoleDefinitionsInner.java
RoleDefinitionsInner.listAsync
public Observable<Page<RoleDefinitionInner>> listAsync(final String scope, final String filter) { return listWithServiceResponseAsync(scope, filter) .map(new Func1<ServiceResponse<Page<RoleDefinitionInner>>, Page<RoleDefinitionInner>>() { @Override public Page<RoleDefinitionInner> call(ServiceResponse<Page<RoleDefinitionInner>> response) { return response.body(); } }); }
java
public Observable<Page<RoleDefinitionInner>> listAsync(final String scope, final String filter) { return listWithServiceResponseAsync(scope, filter) .map(new Func1<ServiceResponse<Page<RoleDefinitionInner>>, Page<RoleDefinitionInner>>() { @Override public Page<RoleDefinitionInner> call(ServiceResponse<Page<RoleDefinitionInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "RoleDefinitionInner", ">", ">", "listAsync", "(", "final", "String", "scope", ",", "final", "String", "filter", ")", "{", "return", "listWithServiceResponseAsync", "(", "scope", ",", "filter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RoleDefinitionInner", ">", ">", ",", "Page", "<", "RoleDefinitionInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "RoleDefinitionInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RoleDefinitionInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get all role definitions that are applicable at scope and above. @param scope The scope of the role definition. @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as well. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RoleDefinitionInner&gt; object
[ "Get", "all", "role", "definitions", "that", "are", "applicable", "at", "scope", "and", "above", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2018_09_01_preview/src/main/java/com/microsoft/azure/management/authorization/v2018_09_01_preview/implementation/RoleDefinitionsInner.java#L495-L503
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/mazha/DocumentRevs.java
DocumentRevs.setOthers
@JsonAnySetter public void setOthers(String name, Object value) { if(name.startsWith("_")) { // Just be defensive throw new RuntimeException("This is a reserved field, and should not be treated as document content."); } this.others.put(name, value); }
java
@JsonAnySetter public void setOthers(String name, Object value) { if(name.startsWith("_")) { // Just be defensive throw new RuntimeException("This is a reserved field, and should not be treated as document content."); } this.others.put(name, value); }
[ "@", "JsonAnySetter", "public", "void", "setOthers", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "name", ".", "startsWith", "(", "\"_\"", ")", ")", "{", "// Just be defensive", "throw", "new", "RuntimeException", "(", "\"This is a reserved field, and should not be treated as document content.\"", ")", ";", "}", "this", ".", "others", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Jackson will automatically put any field it can not find match to this @JsonAnySetter bucket. This is effectively all the document content.
[ "Jackson", "will", "automatically", "put", "any", "field", "it", "can", "not", "find", "match", "to", "this" ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/mazha/DocumentRevs.java#L79-L86
google/identity-toolkit-java-client
src/main/java/com/google/identitytoolkit/GitkitClient.java
GitkitClient.createFromJson
public static GitkitClient createFromJson(String configPath) throws GitkitClientException, JSONException, IOException { return createFromJson(configPath, null); }
java
public static GitkitClient createFromJson(String configPath) throws GitkitClientException, JSONException, IOException { return createFromJson(configPath, null); }
[ "public", "static", "GitkitClient", "createFromJson", "(", "String", "configPath", ")", "throws", "GitkitClientException", ",", "JSONException", ",", "IOException", "{", "return", "createFromJson", "(", "configPath", ",", "null", ")", ";", "}" ]
Constructs a Gitkit client from a JSON config file @param configPath Path to JSON configuration file @return Gitkit client
[ "Constructs", "a", "Gitkit", "client", "from", "a", "JSON", "config", "file" ]
train
https://github.com/google/identity-toolkit-java-client/blob/61dda1aabbd541ad5e431e840fd266bfca5f8a4a/src/main/java/com/google/identitytoolkit/GitkitClient.java#L119-L122
jboss-integration/fuse-bxms-integ
switchyard/switchyard-component-bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskServiceRegistry.java
BPMTaskServiceRegistry.getTaskService
public static final synchronized BPMTaskService getTaskService(QName serviceDomainName, QName serviceName) { KnowledgeRuntimeManager runtimeManager = KnowledgeRuntimeManagerRegistry.getRuntimeManager(serviceDomainName, serviceName); if (runtimeManager != null) { RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(); if (runtimeEngine != null) { final TaskService taskService = runtimeEngine.getTaskService(); if (taskService != null) { InvocationHandler ih = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(taskService, args); } }; return (BPMTaskService)Proxy.newProxyInstance(BPMTaskService.class.getClassLoader(), new Class[] {BPMTaskService.class}, ih); } } } return null; }
java
public static final synchronized BPMTaskService getTaskService(QName serviceDomainName, QName serviceName) { KnowledgeRuntimeManager runtimeManager = KnowledgeRuntimeManagerRegistry.getRuntimeManager(serviceDomainName, serviceName); if (runtimeManager != null) { RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(); if (runtimeEngine != null) { final TaskService taskService = runtimeEngine.getTaskService(); if (taskService != null) { InvocationHandler ih = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(taskService, args); } }; return (BPMTaskService)Proxy.newProxyInstance(BPMTaskService.class.getClassLoader(), new Class[] {BPMTaskService.class}, ih); } } } return null; }
[ "public", "static", "final", "synchronized", "BPMTaskService", "getTaskService", "(", "QName", "serviceDomainName", ",", "QName", "serviceName", ")", "{", "KnowledgeRuntimeManager", "runtimeManager", "=", "KnowledgeRuntimeManagerRegistry", ".", "getRuntimeManager", "(", "serviceDomainName", ",", "serviceName", ")", ";", "if", "(", "runtimeManager", "!=", "null", ")", "{", "RuntimeEngine", "runtimeEngine", "=", "runtimeManager", ".", "getRuntimeEngine", "(", ")", ";", "if", "(", "runtimeEngine", "!=", "null", ")", "{", "final", "TaskService", "taskService", "=", "runtimeEngine", ".", "getTaskService", "(", ")", ";", "if", "(", "taskService", "!=", "null", ")", "{", "InvocationHandler", "ih", "=", "new", "InvocationHandler", "(", ")", "{", "@", "Override", "public", "Object", "invoke", "(", "Object", "proxy", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "return", "method", ".", "invoke", "(", "taskService", ",", "args", ")", ";", "}", "}", ";", "return", "(", "BPMTaskService", ")", "Proxy", ".", "newProxyInstance", "(", "BPMTaskService", ".", "class", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "BPMTaskService", ".", "class", "}", ",", "ih", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Gets a task service. @param serviceDomainName the service domain name @param serviceName the service name @return the task service
[ "Gets", "a", "task", "service", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskServiceRegistry.java#L38-L56
fernandospr/javapns-jdk16
src/main/java/javapns/Push.java
Push.sendPayloads
private static PushedNotifications sendPayloads(Object keystore, String password, boolean production, Object payloadDevicePairs) throws CommunicationException, KeystoreException { PushedNotifications notifications = new PushedNotifications(); if (payloadDevicePairs == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<PayloadPerDevice> pairs = Devices.asPayloadsPerDevices(payloadDevicePairs); notifications.setMaxRetained(pairs.size()); for (PayloadPerDevice ppd : pairs) { Device device = ppd.getDevice(); Payload payload = ppd.getPayload(); try { PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (Exception e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; }
java
private static PushedNotifications sendPayloads(Object keystore, String password, boolean production, Object payloadDevicePairs) throws CommunicationException, KeystoreException { PushedNotifications notifications = new PushedNotifications(); if (payloadDevicePairs == null) return notifications; PushNotificationManager pushManager = new PushNotificationManager(); try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(keystore, password, production); pushManager.initializeConnection(server); List<PayloadPerDevice> pairs = Devices.asPayloadsPerDevices(payloadDevicePairs); notifications.setMaxRetained(pairs.size()); for (PayloadPerDevice ppd : pairs) { Device device = ppd.getDevice(); Payload payload = ppd.getPayload(); try { PushedNotification notification = pushManager.sendNotification(device, payload, false); notifications.add(notification); } catch (Exception e) { notifications.add(new PushedNotification(device, payload, e)); } } } finally { try { pushManager.stopConnection(); } catch (Exception e) { } } return notifications; }
[ "private", "static", "PushedNotifications", "sendPayloads", "(", "Object", "keystore", ",", "String", "password", ",", "boolean", "production", ",", "Object", "payloadDevicePairs", ")", "throws", "CommunicationException", ",", "KeystoreException", "{", "PushedNotifications", "notifications", "=", "new", "PushedNotifications", "(", ")", ";", "if", "(", "payloadDevicePairs", "==", "null", ")", "return", "notifications", ";", "PushNotificationManager", "pushManager", "=", "new", "PushNotificationManager", "(", ")", ";", "try", "{", "AppleNotificationServer", "server", "=", "new", "AppleNotificationServerBasicImpl", "(", "keystore", ",", "password", ",", "production", ")", ";", "pushManager", ".", "initializeConnection", "(", "server", ")", ";", "List", "<", "PayloadPerDevice", ">", "pairs", "=", "Devices", ".", "asPayloadsPerDevices", "(", "payloadDevicePairs", ")", ";", "notifications", ".", "setMaxRetained", "(", "pairs", ".", "size", "(", ")", ")", ";", "for", "(", "PayloadPerDevice", "ppd", ":", "pairs", ")", "{", "Device", "device", "=", "ppd", ".", "getDevice", "(", ")", ";", "Payload", "payload", "=", "ppd", ".", "getPayload", "(", ")", ";", "try", "{", "PushedNotification", "notification", "=", "pushManager", ".", "sendNotification", "(", "device", ",", "payload", ",", "false", ")", ";", "notifications", ".", "add", "(", "notification", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "notifications", ".", "add", "(", "new", "PushedNotification", "(", "device", ",", "payload", ",", "e", ")", ")", ";", "}", "}", "}", "finally", "{", "try", "{", "pushManager", ".", "stopConnection", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "return", "notifications", ";", "}" ]
Push a different preformatted payload for each device. @param keystore a keystore containing your private key and the certificate signed by Apple ({@link java.io.File}, {@link java.io.InputStream}, byte[], {@link java.security.KeyStore} or {@link java.lang.String} for a file path) @param password the keystore's password. @param production true to use Apple's production servers, false to use the sandbox servers. @param payloadDevicePairs a list or an array of PayloadPerDevice: {@link java.util.List}<{@link javapns.notification.PayloadPerDevice}>, {@link javapns.notification.PayloadPerDevice PayloadPerDevice[]} or {@link javapns.notification.PayloadPerDevice} @return a list of pushed notifications, each with details on transmission results and error (if any) @throws KeystoreException thrown if an error occurs when loading the keystore @throws CommunicationException thrown if an unrecoverable error occurs while trying to communicate with Apple servers
[ "Push", "a", "different", "preformatted", "payload", "for", "each", "device", "." ]
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/Push.java#L291-L317
aws/aws-sdk-java
aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/util/SignatureChecker.java
SignatureChecker.verifySignature
public boolean verifySignature(String message, String signature, PublicKey publicKey){ boolean result = false; try { byte[] sigbytes = Base64.decode(signature.getBytes()); Signature sigChecker = SIG_CHECKER.get(); sigChecker.initVerify(publicKey); sigChecker.update(message.getBytes()); result = sigChecker.verify(sigbytes); } catch (InvalidKeyException e) { // Rare exception: The private key was incorrectly formatted } catch (SignatureException e) { // Rare exception: Catch-all exception for the signature checker } return result; }
java
public boolean verifySignature(String message, String signature, PublicKey publicKey){ boolean result = false; try { byte[] sigbytes = Base64.decode(signature.getBytes()); Signature sigChecker = SIG_CHECKER.get(); sigChecker.initVerify(publicKey); sigChecker.update(message.getBytes()); result = sigChecker.verify(sigbytes); } catch (InvalidKeyException e) { // Rare exception: The private key was incorrectly formatted } catch (SignatureException e) { // Rare exception: Catch-all exception for the signature checker } return result; }
[ "public", "boolean", "verifySignature", "(", "String", "message", ",", "String", "signature", ",", "PublicKey", "publicKey", ")", "{", "boolean", "result", "=", "false", ";", "try", "{", "byte", "[", "]", "sigbytes", "=", "Base64", ".", "decode", "(", "signature", ".", "getBytes", "(", ")", ")", ";", "Signature", "sigChecker", "=", "SIG_CHECKER", ".", "get", "(", ")", ";", "sigChecker", ".", "initVerify", "(", "publicKey", ")", ";", "sigChecker", ".", "update", "(", "message", ".", "getBytes", "(", ")", ")", ";", "result", "=", "sigChecker", ".", "verify", "(", "sigbytes", ")", ";", "}", "catch", "(", "InvalidKeyException", "e", ")", "{", "// Rare exception: The private key was incorrectly formatted", "}", "catch", "(", "SignatureException", "e", ")", "{", "// Rare exception: Catch-all exception for the signature checker", "}", "return", "result", ";", "}" ]
Does the actual Java cryptographic verification of the signature. This method does no handling of the many rare exceptions it is required to catch. This can also be used to verify the signature from the x-amz-sns-signature http header @param message Exact string that was signed. In the case of the x-amz-sns-signature header the signing string is the entire post body @param signature Base64-encoded signature of the message @return
[ "Does", "the", "actual", "Java", "cryptographic", "verification", "of", "the", "signature", ".", "This", "method", "does", "no", "handling", "of", "the", "many", "rare", "exceptions", "it", "is", "required", "to", "catch", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sns/src/main/java/com/amazonaws/services/sns/util/SignatureChecker.java#L147-L161
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.fetchByG_K_T
@Override public CPMeasurementUnit fetchByG_K_T(long groupId, String key, int type) { return fetchByG_K_T(groupId, key, type, true); }
java
@Override public CPMeasurementUnit fetchByG_K_T(long groupId, String key, int type) { return fetchByG_K_T(groupId, key, type, true); }
[ "@", "Override", "public", "CPMeasurementUnit", "fetchByG_K_T", "(", "long", "groupId", ",", "String", "key", ",", "int", "type", ")", "{", "return", "fetchByG_K_T", "(", "groupId", ",", "key", ",", "type", ",", "true", ")", ";", "}" ]
Returns the cp measurement unit where groupId = &#63; and key = &#63; and type = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param groupId the group ID @param key the key @param type the type @return the matching cp measurement unit, or <code>null</code> if a matching cp measurement unit could not be found
[ "Returns", "the", "cp", "measurement", "unit", "where", "groupId", "=", "&#63", ";", "and", "key", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder", "cache", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L2606-L2609
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareModuleManagement.java
JpaSoftwareModuleManagement.assertMetaDataQuota
private void assertMetaDataQuota(final Long moduleId, final int requested) { final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerSoftwareModule(); QuotaHelper.assertAssignmentQuota(moduleId, requested, maxMetaData, SoftwareModuleMetadata.class, SoftwareModule.class, softwareModuleMetadataRepository::countBySoftwareModuleId); }
java
private void assertMetaDataQuota(final Long moduleId, final int requested) { final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerSoftwareModule(); QuotaHelper.assertAssignmentQuota(moduleId, requested, maxMetaData, SoftwareModuleMetadata.class, SoftwareModule.class, softwareModuleMetadataRepository::countBySoftwareModuleId); }
[ "private", "void", "assertMetaDataQuota", "(", "final", "Long", "moduleId", ",", "final", "int", "requested", ")", "{", "final", "int", "maxMetaData", "=", "quotaManagement", ".", "getMaxMetaDataEntriesPerSoftwareModule", "(", ")", ";", "QuotaHelper", ".", "assertAssignmentQuota", "(", "moduleId", ",", "requested", ",", "maxMetaData", ",", "SoftwareModuleMetadata", ".", "class", ",", "SoftwareModule", ".", "class", ",", "softwareModuleMetadataRepository", "::", "countBySoftwareModuleId", ")", ";", "}" ]
Asserts the meta data quota for the software module with the given ID. @param moduleId The software module ID. @param requested Number of meta data entries to be created.
[ "Asserts", "the", "meta", "data", "quota", "for", "the", "software", "module", "with", "the", "given", "ID", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareModuleManagement.java#L548-L552
yatechorg/jedis-utils
src/main/java/org/yatech/jedis/collections/JedisSortedSet.java
JedisSortedSet.removeRangeByRank
public long removeRangeByRank(final long start, final long end) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zremrangeByRank(getKey(), start, end); } }); }
java
public long removeRangeByRank(final long start, final long end) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.zremrangeByRank(getKey(), start, end); } }); }
[ "public", "long", "removeRangeByRank", "(", "final", "long", "start", ",", "final", "long", "end", ")", "{", "return", "doWithJedis", "(", "new", "JedisCallable", "<", "Long", ">", "(", ")", "{", "@", "Override", "public", "Long", "call", "(", "Jedis", "jedis", ")", "{", "return", "jedis", ".", "zremrangeByRank", "(", "getKey", "(", ")", ",", "start", ",", "end", ")", ";", "}", "}", ")", ";", "}" ]
Removes all elements in the sorted set with rank between start and stop. Both start and stop are 0 -based indexes with 0 being the element with the lowest score. These indexes can be negative numbers, where they indicate offsets starting at the element with the highest score. For example: -1 is the element with the highest score, -2 the element with the second highest score and so forth. @param start @param end @return the number of elements removed.
[ "Removes", "all", "elements", "in", "the", "sorted", "set", "with", "rank", "between", "start", "and", "stop", ".", "Both", "start", "and", "stop", "are", "0", "-", "based", "indexes", "with", "0", "being", "the", "element", "with", "the", "lowest", "score", ".", "These", "indexes", "can", "be", "negative", "numbers", "where", "they", "indicate", "offsets", "starting", "at", "the", "element", "with", "the", "highest", "score", ".", "For", "example", ":", "-", "1", "is", "the", "element", "with", "the", "highest", "score", "-", "2", "the", "element", "with", "the", "second", "highest", "score", "and", "so", "forth", "." ]
train
https://github.com/yatechorg/jedis-utils/blob/1951609fa6697df4f69be76e7d66b9284924bd97/src/main/java/org/yatech/jedis/collections/JedisSortedSet.java#L321-L328
networknt/light-4j
client/src/main/java/com/networknt/client/ssl/ClientX509ExtendedTrustManager.java
ClientX509ExtendedTrustManager.checkIdentity
private void checkIdentity(SSLSession session, X509Certificate cert) throws CertificateException { if (session == null) { throw new CertificateException("No handshake session"); } if (EndpointIdentificationAlgorithm.HTTPS == identityAlg) { String hostname = session.getPeerHost(); APINameChecker.verifyAndThrow(hostname, cert); } }
java
private void checkIdentity(SSLSession session, X509Certificate cert) throws CertificateException { if (session == null) { throw new CertificateException("No handshake session"); } if (EndpointIdentificationAlgorithm.HTTPS == identityAlg) { String hostname = session.getPeerHost(); APINameChecker.verifyAndThrow(hostname, cert); } }
[ "private", "void", "checkIdentity", "(", "SSLSession", "session", ",", "X509Certificate", "cert", ")", "throws", "CertificateException", "{", "if", "(", "session", "==", "null", ")", "{", "throw", "new", "CertificateException", "(", "\"No handshake session\"", ")", ";", "}", "if", "(", "EndpointIdentificationAlgorithm", ".", "HTTPS", "==", "identityAlg", ")", "{", "String", "hostname", "=", "session", ".", "getPeerHost", "(", ")", ";", "APINameChecker", ".", "verifyAndThrow", "(", "hostname", ",", "cert", ")", ";", "}", "}" ]
check server identify against hostnames. This method is used to enhance X509TrustManager to provide standard identity check. This method can be applied to both clients and servers. @param session @param cert @throws CertificateException
[ "check", "server", "identify", "against", "hostnames", ".", "This", "method", "is", "used", "to", "enhance", "X509TrustManager", "to", "provide", "standard", "identity", "check", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/client/src/main/java/com/networknt/client/ssl/ClientX509ExtendedTrustManager.java#L175-L184
normanmaurer/niosmtp
src/main/java/me/normanmaurer/niosmtp/delivery/chain/EhloResponseListener.java
EhloResponseListener.initSupportedExtensions
private void initSupportedExtensions(SMTPClientSession session, SMTPResponse response) { Iterator<String> lines = response.getLines().iterator(); while(lines.hasNext()) { String line = lines.next(); if (line.equalsIgnoreCase(PIPELINING_EXTENSION)) { session.addSupportedExtensions(PIPELINING_EXTENSION); } else if (line.equalsIgnoreCase(STARTTLS_EXTENSION)) { session.addSupportedExtensions(STARTTLS_EXTENSION); } } }
java
private void initSupportedExtensions(SMTPClientSession session, SMTPResponse response) { Iterator<String> lines = response.getLines().iterator(); while(lines.hasNext()) { String line = lines.next(); if (line.equalsIgnoreCase(PIPELINING_EXTENSION)) { session.addSupportedExtensions(PIPELINING_EXTENSION); } else if (line.equalsIgnoreCase(STARTTLS_EXTENSION)) { session.addSupportedExtensions(STARTTLS_EXTENSION); } } }
[ "private", "void", "initSupportedExtensions", "(", "SMTPClientSession", "session", ",", "SMTPResponse", "response", ")", "{", "Iterator", "<", "String", ">", "lines", "=", "response", ".", "getLines", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "lines", ".", "hasNext", "(", ")", ")", "{", "String", "line", "=", "lines", ".", "next", "(", ")", ";", "if", "(", "line", ".", "equalsIgnoreCase", "(", "PIPELINING_EXTENSION", ")", ")", "{", "session", ".", "addSupportedExtensions", "(", "PIPELINING_EXTENSION", ")", ";", "}", "else", "if", "(", "line", ".", "equalsIgnoreCase", "(", "STARTTLS_EXTENSION", ")", ")", "{", "session", ".", "addSupportedExtensions", "(", "STARTTLS_EXTENSION", ")", ";", "}", "}", "}" ]
Return all supported extensions which are included in the {@link SMTPResponse} @param response @return extensions
[ "Return", "all", "supported", "extensions", "which", "are", "included", "in", "the", "{", "@link", "SMTPResponse", "}" ]
train
https://github.com/normanmaurer/niosmtp/blob/817e775610fc74de3ea5a909d4b98d717d8aa4d4/src/main/java/me/normanmaurer/niosmtp/delivery/chain/EhloResponseListener.java#L153-L163
rhuss/jolokia
agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java
ObjectToJsonConverter.convertToJson
public Object convertToJson(Object pValue, List<String> pPathParts, JsonConvertOptions pOptions) throws AttributeNotFoundException { Stack<String> extraStack = pPathParts != null ? EscapeUtil.reversePath(pPathParts) : new Stack<String>(); return extractObjectWithContext(pValue, extraStack, pOptions, true); }
java
public Object convertToJson(Object pValue, List<String> pPathParts, JsonConvertOptions pOptions) throws AttributeNotFoundException { Stack<String> extraStack = pPathParts != null ? EscapeUtil.reversePath(pPathParts) : new Stack<String>(); return extractObjectWithContext(pValue, extraStack, pOptions, true); }
[ "public", "Object", "convertToJson", "(", "Object", "pValue", ",", "List", "<", "String", ">", "pPathParts", ",", "JsonConvertOptions", "pOptions", ")", "throws", "AttributeNotFoundException", "{", "Stack", "<", "String", ">", "extraStack", "=", "pPathParts", "!=", "null", "?", "EscapeUtil", ".", "reversePath", "(", "pPathParts", ")", ":", "new", "Stack", "<", "String", ">", "(", ")", ";", "return", "extractObjectWithContext", "(", "pValue", ",", "extraStack", ",", "pOptions", ",", "true", ")", ";", "}" ]
Convert the return value to a JSON object. @param pValue the value to convert @param pPathParts path parts to use for extraction @param pOptions options used for parsing @return the converter object. This either a subclass of {@link org.json.simple.JSONAware} or a basic data type like String or Long. @throws AttributeNotFoundException if within an path an attribute could not be found
[ "Convert", "the", "return", "value", "to", "a", "JSON", "object", "." ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java#L108-L112
Netflix/Hystrix
hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/MethodProvider.java
MethodProvider.unbride
public Method unbride(final Method bridgeMethod, Class<?> aClass) throws IOException, NoSuchMethodException, ClassNotFoundException { if (bridgeMethod.isBridge() && bridgeMethod.isSynthetic()) { if (cache.containsKey(bridgeMethod)) { return cache.get(bridgeMethod); } ClassReader classReader = new ClassReader(aClass.getName()); final MethodSignature methodSignature = new MethodSignature(); classReader.accept(new ClassVisitor(ASM5) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { boolean bridge = (access & ACC_BRIDGE) != 0 && (access & ACC_SYNTHETIC) != 0; if (bridge && bridgeMethod.getName().equals(name) && getParameterCount(desc) == bridgeMethod.getParameterTypes().length) { return new MethodFinder(methodSignature); } return super.visitMethod(access, name, desc, signature, exceptions); } }, 0); Method method = aClass.getDeclaredMethod(methodSignature.name, methodSignature.getParameterTypes()); cache.put(bridgeMethod, method); return method; } else { return bridgeMethod; } }
java
public Method unbride(final Method bridgeMethod, Class<?> aClass) throws IOException, NoSuchMethodException, ClassNotFoundException { if (bridgeMethod.isBridge() && bridgeMethod.isSynthetic()) { if (cache.containsKey(bridgeMethod)) { return cache.get(bridgeMethod); } ClassReader classReader = new ClassReader(aClass.getName()); final MethodSignature methodSignature = new MethodSignature(); classReader.accept(new ClassVisitor(ASM5) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { boolean bridge = (access & ACC_BRIDGE) != 0 && (access & ACC_SYNTHETIC) != 0; if (bridge && bridgeMethod.getName().equals(name) && getParameterCount(desc) == bridgeMethod.getParameterTypes().length) { return new MethodFinder(methodSignature); } return super.visitMethod(access, name, desc, signature, exceptions); } }, 0); Method method = aClass.getDeclaredMethod(methodSignature.name, methodSignature.getParameterTypes()); cache.put(bridgeMethod, method); return method; } else { return bridgeMethod; } }
[ "public", "Method", "unbride", "(", "final", "Method", "bridgeMethod", ",", "Class", "<", "?", ">", "aClass", ")", "throws", "IOException", ",", "NoSuchMethodException", ",", "ClassNotFoundException", "{", "if", "(", "bridgeMethod", ".", "isBridge", "(", ")", "&&", "bridgeMethod", ".", "isSynthetic", "(", ")", ")", "{", "if", "(", "cache", ".", "containsKey", "(", "bridgeMethod", ")", ")", "{", "return", "cache", ".", "get", "(", "bridgeMethod", ")", ";", "}", "ClassReader", "classReader", "=", "new", "ClassReader", "(", "aClass", ".", "getName", "(", ")", ")", ";", "final", "MethodSignature", "methodSignature", "=", "new", "MethodSignature", "(", ")", ";", "classReader", ".", "accept", "(", "new", "ClassVisitor", "(", "ASM5", ")", "{", "@", "Override", "public", "MethodVisitor", "visitMethod", "(", "int", "access", ",", "String", "name", ",", "String", "desc", ",", "String", "signature", ",", "String", "[", "]", "exceptions", ")", "{", "boolean", "bridge", "=", "(", "access", "&", "ACC_BRIDGE", ")", "!=", "0", "&&", "(", "access", "&", "ACC_SYNTHETIC", ")", "!=", "0", ";", "if", "(", "bridge", "&&", "bridgeMethod", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", "&&", "getParameterCount", "(", "desc", ")", "==", "bridgeMethod", ".", "getParameterTypes", "(", ")", ".", "length", ")", "{", "return", "new", "MethodFinder", "(", "methodSignature", ")", ";", "}", "return", "super", ".", "visitMethod", "(", "access", ",", "name", ",", "desc", ",", "signature", ",", "exceptions", ")", ";", "}", "}", ",", "0", ")", ";", "Method", "method", "=", "aClass", ".", "getDeclaredMethod", "(", "methodSignature", ".", "name", ",", "methodSignature", ".", "getParameterTypes", "(", ")", ")", ";", "cache", ".", "put", "(", "bridgeMethod", ",", "method", ")", ";", "return", "method", ";", "}", "else", "{", "return", "bridgeMethod", ";", "}", "}" ]
Finds generic method for the given bridge method. @param bridgeMethod the bridge method @param aClass the type where the bridge method is declared @return generic method @throws IOException @throws NoSuchMethodException @throws ClassNotFoundException
[ "Finds", "generic", "method", "for", "the", "given", "bridge", "method", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/utils/MethodProvider.java#L232-L257
looly/hutool
hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
MapUtil.newHashMap
public static <K, V> HashMap<K, V> newHashMap(int size) { return newHashMap(size, false); }
java
public static <K, V> HashMap<K, V> newHashMap(int size) { return newHashMap(size, false); }
[ "public", "static", "<", "K", ",", "V", ">", "HashMap", "<", "K", ",", "V", ">", "newHashMap", "(", "int", "size", ")", "{", "return", "newHashMap", "(", "size", ",", "false", ")", ";", "}" ]
新建一个HashMap @param <K> Key类型 @param <V> Value类型 @param size 初始大小,由于默认负载因子0.75,传入的size会实际初始大小为size / 0.75 @return HashMap对象
[ "新建一个HashMap" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L94-L96
OpenTSDB/opentsdb
src/utils/PluginLoader.java
PluginLoader.searchForJars
private static void searchForJars(final File file, List<File> jars) { if (file.isFile()) { if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) { jars.add(file); LOG.debug("Found a jar: " + file.getAbsolutePath()); } } else if (file.isDirectory()) { File[] files = file.listFiles(); if (files == null) { // if this is null, it's due to a security issue LOG.warn("Access denied to directory: " + file.getAbsolutePath()); } else { for (File f : files) { searchForJars(f, jars); } } } }
java
private static void searchForJars(final File file, List<File> jars) { if (file.isFile()) { if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) { jars.add(file); LOG.debug("Found a jar: " + file.getAbsolutePath()); } } else if (file.isDirectory()) { File[] files = file.listFiles(); if (files == null) { // if this is null, it's due to a security issue LOG.warn("Access denied to directory: " + file.getAbsolutePath()); } else { for (File f : files) { searchForJars(f, jars); } } } }
[ "private", "static", "void", "searchForJars", "(", "final", "File", "file", ",", "List", "<", "File", ">", "jars", ")", "{", "if", "(", "file", ".", "isFile", "(", ")", ")", "{", "if", "(", "file", ".", "getAbsolutePath", "(", ")", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".jar\"", ")", ")", "{", "jars", ".", "add", "(", "file", ")", ";", "LOG", ".", "debug", "(", "\"Found a jar: \"", "+", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "}", "else", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "File", "[", "]", "files", "=", "file", ".", "listFiles", "(", ")", ";", "if", "(", "files", "==", "null", ")", "{", "// if this is null, it's due to a security issue", "LOG", ".", "warn", "(", "\"Access denied to directory: \"", "+", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "else", "{", "for", "(", "File", "f", ":", "files", ")", "{", "searchForJars", "(", "f", ",", "jars", ")", ";", "}", "}", "}", "}" ]
Recursive method to search for JAR files starting at a given level @param file The directory to search in @param jars A list of file objects that will be loaded with discovered jar files @throws SecurityException if a security manager exists and prevents reading
[ "Recursive", "method", "to", "search", "for", "JAR", "files", "starting", "at", "a", "given", "level" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/utils/PluginLoader.java#L227-L244
gs2io/gs2-java-sdk-core
src/main/java/io/gs2/AbstractGs2Client.java
AbstractGs2Client.createHttpGet
protected HttpGet createHttpGet(String url, IGs2Credential credential, String service, String module, String function) { Long timestamp = System.currentTimeMillis()/1000; url = StringUtils.replace(url, "{service}", service); url = StringUtils.replace(url, "{region}", region.getName()); HttpGet get = new HttpGet(url); get.setHeader("Content-Type", "application/json"); credential.authorized(get, service, module, function, timestamp); return get; }
java
protected HttpGet createHttpGet(String url, IGs2Credential credential, String service, String module, String function) { Long timestamp = System.currentTimeMillis()/1000; url = StringUtils.replace(url, "{service}", service); url = StringUtils.replace(url, "{region}", region.getName()); HttpGet get = new HttpGet(url); get.setHeader("Content-Type", "application/json"); credential.authorized(get, service, module, function, timestamp); return get; }
[ "protected", "HttpGet", "createHttpGet", "(", "String", "url", ",", "IGs2Credential", "credential", ",", "String", "service", ",", "String", "module", ",", "String", "function", ")", "{", "Long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "1000", ";", "url", "=", "StringUtils", ".", "replace", "(", "url", ",", "\"{service}\"", ",", "service", ")", ";", "url", "=", "StringUtils", ".", "replace", "(", "url", ",", "\"{region}\"", ",", "region", ".", "getName", "(", ")", ")", ";", "HttpGet", "get", "=", "new", "HttpGet", "(", "url", ")", ";", "get", ".", "setHeader", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", ";", "credential", ".", "authorized", "(", "get", ",", "service", ",", "module", ",", "function", ",", "timestamp", ")", ";", "return", "get", ";", "}" ]
GETリクエストを生成 @param url アクセス先URL @param credential 認証情報 @param service アクセス先サービス @param module アクセス先モジュール @param function アクセス先ファンクション @return リクエストオブジェクト
[ "GETリクエストを生成" ]
train
https://github.com/gs2io/gs2-java-sdk-core/blob/fe66ee4e374664b101b07c41221a3b32c844127d/src/main/java/io/gs2/AbstractGs2Client.java#L158-L166
alkacon/opencms-core
src/org/opencms/importexport/CmsImportVersion7.java
CmsImportVersion7.addAccountsUserRules
protected void addAccountsUserRules(Digester digester, String xpath) { String xp_user = xpath + N_USERS + "/" + N_USER + "/"; digester.addCallMethod(xp_user + N_NAME, "setUserName", 0); digester.addCallMethod(xp_user + N_PASSWORD, "setUserPassword", 0); digester.addCallMethod(xp_user + N_FIRSTNAME, "setUserFirstname", 0); digester.addCallMethod(xp_user + N_LASTNAME, "setUserLastname", 0); digester.addCallMethod(xp_user + N_EMAIL, "setUserEmail", 0); digester.addCallMethod(xp_user + N_FLAGS, "setUserFlags", 0); digester.addCallMethod(xp_user + N_DATECREATED, "setUserDateCreated", 0); digester.addCallMethod(xp_user + N_USERINFO, "importUser"); String xp_info = xp_user + N_USERINFO + "/" + N_USERINFO_ENTRY; digester.addCallMethod(xp_info, "importUserInfo", 3); digester.addCallParam(xp_info, 0, A_NAME); digester.addCallParam(xp_info, 1, A_TYPE); digester.addCallParam(xp_info, 2); digester.addCallMethod(xp_user + N_USERROLES + "/" + N_USERROLE, "importUserRole", 0); digester.addCallMethod(xp_user + N_USERGROUPS + "/" + N_USERGROUP, "importUserGroup", 0); }
java
protected void addAccountsUserRules(Digester digester, String xpath) { String xp_user = xpath + N_USERS + "/" + N_USER + "/"; digester.addCallMethod(xp_user + N_NAME, "setUserName", 0); digester.addCallMethod(xp_user + N_PASSWORD, "setUserPassword", 0); digester.addCallMethod(xp_user + N_FIRSTNAME, "setUserFirstname", 0); digester.addCallMethod(xp_user + N_LASTNAME, "setUserLastname", 0); digester.addCallMethod(xp_user + N_EMAIL, "setUserEmail", 0); digester.addCallMethod(xp_user + N_FLAGS, "setUserFlags", 0); digester.addCallMethod(xp_user + N_DATECREATED, "setUserDateCreated", 0); digester.addCallMethod(xp_user + N_USERINFO, "importUser"); String xp_info = xp_user + N_USERINFO + "/" + N_USERINFO_ENTRY; digester.addCallMethod(xp_info, "importUserInfo", 3); digester.addCallParam(xp_info, 0, A_NAME); digester.addCallParam(xp_info, 1, A_TYPE); digester.addCallParam(xp_info, 2); digester.addCallMethod(xp_user + N_USERROLES + "/" + N_USERROLE, "importUserRole", 0); digester.addCallMethod(xp_user + N_USERGROUPS + "/" + N_USERGROUP, "importUserGroup", 0); }
[ "protected", "void", "addAccountsUserRules", "(", "Digester", "digester", ",", "String", "xpath", ")", "{", "String", "xp_user", "=", "xpath", "+", "N_USERS", "+", "\"/\"", "+", "N_USER", "+", "\"/\"", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_NAME", ",", "\"setUserName\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_PASSWORD", ",", "\"setUserPassword\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_FIRSTNAME", ",", "\"setUserFirstname\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_LASTNAME", ",", "\"setUserLastname\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_EMAIL", ",", "\"setUserEmail\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_FLAGS", ",", "\"setUserFlags\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_DATECREATED", ",", "\"setUserDateCreated\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_USERINFO", ",", "\"importUser\"", ")", ";", "String", "xp_info", "=", "xp_user", "+", "N_USERINFO", "+", "\"/\"", "+", "N_USERINFO_ENTRY", ";", "digester", ".", "addCallMethod", "(", "xp_info", ",", "\"importUserInfo\"", ",", "3", ")", ";", "digester", ".", "addCallParam", "(", "xp_info", ",", "0", ",", "A_NAME", ")", ";", "digester", ".", "addCallParam", "(", "xp_info", ",", "1", ",", "A_TYPE", ")", ";", "digester", ".", "addCallParam", "(", "xp_info", ",", "2", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_USERROLES", "+", "\"/\"", "+", "N_USERROLE", ",", "\"importUserRole\"", ",", "0", ")", ";", "digester", ".", "addCallMethod", "(", "xp_user", "+", "N_USERGROUPS", "+", "\"/\"", "+", "N_USERGROUP", ",", "\"importUserGroup\"", ",", "0", ")", ";", "}" ]
Adds the XML digester rules for users.<p> @param digester the digester to add the rules to @param xpath the base xpath for the rules
[ "Adds", "the", "XML", "digester", "rules", "for", "users", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportVersion7.java#L3008-L3028
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnBatchNormalizationForwardInference
public static int cudnnBatchNormalizationForwardInference( cudnnHandle handle, int mode, Pointer alpha, /** alpha[0] = result blend factor */ Pointer beta, /** beta[0] = dest layer blend factor */ cudnnTensorDescriptor xDesc, Pointer x, /** NxCxHxW */ cudnnTensorDescriptor yDesc, Pointer y, /** NxCxHxW */ cudnnTensorDescriptor bnScaleBiasMeanVarDesc, Pointer bnScale, Pointer bnBias, Pointer estimatedMean, Pointer estimatedVariance, double epsilon) { return checkResult(cudnnBatchNormalizationForwardInferenceNative(handle, mode, alpha, beta, xDesc, x, yDesc, y, bnScaleBiasMeanVarDesc, bnScale, bnBias, estimatedMean, estimatedVariance, epsilon)); }
java
public static int cudnnBatchNormalizationForwardInference( cudnnHandle handle, int mode, Pointer alpha, /** alpha[0] = result blend factor */ Pointer beta, /** beta[0] = dest layer blend factor */ cudnnTensorDescriptor xDesc, Pointer x, /** NxCxHxW */ cudnnTensorDescriptor yDesc, Pointer y, /** NxCxHxW */ cudnnTensorDescriptor bnScaleBiasMeanVarDesc, Pointer bnScale, Pointer bnBias, Pointer estimatedMean, Pointer estimatedVariance, double epsilon) { return checkResult(cudnnBatchNormalizationForwardInferenceNative(handle, mode, alpha, beta, xDesc, x, yDesc, y, bnScaleBiasMeanVarDesc, bnScale, bnBias, estimatedMean, estimatedVariance, epsilon)); }
[ "public", "static", "int", "cudnnBatchNormalizationForwardInference", "(", "cudnnHandle", "handle", ",", "int", "mode", ",", "Pointer", "alpha", ",", "/** alpha[0] = result blend factor */", "Pointer", "beta", ",", "/** beta[0] = dest layer blend factor */", "cudnnTensorDescriptor", "xDesc", ",", "Pointer", "x", ",", "/** NxCxHxW */", "cudnnTensorDescriptor", "yDesc", ",", "Pointer", "y", ",", "/** NxCxHxW */", "cudnnTensorDescriptor", "bnScaleBiasMeanVarDesc", ",", "Pointer", "bnScale", ",", "Pointer", "bnBias", ",", "Pointer", "estimatedMean", ",", "Pointer", "estimatedVariance", ",", "double", "epsilon", ")", "{", "return", "checkResult", "(", "cudnnBatchNormalizationForwardInferenceNative", "(", "handle", ",", "mode", ",", "alpha", ",", "beta", ",", "xDesc", ",", "x", ",", "yDesc", ",", "y", ",", "bnScaleBiasMeanVarDesc", ",", "bnScale", ",", "bnBias", ",", "estimatedMean", ",", "estimatedVariance", ",", "epsilon", ")", ")", ";", "}" ]
<pre> Performs Batch Normalization during Inference: y[i] = bnScale[k]*(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + bnBias[k] with bnScale, bnBias, runningMean, runningInvVariance tensors indexed according to spatial or per-activation mode. Refer to cudnnBatchNormalizationForwardTraining above for notes on function arguments. </pre>
[ "<pre", ">", "Performs", "Batch", "Normalization", "during", "Inference", ":", "y", "[", "i", "]", "=", "bnScale", "[", "k", "]", "*", "(", "x", "[", "i", "]", "-", "estimatedMean", "[", "k", "]", ")", "/", "sqrt", "(", "epsilon", "+", "estimatedVariance", "[", "k", "]", ")", "+", "bnBias", "[", "k", "]", "with", "bnScale", "bnBias", "runningMean", "runningInvVariance", "tensors", "indexed", "according", "to", "spatial", "or", "per", "-", "activation", "mode", ".", "Refer", "to", "cudnnBatchNormalizationForwardTraining", "above", "for", "notes", "on", "function", "arguments", ".", "<", "/", "pre", ">" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2450-L2467
Bedework/bw-util
bw-util-xml/src/main/java/org/bedework/util/xml/XmlUtil.java
XmlUtil.getOneNodeVal
public static String getOneNodeVal(final Node el, final String name) throws SAXException { /* We expect one child of type text */ if (!el.hasChildNodes()) { return null; } NodeList children = el.getChildNodes(); if (children.getLength() > 1){ throw new SAXException("Multiple property values: " + name); } Node child = children.item(0); return child.getNodeValue(); }
java
public static String getOneNodeVal(final Node el, final String name) throws SAXException { /* We expect one child of type text */ if (!el.hasChildNodes()) { return null; } NodeList children = el.getChildNodes(); if (children.getLength() > 1){ throw new SAXException("Multiple property values: " + name); } Node child = children.item(0); return child.getNodeValue(); }
[ "public", "static", "String", "getOneNodeVal", "(", "final", "Node", "el", ",", "final", "String", "name", ")", "throws", "SAXException", "{", "/* We expect one child of type text */", "if", "(", "!", "el", ".", "hasChildNodes", "(", ")", ")", "{", "return", "null", ";", "}", "NodeList", "children", "=", "el", ".", "getChildNodes", "(", ")", ";", "if", "(", "children", ".", "getLength", "(", ")", ">", "1", ")", "{", "throw", "new", "SAXException", "(", "\"Multiple property values: \"", "+", "name", ")", ";", "}", "Node", "child", "=", "children", ".", "item", "(", "0", ")", ";", "return", "child", ".", "getNodeValue", "(", ")", ";", "}" ]
Get the value of an element. We expect 0 or 1 child nodes. For no child node we return null, for more than one we raise an exception. @param el Node whose value we want @param name String name to make exception messages more readable @return String node value or null @throws SAXException
[ "Get", "the", "value", "of", "an", "element", ".", "We", "expect", "0", "or", "1", "child", "nodes", ".", "For", "no", "child", "node", "we", "return", "null", "for", "more", "than", "one", "we", "raise", "an", "exception", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-xml/src/main/java/org/bedework/util/xml/XmlUtil.java#L152-L167
Ordinastie/MalisisCore
src/main/java/net/malisis/core/renderer/icon/Icon.java
Icon.from
public static Icon from(Item item, int metadata) { Pair<Item, Integer> p = Pair.of(item, metadata); if (vanillaIcons.get(p) != null) return vanillaIcons.get(p); VanillaIcon icon = new VanillaIcon(item, metadata); vanillaIcons.put(p, icon); return icon; }
java
public static Icon from(Item item, int metadata) { Pair<Item, Integer> p = Pair.of(item, metadata); if (vanillaIcons.get(p) != null) return vanillaIcons.get(p); VanillaIcon icon = new VanillaIcon(item, metadata); vanillaIcons.put(p, icon); return icon; }
[ "public", "static", "Icon", "from", "(", "Item", "item", ",", "int", "metadata", ")", "{", "Pair", "<", "Item", ",", "Integer", ">", "p", "=", "Pair", ".", "of", "(", "item", ",", "metadata", ")", ";", "if", "(", "vanillaIcons", ".", "get", "(", "p", ")", "!=", "null", ")", "return", "vanillaIcons", ".", "get", "(", "p", ")", ";", "VanillaIcon", "icon", "=", "new", "VanillaIcon", "(", "item", ",", "metadata", ")", ";", "vanillaIcons", ".", "put", "(", "p", ",", "icon", ")", ";", "return", "icon", ";", "}" ]
Gets a {@link Icon} for the texture used for the {@link Item} @param item the item @return the malisis icon
[ "Gets", "a", "{", "@link", "Icon", "}", "for", "the", "texture", "used", "for", "the", "{", "@link", "Item", "}" ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/icon/Icon.java#L512-L521
google/error-prone
check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java
FindIdentifiers.findIdent
@Nullable public static Symbol findIdent(String name, VisitorState state, KindSelector kind) { ClassType enclosingClass = ASTHelpers.getType(state.findEnclosing(ClassTree.class)); if (enclosingClass == null || enclosingClass.tsym == null) { return null; } Env<AttrContext> env = Enter.instance(state.context).getClassEnv(enclosingClass.tsym); MethodTree enclosingMethod = state.findEnclosing(MethodTree.class); if (enclosingMethod != null) { env = MemberEnter.instance(state.context).getMethodEnv((JCMethodDecl) enclosingMethod, env); } try { Method method = Resolve.class.getDeclaredMethod("findIdent", Env.class, Name.class, KindSelector.class); method.setAccessible(true); Symbol result = (Symbol) method.invoke(Resolve.instance(state.context), env, state.getName(name), kind); return result.exists() ? result : null; } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } }
java
@Nullable public static Symbol findIdent(String name, VisitorState state, KindSelector kind) { ClassType enclosingClass = ASTHelpers.getType(state.findEnclosing(ClassTree.class)); if (enclosingClass == null || enclosingClass.tsym == null) { return null; } Env<AttrContext> env = Enter.instance(state.context).getClassEnv(enclosingClass.tsym); MethodTree enclosingMethod = state.findEnclosing(MethodTree.class); if (enclosingMethod != null) { env = MemberEnter.instance(state.context).getMethodEnv((JCMethodDecl) enclosingMethod, env); } try { Method method = Resolve.class.getDeclaredMethod("findIdent", Env.class, Name.class, KindSelector.class); method.setAccessible(true); Symbol result = (Symbol) method.invoke(Resolve.instance(state.context), env, state.getName(name), kind); return result.exists() ? result : null; } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } }
[ "@", "Nullable", "public", "static", "Symbol", "findIdent", "(", "String", "name", ",", "VisitorState", "state", ",", "KindSelector", "kind", ")", "{", "ClassType", "enclosingClass", "=", "ASTHelpers", ".", "getType", "(", "state", ".", "findEnclosing", "(", "ClassTree", ".", "class", ")", ")", ";", "if", "(", "enclosingClass", "==", "null", "||", "enclosingClass", ".", "tsym", "==", "null", ")", "{", "return", "null", ";", "}", "Env", "<", "AttrContext", ">", "env", "=", "Enter", ".", "instance", "(", "state", ".", "context", ")", ".", "getClassEnv", "(", "enclosingClass", ".", "tsym", ")", ";", "MethodTree", "enclosingMethod", "=", "state", ".", "findEnclosing", "(", "MethodTree", ".", "class", ")", ";", "if", "(", "enclosingMethod", "!=", "null", ")", "{", "env", "=", "MemberEnter", ".", "instance", "(", "state", ".", "context", ")", ".", "getMethodEnv", "(", "(", "JCMethodDecl", ")", "enclosingMethod", ",", "env", ")", ";", "}", "try", "{", "Method", "method", "=", "Resolve", ".", "class", ".", "getDeclaredMethod", "(", "\"findIdent\"", ",", "Env", ".", "class", ",", "Name", ".", "class", ",", "KindSelector", ".", "class", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "Symbol", "result", "=", "(", "Symbol", ")", "method", ".", "invoke", "(", "Resolve", ".", "instance", "(", "state", ".", "context", ")", ",", "env", ",", "state", ".", "getName", "(", "name", ")", ",", "kind", ")", ";", "return", "result", ".", "exists", "(", ")", "?", "result", ":", "null", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "new", "LinkageError", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Finds a declaration with the given name and type that is in scope at the current location.
[ "Finds", "a", "declaration", "with", "the", "given", "name", "and", "type", "that", "is", "in", "scope", "at", "the", "current", "location", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java#L85-L106
apache/incubator-druid
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorManager.java
SupervisorManager.possiblySuspendOrResumeSupervisorInternal
private boolean possiblySuspendOrResumeSupervisorInternal(String id, boolean suspend) { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair == null || pair.rhs.isSuspended() == suspend) { return false; } SupervisorSpec nextState = suspend ? pair.rhs.createSuspendedSpec() : pair.rhs.createRunningSpec(); possiblyStopAndRemoveSupervisorInternal(nextState.getId(), false); return createAndStartSupervisorInternal(nextState, true); }
java
private boolean possiblySuspendOrResumeSupervisorInternal(String id, boolean suspend) { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair == null || pair.rhs.isSuspended() == suspend) { return false; } SupervisorSpec nextState = suspend ? pair.rhs.createSuspendedSpec() : pair.rhs.createRunningSpec(); possiblyStopAndRemoveSupervisorInternal(nextState.getId(), false); return createAndStartSupervisorInternal(nextState, true); }
[ "private", "boolean", "possiblySuspendOrResumeSupervisorInternal", "(", "String", "id", ",", "boolean", "suspend", ")", "{", "Pair", "<", "Supervisor", ",", "SupervisorSpec", ">", "pair", "=", "supervisors", ".", "get", "(", "id", ")", ";", "if", "(", "pair", "==", "null", "||", "pair", ".", "rhs", ".", "isSuspended", "(", ")", "==", "suspend", ")", "{", "return", "false", ";", "}", "SupervisorSpec", "nextState", "=", "suspend", "?", "pair", ".", "rhs", ".", "createSuspendedSpec", "(", ")", ":", "pair", ".", "rhs", ".", "createRunningSpec", "(", ")", ";", "possiblyStopAndRemoveSupervisorInternal", "(", "nextState", ".", "getId", "(", ")", ",", "false", ")", ";", "return", "createAndStartSupervisorInternal", "(", "nextState", ",", "true", ")", ";", "}" ]
Suspend or resume a supervisor with a given id. <p/> Caller should have acquired [lock] before invoking this method to avoid contention with other threads that may be starting, stopping, suspending and resuming supervisors. @return true if a supervisor was suspended or resumed, false if there was no supervisor with this id or suspend a suspended supervisor or resume a running supervisor
[ "Suspend", "or", "resume", "a", "supervisor", "with", "a", "given", "id", ".", "<p", "/", ">", "Caller", "should", "have", "acquired", "[", "lock", "]", "before", "invoking", "this", "method", "to", "avoid", "contention", "with", "other", "threads", "that", "may", "be", "starting", "stopping", "suspending", "and", "resuming", "supervisors", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorManager.java#L263-L273
rodionmoiseev/c10n
core/src/main/java/com/github/rodionmoiseev/c10n/share/utils/ReflectionUtils.java
ReflectionUtils.getC10NKey
public static String getC10NKey(String keyPrefix, Method method) { String key = getKeyAnnotationBasedKey(method); if (null == key) { //fallback to default key based on class FQDN and method name key = ReflectionUtils.getDefaultKey(method); } if (keyPrefix.length() > 0) { key = keyPrefix + "." + key; } return key; }
java
public static String getC10NKey(String keyPrefix, Method method) { String key = getKeyAnnotationBasedKey(method); if (null == key) { //fallback to default key based on class FQDN and method name key = ReflectionUtils.getDefaultKey(method); } if (keyPrefix.length() > 0) { key = keyPrefix + "." + key; } return key; }
[ "public", "static", "String", "getC10NKey", "(", "String", "keyPrefix", ",", "Method", "method", ")", "{", "String", "key", "=", "getKeyAnnotationBasedKey", "(", "method", ")", ";", "if", "(", "null", "==", "key", ")", "{", "//fallback to default key based on class FQDN and method name", "key", "=", "ReflectionUtils", ".", "getDefaultKey", "(", "method", ")", ";", "}", "if", "(", "keyPrefix", ".", "length", "(", ")", ">", "0", ")", "{", "key", "=", "keyPrefix", "+", "\".\"", "+", "key", ";", "}", "return", "key", ";", "}" ]
<p>Work out method's bundle key. <h2>Bundle key resolution</h2> <p>Bundle key is generated as follows: <ul> <li>If there are no {@link com.github.rodionmoiseev.c10n.C10NKey} annotations, key is the <code>Class FQDN '.' Method Name</code>. If method has arguments, method name is post-fixed with argument types delimited with '_', e.g. <code>myMethod_String_int</code></li> <li>If declaring interface or any of the super-interfaces contain {@link com.github.rodionmoiseev.c10n.C10NKey} annotation <code>C</code> then <ul> <li>For methods without {@link com.github.rodionmoiseev.c10n.C10NKey} annotation, key becomes <code>C '.' Method Name</code></li> <li>For methods with {@link com.github.rodionmoiseev.c10n.C10NKey} annotation <code>M</code>, key is <code>C '.' M</code></li> <li>For methods with {@link com.github.rodionmoiseev.c10n.C10NKey} annotation <code>M</code>, value for which starts with a '.', the key is just <code>M</code> (i.e. key is assumed to be absolute)</li> </ul> </li> <li>If no declaring interfaces have {@link com.github.rodionmoiseev.c10n.C10NKey} annotation, but a method contains annotation <code>M</code>, then key is just <code>M</code>.</li> <li>Lastly, if global key prefix is specified, it is always prepended to the final key, delimited by '.'</li> </ul> <h2>Looking for c10n key in parent interfaces</h2> <p>The lookup of c10n key in parent interfaces is done breadth-first, starting from the declaring class. That is, if the declaring class does not have c10n key, all interfaces it extends are checked in declaration order first. If no key is found, this check is repeated for each of the super interfaces in the same order. @param keyPrefix global key prefix @param method method to extract the key from @return method c10n bundle key (not null)
[ "<p", ">", "Work", "out", "method", "s", "bundle", "key", "." ]
train
https://github.com/rodionmoiseev/c10n/blob/8f3ce95395b1775b536294ed34b1b5c1e4540b03/core/src/main/java/com/github/rodionmoiseev/c10n/share/utils/ReflectionUtils.java#L65-L75
alkacon/opencms-core
src/org/opencms/jsp/util/CmsJspStatusBean.java
CmsJspStatusBean.getPageContent
public String getPageContent(String element) { // Determine the folder to read the contents from String contentFolder = property(CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, "search", ""); if (CmsStringUtil.isEmpty(contentFolder)) { contentFolder = VFS_FOLDER_HANDLER + "contents/"; } // determine the file to read the contents from String fileName = "content" + getStatusCodeMessage() + ".html"; if (!getCmsObject().existsResource(contentFolder + fileName)) { // special file does not exist, use generic one fileName = "content" + UNKKNOWN_STATUS_CODE + ".html"; } // get the content return getContent(contentFolder + fileName, element, getLocale()); }
java
public String getPageContent(String element) { // Determine the folder to read the contents from String contentFolder = property(CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, "search", ""); if (CmsStringUtil.isEmpty(contentFolder)) { contentFolder = VFS_FOLDER_HANDLER + "contents/"; } // determine the file to read the contents from String fileName = "content" + getStatusCodeMessage() + ".html"; if (!getCmsObject().existsResource(contentFolder + fileName)) { // special file does not exist, use generic one fileName = "content" + UNKKNOWN_STATUS_CODE + ".html"; } // get the content return getContent(contentFolder + fileName, element, getLocale()); }
[ "public", "String", "getPageContent", "(", "String", "element", ")", "{", "// Determine the folder to read the contents from", "String", "contentFolder", "=", "property", "(", "CmsPropertyDefinition", ".", "PROPERTY_TEMPLATE_ELEMENTS", ",", "\"search\"", ",", "\"\"", ")", ";", "if", "(", "CmsStringUtil", ".", "isEmpty", "(", "contentFolder", ")", ")", "{", "contentFolder", "=", "VFS_FOLDER_HANDLER", "+", "\"contents/\"", ";", "}", "// determine the file to read the contents from", "String", "fileName", "=", "\"content\"", "+", "getStatusCodeMessage", "(", ")", "+", "\".html\"", ";", "if", "(", "!", "getCmsObject", "(", ")", ".", "existsResource", "(", "contentFolder", "+", "fileName", ")", ")", "{", "// special file does not exist, use generic one", "fileName", "=", "\"content\"", "+", "UNKKNOWN_STATUS_CODE", "+", "\".html\"", ";", "}", "// get the content", "return", "getContent", "(", "contentFolder", "+", "fileName", ",", "element", ",", "getLocale", "(", ")", ")", ";", "}" ]
Returns the processed output of the specified element of an OpenCms page.<p> The page to get the content from is looked up in the property value "template-elements". If no value is found, the page is read from the "contents/" subfolder of the handler folder.<p> For each status code, an individual page can be created by naming it "content${STATUSCODE}.html". If the individual page can not be found, the content is read from "contentunknown.html".<p> @param element name of the element @return the processed output of the specified element of an OpenCms page
[ "Returns", "the", "processed", "output", "of", "the", "specified", "element", "of", "an", "OpenCms", "page", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspStatusBean.java#L256-L273
dickschoeller/gedbrowser
gedbrowser-writer/src/main/java/org/schoellerfamily/gedbrowser/writer/users/UsersWriter.java
UsersWriter.appendRoles
private void appendRoles(final StringBuilder builder, final User user) { for (final UserRoleName role : user.getRoles()) { append(builder, ",", role.name()); } }
java
private void appendRoles(final StringBuilder builder, final User user) { for (final UserRoleName role : user.getRoles()) { append(builder, ",", role.name()); } }
[ "private", "void", "appendRoles", "(", "final", "StringBuilder", "builder", ",", "final", "User", "user", ")", "{", "for", "(", "final", "UserRoleName", "role", ":", "user", ".", "getRoles", "(", ")", ")", "{", "append", "(", "builder", ",", "\",\"", ",", "role", ".", "name", "(", ")", ")", ";", "}", "}" ]
Append roles to the builder. @param builder the builder @param user the user whose roles are appended
[ "Append", "roles", "to", "the", "builder", "." ]
train
https://github.com/dickschoeller/gedbrowser/blob/e3e10b1ff3a34ebde9b7edcbfafcd5fe6fb3b3e1/gedbrowser-writer/src/main/java/org/schoellerfamily/gedbrowser/writer/users/UsersWriter.java#L122-L126
lonnyj/liquibase-spatial
src/main/java/liquibase/ext/spatial/sqlgenerator/AbstractSpatialInsertGenerator.java
AbstractSpatialInsertGenerator.handleColumnValue
protected Object handleColumnValue(final Object oldValue, final Database database) { final Object newValue = WktConversionUtils.handleColumnValue(oldValue, database, this); return newValue; }
java
protected Object handleColumnValue(final Object oldValue, final Database database) { final Object newValue = WktConversionUtils.handleColumnValue(oldValue, database, this); return newValue; }
[ "protected", "Object", "handleColumnValue", "(", "final", "Object", "oldValue", ",", "final", "Database", "database", ")", "{", "final", "Object", "newValue", "=", "WktConversionUtils", ".", "handleColumnValue", "(", "oldValue", ",", "database", ",", "this", ")", ";", "return", "newValue", ";", "}" ]
If the old value is a geometry or a Well-Known Text, convert it to the appropriate new value. Otherwise, this method returns the old value. @param oldValue the old value. @param database the database instance. @return the new value.
[ "If", "the", "old", "value", "is", "a", "geometry", "or", "a", "Well", "-", "Known", "Text", "convert", "it", "to", "the", "appropriate", "new", "value", ".", "Otherwise", "this", "method", "returns", "the", "old", "value", "." ]
train
https://github.com/lonnyj/liquibase-spatial/blob/36ae41b0d3d08bb00a22c856e51ffeed08891c0e/src/main/java/liquibase/ext/spatial/sqlgenerator/AbstractSpatialInsertGenerator.java#L83-L86
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MemberMap.java
MemberMap.cloneAdding
static MemberMap cloneAdding(MemberMap source, MemberImpl... newMembers) { Map<Address, MemberImpl> addressMap = new LinkedHashMap<>(source.addressToMemberMap); Map<String, MemberImpl> uuidMap = new LinkedHashMap<>(source.uuidToMemberMap); for (MemberImpl member : newMembers) { putMember(addressMap, uuidMap, member); } return new MemberMap(source.version + newMembers.length, addressMap, uuidMap); }
java
static MemberMap cloneAdding(MemberMap source, MemberImpl... newMembers) { Map<Address, MemberImpl> addressMap = new LinkedHashMap<>(source.addressToMemberMap); Map<String, MemberImpl> uuidMap = new LinkedHashMap<>(source.uuidToMemberMap); for (MemberImpl member : newMembers) { putMember(addressMap, uuidMap, member); } return new MemberMap(source.version + newMembers.length, addressMap, uuidMap); }
[ "static", "MemberMap", "cloneAdding", "(", "MemberMap", "source", ",", "MemberImpl", "...", "newMembers", ")", "{", "Map", "<", "Address", ",", "MemberImpl", ">", "addressMap", "=", "new", "LinkedHashMap", "<>", "(", "source", ".", "addressToMemberMap", ")", ";", "Map", "<", "String", ",", "MemberImpl", ">", "uuidMap", "=", "new", "LinkedHashMap", "<>", "(", "source", ".", "uuidToMemberMap", ")", ";", "for", "(", "MemberImpl", "member", ":", "newMembers", ")", "{", "putMember", "(", "addressMap", ",", "uuidMap", ",", "member", ")", ";", "}", "return", "new", "MemberMap", "(", "source", ".", "version", "+", "newMembers", ".", "length", ",", "addressMap", ",", "uuidMap", ")", ";", "}" ]
Creates clone of source {@code MemberMap} additionally including new members. @param source source map @param newMembers new members to add @return clone map
[ "Creates", "clone", "of", "source", "{", "@code", "MemberMap", "}", "additionally", "including", "new", "members", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MemberMap.java#L145-L154
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/basic/service_stats.java
service_stats.get
public static service_stats get(nitro_service service, String name) throws Exception{ service_stats obj = new service_stats(); obj.set_name(name); service_stats response = (service_stats) obj.stat_resource(service); return response; }
java
public static service_stats get(nitro_service service, String name) throws Exception{ service_stats obj = new service_stats(); obj.set_name(name); service_stats response = (service_stats) obj.stat_resource(service); return response; }
[ "public", "static", "service_stats", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "service_stats", "obj", "=", "new", "service_stats", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "service_stats", "response", "=", "(", "service_stats", ")", "obj", ".", "stat_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch statistics of service_stats resource of given name .
[ "Use", "this", "API", "to", "fetch", "statistics", "of", "service_stats", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/basic/service_stats.java#L390-L395
livetribe/livetribe-slp
core/src/main/java/org/livetribe/slp/spi/ServiceInfoCache.java
ServiceInfoCache.addAttributes
public Result<T> addAttributes(ServiceInfo.Key key, Attributes attributes) { T previous = null; T current = null; lock(); try { previous = get(key); // Updating a service that does not exist must fail (RFC 2608, 9.3) if (previous == null) throw new ServiceLocationException("Could not find service to update " + key, SLPError.INVALID_UPDATE); current = (T)previous.addAttributes(attributes); keysToServiceInfos.put(current.getKey(), current); current.setRegistered(true); previous.setRegistered(false); } finally { unlock(); } notifyServiceUpdated(previous, current); return new Result<T>(previous, current); }
java
public Result<T> addAttributes(ServiceInfo.Key key, Attributes attributes) { T previous = null; T current = null; lock(); try { previous = get(key); // Updating a service that does not exist must fail (RFC 2608, 9.3) if (previous == null) throw new ServiceLocationException("Could not find service to update " + key, SLPError.INVALID_UPDATE); current = (T)previous.addAttributes(attributes); keysToServiceInfos.put(current.getKey(), current); current.setRegistered(true); previous.setRegistered(false); } finally { unlock(); } notifyServiceUpdated(previous, current); return new Result<T>(previous, current); }
[ "public", "Result", "<", "T", ">", "addAttributes", "(", "ServiceInfo", ".", "Key", "key", ",", "Attributes", "attributes", ")", "{", "T", "previous", "=", "null", ";", "T", "current", "=", "null", ";", "lock", "(", ")", ";", "try", "{", "previous", "=", "get", "(", "key", ")", ";", "// Updating a service that does not exist must fail (RFC 2608, 9.3)", "if", "(", "previous", "==", "null", ")", "throw", "new", "ServiceLocationException", "(", "\"Could not find service to update \"", "+", "key", ",", "SLPError", ".", "INVALID_UPDATE", ")", ";", "current", "=", "(", "T", ")", "previous", ".", "addAttributes", "(", "attributes", ")", ";", "keysToServiceInfos", ".", "put", "(", "current", ".", "getKey", "(", ")", ",", "current", ")", ";", "current", ".", "setRegistered", "(", "true", ")", ";", "previous", ".", "setRegistered", "(", "false", ")", ";", "}", "finally", "{", "unlock", "(", ")", ";", "}", "notifyServiceUpdated", "(", "previous", ",", "current", ")", ";", "return", "new", "Result", "<", "T", ">", "(", "previous", ",", "current", ")", ";", "}" ]
Updates an existing ServiceInfo identified by the given Key, adding the given attributes. @param key the service's key @param attributes the attributes to add @return a result whose previous is the service prior the update and where current is the current service
[ "Updates", "an", "existing", "ServiceInfo", "identified", "by", "the", "given", "Key", "adding", "the", "given", "attributes", "." ]
train
https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/spi/ServiceInfoCache.java#L185-L210
lshift/jamume
src/main/java/net/lshift/java/dispatch/JavaC3.java
JavaC3.isCandidate
private static <X> Predicate<X> isCandidate(final Iterable<List<X>> remainingInputs) { return new Predicate<X>() { Predicate<List<X>> headIs(final X c) { return new Predicate<List<X>>() { public boolean apply(List<X> input) { return !input.isEmpty() && c.equals(input.get(0)); } }; } Predicate<List<X>> tailContains(final X c) { return new Predicate<List<X>>() { public boolean apply(List<X> input) { return input.indexOf(c) > 0; } }; } public boolean apply(final X c) { return any(remainingInputs, headIs(c)) && all(remainingInputs, not(tailContains(c))); } }; }
java
private static <X> Predicate<X> isCandidate(final Iterable<List<X>> remainingInputs) { return new Predicate<X>() { Predicate<List<X>> headIs(final X c) { return new Predicate<List<X>>() { public boolean apply(List<X> input) { return !input.isEmpty() && c.equals(input.get(0)); } }; } Predicate<List<X>> tailContains(final X c) { return new Predicate<List<X>>() { public boolean apply(List<X> input) { return input.indexOf(c) > 0; } }; } public boolean apply(final X c) { return any(remainingInputs, headIs(c)) && all(remainingInputs, not(tailContains(c))); } }; }
[ "private", "static", "<", "X", ">", "Predicate", "<", "X", ">", "isCandidate", "(", "final", "Iterable", "<", "List", "<", "X", ">", ">", "remainingInputs", ")", "{", "return", "new", "Predicate", "<", "X", ">", "(", ")", "{", "Predicate", "<", "List", "<", "X", ">", ">", "headIs", "(", "final", "X", "c", ")", "{", "return", "new", "Predicate", "<", "List", "<", "X", ">", ">", "(", ")", "{", "public", "boolean", "apply", "(", "List", "<", "X", ">", "input", ")", "{", "return", "!", "input", ".", "isEmpty", "(", ")", "&&", "c", ".", "equals", "(", "input", ".", "get", "(", "0", ")", ")", ";", "}", "}", ";", "}", "Predicate", "<", "List", "<", "X", ">", ">", "tailContains", "(", "final", "X", "c", ")", "{", "return", "new", "Predicate", "<", "List", "<", "X", ">", ">", "(", ")", "{", "public", "boolean", "apply", "(", "List", "<", "X", ">", "input", ")", "{", "return", "input", ".", "indexOf", "(", "c", ")", ">", "0", ";", "}", "}", ";", "}", "public", "boolean", "apply", "(", "final", "X", "c", ")", "{", "return", "any", "(", "remainingInputs", ",", "headIs", "(", "c", ")", ")", "&&", "all", "(", "remainingInputs", ",", "not", "(", "tailContains", "(", "c", ")", ")", ")", ";", "}", "}", ";", "}" ]
To be a candidate for the next place in the linearization, you must be the head of at least one list, and in the tail of none of the lists. @param remainingInputs the lists we are looking for position in. @return true if the class is a candidate for next.
[ "To", "be", "a", "candidate", "for", "the", "next", "place", "in", "the", "linearization", "you", "must", "be", "the", "head", "of", "at", "least", "one", "list", "and", "in", "the", "tail", "of", "none", "of", "the", "lists", "." ]
train
https://github.com/lshift/jamume/blob/754d9ab29311601328a2f39928775e4e010305b7/src/main/java/net/lshift/java/dispatch/JavaC3.java#L186-L210
aws/aws-sdk-java
aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/JobDetail.java
JobDetail.withParameters
public JobDetail withParameters(java.util.Map<String, String> parameters) { setParameters(parameters); return this; }
java
public JobDetail withParameters(java.util.Map<String, String> parameters) { setParameters(parameters); return this; }
[ "public", "JobDetail", "withParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "setParameters", "(", "parameters", ")", ";", "return", "this", ";", "}" ]
<p> Additional parameters passed to the job that replace parameter substitution placeholders or override any corresponding parameter defaults from the job definition. </p> @param parameters Additional parameters passed to the job that replace parameter substitution placeholders or override any corresponding parameter defaults from the job definition. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Additional", "parameters", "passed", "to", "the", "job", "that", "replace", "parameter", "substitution", "placeholders", "or", "override", "any", "corresponding", "parameter", "defaults", "from", "the", "job", "definition", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/JobDetail.java#L865-L868
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/factory/H2GISDBFactory.java
H2GISDBFactory.createDataSource
public static DataSource createDataSource(String dbName ,boolean initSpatial) throws SQLException { return createDataSource(dbName, initSpatial, H2_PARAMETERS); }
java
public static DataSource createDataSource(String dbName ,boolean initSpatial) throws SQLException { return createDataSource(dbName, initSpatial, H2_PARAMETERS); }
[ "public", "static", "DataSource", "createDataSource", "(", "String", "dbName", ",", "boolean", "initSpatial", ")", "throws", "SQLException", "{", "return", "createDataSource", "(", "dbName", ",", "initSpatial", ",", "H2_PARAMETERS", ")", ";", "}" ]
Create a database and return a DataSource @param dbName DataBase name, or path URI @param initSpatial True to enable basic spatial capabilities @return DataSource @throws SQLException
[ "Create", "a", "database", "and", "return", "a", "DataSource" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/factory/H2GISDBFactory.java#L93-L95
groovy/groovy-core
subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java
StreamingJsonBuilder.call
public Object call(Collection coll, Closure c) throws IOException { StreamingJsonDelegate.writeCollectionWithClosure(writer, coll, c); return null; }
java
public Object call(Collection coll, Closure c) throws IOException { StreamingJsonDelegate.writeCollectionWithClosure(writer, coll, c); return null; }
[ "public", "Object", "call", "(", "Collection", "coll", ",", "Closure", "c", ")", "throws", "IOException", "{", "StreamingJsonDelegate", ".", "writeCollectionWithClosure", "(", "writer", ",", "coll", ",", "c", ")", ";", "return", "null", ";", "}" ]
A collection and closure passed to a JSON builder will create a root JSON array applying the closure to each object in the collection <p> Example: <pre class="groovyTestCase"> class Author { String name } def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")] new StringWriter().with { w -> def json = new groovy.json.StreamingJsonBuilder(w) json authors, { Author author -> name author.name } assert w.toString() == '[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]' } </pre> @param coll a collection @param c a closure used to convert the objects of coll
[ "A", "collection", "and", "closure", "passed", "to", "a", "JSON", "builder", "will", "create", "a", "root", "JSON", "array", "applying", "the", "closure", "to", "each", "object", "in", "the", "collection", "<p", ">", "Example", ":", "<pre", "class", "=", "groovyTestCase", ">", "class", "Author", "{", "String", "name", "}", "def", "authors", "=", "[", "new", "Author", "(", "name", ":", "Guillaume", ")", "new", "Author", "(", "name", ":", "Jochen", ")", "new", "Author", "(", "name", ":", "Paul", ")", "]" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java#L184-L188
impossibl/stencil
engine/src/main/java/com/impossibl/stencil/engine/internal/StencilOperands.java
StencilOperands.toCollection
public Collection<?> toCollection(Object val) { if (val == null) { return Collections.emptyList(); } else if (val instanceof Collection<?>) { return (Collection<?>) val; } else if (val.getClass().isArray()) { return newArrayList((Object[]) val); } else if (val instanceof Map<?,?>) { return ((Map<?,?>)val).entrySet(); } else { return newArrayList(val); } }
java
public Collection<?> toCollection(Object val) { if (val == null) { return Collections.emptyList(); } else if (val instanceof Collection<?>) { return (Collection<?>) val; } else if (val.getClass().isArray()) { return newArrayList((Object[]) val); } else if (val instanceof Map<?,?>) { return ((Map<?,?>)val).entrySet(); } else { return newArrayList(val); } }
[ "public", "Collection", "<", "?", ">", "toCollection", "(", "Object", "val", ")", "{", "if", "(", "val", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Collection", "<", "?", ">", ")", "{", "return", "(", "Collection", "<", "?", ">", ")", "val", ";", "}", "else", "if", "(", "val", ".", "getClass", "(", ")", ".", "isArray", "(", ")", ")", "{", "return", "newArrayList", "(", "(", "Object", "[", "]", ")", "val", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Map", "<", "?", ",", "?", ">", ")", "{", "return", "(", "(", "Map", "<", "?", ",", "?", ">", ")", "val", ")", ".", "entrySet", "(", ")", ";", "}", "else", "{", "return", "newArrayList", "(", "val", ")", ";", "}", "}" ]
Coerce to a collection @param val Object to be coerced. @return The Collection coerced value.
[ "Coerce", "to", "a", "collection" ]
train
https://github.com/impossibl/stencil/blob/4aac1be605542b4248be95bf8916be4e2f755d1c/engine/src/main/java/com/impossibl/stencil/engine/internal/StencilOperands.java#L1153-L1170